DEV Community

GreggHume
GreggHume

Posted on

16

Whatsapp Webhook Setup and Nodejs Code Example

Solution

If you are getting a validation error the problem is not with ngrok, localtunnel or whatever proxy you are using, its with your webhook code.

Your webhook needs to be a POST and a GET because meta dashboard does a GET for url validation but when the webhook is fired they do POSTs.

Here is the webhook code:

  // this is a GET and POST endpoint
  async whatsapp(ctx) {
    const token = "secret"; // same secret you type in the secret input in the whatsapp dashboard

    // these params are sent when you do the 
    // callback url validation in the dashboard
    const mode = ctx.request.query['hub.mode'];
    const challenge = ctx.request.query['hub.challenge'];
    const verify_token = ctx.request.query['hub.verify_token'];

    // confirms with whatsapp webhook/callback url is good (only happens once)
    if (mode === "subscribe" && verify_token === token) {
     return ctx.send(challenge, 200);
    }

    // handle webhook post data (type taken from attached repo in article, see below)
    const body = ctx.request.body as WebhookObject;

    // do some stuff here

    // then reply to whatsapp with status 200 otherwise it will
    // repeatedly send the webhook for same messages
    ctx.send(200)
  }
Enter fullscreen mode Exit fullscreen mode

Types

If you want the types for what is returned from the webhook then copy and paste them from this repo, the author did a great job at typing, although it is a little outdated:
https://github.com/WhatsApp/WhatsApp-Nodejs-SDK/blob/main/src/types/webhooks.ts

Error (you may have encountered)

"The callback URL or verify token couldn't be validated. Please verify the provided information or try again later."

whatsapp webhook error

Once you have your code correct and your webhook endpoint is set to GET and POST, then your webhook will verify.

Fun tip (vscode built in proxy)

In vscode there is a tab in your terminal/console that says 'ports', you click on there and then you click on add port and type in your server port, it creates a tunnel/proxy for you the same as ngrok or localtunnel would:
vscode built in proxy tunnel 'ports'

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay