使用PHP集成WhatsApp无法发送消息:template参数需为JSON对象
解决WhatsApp API发送消息时"Param template must be a JSON object"错误
错误信息
{"error":{"message":"(#100) Param template must be a JSON object.","type":"OAuthException","code":100,"fbtrace_id":"AjrrMHcEN9C2jkiL8MNy_Rz"}}
问题原因
原代码中template字段被赋值为字符串,而WhatsApp API要求该参数必须是JSON对象。当json_encode处理这个字符串时,会把它转义成JSON字符串值,而非预期的JSON对象结构,直接导致接口参数校验失败。同时原代码的template字符串还存在语法错误(比如parameters后缺失冒号),且components结构不符合API要求(API要求components是对象数组)。
修正后的代码
<?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); curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string); $resp = curl_exec($curl); curl_close($curl); echo $resp; ?>
关键修改说明
- 将
template字段的字符串值替换为PHP关联数组,让json_encode将其转换为符合要求的JSON对象 - 调整
components为对象数组结构(API要求每个组件是数组中的独立元素) - 补全原字符串中缺失的语法符号,统一数组键值对格式,确保
json_encode生成标准JSON结构
内容的提问来源于stack exchange,提问作者Hafiz Hanif
相关产品推荐
相关产品推荐

