如何在WhatsApp Cloud API中处理用户按钮点击并回复?
实现WhatsApp机器人按钮点击的对应回复
用户点击你设置的交互式按钮后,Facebook的Webhook会推送包含按钮reply.id的消息payload,而非普通文本。你需要先解析这个payload,再根据不同按钮ID发送对应回复,具体实现如下:
1. 封装通用消息发送函数
先封装一个通用函数,避免重复编写Axios请求代码:
const axios = require("axios").default; // 通用发送WhatsApp消息函数 async function sendWhatsAppMessage(phone_id, token, to, messageData) { try { await axios({ method: "post", url: `https://graph.facebook.com/v17.0/${phone_id}/messages?access_token=${token}`, data: { messaging_product: "whatsapp", recipient_type: "individual", to: to, ...messageData }, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("消息发送失败:", error.response?.data || error.message); } }
2. 修改start_bot函数,处理按钮点击逻辑
更新start_bot函数,加入对按钮回复的判断逻辑。注意:用户点击按钮时,Webhook推送的消息会包含interactive字段,需从中提取reply.id(即你设置的vawp、lp、rofc):
function start_bot(webhookPayload, phone_id, token) { // 解析Webhook中的核心数据 const messageEntry = webhookPayload.entry[0].changes[0].value; const from = messageEntry.messages[0].from; const user_name = messageEntry.contacts[0].profile.name; const message = messageEntry.messages[0]; // 处理用户发送"Hi"的场景 if (message.type === "text" && message.text.body === "Hi") { sendWhatsAppMessage(phone_id, token, from, { type: "interactive", interactive: { type: "button", body: { text: `👋 Hello ${user_name}, welcome to Expatman! We are here to help you with your visa, work permit, labor placement, and foreign company representation needs. To get started, please select one of the following service options: 👇`, }, action: { buttons: [ { type: "reply", reply: { id: "vawp", title: "Visas" } }, { type: "reply", reply: { id: "lp", title: "Labour" } }, { type: "reply", reply: { id: "rofc", title: "Representation" } }, ], }, }, }); } // 处理按钮点击的回复场景 else if (message.type === "interactive" && message.interactive.type === "button_reply") { const buttonId = message.interactive.button_reply.id; let replyText = ""; // 根据按钮ID匹配对应回复内容 switch (buttonId) { case "vawp": replyText = "🔹 我们提供各类签证办理服务,包括工作签、旅游签、商务签等。请告知你的国籍和目标国家,我们会为你提供详细办理指南。"; break; case "lp": replyText = "🔹 劳工安置服务涵盖岗位匹配、合同办理、合规指导等。请描述你的技能和期望岗位类型,我们将为你对接合适的雇主资源。"; break; case "rofc": replyText = "🔹 外国公司代表服务包括本地注册、合规咨询、业务对接等。请告知你的公司所属行业和拓展需求,我们会定制专属解决方案。"; break; default: replyText = "⚠️ 抱歉,我暂时无法识别这个选项,请重新选择。"; } // 发送对应文本回复 sendWhatsAppMessage(phone_id, token, from, { type: "text", text: { body: replyText } }); } } module.exports = start_bot;
3. 关键注意事项
- Webhook解析:Facebook推送的payload结构有多层嵌套,需正确提取
messages和contacts中的数据。 - 按钮ID匹配:确保
switch中的ID和你设置的按钮reply.id完全一致,否则无法触发对应回复。 - 异步处理:使用
async/await处理Axios请求,避免因异步请求未完成导致的消息丢失问题。
内容的提问来源于stack exchange,提问作者Intellibots
相关产品推荐
相关产品推荐

