如何在Node.js中通过WhatsApp API获取并列出收到的消息?
WhatsApp API 接收并列出消息的解决方案
一、实时接收消息的核心端点就是你已有的 /webhook POST 接口
WhatsApp Cloud API 没有专门的「拉取消息」API 端点,所有用户发送的消息都是通过你配置的 Webhook 地址(也就是你的/webhook POST 接口)主动推送过来的。你当前的代码已经在正确处理这个逻辑:当用户发消息给你的 WhatsApp 号码时,Meta 会把消息数据以 POST 请求的形式发送到这个端点,你也已经实现了基础的消息解析(提取发送者、消息内容)和自动回复。
二、如何「列出」收到的消息?
如果你需要保存并查看历史消息,只需要在接收消息的逻辑里添加存储步骤即可。以下是具体修改方案:
1. 添加消息存储与查询逻辑
在你的 app.js 中修改代码,增加消息存储和查询接口:
// 顶部定义数组临时存储消息(仅测试用,Glitch重启会丢失,建议用数据库持久化) let receivedMessages = []; // 原有的/webhook POST接口修改 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; let msgTimestamp = req.body.entry[0].changes[0].value.messages[0].timestamp; // 将消息存入数组 receivedMessages.push({ senderPhone: from, content: msg_body, sendTime: new Date(parseInt(msgTimestamp) * 1000), botPhoneId: phone_number_id }); // 原自动回复逻辑不变 axios({ method: "POST", url: "https://graph.facebook.com/v12.0/" + phone_number_id + "/messages?access_token=" + token, data: { messaging_product: "whatsapp", to: from, text: { body: "Ack: " + msg_body }, }, headers: { "Content-Type": "application/json" }, }); } res.sendStatus(200); } else { res.sendStatus(404); } }); // 新增GET接口,用于列出所有收到的消息 app.get("/messages", (req, res) => { res.json({ totalCount: receivedMessages.length, messages: receivedMessages }); });
2. 持久化存储建议
上面用数组存储的方式仅适合测试,Glitch 项目重启后数据会丢失。如果需要长期保存消息,建议使用 Glitch 支持的数据库(如 MongoDB、PostgreSQL)替代数组。
三、关键补充
WhatsApp Cloud API 不支持主动拉取历史消息,所有消息只能通过 Webhook 实时接收并存储。如果需要回溯更早的消息,只能依赖你之前存储的记录。
四、代码小优化
你代码中的 Webhook 验证部分硬编码了"xxxx",建议改成使用环境变量,更安全也符合规范:
if (mode === "subscribe" && token === verify_token) { console.log("WEBHOOK_VERIFIED"); res.status(200).send(challenge); }
内容的提问来源于stack exchange,提问作者E. Biagi
相关产品推荐
相关产品推荐

