Javascript to PHP add string array send Post API OAuth - php

I add a new contact API - send POST, according to the example below.
https://intranet_name.bitrix24.com/rest/crm.contact.add?auth=authentication_code&fields[NAME]=Maria&fields[SECOND_NAME]=Anna&fields[LAST_NAME]=Nowacka
It adds correctly, works.
I can not deal with the addition of the PHONE array, how to do it?
<script type="text/javascript">
BX24.callMethod(
"crm.contact.add",
{
fields:
{
"NAME": "John",
"SECOND_NAME": "Lancelot",
"LAST_NAME": "Doe",
"OPENED": "Y",
"ASSIGNED_BY_ID": 1,
"TYPE_ID": "CLIENT",
"SOURCE_ID": "SELF",
"PHOTO": { "fileData": document.getElementById('photo') },
"PHONE": [ { "VALUE": "555888", "VALUE_TYPE": "WORK" } ]
},
params: { "REGISTER_SONET_EVENT": "Y" }
},
function(result)
{
if(result.error())
console.error(result.error());
else
console.info("Created a new contact; ID=" + result.data());
}
);
OAuth 2.0 Protocol API documentation

I changed to uURL, it works.
You had to add a square bracket.
$data = array(
"fields" => array(
"NAME" => "Nowy2",
"LAST_NAME" => "Testowy1",
"ADDRESS" => "NowodÄ…browska 45",
"ADDRESS_POSTAL_CODE" => "54-345",
"ADDRESS_CITY" => "Warszawa",
"ADDRESS_COUNTRY" => "Polska",
"TYPE_ID" => "CLIENT",
"PHONE" => array([
"VALUE" => 994556765,
"VALUE_TYPE" => "WORK"]
)
)
);

Related

Authorize.net API integration "invalid child element 'transactionSettings' in namespace" when charging payment profile

Im integrating with authorize.net and process credit card transactions. I have the charge working fine for processing direct credit card payment :
$authnet_info = array(
'createTransactionRequest' => array(
'merchantAuthentication' => array(
'name' => ######,
'transactionKey' => #######
),
'refId' => $data['reference_id'],
'transactionRequest' => array(
'transactionType' => 'authCaptureTransaction',
'amount' => $data['charge_amount'],
'payment' => array(
'creditCard' => array(
'cardNumber' => $data['cc_number'],
'expirationDate' => $data['cc_expiration'],
"cardCode" => $data['cvc']
)
),
'customer' => array(
'type' => 'business',
'id' => $data['id_company']
),
'billTo' => array(
"firstName" => $data['first_name'],
"lastName" => $data['last_name'],
'company' => $data['company_name'],
"address" => $data['address'],
"city" => $data['city'],
"state" => $data['state'],
"zip" => $data['zipcode']
),
"transactionSettings" => array (
"setting" => array (
array(
"settingName" => "duplicateWindow",
"settingValue" => "5"
)
)
)
)
)
);
This works just fine however when i try to pass the same setting
"transactionSettings" => array (
"setting" => array (
array(
"settingName" => "duplicateWindow",
"settingValue" => "5"
)
)
)
For charging against a payment profile i get the following error:
(
[code] => E00003
[text] => The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'transactionSettings' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'subsequentAuthInformation, otherTax, shipFrom, authorizationIndicatorType' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'.
)
Here is the post i am sending to authorize.net
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "######",
"transactionKey": "##########"
},
"refId": "62",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "25.00",
"profile": {
"customerProfileId": "1231231",
"paymentProfile": {
"paymentProfileId": "34534534534"
}
},
"customer": {
"type": "business",
"id": 5
},
"processingOptions": {
"isSubsequentAuth": "false"
},
"transactionSettings": {
"setting": [{
"settingName": "duplicateWindow",
"settingValue": "5"
}]
}
}
}
}
When i remove the transaction settings part of my post the charge goes through fine. Does anyone know where this setting needs to be placed? Their documentation clearly states in this location that i am placing however im not sure why it wont go through.
Edit: I tried the method mentioned below and received the same error:
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "#####",
"transactionKey": "#######dfsd"
},
"refId": "62",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "25.00",
"profile": {
"customerProfileId": "502810352",
"paymentProfile": {
"paymentProfileId": "511258154"
}
},
"customer": {
"type": "business",
"id": 5
},
"processingOptions": {
"isSubsequentAuth": "false"
}
},
"transactionSettings": {
"setting": [{
"settingName": "duplicateWindow",
"settingValue": "5"
}]
}
}
}
EDIT: i answered the question apparently i had a extra setting within the request that doesnt need to be present
Ok so i figured out the issue for anyone else facing the same problem. The issue seemed to be the
"processingOptions": {
"isSubsequentAuth": "false"
}
setting within the request. I guess it not valid with the transactionsetting being present.
I ended up passing the following request and it worked fine
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "#####",
"transactionKey": "######"
},
"refId": "62",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "25.00",
"profile": {
"customerProfileId": "sdfsdf",
"paymentProfile": {
"paymentProfileId": "51sdfsdf1258154"
}
},
"customer": {
"type": "business",
"id": 5
},
"transactionSettings": {
"setting": [{
"settingName": "duplicateWindow",
"settingValue": "5"
}]
}
}
}
}

PHP array only showing last product within json

I have a shopping cart and once the action placeorder.php is hit, i have set-up a webhook to post to discord.
The cart uses session arrays to store the cart information.
the session array is set as below on the product.php page when the "add to card" button is pressed
$_SESSION['cart'] = array($product_id => $quantity);
The product IDs are pulled from a mysql DB.
With 2x items added to the cart, the array is as follows:
["cart"]=>
array(2) {
[1]=> int(5)
[4]=> int(3)
}
If I echo the array it comes out as
foreach ($products as $product){
echo $product[name];
echo $products_in_cart[$product['id']];
}
Output: camera5laptop3
$products_in_cart[$product['id'] is simply grabbing the quantity ordered.
The JSON Structure
I am trying to make it so that every product name in the cart appears on a new line (\n) under the "Ordered Products" field. and the same for the quanity.
This would be through a foreach but since the json structure is within json_encode() I am struggling.
The below set-up currently only shows the last $product['name'] and $products_in_cart[$product['id'] in the array
$msg = json_encode([
// Message
"content" => "",
// Username
//"username" => "",
// Avatar URL.
// Uncomment to use custom avatar instead of bot's pic
//"avatar_url" => "",
// text-to-speech
"tts" => false,
// file_upload
// "file" => "",
// Embeds Array
"embeds" => [
[
// Title
"title" => "New Order",
// Embed Type, do not change.
"type" => "rich",
// Description
"description" => "New order, go sort it",
// Link in title
//"url" => "",
// Timestamp, only ISO8601
"timestamp" => $timestamp,
// Left border color, in HEX
"color" => hexdec( "3366ff" ),
// Footer text
"footer" => [
"text" => "Sent from thestash.store",
"icon_url" => ""
],
// Embed image
"image" => [
"url" => ""
],
// thumbnail
//"thumbnail" => [
// "url" => ""
//],
// Author name & url
"author" => [
"name" => "TEST3",
"url" => ""
],
// Custom fields
"fields" => [
// Field 1
[
"name" => "Ordered Products",
"value" => $product['name'],
"inline" => true
],
// Field 2
// Field 1
[
"name" => "Quantity",
"value" => $products_in_cart[$product['id']],
"inline" => true
],
[
"name" => "Order Total $",
"value" => $subtotal,
],
[
"name" => "Customer Alias",
"value" => $_SESSION['alias'],
"inline" => true
],
[
"name" => "Customer Number",
"value" => $_SESSION['number'],
"inline" => true
],
[
"name" => "Affiliation",
"value" => $_SESSION['affiliation'],
"inline" => true
],
// etc
]
]
]
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
Current Output on discord:
Attempting to output as (manuall set in JSON)
print_r($msg);
{
"content": "",
"tts": false,
"embeds": [
{
"title": "New Order",
"type": "rich",
"description": "New order, go sort it",
"timestamp": "2023-01-13T11:57:22+00:00",
"color": 3368703,
"footer": {
"text": "Sent from thestash.store",
"icon_url": ""
},
"image": {
"url": ""
},
"author": {
"name": "TEST3",
"url": "https://thestash.store"
},
"fields": [
{
"name": "Ordered Products",
"value": "laptop",
"inline": true
},
{
"name": "Quantity",
"value": 3,
"inline": true
},
{
"name": "Order Total $",
"value": 96000
},
{
"name": "Customer Alias",
"value": "quigg",
"inline": true
},
{
"name": "Customer Number",
"value": "1239871237378127",
"inline": true
},
{
"name": "Affiliation",
"value": "yes",
"inline": true
}
]
}
]
}
Attempting to have the JSON format as follows. Where each $product[name] and $products_in_cart[$product['id']] is on a new line. Currently the last $product[name] and $products_in_cart[$product['id']] show
{
"content": "",
"tts": false,
"embeds": [
{
"title": "New Order",
"type": "rich",
"description": "New order, go sort it",
"timestamp": "2023-01-13T11:57:22+00:00",
"color": 3368703,
"footer": {
"text": "Sent from thestash.store",
"icon_url": ""
},
"image": {
"url": ""
},
"author": {
"name": "TEST3",
"url": "https://thestash.store"
},
"fields": [
{
"name": "Ordered Products",
"value": "camera\nlaptop",
"inline": true
},
{
"name": "Quantity",
"value": "5\n3",
"inline": true
},
{
"name": "Order Total $",
"value": 96000
},
{
"name": "Customer Alias",
"value": "quigg",
"inline": true
},
{
"name": "Customer Number",
"value": "1239871237378127",
"inline": true
},
{
"name": "Affiliation",
"value": "yes",
"inline": true
}
]
}
]
}
So it's just a case of adding extra things into two strings, separated by newlines. So just loop over the products array to create two strings, one for the name and one for the quantity, and put those into variables. Then, you can just use those variables in the right places in your Fields array.
Heres the general idea:
$names = "";
$quantities = "";
foreach ($products as $product){
$names .= ($names != "" ? "\n" : "").$product["name"];
$quantities .= ($quantities != "" ? "\n" : "").$products_in_cart[$product['id']];
}
Then in the bit where you build the array:
...
"fields" => [
[
"name" => "Ordered Products",
"value" => $names,
"inline" => true
],
[
"name" => "Quantity",
"value" => $quantities,
"inline" => true
],
...

How to access a json child in php respect validation?

I'm trying to validate the following json file but I can't find the way to access the "Address" child, how should I do it? Everything goes fine until it tries to access the "address" field.
Json:
{
"first_name": "Test",
"last_name": "Test",
"email": "test#gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}
Code:
$data = $this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" =>[
"country" => v::stringVal()->notEmpty(),
"postal_code" => v::stringVal()->notEmpty(),
"city" => v::stringVal()->notEmpty(),
"street" => v::stringVal()->notEmpty(),
"number" => v::stringVal()->notEmpty(),
"floor" => v::stringVal()->notEmpty(),
"door" => v::stringVal()->notEmpty(),
],
"password" => v::base64()->notEmpty(),
"birth_date" => v::date()->notEmpty()
]);
Looks like you are using Respect\Validation\Validator. We can make use of chained validation and the Key function to validate sub-arrays as shown in the docs.
$data = [
'parentKey' => [
'field1' => 'value1',
'field2' => 'value2'
'field3' => true,
]
];
Using the next combination of rules, we can validate child keys.
v::key(
'parentKey',
v::key('field1', v::stringType())
->key('field2', v::stringType())
->key('field3', v::boolType())
)
->assert($data); // You can also use check() or validate()
Applied to your data, the validation could look like this:
use Respect\Validation\Validator as v;
$json = json_decode('{
"first_name": "Test",
"last_name": "Test",
"email": "test#gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}', true);
v::create()
->key('first_name', v::stringType()->length(1, 32))
->key('last_name', v::stringVal()->notEmpty())
//->..
->key('address',
v::key('country', v::stringType()->length(1, 32))
->key('postal_code', v::stringType()->length(1, 32))
->key('city', v::stringType()->length(1, 32))
//->..
)
->key('password', v::stringVal()->notEmpty())
->key('birth_date', v::stringVal()->notEmpty())
->assert($json); // You can also use check() or validate()
That is the way to access the child of the json:
$this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" => v::notEmpty()
->key("country", v::stringVal()->notEmpty())->key("postal_code", v::stringVal())->key("city", v::stringVal()->notEmpty())->key("street", v::stringVal()->notEmpty())->key("number", v::stringVal())->key("floor", v::stringVal())->key("door", v::stringVal()),
"password" => v::base64()->notEmpty(),
"birth_date" => v::date('d/m/Y')->notEmpty()
]);

set a custom multiselect via JIRA REST API

I'm trying to set a custom field of type Multiselect via JIRA rest API using php. For reason I'm getting the following error:
{"errorMessages":[],"errors":{"Functionality Impacted":"expected 'value' property to be a string"}}
I have the following code for setting the custom field:
public function requestRemedy($summary, $description, $priority, $goliveDate,$startTime,
$endTime,$clientImpact,$impactedFunctionality,$fundTransfers ,$fieldAffected, $remedyChangeType,
$changeReason,$remedyImpact, $urgency,$riskLevel,$nameRequestor,$emailRequestor)
{
$json = Array ( "fields" => Array (
"project" => Array
( "id" => 10051 ),
"summary" => $summary,
"description" =>$description,
"issuetype" => Array ( "name" => "Remedy Change Management" ),
"priority" => Array("id" => $priority),
"customfield_13774" => $goliveDate,
"customfield_14408" => "$startTime",
"customfield_14409" => "$endTime",
"customfield_14412" => "$clientImpact",
"customfield_14908" =>Array ( 0 => Array(
"value" => ($impactedFunctionality),
)),
"customfield_14414" => Array("id" =>$fundTransfers),
// "customfield_14415" =>Array("id" => $businessOnline,"child" =>Array("id" => $businessDependency) ),
"customfield_14602" => Array("id" =>$fieldAffected),
"customfield_14422" => Array("id" =>$remedyChangeType),
"customfield_14423" => Array("id" =>$changeReason),
"customfield_14424" => Array("id" =>$remedyImpact),
"customfield_14425" => Array("id" =>$urgency),
"customfield_14426" => Array("id" =>$riskLevel),
"customfield_14700"=>$nameRequestor,
"customfield_14702"=>$emailRequestor
)
);
return $json;
}
After adding some dummy data to test the final structure of json, I get the following result:
{
"fields": {
"project": {
"id": 10051
},
"summary": "Test",
"description": "Human DeSC",
"issuetype": {
"name": "Remedy Change Management"
},
"priority": {
"id": "2"
},
"customfield_13774": "2016-11-08",
"customfield_14408": "2016-11-01T07:35:00.000+0200",
"customfield_14409": "2016-11-01T08:35:00.000+0200",
"customfield_14412": "cLIENT iMPACT",
"customfield_14908": [{
"value": ["Savings Accounts", "Current Accounts", "Call Deposits"]
}],
"customfield_14414": {
"id": "13647"
},
"customfield_14602": {
"id": "14022"
},
"customfield_14422": {
"id": "13712"
},
"customfield_14423": {
"id": "13718"
},
"customfield_14424": {
"id": "13722"
},
"customfield_14425": {
"id": "13726"
},
"customfield_14426": {
"id": "13730"
},
"customfield_14700": "Pastor Dan",
"customfield_14702": "email#time.com"
}
}
Which means the issue is here:
"customfield_14908": [{
"value": ["Savings Accounts", "Current Accounts", "Call Deposits"]
}],
the expected structure is:
"customfield_10008": [ {"value": "Savings Accounts" }, {"value": "Current Accounts" }, {"value": "Call Deposits" }]
Now I'm not sure how to build this using an associative array
The custom field I'm trying to set is customfield_14908. What I'm finding weird is that I used similar code for setting a multiselect field on JIRA version 7.2.1 and it works well, but not working on JIRA version 7.0.

I can not get data to aggregate It. PHP + mongoDB

It works like I need:
$out = $collection->aggregate(
array(
'$match' => array('type' => 'chair')
),
array(
'$project' => array(
'chairtype' => 1,
'mijczjeqeo'=>1
)
),
array(
'$group' => array(
'_id' => '$chairtype',
'MIDDLE_mijczjeqeo' => array('$avg' => '$mijczjeqeo'),
'SUMMA__mijczjeqeo' => array('$sum' => '$mijczjeqeo')
)
)
);
my_dump($out);
But i need to get true data for aggregation from array in the same documents: versions[0][content][mijczjeqeo]
Please correct my script. It does not work:
$out = $collection->aggregate(
array(
'$match' => array('type' => 'chair')
),
array(
'$project' => array(
'chairtype' => 1,
'versions.0.content.mijczjeqeo'=>1
)
),
array(
'$group' => array(
'_id' => '$chairtype',
'MIDDLEmijczjeqeo' => array('$avg' => '$versions.0.content.mijczjeqeo'),
'SUMMAmijczjeqeo' => array('$sum' => '$versions[0]["content"]["mijczjeqeo"]')
)
)
);
no one method does not work:
'MIDDLEmijczjeqeo' => array('$avg' => '$versions.0.content.mijczjeqeo')
'SUMMAmijczjeqeo' => array('$sum' => '$versions[0]["content"]["mijczjeqeo"]')
I think the problem near .0.
I try to do it in mongo console...
db.documents.aggregate({$match:{'type':'chair'}},{$project:{'chairtype': 1, 'mijczjeqeo':1}},{$group:{'_id':'$chairtype','MID':{$avg:'$mijczjeqeo'}}})
{
"result" : [
{
"_id" : "T",
"MID" : 6.615384615384615
},
{
"_id" : "G",
"MID" : 8.310344827586206
},
{
"_id" : "E",
"MID" : 6.9523809523809526
}
],
"ok" : 1
}
db.documents.aggregate({$match:{'type':'chair'}},{$project:{'chairtype': 1, 'versions.0.content.mijczjeqeo':1}},{$group:{'_id':'$chairtype','MID':{$avg:'$versions.0.content.mijczjeqeo'}}})
{
"result" : [
{
"_id" : "T",
"MID" : 0
},
{
"_id" : "G",
"MID" : 0
},
{
"_id" : "E",
"MID" : 0
}
],
"ok" : 1
}
Well you cannot project like that in the aggregation pipeline. If you want to act on array elements within an aggregation statement you first need to $unwind the array and then either $match the required element(s) or as in your case choose the $first item using an additional $group stage.
Your question does not show the structure of a document so I'll just use a sample, as my "chairs" collection:
{
"_id": 1,
"type": "chair",
"chairtype": "A",
"versions": [
{
"revision": 1,
"content": {
"name": "ABC",
"value": 10
}
},
{
"revision": 2,
"content": {
"name": "BBB",
"value": 15
}
}
]
}
{
"_id": 2,
"type": "chair",
"chairtype": "A",
"versions": [
{
"revision": 1,
"content": {
"name": "CCC",
"value": 20
}
},
{
"revision": 2,
"content": {
"name": "BAB",
"value": 12
}
}
]
}
Minimal, but enough to get the point. Now the aggregate statement:
db.chairs.aggregate([
// Normal query matching, which is good
{ "$match": { "type": "chair" } },
// Unwind the array to de-normalize
{ "$unwind": "$versions" },
// Group by the document in order to get the "first" array element
{ "$group": {
"_id": "$_id",
"chairtype": { "$first": "$chairtype" },
"versions": { "$first": "$versions" }
}},
// Then group by "chairtype" to get your average values
{ "$group": {
"_id": "$chairtype",
"MID": {"$avg": "$versions.content.value"}
}}
])
Of course if your actual document has nested arrays then you will be "unwinding" and "matching" the required elements. But that is the general process of "narrowing down" the array contents to the elements you need.

Categories