I'm POSTing to an API that expects a json array called "updateRecord" in the body. I've tried a hundred different methods of getting the data across, but each method fails except for me literally writing the array as escaped text inside the CURLOPT_POSTFIELDS option.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url.com/update");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"updateRecord\":[{\"fielda\":\"77777\",
\"fieldb\":\"11.77\",\"fieldc\":\"12\",\"fieldd\":\"12\",\"fielde\":\"99\",
\"fieldf\":\"01\",\"fieldg\":\"TEST\",
\"fieldh\":\"Y\",\"fieldi\":\"Approved\"}]}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Authorization: Basic XXXXXXXXXXXXXXXXXX";
$headers[] = "Cache-Control: no-cache";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close ($ch);
echo $result;
For static test data to prove the API works, this is fine, but I am lost on how to take a pre-existing array in PHP and convert it into a format that will work here, like:
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
you could use json_encode() to serialize your array:
$arr = array('updateRecord' => array(
array(
'fielda' => '77777',
'fieldb' => '11.77',
'fieldc' => '12',
'fieldd' => '12',
'fielde' => '99',
'fieldf' => '01',
'fieldg' => 'TEST',
'fieldh' => 'Y',
'fieldi' => 'Approved',
),
),
);
$serial = json_encode($arr) ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $serial);
$serial will look like :
{"updateRecord":[{"fielda":"77777","fieldb":"11.77","fieldc":"12","fieldd":"12","fielde":"99","fieldf":"01","fieldg":"TEST","fieldh":"Y","fieldi":"Approved"}]}
Related
Am trying to use PHP 7.2 to submit a new job to the Watson Video Enrichment API.
Here's my code:
//set some vars for all tasks
$apiUrl = 'https://api-dal.watsonmedia.ibm.com/video-enrichment/v2';
$apiKey = 'xxxxxxxx';
//vars for this task
$path = '/jobs';
$name = 'Test1';
$notification_url = 'https://example.com/notification.php';
$url = 'https://example.com/video.mp4';
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => "simple.custom-model",
"upload" => array(
"url" => $url
)
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_URL, $apiUrl.$path );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: APIKey '.$apiKey
));
$result = curl_exec($ch);
echo $result;
But I can't get it to work, even with varying CURLOPTs, like:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
I keep getting the response: Bad Request.
Here's the API docs.
Am I setting up the POST CURL all wrong? Is my $data array wrong? Any idea how to fix this?
Reading their API documentation, it looks like the field preset is not of type string. Rather it has a schema defined here. This appears similar to how you are using the upload schema.
You should change your data array to look like this:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"video_url" => "https://example.com/path/to/your/video"
),
"upload" => array(
"url" => $url
)
);
Ok, I figured it out. Thanks to #TheGentleman for pointing the way.
My data array should look like:
$data = array(
"name" => $name,
"notification_url" => $notification_url,
"preset" => array(
"simple.custom-model" => array(
"video_url" => $url,
"language" => "en-US"
)
),
"upload" => array(
"url" => $url
)
);
I am using an online laravel api documentation in my app. When i run my code in my browser, i get the error "pass phonenumber field as an array". But the number field is being already passed as an array field. What could i be missing below in my code ? Thanks in advance
public function testAPI(Request $request)
{
$on_call_back = 'https://learntoday.co.uk/var';
$id = '*****';
$url = $on_call_back.'?key='.$id;
$variables = [
'phoneNumber' => ['44234200234','44234242002'],
'from' => 'world',
'content' => 'I love to code',
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($variables));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
}
When i return $variables, i get the response
Array
(
[phoneNumber] => Array
(
[0] => 44234200234
[1] => 44234242002
)
[from] => test
[content] => I love to code
)
{"status":"error","message":"Make sure you are passing the phoneNumber field as an array"}
Your syntax of the array seems to be wrong, have you tried putting each number into single quotes like this:
'phoneNumber' => ['44234200234', '44234242002'],
Change
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($variables));
to
curl_setopt($ch, CURLOPT_POSTFIELDS, $variables);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($variables));
You can also do curl_setopt($ch, CURLOPT_POST, 1); instead of CURLOPT_CUSTOMREQUEST.
Please try send $variable as below code
$variables = array(
'phoneNumber' => array('44234200234','44234242002'),
'from' => 'world',
'content' => 'I love to code',
);
You should try this:
$variables = [
'phoneNumber' => ['44234200234','44234242002'],
'from' => 'world',
'content' => 'I love to code',
];
Updated answer
public function testAPI(Request $request)
{
$on_call_back = 'https://learntoday.co.uk/var';
$id = '*****';
$url = $on_call_back.'?key='.$id;
$variables = [
'phoneNumber' => ['44234200234','44234242002'],
'from' => 'world',
'content' => 'I love to code',
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($variables));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
}
UPDATE*
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_ENV["https://cf6307f08afef7f0f9f449a55c6fd79b#api.dialmycalls.com/2.0/service/text"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = array (
'name' => 'Dorothy',
'keyword_id' => '351aa984-9a7b-11e8-a4d5-0cc47ab3cb58',
'messages' => 'test123456',
array ("contacts" => array(
array(
"phone" => "12294622255"
))));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
?>
I am still getting
`Error: malformed`
So maybe a little more information about the json construction might help
These are the required fields
name - > name of broadcast
keyword_id - > 351aa984-9a7b-11e8-a4d5-0cc47ab3cb58
messages - > list format but only sending single message "test123456"
contacts - > List format with substring of phone: then number 1234567891
ORIGINAL QUESTION
So i am trying to setup a php page with DialMyCall's API just to sent text with the variables
$numbers (Command Delimited)
$message (message of SMS)
The example that DialMyCode gives is
curl -i -H "Content-Type: application/json" -X POST -d "{\"keyword_id\": \"dfe49537-a0a8-4f4a-98a1-e03df388af11\", \"send_immediately\": true,\"messages\": [\"Testing testing\"], \"contacts\": [{\"phone\":\"1116551235\"},{\"phone\":\"1116551234\"}]}" https://$API_KEY#api.dialmycalls.com/2.0/service/text
I have tried to convert this into php but i cannot get it to work
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_ENV["https://APIKEY#api.dialmycalls.com/2.0/service/text"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array (
'name' => 'Dorothy',
'keyword_id' => '351aa984-9a7b-11e8-a4d5-0cc47ab3cb58',
'message' => 'test123456',
'contacts' => 'phone: 1234567891',
));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
?>
Error recieved
Error: malformed
What i should get is a success message in JSON and a text message sent.
You need to send your data as a JSON string. When you pass an array to CURLOPT_POSTFIELDS, it formats/passes it like form data. Here, you want to pass a json object as the body, so use something like this below:
$data = array (
'name' => 'Dorothy',
'keyword_id' => '351aa984-9a7b-11e8-a4d5-0cc47ab3cb58',
'messages' => array('test123456'),
'contacts' => array(
array('phone' => '1234567891')
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
I'm trying to convert a curl command to be used in a php script
curl -k -F "request={'timezone':'America/New_York','lang':'en'};type=application/json" -F "voiceData=#d8696c304d09eb1.wav;type=audio/wav" -H "Authorization: Bearer x" -H "ocp-apim-subscription-key:x" "http://example.com"
and here is my php script
<?
$data = array("timezone" => "America/New_York", "lang" => "en", "voiceData" => "d8696c304d09eb1.wav");
$data_string = json_encode($data);
$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer x',
'ocp-apim-subscription-key:x')
);
$result = curl_exec($ch);
?>
I understand that the send audio file bit is not right but i cant find an example how to post it.
I have edited this in response to the post fields but if I include $ch i get no output if don't include the output complains that no post request. Any ideas?
<?
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer x',
'ocp-apim-subscription-key:x')
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
'voicedata' => new CURLFile("d8696c304d09eb1.wav")
)
);
$result = curl_exec($ch);
echo $result;
?>
You're missing the request= in your POST fields. Also, sending files using #filename is deprecated, you should use the CURLFile class.
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
'voicedata' => new CURLFile("d8696c304d09eb1.wav")
)
);
I need to send an XML as soap request using CURL. I have created xml using
$xml = "<?xml .............." blah blah
That looks like
<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><extLoginData xmlns='http://www.JOI.com/schemas/ViaSub.WMS/'><ThreePLKey>4dfdf34</ThreePLKey><Login>abv</Login><Password>abc</Password><FacilityID>1ee</FacilityID><CustomerID>xfs</CustomerID></extLoginData><orders xmlns='http://www.JOI.com/schemas/ViaSub.WMS/'><Order><TransInfo><ReferenceNum>Test</ReferenceNum><PONum>12345</PONum></TransInfo><ShipTo><Name></Name><CompanyName>Peter's Test</CompanyName><Address><Address1>7301 Lennox Ave Unit E3</Address1><Address2></Address2><City>Los Angeles</City><State>CA</State><Zip>90010</Zip><Country>US</Country></Address><PhoneNumber1>858-449-8022</PhoneNumber1><EmailAddress1>lshaules#mercatismedia.com</EmailAddress1><CustomerName>Elizabeth Shaules</CustomerName></ShipTo><ShippingInstructions><Carrier>USPS</Carrier><Mode>First Class Mail</Mode><BillingCode>Prepaid</BillingCode></ShippingInstructions><OrderLineItems><OrderLineItem><SKU>947</SKU><Qualifier>XXX</Qualifier><Qty>1</Qty></OrderLineItem></OrderLineItems></Order></orders></soap:Body></soap:Envelope>
And I am using following code to send CURL request
$url = 'http://someurl.com/Contracts.asmx';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 120);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'SOAPAction:"http://www.example.com/ViaSub.WMS/CreateOrders"',
'Content-Type: text/xml; charset=utf-8',
));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $orderXml);
$result = curl_exec($curl);
But I am getting
soap:ServerServer was unable to process request. ---> Sequence contains no elements
I have searched but haven't found any thing related to it. Can you please let me know what I am doing wrong and how I do it?
This looks like a schema validation error. You don't provide a link to the definition, but a quick search showed me this documentation page. If this is the one you need take a look at the WSDL: https://secure-wms.com/webserviceexternal/contracts.asmx?WSDL
Look for instance the element PalletCount within Order. You see it has minOccurs="1", meaning it's mandatory. But in the xml string you copy there's no such element. That's indeed a sequence with missing elements. (There may be some other schema inconsistencies, have a close look).
Also, consider using the SoapClient PHP class
$WSDL = 'https://secure-wms.com/webserviceexternal/contracts.asmx?WSDL';
$options = [
'trace' => true,
'cache' => WSDL_CACHE_NONE,
'exceptions' => true
];
$client = new SoapClient($WSDL, $options);
$payload = [
'extLoginData' => [
'ThreePLKey' => '4dfdf34',
'Login' => 'abv',
'Password' => 'abc',
'FacilityID' => '1ee',
'CustomerID' => 'xfs'
],
'orders' => [
'Order' => [
// etc...
]
]
]);
$response = $client->CreateOrders($payload);
This way the client handles the schema validation, headers setting (you can set additional headers, though), the namespacing, and the array to xml conversion.
Use this
$xml = "<?xml ..............</soap:Envelope>";
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://www.example.com/ViaSub.WMS/CreateOrders",
"Content-length: ".strlen($xml),
); //SOAPAction: your op URL
$url = 'http://someurl.com/Contracts.asmx';
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);