Passing Variable to Curl Post Field - php

I want to pass dynamic value stored in variable named as $order2, I want to pass that value to postfield using CURL Request.
<?php
$order2 = "1604";
$curl2 = curl_init();
curl_setopt_array($curl2, array(
CURLOPT_URL => "https://ssapi.shipstation.com/orders/createlabelfororder",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"{\n \"orderId\": $order2 ,\n \"carrierCode\": \"stamps_com\",\n \"serviceCode\": \"usps_priority_mail\",\n \"packageCode\": \"small_flat_rate_box\",\n \"confirmation\": null,\n \"shipDate\": \"2021-11-05\",\n \"weight\": {\n \"value\": 2,\n \"units\": \"pounds\"\n },\n \"dimensions\": null,\n \"insuranceOptions\": null,\n \"internationalOptions\": null,\n \"advancedOptions\": null,\n \"testLabel\": true\n}",
CURLOPT_HTTPHEADER => array(
"Host: ssapi.shipstation.com",
"Authorization:Basic MYAUTHCODE",
"Content-Type: application/json"
),
));
$response2 = curl_exec($curl2);
curl_close($curl2);
echo $response2;
It is returning me following response :
{"Message":"The request is
invalid.","ModelState":{"request.orderId":["Error reading integer.
Unexpected token: Undefined. Path 'orderId', line 2, position 15."]}}

Related

PHP CURL is not working while converting from curl command

i have a curl command, its working fine in terminal and want to convert in PHP code but its giving 415 Unsupported Media Type error.
CURL Command:
curl --location
--request POST 'https://securegw-uat.starhealth.in/api/proposal-service/v2/ckyc/generate'
--header 'APIKEY: 25861f5655bd4640b5518ceb2bfb5f94'
--header 'SECRETKEY: beec6bf3afff4efdab1f6a80d8601fbf'
--form 'bodyJson="{\"ckycId\":10036801290855,\"idOrAddressProofDocumentId\": 1,\"titleId\": 1,\"firstName\": \"Swadhin\",\"middleName\": \"\",\"lastName\": \"Dhal\",\"genderId\": 1,\"birthdate\": \"November 01, 1973\",\"occupationId\": 1,\"residentialStatusId\": 1,\"pan\": \"BLAPT0864M\",\"familyRelationshipId\": 3,\"familyMemberTitleId\": 2,\"familyMemberFirstName\": \"Rachita\",\"familyMemberLastName\": \"Dhal\",\"addressLineOne\": \"No. 20\",\"addressLineTwo\": \"Nehru Street\",\"cityName\": \"Triplicane\",\"districtName\": \"Chennai\",\"stateCode\": \"TN\",\"countryCode\": \"IN\",\"postalCode\": \"600005\",\"incomeSourceId\": 1,\"isAnyonePEP\": 0}";type=application/json'
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://securegw-uat.starhealth.in/api/proposal-service/v2/ckyc/generate',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('bodyJson' => '{
"ckycId": 10036801290855,
"idOrAddressProofDocumentId": 1,
"idOrAddressProofDocumentNumber": "1234",
"titleId": 1,
"firstName": "Swadhin",
"middleName": "",
"lastName": "Dhal",
"genderId": 1,
"birthdate": "November 01, 1973",
"occupationId": 1,
"residentialStatusId": 1,
"pan": "BLAPT0864M",
"familyRelationshipId": 3,
"familyMemberTitleId": 2,
"familyMemberFirstName": "Rachita",
"familyMemberLastName": "Dhal",
"addressLineOne": "No. 20",
"addressLineTwo": "Nehru Street",
"cityName": "Triplicane",
"districtName": "Chennai",
"stateCode": "TN",
"countryCode": "IN",
"postalCode": "600005",
"incomeSourceId": 1,
"isAnyonePEP": 0
}'),
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data',
'APIKEY: 25861f5655bd4640b5518ceb2bfb5f94',
'SECRETKEY: beec6bf3afff4efdab1f6a80d8601fbf'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;`
Please try to specify the header to --header 'Content-Type: multipart/form-data'.

Curl works in postman but doesn't work in php code

I'm developing a service for sending otp by sms. The phone company sent the following curl which I imported into Postman (method POST):
curl -H "Content-Type: multipart/form-data" -H "X-Token: <token>"
-F payloadSend="{ \"alias\": \"<alias>\", \"startDate\": null,
\"endDate\": null, \"period\": null, \"recurrencesNumber\": null,
\"recurrencesInterval\": null, \"validityPeriod\": null, \"sentNotify\":
false, \"deliveredNotify\": false, \"msisdnToNotify\": null,\"sr\": false,
\"campaignChannel\": { \"channelName\": \"UCP\", \"zone\": null,
\"zoneType\": null, \"collectionTime\": null }, \"campaignMessage\": {
\"messageType\": null, \"messageContent\": \"<testo>\",
\"template\": null, \"file\": \"string\", \"msisdn\": \"<msisdn>\",
\"listMsisdn\": null, \"fileMsisdn\": \"null\", \"name\": null,
\"surname\": null, \"extra\": null, \"status\": \"string\", \"delivered\":
\"string\" } };type=application/json" "https://channel-ssc.api.services.smb.telecomitalia.it/channels/UCP/campaigns?destination
=msisdn&message=static&delivery=immediate&type=single&mo
de=fast" --trace-ascii -
In postman everything works correctly and the sms arrives on my mobile device.
I used the tool in postman to create the code in Curl PHP (Code snippet):
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://channel-sscapi.services.smb.telecomitalia.it/channels/UCP/campaigns?destination=msisdn&message=static&delivery=immediate&type=single&mode=fast',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('payloadSend' => '{ "alias": "<alias>", "sentNotify":false, "deliveredNotify": false, "sr": false, "campaignChannel": { "channelName": "UCP" }, "campaignMessage": {"messageContent": "TEST TEST TEST!","msisdn": "<telephon number>"} }'),
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data',
'X-Token: <token>'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>
When I run the page I get an error:
{"timestamp":"2022-08-18T19:53:14.574+00:00","status":415,"error":"Unsupported Media Type","message":"","path":"/restful/channels/UCP/campaigns"}
If I change the CURLOPT_POSTFIELDS with this array (=> with :)
CURLOPT_POSTFIELDS => array('payloadSend: { "alias": "<alias>", "sentNotify":false, "deliveredNotify": false, "sr": false, "campaignChannel": { "channelName": "UCP" }, "campaignMessage": {"messageContent": "TEST TEST TEST!","msisdn": "<telephon number>"} }'),
The error is:
{"timestamp":"2022-08-18T20:14:45.613+00:00","status":400,"error":"Bad Request","message":"","path":"/restful/channels/UCP/campaigns"}
I think the problem is the array in CURLOPT_POSTFIELDS but I don't understand how to fix the error. anyone have any ideas?
Thanks everyone for the help.

Curl iteratively pass multiple payloads from json or array

How do I pass multidimensional associative array or a json as a payload to cURL request. I have been trying to wrap my head around this for sometime now without any success.
Here is what I have done so far. I make a curl request and pass a json to the CURLOPT_POSTFIELDS fields. This works alright. The problem is I want the code to run for multiple users which are in a json string saved in a variable
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url/tokens',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"customerName": "orland",
"mno": "Network",
"amount": "1",
"msisdn": "447911123456",
"description": "Awaiting",
"reference": "0fgdufgdfgdfs"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
The above code works fine.
But the payload for CURLOPT_POSTFIELDS is not fixed.
So this is what I tried doing, I encoded the json string and tried passing it to a for loop. I am sure the approach isn't bad, but I am not getting the syntax quite right. Here is my code.
<?php
$recip = '[{
"customerName": "Sorland",
"mno": "Network",
"amount": "1",
"msisdn": "447911123346",
"description": "Awaiting",
"reference": "0fgdufgdfgdfs"
},
{
"customerName": "Corland",
"mno": "MTN",
"amount": 1,
"msisdn": "447911123678",
"description": "Awaiting",
"reference": "0jsbfbsubfhbj"
},
{
"customerName": "orland",
"mno": "MTN",
"amount": 1,
"msisdn": "447911123111",
"description": "Awaiting",
"reference": "1234568djnfjnfjds"
}]';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url.com/api/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>
echo ("'{<br>");
foreach($arr[$keys[$i]] as $key => $value) {
echo implode($key . " : " . $value . ",<br>");
}
echo "}',<br>";
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
I want to use a for loop to make multiple curl request with different payloads, and the payloads are coming from the json data above. I converted the json to an array to be able to loop through and converted it back to a json for CURLOPT_POSTFIELDS.
This seems a simpler way to make multiple call to curl and save the responses, hope I got the right end of the stick this time :)
$recip =
'[
{"customerName": "Sorland", "mno": "Network", "amount": "1",
"msisdn": "447911123346","description": "Awaiting","reference": "0fgdufgdfgdfs"
},
{"customerName": "Corland","mno": "MTN","amount": 1,
"msisdn": "447911123678","description": "Awaiting","reference": "0jsbfbsubfhbj"
},
{"customerName": "orland","mno": "MTN","amount": 1,"msisdn": "447911123111",
"description": "Awaiting","reference": "1234568djnfjnfjds"
}
]';
// make a PHP datatype out of the JSON so you can use it
$recipients = json_decode($recip);
$responses = [];
foreach ( $recipients as $r) {
$curl = curl_init();
// convert $r back to json so it can be passed as param
$postfield = json_encode($r);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url.com/api/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postfield,
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
));
$response[] = curl_exec($curl);
// if you need to know which customer the response was for
// use this next line instead, for example
//$response[$r->customerName] = curl_exec($curl);
curl_close($curl);
}
// this is now an array of all responses
print_r($responses);

How do I correctly concatenate this php string

$name = $_POST["fname"];
echo $name;
CURLOPT_POSTFIELDS => "{\n
\"DisplayName\": \" ".$name." \",\n
\"PrimaryEmailAddr\": {\n \"Address\": \"jdrew#myemail.com\"\n }\n}\n",
I am trying to make a POST request with the details in the form which actioned the php file,
the echo prints the correct information, ive tried + and . and { and "" and all manner of things to no avail, hopefully anyone with an ounce of know how can fix this one , this is m first time near php :/
edit:
$jsons = array(
"DisplayName"=> "scsKing's Groceries",
"Suffix"=> "Jr",
"Title"=> "Mr",
"MiddleName"=> "B",
"Notes"=> "Here are other details.",
"FamilyName"=> "King",
"GivenName"=> "James"
);
$JsonString = json_encode($jsons);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://quickbooks.api.intuit.com/v3/company/123146505733159/customer?minorversion=41",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $JsonString,
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Accept-Encoding: gzip, deflate",
Would this be the correct format, it returns cURL Error #:Operation timed out after 30000 milliseconds with 0 bytes received
thanks

SendGrid Add new Contact to marketing contact list using php curl

Hi im trying to use a custom form on my website to add a new contact to our marketing list, each contact will contain an email and first name.
Im trying to follow this documentation but am having no success:
https://sendgrid.api-docs.io/v3.0/contacts/add-or-update-a-contact
I have tried using their tool but it always says incorrect JSON but when i use an online validator it says correct, I can't figure out how to match theirs to get my request to post.
This is my current code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{\"list_ids\":[\"bf3ce5bd-14a2-414b-9b81-*****8e8ea62\"],\"contacts\":[{\"email\":\"$email\",\"first_name\":\"$first_name\"]}",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer SG.OCFHb********P3iuikQ.bqKdM-da7X609ZNo9UT7y*********u5fDlfQo80o",
"content-type: application/json"
),
));
You just should be added } chars after $first_name.
This is valid JSON:
CURLOPT_POSTFIELDS => "{\"list_ids\":[\"bf3ce5bd-14a2-414b-9b81-*****8e8ea62\"],\"contacts\":[{\"email\":\"$email\",\"first_name\":\"$first_name\"}]}",
You can check it with https://jsonformatter.curiousconcept.com/ validator website.
One little trick to not have to deal with all the backslashes and escaping is to use a pre-defined object literal in PHP, by using arrays with (object) in front of them, to define the objects nested in the structures.
make an object, turn it into JSON with json_encode
enter the encoded JSON object into the CURLOPT_POSTFIELDS in the cURL request.
<?php
// make custom fields object for entry into the cURL later on:
// THERE IS NO OBJECT LITERAL IN PHP, but using (object) in front of an array, voila
$contact_info = (object)[
"list_ids" => [
"eeee-eeee-eeee-eeee-eeeeexample" // array of list ids here.
],
"contacts" => [ // this is an array of objects (array[object]), according to the api-docs.
(object)[
"email" => "email#example.com",
"country" => "the country",
"city" => "the city",
"custom_fields" => (object)[
"e1_T" => "sign-up-page-name", // only custom fields use ids as the key.
"e2_T" => "next-custom-field" // keep adding custom fields in this array.
]
]
]
];
// now all we have to do is to encode the object into JSON:
$json_contact_data = json_encode($contact_info);
// now add the contact:
$curl = curl_init();
// update the contact
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $json_contact_data, // here we enter the pre-configured json from above.
CURLOPT_HTTPHEADER => array(
"authorization: Bearer " . $your_api_key . "",
"content-type: application/json"
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$decoded = json_decode($response, true); // decode into associative array.
if ($err) {
echo "cURL Error #: " . $err;
} else {
print_r($decoded); // print the decoded json message.
}
?>
This is the best way:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.sendgrid.com/v3/marketing/contacts',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS =>'{"list_ids": ["list-ID"], "contacts": [{"email": "' . $_GET["email"] . '"}]}',
CURLOPT_HTTPHEADER => array(
': ',
'Authorization: Bearer SG.000000000',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
die();

Categories