I'm trying to send a template message in PHP using the WhatsApp Cloud API and I'm struggling with what should be a simple fix but I've been staring at the code for too long and would welcome a second pair of eyes to spot where I'm going wrong.
The error message I keep getting is:
(#100) Param template['components'][0] must be a JSON object.
Looking at the WhatsApp docs for sending a template, I can see that I need to send the components/parameters as an array of objects.
Here's my current code:
$var1 = array('type' => 'text', 'text' => $clientName);
$var2 = array('type' => 'text', 'text' => $data['meetingDate']);
$var3 = array('type' => 'text', 'text' => $data['meetingStart']);
$var4 = array('type' => 'text', 'text' => $data['meetingLocation']);
$data = [
"messaging_product" => "whatsapp",
"to" => $clientNumber,
"type" => "template",
"template" => array(
"name" => "brufton_meeting",
"language" => array(
"code" => "en_GB"
),
"components" => array("type" => "body", "parameters" => array($var1, $var2, $var3, $var4))
),
];
$whatsappData = json_encode($data, JSON_FORCE_OBJECT);
$whatsappHeader = array(
'Authorization: Bearer ' . {TOKEN},
'Content-Type: application/json'
);
$ch = curl_init("https://graph.facebook.com/v21.0/".$_SESSION['whatsappNumberID']."/messages");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $whatsappData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $whatsappHeader);
$resultWhatsApp = curl_exec($ch);
When this is loading, running a print_r on the $whatsappData I get:
{"messaging_product":"whatsapp","to":"+447719303165","type":"template","template":{"name":"brufton_meeting","language":{"code":"en_GB"},"components":{"type":"body","parameters":{"0":{"type":"text","text":"Andrew Broughton"},"1":{"type":"text","text":"Monday 1st May 2023"},"2":{"type":"text","text":"11:30"},"3":{"type":"text","text":"https:\/\/zoom.us\/j\/7797022566"}}}}}
So I can see that the parameters aren't being marked up as an object and being added as a variable, I just can't seem to correct this and been going around in circles for a while now missing the (very likely) obvious solution!
I've tested this using a template with no variables and that works fine. I've double checked the spelling of the template and language too. It's only when using a template with variables that I'm getting stuck so I'm reasonably confident the problem is with this coding rather than an authentication issue.
I solved the issue and turns out that I was right that it was an error with my code.
I needed to double array the components for the json_encode to create the object
"components" => array(array("type" => "body", "parameters" => array($var1, $var2, $var3, $var4)))
I also switched off the "JSON_FORCE_OBJECT" tag and then it all worked as expected