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

为何WhatsApp Business PHP API发送的模板消息会被接收两次?

解决WhatsApp Cloud API重复发送消息的问题

问题根源分析

  1. 重复执行curl请求
    代码里连续调用了两次curl_exec($curl):
$response = json_decode(curl_exec($curl), true);
//print_r($response);
$jsonResult = curl_exec($curl) ;

每调用一次curl_exec就会向Meta API发送一次请求,这是导致接收方收到两条重复消息的直接原因。

  1. 请求参数冲突
    $fields数组里重复定义了type字段:
'type' => 'template',
'template' => $template_array,
'type' => 'text',
'text' => $text_arr

PHP数组中重复的键会被最后一次赋值覆盖,最终type会变成text,但你实际要发送的是模板消息,这种参数冲突可能引发接口异常,同时冗余的text参数完全没必要。

修正后的完整代码

$messageBody = 'Welcome and congratulations!! This message demonstrates your ability to send a WhatsApp message notification from the Cloud API, hosted by Meta. Thank you for taking the time to test with us.' ;

$template_array = array(
    "name" => $templateName,
    "language" => array("code" => "en_US"), // 直接传数组,不要用字符串格式
    //"components" => array() // 模板有参数时用数组传入,不要留空字符串
) ;

// 移除冗余的text参数,模板消息只保留template相关配置
$fields = array(
    'messaging_product' => 'whatsapp',
    'recipient_type' => 'individual',
    'to' => 91 . $toMobile,
    'type' => 'template',
    'template' => $template_array
) ;


$headers = array( 
    "Authorization: Bearer " . $accessToken, 
    "Content-Type: application/json"
);

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $postUrl);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields) );
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// 只执行一次curl请求,复用结果做解析和输出
$jsonResult = curl_exec($curl) ;
$resultCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$response = json_decode($jsonResult, true);

echo $resultCode . ' - ' . $jsonResult ;

curl_close($curl);

额外注意事项

  • 确认$templateName是Meta商务平台已审核通过的模板名称
  • language字段必须传数组,不要手动转成字符串,否则JSON编码后格式会不符合API要求
  • 发送模板消息时,不要混入text类型的参数,避免接口判断逻辑混乱

内容的提问来源于stack exchange,提问作者Pisumathu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:52:47