Got cURL code working on terminal to change the forwarded phone number on an online SIP service (don't have access to the REST API server-side):
curl --request PUT --header "Accept: application/json" --header "Authorization: Basic abcdefABCDEFmysecretkey123456" -d '{"forwardings":[{"destination":"+447979123456","timeout":0,"active":true}]}' --header "Content-type: application/json" https://api.sipgate.com/v2/w0/phonelines/p0/forwardings
However my efforts to replicate this code in PHP are resulting in an {"error":"cannot parse content"} response:
$ch = curl_init();
$churl='https://api.sipgate.com/v2/w0/phonelines/p0/forwardings';
$chdata = array(
'forwardings' => array(
'destination' => '+447979123456',
'timeout' => 0,
'active' => true
)
);
$chdata2 = http_build_query($chdata);
curl_setopt($ch, CURLOPT_URL, $churl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-type: application/json",
"charset: utf-8",
"Accept: application/json",
"Authorization: Basic abcdefABCDEFmysecretkey123456"
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $chdata2);
$json = curl_exec($ch);
echo $json;
curl_close($ch);
What am I missing?
http_build_queryencodes the data asapplication/x-www-form-urlencoded. The data in your CLI cURL statement is JSON however, and that is even what you made theContent-Typeheader say.json_encodedoes not properly handle nested arrays? When I changehttp_build_array($chdata)tojson_encode($chdata)(which I actually tried first), the server response changes tocom.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token- this is what made me pivot towards http_build_query'forwardings' => array(...)needs to be'forwardings' => array( array(...) ).