how to register whatsapp webhooks in nodejs

Viewed 157

I'm trying to integrate whatsapp account with bot framework bot but I faced a problem in integrating

my code is:

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);
    }
});

Ok The problem is I can't verify the whatsapp webhook see the image

2 Answers

You can't connect to the api from your localhost. Whatsapp Api requires a https connection with a certificate. Host your server on heroku/glitch,etc.

You missed the POST request for webhook, there you can get the body of the notification after varification from GET the request,

// 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);
  }
});

Follow the WhatsApp Sample app endpoints for more detailed explanation.

Related