如何在nodejs中注册whatsapp webhooks



我正在尝试将whatsapp帐户与bot框架bot集成,但我在集成

时遇到了问题我的代码是:
const restify = require('restify');
// Create HTTP server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
console.log(`n${ server.name } listening to ${ server.url }`);
});
const token = "verify-token"
// verfiy the web hok
server.get('/webhooks',  (req, res) => {
console.log(req);
if (
req.query['hub.mode'] == 'subscribe' &&
req.query['hub.verify_token'] == token
) {
res.send(req.query['hub.challenge']);
} else {
res.sendStatus(400);
}
});

问题是我无法验证whatsapp的webhook查看图片

您无法从本地主机连接到api。Whatsapp Api需要一个带有证书的https连接。把你的服务器放在heroku/glitch等上

您错过了webhook的POST请求,在那里您可以从get请求更改后获得通知的正文,

// verfiy the web hok
server.get('/webhooks',  (req, res) => {
console.log(req);
if (
req.query['hub.mode'] == 'subscribe' &&
req.query['hub.verify_token'] == token
) {
res.send(req.query['hub.challenge']);
} else {
res.sendStatus(400);
}
});
// Accepts POST requests at /webhook endpoint
app.post("/webhook", (req, res) => {
// Parse the request body from the POST
let body = req.body;
// info on WhatsApp text message payload: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/payload-examples#text-messages
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]
) {
// do your stuff here.....
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; // extract the phone number from the webhook payload
let msg_body = req.body.entry[0].changes[0].value.messages[0].text.body; // extract the message text from the webhook payload
}
res.sendStatus(200);
} else {
// Return a '404 Not Found' if event is not from a WhatsApp API
res.sendStatus(404);
}
});

遵循WhatsApp示例应用程序端点获取更详细的解释。

最新更新