I have an application that will connect to an external API. In the API manual, json looks like this:
{
"from": "5510999999999",
"to": "55108888888888",
"contents": [
{
"type": "text",
"text": "Hi Zenvia!"
}
]
}
My PHP looks like this:
class zenvia{
public function SMS($telefone,$mensagem)
{
$method = 'POST';
$from = '55219999999999';
$to = '55'.$telefone;
$msg = $mensagem;
$body = [
"from" => $from,
"to" => $to,
"contents" => [
"type" => "text",
"text" => $msg
]
];
$campos = json_encode($body);
$url = 'https://api.zenvia.com/v2/channels/sms/messages';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $campos);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'X-API-TOKEN: xxxxxxxxxxxxxxxxxxxxx'
));
$resposta = curl_exec($ch);
echo $resposta;
if(curl_error($ch))
{
echo curl_error($ch);
return curl_error($ch);
}
else
{
json_decode($resposta);
}
curl_close($ch);
}
}
But when I run the app, it returns the following error:
{"code":"VALIDATION_ERROR","message":"Request has one or more errors\n In body\n For Content-Type application/json\n Unable to deserialize value\n at: allOf\n at: 0 > contents\n Expected an array.Received: [object Object]\n at: 1 > contents\n Expected an array.Received: undefined"}
I don't have much experience with PHP/Json. How can I correct that?
Sorry for my Spanish.
The error message says exactly what the problem is:
Solution:
You need it to
contents
be an array with an object inside ( inPHP
an associative array ):References: