BotNetwork

WhatsApp Cloud API webhooks: verify token, signatures and retries

Every incoming WhatsApp message and every delivery receipt reaches your bot as an HTTPS POST from Meta. Getting that endpoint right means three things: pass the one-time verification, reject anything Meta did not sign, and process each event once even though Meta may deliver it many times.

Published 9 min read

What this post covers

Our first-message tutorial ends with a short webhook sketch. This post goes deeper into the receiving side of the WhatsApp Cloud API: what Meta sends, what it expects back, how retries work and which mistakes let forged or duplicated events into your bot. Everything below is based on Meta's official documentation at the time of writing; Meta reorganizes these pages often, so check the sources at the end before you ship.

What Meta expects from your endpoint

According to Meta's "Create a webhook endpoint" page, your server must:

  • Use HTTPS with a valid certificate. Self-signed certificates are not supported.
  • Accept GET and POST on the same callback URL. GET is for verification; POST carries the events.
  • Validate both kinds of request and respond with HTTP 200 only when they are valid.

You set the callback URL and a verify token in the App Dashboard under WhatsApp > Configuration (or Use cases > Customize > Configuration if you created the app with the "Connect with customers through WhatsApp" use case). A stable domain is much easier to manage than a tunnel URL that changes every restart. You can register one with Namecheap domains and point a subdomain such as wa.example.com at your server; our guide to a custom domain and HTTPS for your bot covers DNS records and certificates.

Step 1: the verification request

Whenever you set or edit the callback URL or the verify token in the dashboard, Meta sends a GET request like this:

GET https://wa.example.com/webhook?hub.mode=subscribe&hub.challenge=1158201444&hub.verify_token=YOUR_VERIFY_TOKEN
  • hub.mode is always subscribe.
  • hub.challenge is a value generated by Meta that you must echo back.
  • hub.verify_token is the string you typed into the Verify token field.

If the token matches the one stored on your server, respond with status 200 and the raw hub.challenge value as the body. Otherwise respond with a 400-level status. Meta only considers the endpoint verified, and only starts sending webhooks, when it gets a 200 with the challenge.

Two practical notes:

  • The verify token is a string you choose, not the app secret and not your access token. Generate a long random value and keep it in an environment variable.
  • Some frameworks rename query parameters. Meta's Graph API docs point out that PHP converts the periods in hub.mode into underscores, so read hub_mode there.

Step 2: validate X-Hub-Signature-256 on every POST

Each event notification arrives as a POST with a JSON body and a header like this:

X-Hub-Signature-256: sha256=b63bb356dff0f1c24379efea2d6ef0b2e2040853339d1bcf13f9018790b1f7d2

The value after sha256= is an HMAC-SHA256 of the request body, keyed with your app secret (App Dashboard > App settings > Basic). To validate it, compute the same HMAC over the body and compare. If the values do not match, treat the request as invalid and do not process it.

The rules that matter in practice:

  • Hash the raw bytes. Compute the HMAC over exactly the bytes you received, before any JSON parsing. If you parse and re-serialize the payload, spacing, key order and Unicode escaping can change and a genuine request will fail the check. This bites most often with non-ASCII text such as accents.
  • Compare in constant time. Use hmac.compare_digest in Python or crypto.timingSafeEqual in Node.js instead of ==.
  • Fail closed. A missing header, a header without the sha256= prefix or any mismatch should all return a 4xx and stop processing.
  • Protect the app secret. It signs your webhooks and is also used to create app access tokens. Meta's Basic Settings docs say you should reset it immediately in the dashboard if it is compromised, and that it cannot be rotated programmatically, so plan the reset as a manual step. Our post on securing bot tokens covers storage.

Unlike Slack, Meta's signature has no timestamp, so the HMAC alone does not stop someone from replaying a captured request. The deduplication in step 4 is what makes a replay harmless.

Step 3: answer 200 quickly, then do the work

Respond with HTTP 200 to every valid POST. Meta's docs describe what happens otherwise: if a webhook request gets any status other than 200, or cannot be delivered for another reason, Meta retries immediately and then with decreasing frequency for up to 7 days, after which unacknowledged notifications are dropped.

That has two consequences:

  1. Do not call a language model, a database migration or the Send API before you respond. Put the event on a queue and return. Slow handlers that time out look like failures and trigger retries.
  2. Do not return an error just because your own business logic failed on a valid event. Acknowledge it, record the failure and handle it in your worker, otherwise Meta keeps redelivering an event you already received.

There is no API to fetch historical webhook data, so whatever you acknowledge must be stored by you. Payloads can be up to 3 MB, and Meta may batch up to 1000 updates in one request, although batching is not guaranteed.

Step 4: deduplicate messages and statuses

Meta's WhatsApp docs state plainly that retries can produce duplicate notifications, and that retries are sent to every app subscribed to the account. Your handler must be idempotent. The messages field carries two kinds of payloads inside entry[].changes[].value:

  • messages: incoming messages from users. Each has an id (a wamid... value). Store it and skip any message whose ID you have already processed.
  • statuses: updates for messages you sent, with status set to sent, delivered, read, failed or played (the first play of a voice message). Deduplicate on the pair of message ID and status.

Do not assume every status arrives. The status reference notes that when a message is delivered and read at the same time, the delivered webhook is not sent. Treat read as implying delivered, and never build logic that waits for a specific status before continuing.

Also identify users carefully. Recent payloads include a business-scoped user ID in user_id and from_user_id, and Meta says phone-number fields such as wa_id and from may be omitted for users who have adopted a username. Key your conversation state on the BSUID where it is present. For the general patterns behind this step, see idempotent message handling.

A tested Python endpoint

This FastAPI app implements steps 1 to 4. It was tested with FastAPI's TestClient: a valid challenge, a wrong token, a correctly signed message containing accented text, the same message delivered twice (queued once), a body altered by one byte and a request without a signature.

import asyncio, hashlib, hmac, json, os
from fastapi import FastAPI, Request, Response

APP_SECRET = os.environ["WA_APP_SECRET"].encode()
VERIFY_TOKEN = os.environ["WA_VERIFY_TOKEN"]

app = FastAPI()
queue: asyncio.Queue = asyncio.Queue()
seen: set[str] = set()  # use Redis or a database table in production


@app.get("/webhook")
async def verify(request: Request):
    q = request.query_params
    token = q.get("hub.verify_token", "")
    if q.get("hub.mode") == "subscribe" and hmac.compare_digest(token, VERIFY_TOKEN):
        return Response(q.get("hub.challenge", ""), media_type="text/plain")
    return Response(status_code=403)


def valid_signature(raw: bytes, header: str) -> bool:
    if not header.startswith("sha256="):
        return False
    expected = hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header[len("sha256="):])


@app.post("/webhook")
async def receive(request: Request):
    raw = await request.body()  # raw bytes, before any JSON parsing
    if not valid_signature(raw, request.headers.get("x-hub-signature-256", "")):
        return Response(status_code=401)
    payload = json.loads(raw)
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            if change.get("field") != "messages":
                continue
            value = change.get("value", {})
            for msg in value.get("messages", []):
                key = "msg:" + msg["id"]
                if key not in seen:
                    seen.add(key)
                    await queue.put(("message", value["metadata"]["phone_number_id"], msg))
            for st in value.get("statuses", []):
                key = f"st:{st['id']}:{st['status']}"
                if key not in seen:
                    seen.add(key)
                    await queue.put(("status", value["metadata"]["phone_number_id"], st))
    return Response(status_code=200)

A background worker reads from queue and does the slow part: replying through the Send API, calling a model or writing to your database. The in-memory seen set is only for illustration; it is lost on restart and not shared between instances, so use a table with a unique key or a Redis SET NX with an expiry longer than the seven-day retry window. Keep phone_number_id from metadata with each job so that a bot serving several numbers replies from the right one.

To test signatures locally without Meta, our webhook signature generator computes the HMAC for a body and secret you paste in.

Optional: mTLS and IP allowlists

The signature check is the baseline. Meta also supports mutual TLS for webhooks: once enabled, Meta presents a client certificate signed by a Meta CA, and your server or load balancer verifies it and checks that the common name is client.webhooks.fbclientcerts.com. The Graph API page includes Nginx and AWS ALB examples and the CA file to trust. Note that the CA changed in 2026 (the previous DigiCert-signed certificate expired on April 15, 2026), so download the current file from that page rather than copying an old one.

Meta also explains how to list its webhook IP ranges, but warns that they change periodically and recommends mTLS instead of a hard-coded allowlist.

Where to run it

The endpoint has to be reachable over HTTPS around the clock; a host that sleeps when idle can fail or time out on the first request and trigger retries. Any always-on VPS or container platform behind a reverse proxy works. Meta's Basic Settings page lists a terms of service URL among the fields required to switch an app to Live mode, and you will want a privacy policy page next to it. Namecheap hosting can serve those static pages while the bot itself runs elsewhere. Keeping the domain and that small site together in one Namecheap account keeps renewals in one place.

Troubleshooting

  • The dashboard will not save the callback URL. Your GET handler is not returning 200 with the exact hub.challenge value, the verify token does not match, or the certificate is invalid or self-signed.
  • Every POST fails the signature check. You are hashing parsed JSON instead of the raw body, using the access token instead of the app secret, or a proxy is modifying the body.
  • Verification works but no events arrive. Subscribe to the messages field after verifying, send a test payload from the Configuration panel, and check that the app is in Live mode; Meta notes that some webhooks are not sent in Dev mode.
  • Users get the same reply twice. Your deduplication is missing, in memory only, or happening after the reply instead of before.

Checklist

  • GET handler echoes hub.challenge only when hub.verify_token matches.
  • HMAC-SHA256 computed over the raw body with the app secret, compared in constant time.
  • Missing or invalid signatures rejected with a 4xx.
  • HTTP 200 returned quickly; real work done by a worker.
  • Message IDs and message ID plus status deduplicated in durable storage for longer than seven days.
  • Logic does not depend on receiving every status.
  • Users keyed by BSUID where present.

Sources