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

使用WhatsApp API发送自定义消息无报错但未送达问题求助

WhatsApp API自定义消息发送失败排查

我用以下PHP代码调用WhatsApp API发送自定义文本消息,代码无报错,API返回了包含消息ID的成功响应,但实际消息并未发送到目标号码;使用模板消息则可以正常发送。

API返回结果:

Array ( 
    [messaging_product] => whatsapp 
    [contacts] => Array ( 
        [0] => Array ( 
            [input] => 44596565965
            [wa_id] => 44596565965 
        ) 
    ) 
    [messages] => Array ( 
        [0] => Array ( 
            [id] => wamid.HBgLMzQ2MzI4Njc4NTgVAgARGBI1MUNBQUVGOTM3NkE1MjZFREIA 
        ) 
    ) 
)

我的代码:

$token='654464645321813vbnj3hj5g3jg1j5g3j131j3ghj1';
$telefono = '44596565965';
$url = 'https://graph.facebook.com/v16.0/109571185362363/messages';


$mensaje=''
.'{'
.'"messaging_product": "whatsapp",' 
.'"recipient-type": "individual",'

.'"to": "'.$telefono.'",' 

.'"type":"text",'

.'"text": '
.'{'
.'"preview_url": "false",'
.'"body": ""hello this is Test"'
.'}' 

.'}';

$header = array("Authorization: Bearer " . $token, "Content-Type: application/json",);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $mensaje);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($curl), true);
print_r($response);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
?>

问题根源

  • JSON格式错误:手动拼接的JSON中,body字段值多了一对双引号,写成了""hello this is Test",正确格式应为"hello this is Test",多余引号会导致JSON解析异常,虽API返回成功响应,但消息内容无效无法送达。
  • 字段名不规范:recipient-type不符合官方API要求,正确字段名是recipient_type(下划线分隔,而非横杠)。
  • 手动拼接JSON易出错:直接拼接字符串构造JSON极易出现语法错误,建议用json_encode自动生成合法JSON。

修正后的代码

<?php
$token = '654464645321813vbnj3hj5g3jg1j5g3j131j3ghj1';
$telefono = '44596565965';
$url = 'https://graph.facebook.com/v16.0/109571185362363/messages';

// 用数组构造数据,再转成JSON,避免手动拼接错误
$messageData = [
    'messaging_product' => 'whatsapp',
    'recipient_type' => 'individual',
    'to' => $telefono,
    'type' => 'text',
    'text' => [
        'preview_url' => false,
        'body' => 'hello this is Test'
    ]
];
$mensaje = json_encode($messageData);

$header = [
    "Authorization: Bearer " . $token,
    "Content-Type: application/json"
];

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $mensaje);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($curl), true);
print_r($response);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
?>

说明

  • 使用json_encode能确保生成的JSON完全符合语法规范,避免手动拼接时的引号、逗号等错误。
  • 修正了recipient_type字段名,匹配WhatsApp API参数要求。
  • 将preview_url设为布尔值false,而非字符串类型,更贴合API参数定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:15:07