3

Tengo una aplicación que se conectará a una API externa. En el manual de la API, json se ve así:

{
  "from": "5510999999999",
  "to": "55108888888888",
  "contents": [
    {
      "type": "text",
      "text": "Hi Zenvia!"
    }
  ]
}

Mi PHP se ve así:

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);  
    }

}

Pero cuando ejecuto la aplicación, devuelve el siguiente 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"}

No tengo mucha experiencia con PHP / Json. ¿Cómo puedo corregir eso?

Perdón por mi español.

0

1 respuesta 1

3

El mensaje de error dice exactamente cual es el problema:

"contents Expected an array. Received: [object Object]"

Solución:

Necesitas que contents sea un arreglo con un objeto dentro (en PHP un arreglo asociativo):

$body = [
    "from" => $from,
    "to" => $to,
    "contents" => [ // El arreglo
        ["type" => "text", "text" => $msg], // Luego los datos
    ]
];

Referencias:

1
  • Funcionó. Muchas gracias Marcos.
    – JM_2021
    el 5 mar. 2021 a las 15:42

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.