Verify WhatsApp webhooks

Meta signs each POST with an HMAC-SHA256 of the raw body, keyed with your app secret, and sends it as X-Hub-Signature-256: sha256=<hex>, so you can confirm a delivery came from Meta and wasn't changed. Before any POST arrives, your endpoint has to pass a GET handshake: compare hub.verify_token with the string you chose, then return a 200 with the hub.challenge value. The verify token and the app secret are separate values, and only the app secret signs anything.

The facts

Signature header
X-Hub-Signature-256

Format: sha256=<hex>

Scheme
HMAC-SHA256
Signed material
{raw body}

The POST body exactly as sent, with no timestamp or other data added.

URL handshake
GET: echo the challenge

HTTP 200 with the hub.challenge value, after comparing hub.verify_token with the string stored on your server. Anything else leaves the endpoint unverified and no webhooks are sent.

What to build
Recompute a digest over the raw body and compare
Key
shared secret

WhatsApp webhook secret

Meta signs with your app secret, a shared secret that belongs to your Meta app. The verify token is a separate string you choose, used only in the GET handshake. Keep it in an environment variable, not in source code.

  • In the App Dashboard: open your app's Basic settings page, where Meta shows the app secret it assigned to the app.
  • One per Meta app. With several apps subscribed, each verifies with its own secret.
  • Not the verify token: hub.verify_token only proves the GET handshake, and it never signs anything.
  • Rotation: reset a compromised secret in Basic settings. Meta says it cannot be rotated programmatically, and it can reset a leaked secret itself.
  • Meta's webhook docs describe no test and live split for the secret.

Source: WhatsApp docs ↗

Code

express/src/index.js
javascript
// Generated with: whatsapp-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify a WhatsApp (Meta) webhook signature.
 *
 * Meta signs the raw request body with HMAC-SHA256 keyed on your app secret and
 * sends the lowercase hex digest in `X-Hub-Signature-256` as `sha256=<hex>`.
 *
 * @param {Buffer} rawBody - Raw request body (must NOT be parsed/re-serialized)
 * @param {string} signatureHeader - X-Hub-Signature-256 header value
 * @param {string} appSecret - Meta app secret
 * @returns {boolean} Whether the signature is valid
 */
function verifyWhatsAppSignature(rawBody, signatureHeader, appSecret) {
  const [algo, sig] = (signatureHeader || '').split('=');
  if (algo !== 'sha256' || !sig) {
    return false;
  }

  const expected = crypto
    .createHmac('sha256', appSecret)
    .update(rawBody)
    .digest('hex');

  // Timing-safe comparison; returns false on length mismatch instead of throwing.
  try {
    return crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'));
  } catch {
    return false;
  }
}

/**
 * Dispatch a verified WhatsApp payload.
 *
 * Events are wrapped as { object, entry: [{ id, changes: [{ value, field }] }] }.
 * The `field` names the subscription; inbound messages arrive in value.messages[]
 * and outbound status updates in value.statuses[], both under the `messages` field.
 */
function handleWhatsAppEvent(payload) {
  for (const entry of payload.entry || []) {
    for (const change of entry.changes || []) {
      const { field, value } = change;

      if (field === 'messages') {
        for (const message of value.messages || []) {
          // Inbound message from a user.
          console.log(`Message ${message.id} from ${message.from} (${message.type})`);
          switch (message.type) {
            case 'text':
              console.log(`  Text: ${message.text.body}`);
              // Your code: reply, route to an agent, etc.
              break;
            case 'image':
            case 'audio':
            case 'video':
            case 'document':
            case 'sticker':
              console.log(`  Media id: ${message[message.type].id}`);
              // Your code: download media via the Cloud API using the media id.
              break;
            case 'interactive':
              console.log(`  Interactive reply:`, message.interactive);
              break;
            case 'button':
              console.log(`  Button: ${message.button.text}`);
              break;
            case 'reaction':
              console.log(`  Reaction: ${message.reaction.emoji}`);
              break;
            case 'location':
              console.log(`  Location:`, message.location);
              break;
            default:
              console.log(`  Unhandled message type: ${message.type}`);
          }
        }

        for (const status of value.statuses || []) {
          // Delivery receipt for a message you sent: sent | delivered | read | failed.
          console.log(`Status ${status.id}: ${status.status} -> ${status.recipient_id}`);
          if (status.status === 'failed') {
            console.error('  Delivery failed:', status.errors);
          }
          // Your code: update your message record's delivery state.
        }
        continue;
      }

      // Other subscription fields (templates, account, phone number quality, etc.)
      switch (field) {
        case 'message_template_status_update':
          console.log('Template status update:', value.event);
          break;
        case 'account_update':
          console.log('Account update:', value.event);
          break;
        case 'phone_number_quality_update':
          console.log('Phone number quality update:', value.event);
          break;
        default:
          console.log(`Unhandled field: ${field}`);
      }
    }
  }
}

// GET — Meta verification handshake. Echo hub.challenge when the verify token matches.
app.get('/webhooks/whatsapp', (req, res) => {
  const mode = req.query['hub.mode'];
  const token = req.query['hub.verify_token'];
  const challenge = req.query['hub.challenge'];

  if (mode === 'subscribe' && token === process.env.WHATSAPP_VERIFY_TOKEN) {
    // Respond 200 with the raw challenge value (plain text, no JSON).
    return res.status(200).send(challenge);
  }
  return res.sendStatus(403);
});

// POST — event delivery. Must use the raw body for signature verification.
app.post('/webhooks/whatsapp',
  express.raw({ type: '*/*' }),
  (req, res) => {
    const signature = req.headers['x-hub-signature-256'];

    if (!verifyWhatsAppSignature(req.body, signature, process.env.WHATSAPP_APP_SECRET)) {
      console.error('WhatsApp signature verification failed');
      return res.status(401).send('Invalid signature');
    }

    const payload = JSON.parse(req.body.toString('utf8'));

    if (payload.object !== 'whatsapp_business_account') {
      // Acknowledge unknown objects so Meta doesn't retry.
      return res.status(200).send('IGNORED');
    }

    handleWhatsAppEvent(payload);

    // Acknowledge quickly; do heavy work asynchronously.
    res.status(200).send('EVENT_RECEIVED');
  }
);

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = { app, verifyWhatsAppSignature, handleWhatsAppEvent };

// Start server only when run directly (not when imported for testing)
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/whatsapp`);
  });
}
nextjs/app/webhooks/whatsapp/route.ts
typescript
// Generated with: whatsapp-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

/**
 * Verify a WhatsApp (Meta) webhook signature.
 *
 * Meta signs the raw request body with HMAC-SHA256 keyed on your app secret and
 * sends the lowercase hex digest in `X-Hub-Signature-256` as `sha256=<hex>`.
 */
function verifyWhatsAppSignature(
  rawBody: string,
  signatureHeader: string | null,
  appSecret: string
): boolean {
  const [algo, sig] = (signatureHeader || '').split('=');
  if (algo !== 'sha256' || !sig) {
    return false;
  }

  const expected = crypto.createHmac('sha256', appSecret).update(rawBody).digest('hex');

  // Timing-safe comparison; returns false on length mismatch instead of throwing.
  try {
    return crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'));
  } catch {
    return false;
  }
}

/**
 * Dispatch a verified WhatsApp payload.
 *
 * Inbound messages arrive in value.messages[] and outbound status updates in
 * value.statuses[], both under the `messages` field.
 */
function handleWhatsAppEvent(payload: any): void {
  for (const entry of payload.entry || []) {
    for (const change of entry.changes || []) {
      const { field, value } = change;

      if (field === 'messages') {
        for (const message of value.messages || []) {
          console.log(`Message ${message.id} from ${message.from} (${message.type})`);
          switch (message.type) {
            case 'text':
              console.log(`  Text: ${message.text.body}`);
              // Your code: reply, route to an agent, etc.
              break;
            case 'image':
            case 'audio':
            case 'video':
            case 'document':
            case 'sticker':
              console.log(`  Media id: ${message[message.type].id}`);
              // Your code: download media via the Cloud API using the media id.
              break;
            case 'interactive':
              console.log('  Interactive reply:', message.interactive);
              break;
            case 'button':
              console.log(`  Button: ${message.button.text}`);
              break;
            case 'reaction':
              console.log(`  Reaction: ${message.reaction.emoji}`);
              break;
            case 'location':
              console.log('  Location:', message.location);
              break;
            default:
              console.log(`  Unhandled message type: ${message.type}`);
          }
        }

        for (const status of value.statuses || []) {
          console.log(`Status ${status.id}: ${status.status} -> ${status.recipient_id}`);
          if (status.status === 'failed') {
            console.error('  Delivery failed:', status.errors);
          }
          // Your code: update your message record's delivery state.
        }
        continue;
      }

      switch (field) {
        case 'message_template_status_update':
          console.log('Template status update:', value.event);
          break;
        case 'account_update':
          console.log('Account update:', value.event);
          break;
        case 'phone_number_quality_update':
          console.log('Phone number quality update:', value.event);
          break;
        default:
          console.log(`Unhandled field: ${field}`);
      }
    }
  }
}

/**
 * GET — Meta verification handshake.
 * Echo hub.challenge as plain text when the verify token matches.
 */
export async function GET(request: NextRequest) {
  const params = request.nextUrl.searchParams;
  const mode = params.get('hub.mode');
  const token = params.get('hub.verify_token');
  const challenge = params.get('hub.challenge');

  if (mode === 'subscribe' && token === process.env.WHATSAPP_VERIFY_TOKEN) {
    return new NextResponse(challenge, { status: 200 });
  }
  return new NextResponse('Forbidden', { status: 403 });
}

/**
 * POST — event delivery. Verify the signature over the raw body, then dispatch.
 */
export async function POST(request: NextRequest) {
  // Read the raw body FIRST — do not parse before verifying (Meta escapes unicode).
  const rawBody = await request.text();
  const signature = request.headers.get('x-hub-signature-256');

  if (!verifyWhatsAppSignature(rawBody, signature, process.env.WHATSAPP_APP_SECRET!)) {
    console.error('WhatsApp signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
  }

  const payload = JSON.parse(rawBody);

  if (payload.object !== 'whatsapp_business_account') {
    return NextResponse.json({ received: true, ignored: true });
  }

  handleWhatsAppEvent(payload);

  // Acknowledge quickly; do heavy work asynchronously.
  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: whatsapp-webhooks skill
# https://github.com/hookdeck/webhook-skills
import os
import hmac
import hashlib
import json

from dotenv import load_dotenv
from fastapi import FastAPI, Request, Response, HTTPException

load_dotenv()

app = FastAPI()

APP_SECRET = os.environ.get("WHATSAPP_APP_SECRET", "")
VERIFY_TOKEN = os.environ.get("WHATSAPP_VERIFY_TOKEN", "")


def verify_whatsapp_signature(raw_body: bytes, signature_header: str, app_secret: str) -> bool:
    """Verify a WhatsApp (Meta) X-Hub-Signature-256 signature.

    Meta signs the raw request body with HMAC-SHA256 keyed on your app secret and
    sends the lowercase hex digest as ``sha256=<hex>``.
    """
    algo, _, sig = (signature_header or "").partition("=")
    if algo != "sha256" or not sig:
        return False

    expected = hmac.new(app_secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
    # Timing-safe comparison.
    return hmac.compare_digest(sig, expected)


def handle_whatsapp_event(payload: dict) -> None:
    """Dispatch a verified WhatsApp payload.

    Inbound messages arrive in value["messages"] and outbound status updates in
    value["statuses"], both under the ``messages`` field.
    """
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            field = change.get("field")
            value = change.get("value", {})

            if field == "messages":
                for message in value.get("messages", []):
                    msg_type = message.get("type")
                    print(f"Message {message.get('id')} from {message.get('from')} ({msg_type})")
                    if msg_type == "text":
                        print(f"  Text: {message['text']['body']}")
                        # Your code: reply, route to an agent, etc.
                    elif msg_type in ("image", "audio", "video", "document", "sticker"):
                        print(f"  Media id: {message[msg_type]['id']}")
                        # Your code: download media via the Cloud API using the media id.
                    elif msg_type == "interactive":
                        print(f"  Interactive reply: {message['interactive']}")
                    elif msg_type == "button":
                        print(f"  Button: {message['button']['text']}")
                    elif msg_type == "reaction":
                        print(f"  Reaction: {message['reaction']['emoji']}")
                    elif msg_type == "location":
                        print(f"  Location: {message['location']}")
                    else:
                        print(f"  Unhandled message type: {msg_type}")

                for status in value.get("statuses", []):
                    print(
                        f"Status {status.get('id')}: {status.get('status')} "
                        f"-> {status.get('recipient_id')}"
                    )
                    if status.get("status") == "failed":
                        print(f"  Delivery failed: {status.get('errors')}")
                    # Your code: update your message record's delivery state.
                continue

            # Other subscription fields (templates, account, phone number quality, etc.)
            if field == "message_template_status_update":
                print(f"Template status update: {value.get('event')}")
            elif field == "account_update":
                print(f"Account update: {value.get('event')}")
            elif field == "phone_number_quality_update":
                print(f"Phone number quality update: {value.get('event')}")
            else:
                print(f"Unhandled field: {field}")


@app.get("/webhooks/whatsapp")
async def verify_webhook(request: Request):
    """Meta verification handshake. Echo hub.challenge when the verify token matches."""
    params = request.query_params
    mode = params.get("hub.mode")
    token = params.get("hub.verify_token")
    challenge = params.get("hub.challenge")

    if mode == "subscribe" and token == VERIFY_TOKEN:
        # Respond 200 with the raw challenge value (plain text, no JSON).
        return Response(content=challenge, media_type="text/plain")
    raise HTTPException(status_code=403, detail="Verification failed")


@app.post("/webhooks/whatsapp")
async def whatsapp_webhook(request: Request):
    # Read the raw body FIRST — do not parse before verifying (Meta escapes unicode).
    raw_body = await request.body()
    signature_header = request.headers.get("x-hub-signature-256")

    if not verify_whatsapp_signature(raw_body, signature_header, APP_SECRET):
        raise HTTPException(status_code=401, detail="Invalid signature")

    payload = json.loads(raw_body)

    if payload.get("object") != "whatsapp_business_account":
        return {"received": True, "ignored": True}

    handle_whatsapp_event(payload)

    # Acknowledge quickly; do heavy work asynchronously.
    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

From hookdeck/webhook-skills ↗

Or install the WhatsApp webhooks skill:

npx skills add hookdeck/webhook-skills --skill whatsapp-webhooks

Common failures

Body changed before verification

Hash the bytes as received. Meta's Messenger docs, for the same header, say the signature covers an escaped Unicode form of the payload, so re-serializing parsed JSON gives a different result for non-ASCII text.

Verify token used as the key

The verify token only answers the GET handshake. The POST signature is keyed with your app secret.

Another app's secret

Use the secret of the Meta app this endpoint belongs to. A secret that was reset, by you or by Meta after a leak, stops matching until you update it.

Prefix left on the header

The header value starts with sha256=. Compare your hex digest with everything after it.

From Hookdeck's WhatsApp guide

Queue WhatsApp deliveries before they reach your handler.

Event Gateway accepts each WhatsApp delivery, queues it and retries failures on your schedule, with a log of every attempt.

Not affiliated with WhatsApp. Facts are compiled from public sources and linked inline.