0

Cannot send message to my whatsApp using PHP

error:

{"error":{"message":"(#100) Param template must be a JSON object.","type":"OAuthException","code":100,"fbtrace_id":"AjrrMHcEN9C2jkiL8MNy_Rz"}}
<?php
$url = "https://graph.facebook.com/v15.0/{API KEY}/messages";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization:{auth key}', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$data = [
  "messaging_product"=>"whatsapp",
  "to"=>"my number",
  "type"=>"template",
  "template"=> "{
    name:sample_issue_resolution,
    language: {code:en_US }, 
    components:{
      type:body,
      parameters {
        type:text,
        text:Mr Jibran
      }}}"
]
;

$fields_string = json_encode($data);
//echo $fields_string;
//echo $fields_string;
echo "<br/>";
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);

$resp = curl_exec($curl);
curl_close($curl);

echo $resp;
?>
Sammitch
  • 30,782
  • 7
  • 50
  • 77

1 Answers1

2

The way you're defining the payload is incorrect, it must be a single JSON document, not nested JSON text.

$data = [
    "messaging_product"=>"whatsapp",
    "to"=>"my number",
    "type"=>"template",
    "template"=> [
        "name" => "sample_issue_resolution",
        "language" => [ "code" => "en_US" ], 
        "components" => [
            "type" => "body",
            "parameters" => [
                [
                    "type" => "text",
                    "text" => "Mr Jibran"
                ]
            ]
        ]
    ]
];

With the additional correction that templates.components.parameters is an array of objects, not an object.

https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#template-object

If you ever find yourself putting a JSON document inside of another JSON document that is a big red flag that something is wrong.

Sammitch
  • 30,782
  • 7
  • 50
  • 77