使用WhatsApp Business Cloud API通过Webhook无法发送响应问题
问题分析与解决方案
你的核心问题是混淆了Webhook响应和WhatsApp消息发送的逻辑:当前代码里的res.status(200).json(...)只是回复Meta的Webhook服务器,告知它你已成功接收事件,这并不是向用户发送WhatsApp消息的操作。要给用户推送消息,必须主动调用WhatsApp Business Cloud API的「发送消息」接口。
修正步骤
1. 准备必要参数
确保你有以下参数(从Meta开发者平台获取):
WHATSAPP_ACCESS_TOKEN:你的WhatsApp应用访问令牌- 最新的WhatsApp API版本端点(比如
v18.0,可根据Meta官方文档调整)
2. 替换原代码的响应逻辑
把原来处理responseData的部分,改成调用WhatsApp发送消息API的请求,同时注意先给Meta的Webhook返回200响应(避免超时)。
修正后的代码示例:
app.post("/webhook", (req, res) => { let body = req.body; console.log(JSON.stringify(req.body, null, 2)); if (req.body.object) { if ( req.body.entry && req.body.entry[0].changes && req.body.entry[0].changes[0] && req.body.entry[0].changes[0].value.messages && req.body.entry[0].changes[0].value.messages[0] ) { let phone_number_id = req.body.entry[0].changes[0].value.metadata.phone_number_id; let from = req.body.entry[0].changes[0].value.messages[0].from; let msg_body = req.body.entry[0].changes[0].value.messages[0].text.body; // 先给Meta Webhook返回200响应,避免超时 res.status(200).send("OK"); // 调用第三方API axios({ method: "POST", url: API_URL, data: { id: phone_number_id, question: msg_body, email: "N/A", conversation: [], save: true, resolved: "N/A", ads: 0, }, headers: { "Content-Type": "application/json", "x-api-key": process.env.API_KEY, }, }) .then(apiResponse => { if (apiResponse.status !== 200) { throw new Error(`Request failed with status ${apiResponse.status}`); } return apiResponse.data; }) .then(responseData => { console.log(responseData); // 调用WhatsApp API发送消息给用户 return axios({ method: "POST", url: `https://graph.facebook.com/v18.0/${phone_number_id}/messages`, headers: { "Content-Type": "application/json", "Authorization": `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}` }, data: { messaging_product: "whatsapp", recipient_type: "individual", to: from, text: { body: responseData.answer } } }); }) .then(whatsappResponse => { console.log("消息发送成功:", whatsappResponse.data); }) .catch(error => { console.error("处理出错:", error); }); } else { // 非消息事件,返回200 res.status(200).send("OK"); } } else { // 无效Webhook请求,返回404 res.sendStatus(404); } });
关键注意事项
- Webhook响应超时:Meta要求Webhook必须在20秒内返回响应,所以必须先调用
res.status(200).send("OK"),再异步处理第三方API和消息发送,避免超时导致Meta重复推送事件。 - 权限验证:确保你的
WHATSAPP_ACCESS_TOKEN拥有whatsapp_business_messaging权限,且phone_number_id已关联到你的WhatsApp Business账号。 - 号码格式:
from参数是用户的国际格式号码(带+号),直接使用即可,无需修改格式。
内容的提问来源于stack exchange,提问作者callan george
相关产品推荐
相关产品推荐

