How to send JSON request with guzzle6 and Laravel - json

From an API I need to send the request in this format:
Sample Request Body
{
"first_name": "adam.west",
"last_name": "adam.west",
"email_address": "adam.west#example.com",
"phone": {
"number": "11111111111",
"country_code": "UK",
"phone_type": "Mobile",
"extension": "124"
},
"comment": "comment",
}
so with Laravel and Guzzle6, I write this:
$res1 = $client1->post('https://example.com/someurl', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer '.$token,
],
'json' => [
'first_name' => $FirstName,
'last_name' => $Surname,
'email_address' => $Email,
'phone' => [
$phone['number'] = $Mobile,
$phone['country_code'] = $MobileCountryCode,
$phone['phone_type'] = 'Mobile',
$phone['extension'] = $request->dialCode,
],
'comment' => $comment,
]
]);
Everything is fine except phone element - What is the proper way to send phone element - because from API response I got error message "Phone could not be empty"

Related

Groovy: convert url encoded to JSON

I have a string from encoded url like this:
leads%5Bupdate%5D%5B0%5D%5Bid%5D=123432456&leads%5Bupdate%5D%5B0%5D%5Bname%5D=%D0%A1%D0%B4%D0%B5%D0%BB%D0%BA%D0%B0+2342345345345&leads%5Bupdate%5D%5B0%5D%5Bstatus_id%5D=45645676&leads%5Bupdate%5D%5B0%5D%5Bprice%5D=0&leads%5Bupdate%5D%5B0%5D%5Bresponsible_user_id%5D=2423432&leads%5Bupdate%5D%5B0%5D%5Blast_modified%5D=1231423556&leads%5Bupdate%5D%5B0%5D%5Bmodified_user_id%5D=6756756&leads%5Bupdate%5D%5B0%5D%5Bcreated_user_id%5D=2423432&leads%5Bupdate%5D%5B0%5D%5Bdate_create%5D=1234534678&leads%5Bupdate%5D%5B0%5D%5Bpipeline_id%5D=4564564&leads%5Bupdate%5D%5B0%5D%5Baccount_id%5D=34578987&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bid%5D=567834&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bname%5D=MANGO+OFFICE+%D0%9D%D0%BE%D0%BC%D0%B5%D1%80+%D0%BB%D0%B8%D0%BD%D0%B8%D0%B8&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=74994567456&leads%5Bupdate%5D%5B0%5D%5Bcreated_at%5D=1234534678&leads%5Bupdate%5D%5B0%5D%5Bupdated_at%5D=1231423556&account%5Bsubdomain%5D=google&account%5Bid%5D=34578987&account%5B_links%5D%5Bself%5D=https%3A%2F%2Fgoogle.site.com
decoded string:
leads[update][0][id]=123432456&leads[update][0][name]=Сделка+2342345345345&leads[update][0][status_id]=45645676&leads[update][0][price]=0&leads[update][0][responsible_user_id]=2423432&leads[update][0][last_modified]=1231423556&leads[update][0][modified_user_id]=6756756&leads[update][0][created_user_id]=2423432&leads[update][0][date_create]=1234534678&leads[update][0][pipeline_id]=4564564&leads[update][0][account_id]=34578987&leads[update][0][custom_fields][0][id]=567834&leads[update][0][custom_fields][0][name]=MANGO+OFFICE+Номер+линии&leads[update][0][custom_fields][0][values][0][value]=74994567456&leads[update][0][created_at]=1234534678&leads[update][0][updated_at]=1231423556&account[subdomain]=google&account[id]=34578987&account[_links][self]=https://google.site.com
array:
[
'leads' => [
'update' => [
[
'id' => 22652446,
'name' => 'Сделка 74956462949',
'status_id' => 33687064,
'price' => 0,
'responsible_user_id' => 5827756,
'last_modified' => 1675346949,
'modified_user_id' => 8775297,
'created_user_id' => 5827756,
'date_create' => 1640068981,
'pipeline_id' => 3365869,
'account_id' => 28791871,
'custom_fields' => [
[
'id' => 662156,
'name' => 'MANGO OFFICE Номер линии',
'values' => [
[
'value' => 74994551765,
],
],
],
],
'created_at' => 1640068981,
'updated_at' => 1675346949,
],
],
],
'account' => [
'subdomain' => 'google',
'id' => 28791871,
'_links' => [
'self' => 'https://google.site.com'
],
],
]
and JSON:
{
"leads":
{
"update": [
{
"id":22652446,
"name":"\u0421\u0434\u0435\u043b\u043a\u0430 74956462949",
"status_id":33687064,
"price":0,
"responsible_user_id":5827756,
"last_modified":1675346949,
"modified_user_id":8775297,
"created_user_id":5827756,
"date_create":1640068981,
"pipeline_id":3365869,
"account_id":28791871,
"custom_fields": [
{
"id":662156,
"name":"MANGO OFFICE \u041d\u043e\u043c\u0435\u0440 \u043b\u0438\u043d\u0438\u0438",
"values": [
{
"value":74994551765
}
]
}
],
"created_at":1640068981,
"updated_at":1675346949
}
]
},
"account":
{
"subdomain":"google",
"id":28791871,
"_links":
{
"self":"https:\/\/google.site.com"
}
}
}
How I can convert it to JSON with Groovy?
Thanks.
P.S: I read this Convert url encoded data to json but it's not help.

add to JSON ($payload={}) on condition

I feed JSON to some webhook to trigger a notification (M$ Teams). This works well. However, I want to extend my Perl script: I need to add a new node to my "messagecard" construct on a certain condition.
E.g. I defined this:
my $payload={};
$payload = {
'#type' => 'MessageCard',
'#context' => 'http://schema.org/extensions',
themeColor => $event{COLOR},
text => $event{SERVICEOUTPUT},
sections => [{
facts => [{
name => 'Type',
value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
},
]
}],
potentialAction => [{
'#type' => "OpenUri",
name => "View Monitoring",
targets => [{
os => "default",
uri => $naemon_url
}]
}]
};
$ua = LWP::UserAgent->new;
my $req = POST($opt_webhook
, 'Content-Type' => 'application/json; charset=UTF-8'
, 'Content' => encode_json($payload)
);
my $resp = $ua->request($req);
And if (conditon), I want to extend this as follows (order is important):
$payload = {
'#type' => 'MessageCard',
'#context' => 'http://schema.org/extensions',
themeColor => $event{COLOR},
text => $event{SERVICEOUTPUT},
sections => [{
facts => [{
name => 'Type',
value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
},
]
}],
potentialAction => [{
'#type' => "OpenUri",
name => "View Monitoring",
targets => [{
os => "default",
uri => $naemon_url
}]
},
{
'#type' => "OpenUri",
name => "Notes (Logs, Docs,..)",
targets => [{
os => "default",
uri => $event{SERVICENOTESURL}
}]
}]
};
I am unsure how this can be achieved. Can anyone please provide wisdom how to tackle this?
You can push into the array reference that you've got inside your potentialAction key. In order to do that, you need to dereference it as an array.
my $payload = {
'#type' => 'MessageCard',
potentialAction => [{
name => "View Monitoring",
targets => [{
os => "default",
}]
}]
};
if ($maybe) {
push #{ $payload->{potentialAction} }, {
name => "Notes (Logs, Docs,..)",
targets => [{
os => "default",
}]
};
}
If your Perl version is 5.24 or newer you can also use postfix dereferencing, which some people find easier to read.
push $payload->{potentialAction}->#*, ...
See perlref and perlreftut for more information.

How To create update API in yii?

I created an api named valid which is not working. Postman says
"name": "Not Found",
"message": "Page not found.",
"code": 0,
"status": 404,
"type": "yii\\web\\NotFoundHttpException",
"previous": {
"name": "Invalid Route",
"message": "Unable to resolve the request \"user/valid/1\".",
"code": 0,
"type": "yii\\base\\InvalidRouteException"
}
}
My controller name is user controller.
Here is my function
public function actionValid($id)
{
return 'example';
}
i called my route as /user/valid/1.
Any reason why this is happening?
This is how i solved this.
If you want to create your own apis in yii, You must follow these steps.
First add your route in UrlManager Like this
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'extraPatterns' => [
'POST valid/<id>' => 'valid',
'GET listing' => 'listing
]
],
],
]
Now, call your route like this users/valid/{your-id} and users/listing. Make sure to use a plural of your controller's name.
For example, a request of POST /users/data would mean accessing the actiondata function in your usercontroller.

Invoking endpoint with CURL- Post method and json is corrupt

I am invoking an endpoint of mine with CURL with the following command:
curl -H "Content-Type: application/json" -X POST -d '{"TransmissionID":"SO000001","CustomerSO":"SO000001","EndUserName":"Roi_Test","Hold":"","RequestedDate":"2019-02-24 15:00","Currency":"EUR","Address1":"Calle del Maestro Bagant","Address2":"","BuildingName":"","BuildingNumber":"1","Floor":"1","ContactPerson":"roi","City":"Valencia","CountryAbbriviation":"ES","Email":"aaa#joomi.co.il","Phone":"050-7680249","Zip":"46015","Remark":"","Incoterm":"DDP","Status":"","Item":["OrderLine":1,"ItemName":"cl111","ItemDescription":"Description","Quantity":"1.","PriceCurrency":"EUR","Price":"219.9","HSCode":"9900000003463","AWBNumber":"","CarrierName":"PostNL","CountryOfManufacturer":"CN","Base64String":""],"NumberOfSku":1,"NumberOfUnits":1}' "http://server.com/Magicxpi4.6/MgWebRequester.dll?appname=IFSCarolina_Prod&prgname=HTTP&arguments=-AREST_Incoming%%23IncomingFile"
and the JSON received is as follow:
{TransmissionID:SO000001,CustomerSO:SO000001,EndUserName:Roi_Test,Hold:,RequestedDate:2019-02-24 15:00,Currency:EUR,Address1:Calle del Maestro Bagant,Address2:,BuildingName:,BuildingNumber:1,Floor:1,ContactPerson:roi,City:Valencia,CountryAbbriviation:ES,Email:aaa#joomi.co.il,Phone:050-7680249,Zip:46015,Remark:,Incoterm:DDP,Status:,Item:[OrderLine:1,ItemName:cl111,ItemDescription:Description,Quantity:1.,PriceCurrency:EUR,Price:219.9,HSCode:9900000003463,AWBNumber:,CarrierName:PostNL,CountryOfManufacturer:CN,Base64String:],NumberOfSku:1,NumberOfUnits:1}
The data received is looking like a string not like a JSON, the fields and values are missing the " signs...
I have already tried to change between single/double quotes and it did not work.
Any ideas on how to resolve this?
you ARE sending a corrupt json, specifically
"Item": [
"OrderLine": 1,
"ItemName": "cl111",
"ItemDescription": "Description",
"Quantity": "1.",
"PriceCurrency": "EUR",
"Price": "219.9",
"HSCode": "9900000003463",
"AWBNumber": "",
"CarrierName": "PostNL",
"CountryOfManufacturer": "CN",
"Base64String": ""
],
is not valid JSON. in PHP this would be a legal array, as PHP allows string-keys in arrays, but JSON (and JavaScript) does not. but in JSON, objects can have string keys, so the closest thing you'll get to a legal json would be to make "Item" an object instead of an array, for example this would be legal JSON:
{
"TransmissionID": "SO000001",
"CustomerSO": "SO000001",
"EndUserName": "Roi_Test",
"Hold": "",
"RequestedDate": "2019-02-24 15:00",
"Currency": "EUR",
"Address1": "Calle del Maestro Bagant",
"Address2": "",
"BuildingName": "",
"BuildingNumber": "1",
"Floor": "1",
"ContactPerson": "roi",
"City": "Valencia",
"CountryAbbriviation": "ES",
"Email": "aaa#joomi.co.il",
"Phone": "050-7680249",
"Zip": "46015",
"Remark": "",
"Incoterm": "DDP",
"Status": "",
"Item": {
"OrderLine": 1,
"ItemName": "cl111",
"ItemDescription": "Description",
"Quantity": "1.",
"PriceCurrency": "EUR",
"Price": "219.9",
"HSCode": "9900000003463",
"AWBNumber": "",
"CarrierName": "PostNL",
"CountryOfManufacturer": "CN",
"Base64String": ""
},
"NumberOfSku": 1,
"NumberOfUnits": 1
}
btw, are you hand-crafting such large jsons complex jsons? i think you should switch to a scripting language instead to make it more readable and maintainable, ... for example, here is how to do it with PHP-cli:
#!/usr/bin/env php
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://server.com/Magicxpi4.6/MgWebRequester.dll?appname=IFSCarolina_Prod&prgname=HTTP&arguments=-AREST_Incoming%%23IncomingFile',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
) ,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode(array(
'TransmissionID' => 'SO000001',
'CustomerSO' => 'SO000001',
'EndUserName' => 'Roi_Test',
'Hold' => '',
'RequestedDate' => '2019-02-24 15:00',
'Currency' => 'EUR',
'Address1' => 'Calle del Maestro Bagant',
'Address2' => '',
'BuildingName' => '',
'BuildingNumber' => 1,
'Floor' => 1,
'ContactPerson' => 'roi',
'City' => 'Valencia',
'CountryAbbriviation' => 'ES',
'Email' => 'aaa#joomi.co.il',
'Phone' => '050-7680249',
'Zip' => '46015',
'Remark' => '',
'Incoterm' => 'DDP',
'Status' => '',
'Item' => array(
'OrderLine' => 1,
'ItemName' => 'cl111',
'ItemDescription' => 'Description',
'Quantity' => '1.',
'PriceCurrency' => 'EUR',
'Price' => 219.9,
'HSCode' => '9900000003463',
'AWBNumber' => '',
'CarrierName' => 'PostNL',
'CountryOfManufacturer' => 'CN',
'Base64String' => '',
) ,
'NumberOfSku' => 1,
'NumberOfUnits' => 1,
)) ,
));
curl_exec($ch);
curl_close($ch);
2 last things, the "Quantity" of the Item in your JSON is 1. - is the dot supposed to be there, or is it a typo?
i haven't touched the PayPal REST api in a long time, but this reminds me of the PayPal REST api, and in that API, i believe Item is supposed to be an array-of-objects, not just an object, if that's what you want then it would be "Item":[{...}] (in JSON) or 'Item' => array(array(...)) (in PHP)

How access array inside of JSON?

I'm use Guzzle for Laravel to send POST for Webservice, but I can't access array to send picture. That is the structed to I need follow:
{
"title": "xxxxxxxxxxxxxxxxx",
"category_id": "XXXX",
"official_store_id": null,
"pictures": [
{
"id": "XXXXX",
"url": "http://mlb-s1-p.mlstatic.com/292325-MLB25432321923_032017-O.jpg",
"secure_url": "https://mlb-s1-p.mlstatic.com/292325-MLB25432321923_032017-O.jpg",
"size": "500x500",
"max_size": "500x500",
"quality": ""
}
],
}
I try to send it like this:
$r = $client->request('POST', 'https://api.mercadolibre.com/items?access_token='.$token->erp_access_token, [
'json' => [
'title' => $name,
'category_id' => $cat2,
'price' => $price,
'currency_id' => 'BRL',
'available_quantity' => $quantity,
'buying_mode' => 'buy_it_now',
'listing_type_id' => 'gold_special',
'condition' => 'new',
'description' => $description,
'pictures' => [
'url' => $image
]
]
]);
Returns the error:
{"message":"body.invalid_field_types","error":"[invalid property type: [pictures] expected List but was JSONObject value (truncated...)
I read the Guzzle docs, but I not found any example for that case.
Any suggestion?
Change your pictures value from this
'pictures' => [
'url' => $image
]
to this
'pictures' => [
['url' => $image]
]