使用WhatsApp Cloud API发送带变量模板消息报错求助
解决WhatsApp Cloud API模板消息错误:(#100) Param template['components'][0] must be a JSON object.
问题根源
你遇到的错误有两个核心原因:
components格式错误:API要求components是对象数组,但你的代码里直接将其定义为单个对象,导致API无法识别components[0](因为它不是数组的第一个元素)。JSON_FORCE_OBJECT破坏数组结构:这个选项会把所有PHP数组强制转为带数字键的JSON对象,而API要求parameters是纯数组,不是带索引的对象。
修正后的代码
$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改为对象数组 "components" => array( array( "type" => "body", "parameters" => array($var1, $var2, $var3, $var4) ) ) ), ]; // 移除JSON_FORCE_OBJECT,保留默认的数组转JSON数组行为 $whatsappData = json_encode($data); $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);
修正后的JSON输出示例
修正后$whatsappData会变成符合API要求的格式:
{"messaging_product":"whatsapp","to":"+447719303165","type":"template","template":{"name":"brufton_meeting","language":{"code":"en_GB"},"components":[{"type":"body","parameters":[{"type":"text","text":"Andrew Broughton"},{"type":"text","text":"Monday 1st May 2023"},{"type":"text","text":"11:30"},{"type":"text","text":"https:\/\/zoom.us\/j\/7797022566"}]}]}}
可以看到:
components变成了数组,包含一个body对象(对应components[0])parameters是纯数组,没有数字键,完全匹配API对参数数组的要求
内容的提问来源于stack exchange,提问作者Andrew Broughton
相关产品推荐
相关产品推荐

