You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:35:19