WhatsApp webhook security in FastAPI comes down to four checks: answer Meta's verification request, verify the X-Hub-Signature-256 signature on every POST, remove duplicate deliveries, and acknowledge with a fast 200. Skip any one of them and a forged request can trigger your bot, a retry can send the same reply twice, or a slow handler can trigger days of repeat deliveries.
This guide shows a complete receiver in about 100 lines of Python, the 23 tests I ran against it, and what Meta's documentation says about retries, ordering and duplicates. I checked the Meta documentation pages on 2 December 2026. If you are moving a bot off a no-code flow, read WhatsApp Chatbot: n8n to FastAPI Migration alongside this one.
Key takeaways: FastAPI WhatsApp webhook security
- Verification (GET): compare
hub.verify_tokenwith your stored token using a constant-time compare. If it matches, returnhub.challengewith HTTP 200. Otherwise return a non-200 status. - Authentication (POST): compute HMAC-SHA256 of the raw request body with your app secret and compare it to the hex value after
sha256=inX-Hub-Signature-256. - Deduplicate: Meta can deliver the same update more than once. Use
messages[].idfor messages andstatuses[].idplusstatuses[].statusfor status updates. Keep keys for at least 7 days. - Acknowledge fast: return
200quickly and do the slow work in a background task. A non-200 response counts as a failed delivery and is retried. - Never re-serialize JSON before checking the signature. Hash the exact bytes you received.
How Meta's webhook flow works
Per Meta's documentation for creating a webhook endpoint, there are two kinds of requests.
1. The verification request (GET). When you set or edit the callback URL or verify token in the App Dashboard, Meta sends a GET request with three query parameters: hub.mode=subscribe, hub.challenge and hub.verify_token. Your endpoint compares the token with the one you stored. If it matches, you respond with 200 and echo the hub.challenge value. Webhooks are sent only after the endpoint returns the correct challenge.
2. Event notifications (POST). Each event arrives as a JSON body with a Content-Type: application/json header and an X-Hub-Signature-256: sha256=<hash> header. The hash is an HMAC-SHA256 of the payload using your app secret as the key. If your computed value matches, the payload is valid. Meta expects a 200 for a valid delivery.
Other details from the documentation worth designing for:
- A POST can contain a batch of up to 1,000 updates, but batching cannot be guaranteed, so handle each POST on its own terms.
- Failed deliveries are retried immediately and then a few more times with decreasing frequency over the next 7 days. After that, unacknowledged webhooks are dropped, and there is no API to fetch historical webhook data.
- Self-signed TLS certificates are not supported. mTLS is supported.
Hookdeck's production guide adds practical advice built on the same behavior: retries go to all apps subscribed to the account, Meta does not promise ordering, and it suggests load testing for a median latency of 250 ms or less with fewer than 1 percent of requests above 1 second. Treat those latency numbers as a community guideline, not as a Meta SLA.
WhatsApp webhook security: what goes wrong without each check
| Missing check | What happens |
|---|---|
| No signature verification | Anyone who finds your URL can post fake messages and trigger replies, tool calls or database writes |
Verification token compared with == | A timing difference can leak the token; use a constant-time compare |
| Signature checked on re-serialized JSON | Valid requests are rejected because the bytes differ (shown in the tests below) |
| No deduplication | A retry triggers a second reply or a second order |
| Slow handler | Meta sees a failure and retries, which multiplies the load |
| Returning an error for a signed message you cannot parse | Meta keeps retrying a message that can never succeed, for up to 7 days |
| Treating statuses as ordered | A late delivered overwrites a read |
The full receiver
Environment variables: WA_VERIFY_TOKEN (the string you typed in the dashboard), WA_APP_SECRET (your app secret) and optionally WA_MAX_BODY_BYTES.
import hashlib, hmac, json, logging, os, time
from typing import Callable, Protocol
from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, Request
from fastapi.responses import PlainTextResponse
log = logging.getLogger("wa")
VERIFY_TOKEN = os.environ.get("WA_VERIFY_TOKEN", "")
APP_SECRET = os.environ.get("WA_APP_SECRET", "")
MAX_BODY_BYTES = int(os.environ.get("WA_MAX_BODY_BYTES", 1_048_576)) # my limit, not a Meta number
DEDUPE_TTL_SECONDS = 7 * 24 * 3600 # Meta retries for up to 7 days
class SeenStore(Protocol):
def first_time(self, key: str) -> bool: ...
class MemorySeen:
"""Dev/test store. Use Redis in production so every worker shares it."""
def __init__(self, ttl: int = DEDUPE_TTL_SECONDS, clock: Callable[[], float] = time.time):
self.ttl, self.clock, self.data = ttl, clock, {}
def first_time(self, key: str) -> bool:
now = self.clock()
self.data = {k: t for k, t in self.data.items() if now - t < self.ttl}
if key in self.data:
return False
self.data[key] = now
return True
class RedisSeen:
"""SET key 1 NX EX ttl returns True only for the first caller."""
def __init__(self, client, ttl: int = DEDUPE_TTL_SECONDS, prefix: str = "wa:seen:"):
self.r, self.ttl, self.prefix = client, ttl, prefix
def first_time(self, key: str) -> bool:
return bool(self.r.set(self.prefix + key, 1, nx=True, ex=self.ttl))
def signature_ok(raw_body: bytes, header: str | None, secret: str) -> bool:
if not header or not header.startswith("sha256=") or not secret:
return False
received = header[len("sha256="):].strip().lower()
if len(received) != 64:
return False
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(received, expected)
def extract_events(payload: dict):
"""Yield ('message', dedupe_key, obj) and ('status', dedupe_key, obj)."""
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
for m in value.get("messages", []) or []:
yield "message", m["id"], m
for s in value.get("statuses", []) or []:
yield "status", f'{s["id"]}:{s["status"]}', s
def create_app(seen: SeenStore, handler: Callable[[str, dict], None]) -> FastAPI:
app = FastAPI()
@app.get("/webhook")
def verify(mode: str = Query(None, alias="hub.mode"),
token: str = Query(None, alias="hub.verify_token"),
challenge: str = Query(None, alias="hub.challenge")):
ok = (mode == "subscribe" and VERIFY_TOKEN and token is not None
and hmac.compare_digest(token.encode(), VERIFY_TOKEN.encode()))
if not ok:
raise HTTPException(status_code=403)
return PlainTextResponse(challenge or "")
@app.post("/webhook")
async def receive(request: Request, background: BackgroundTasks):
declared = request.headers.get("content-length")
if declared and declared.isdigit() and int(declared) > MAX_BODY_BYTES:
raise HTTPException(status_code=413)
raw = await request.body()
if len(raw) > MAX_BODY_BYTES:
raise HTTPException(status_code=413)
if not signature_ok(raw, request.headers.get("x-hub-signature-256"), APP_SECRET):
raise HTTPException(status_code=403)
try:
payload = json.loads(raw)
events = list(extract_events(payload))
except (ValueError, KeyError, TypeError):
log.error("signed but unparsable payload, acknowledging to stop retries")
return {"status": "ignored"}
fresh = [(kind, obj) for kind, key, obj in events if seen.first_time(f"{kind}:{key}")]
for kind, obj in fresh:
background.add_task(handler, kind, obj)
return {"status": "ok", "new": len(fresh), "duplicates": len(events) - len(fresh)}
return app
Wire it up with your own handler:
import redis
from wa_webhook import create_app, RedisSeen
def handle(kind: str, obj: dict) -> None:
if kind == "message":
... # call your LLM, queue a reply, write to the database
elif kind == "status":
... # update delivery state
app = create_app(RedisSeen(redis.Redis.from_url("redis://localhost:6379/0")), handle)
Design decisions worth explaining
It reads the raw body once. await request.body() returns the exact bytes. The signature is checked on those bytes before any JSON parsing happens. If you let a framework parse the body into a model first, you can no longer reproduce the original bytes reliably.
It uses hmac.compare_digest twice. Once for the signature, once for the verify token. Python's hmac.compare_digest is designed for constant-time comparison.
Bad signatures get 403, signed garbage gets 200. A bad signature is an attacker or a misconfigured secret, and a retry changes nothing. A correctly signed body that you cannot parse came from Meta, so an error status would only make Meta retry it for days. Log it, store the raw body for inspection, and acknowledge it.
Deduplication happens before queuing. The store call first_time() is atomic in Redis (SET ... NX EX), so two workers receiving the same retry at the same moment still process it once. The in-memory version is only safe for a single process.
The status key includes the status. Meta's guidance is to dedupe statuses on statuses[].id together with statuses[].status, because one outgoing message can produce sent, delivered and read updates under the same id.
The body limit is my choice. I set 1 MiB as a default. Meta documents batches of up to 1,000 updates but I did not find a documented maximum byte size, so measure your real payloads and adjust.
How I tested it
I ran everything below on my machine with FastAPI 0.165, httpx 0.29, pytest 9.1 and fakeredis.
23 tests, all passing. They cover:
- verification with a correct token, a wrong token, a wrong mode and missing parameters
- a valid signature, a tampered body, a wrong secret, a missing header, a wrong prefix (
md5=), a short or non-hex value and uppercase hex - a duplicate message processed once, a batch with one duplicate and one new message, and a status sequence
sent, delivered, read, deliveredprocessed three times - an oversize body returning 413, and a signed non-JSON body returning 200 with
ignored - the Redis store with
fakeredis(first call true, second false, TTL set) and the in-memory store expiring after its TTL
One test is worth showing because it demonstrates the most common bug.
def test_reserialising_json_breaks_signature():
obj = {"entry": [{"changes": [{"value": {"messages": [{"id": "w1", "text": {"body": "नमस्ते 👋"}}]}}]}]}
raw = json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode()
header = sign(raw)
reparsed = json.dumps(json.loads(raw)).encode()
assert w.signature_ok(raw, header, SECRET) is True
assert reparsed != raw
assert w.signature_ok(reparsed, header, SECRET) is False
The same message, parsed and dumped again with Python's defaults, produces different bytes (spacing and Unicode escapes), so a valid signature fails. Hindi and Gujarati text and emoji make this more likely to bite Indian deployments, because non-ASCII characters are exactly what serializers escape differently. I do not know which exact escaping Meta uses, and the test does not depend on it. It only shows that any re-serialization can change the bytes.
Handler latency. I sent 1,000 signed POSTs through FastAPI's in-process test client. Median 1.91 ms, 99th percentile 3.36 ms, maximum 5.56 ms. This measures the handler only, with no network and no database, so it says the signature and dedupe logic are cheap, not that your deployment is fast.
End-to-end check with an independent signer. I started the app with uvicorn and sent real HTTP requests with curl, computing the signature with openssl dgst -sha256 -hmac. Results:
| Request | Response |
|---|---|
GET with correct token and challenge 424242 | 200, body 424242 |
| GET with a wrong token | 403 |
| POST signed with openssl | 200, new: 1, duplicates: 0 |
| Same POST again | 200, new: 0, duplicates: 1 |
| POST with one changed word, old signature | 403 |
The handler ran exactly once. Because openssl produced the signature, this also confirms the algorithm matches an implementation I did not write.
What I did not test: real deliveries from Meta, mTLS, multiple workers against a real Redis server (I used fakeredis), behavior behind a proxy that rewrites the body, and load beyond 1,000 sequential requests. Test those in staging before you rely on this in production.
Deployment checklist
- Valid TLS certificate. Meta does not support self-signed certificates.
- Keep the secrets out of code. Store
WA_APP_SECRETandWA_VERIFY_TOKENin environment variables or a secret manager. Rotate the app secret if it leaks. - Do not let a proxy change the body. Nginx should pass the request through untouched. Set
client_max_body_sizeto match your limit, and avoid middleware that parses or compresses the body before your handler. - Use a shared dedupe store such as Redis when you run more than one worker.
- Acknowledge, then work. Do LLM calls and database writes in a background task or a queue. Return
200first. - Store the raw payloads you receive, with a retention period. Meta provides no API to fetch past webhooks, and you will want them for debugging.
- Treat statuses as forward-only. Rank
sent,delivered,readand ignore a lower rank that arrives late. - Log less personal data. Phone numbers and message text are personal data under India's Digital Personal Data Protection Act, 2023. Log ids, not content, and set retention deliberately.
- Alert on signature failures. A sudden spike usually means a wrong secret after a rotation, or a probing attacker.
- Load test your own latency. Hold a median near 250 ms or lower, as the Hookdeck guide suggests.
When to use n8n instead
You can verify the same signature inside a workflow tool. I walked through that pattern for generic webhooks in n8n Webhook Security: Verify Requests With HMAC. A workflow tool is faster to start with. A FastAPI receiver gives you tests, version control, shared Redis deduplication and finer control over responses, which matters once volume or risk grows. When a downstream step fails, pair either approach with retries and alerts, as covered in Self-Healing n8n Workflows.
Frequently asked questions
How do I verify a WhatsApp webhook signature in Python?
Read the raw request body, compute hmac.new(app_secret, raw_body, hashlib.sha256).hexdigest(), and compare it with the value after sha256= in the X-Hub-Signature-256 header using hmac.compare_digest.
What should the GET verification endpoint return?
If hub.mode is subscribe and hub.verify_token matches your stored token, return HTTP 200 with the hub.challenge value. Otherwise return a non-200 status such as 403.
Does Meta retry failed webhooks? Yes. According to Meta's documentation, failed deliveries are retried immediately and then a few more times with decreasing frequency over the next 7 days. Anything unacknowledged after that is dropped.
How do I stop duplicate WhatsApp messages from being processed twice?
Store the message id from messages[] with a time-to-live of at least 7 days. For status updates use statuses[].id together with statuses[].status. In Redis, SET key 1 NX EX 604800 does this atomically.
Should I return an error when the payload is invalid? Return 403 for a bad signature. For a correctly signed payload you cannot process, log it and return 200, because an error would make Meta retry something that cannot succeed.
Are webhook events delivered in order? Meta's documentation does not promise ordering, and updates can arrive out of sequence. Treat message statuses as forward-only and sort messages by timestamp.
Can I use this for other Meta webhooks?
Meta's Graph API webhooks use the same X-Hub-Signature-256 header, but check the documentation for each product, because payload shapes and rules differ. For a different payload, you mainly change the extraction function.
Key takeaways
- Verify the signature on the raw bytes with the app secret, using a constant-time compare.
- Answer the GET challenge only when mode and token both match.
- Deduplicate on message id, and on status id plus status, and keep keys for 7 days.
- Acknowledge fast and process in the background. Return 200 for signed payloads you cannot parse.
- Do not re-serialize JSON before checking the signature.
- Test the unhappy paths: tampered body, missing header, duplicates, oversize bodies and out-of-order statuses.
- Keep personal data out of logs and plan retention.
Migrating a WhatsApp AI Chatbot from n8n to FastAPI
My WhatsApp shopping bot outgrew n8n. Here is what went wrong, what the audit found, and how I decide between n8n and custom code.