
Table of Contents
- The Short Answer
- TL;DR
- Five Ways a Push Reaches You
- What Each Surface Lets You Configure
- The Threat Model in Plain Terms
- Where the Secret Lives
- One Route per Configuration
- The Edge: TLS, Method and Size
- The Ack Contract: Save, Then 200
- Dedupe Keys per Surface
- Replays Are Just Duplicates
- The Receiver in Python, Tested
- A Node Header Check That Doesn’t Throw
- Drilling Your Own Endpoint With cURL
- Rotating a Secret Without Dropping a Push
- Noticing the Push That Never Came
- Backfill per Surface
- Logging Without Leaking
- Decision Matrix
- The Production Checklist
- Unspecified Behaviour and How to Code Around It
- FAQs
The Short Answer
Treat every webhook URL you give a messaging platform as a public, unauthenticated door, because that’s what it is until you add a check. SMS delivery reports, WhatsApp Business API delivery reports, WhatsApp incoming messages and two-way SMS keyword forwards all reach you as plain HTTP requests. Build as if none of them carries a signature you can verify, and bring your own proof.
The design that holds up is the same for all of them. Put a long random secret in the URL path of every route. Where the webhook form lets you add custom headers (the portal webhooks for bulk SMS and WhatsApp do), add a second secret there as well. Check both in constant time and answer 404 on any miss. Then save the raw request under a dedupe key built for that surface, and only after the save, answer 200. A retry or a replay lands on the same key and changes nothing.
The last piece is the one people skip: pushes can go missing and nothing will tell you. Measure push coverage against what you sent, alarm when a surface goes quiet, and backfill from the pull APIs (getDlr, WAApi/report, the WhatsApp inbox) on a schedule. Two-way SMS forwards have no API backfill, so that route needs the most uptime and the loudest silence alarm.
TL;DR
- Five push surfaces, different tools. The
SMSApi/webhook/createcall takes only a URL and a TPS rate. Portal webhooks (SMS and WhatsApp, DLR or MO) add your own field names, custom parameters and custom headers. Two-way SMS keyword forwards use a GET template you write. - Assume no signature. Design as if nothing in these pushes is signed. A secret you set is your proof a request came from the platform.
- Path secret everywhere, header secret where possible. 32 random bytes, base64url, 43 characters. Compare against every accepted secret in constant time so rotation works.
- 404 on any failed check. Don’t parse, don’t store, don’t hint that the route exists.
- Save, then 200. Answer only after a durable insert. Duplicates also get 200.
- One dedupe key per surface.
messages[].idfor WhatsApp MO, message or transaction ID plus status for delivery reports, number plus time plus text hash for keyword SMS, a body hash when you don’t know the shape. - Replays are duplicates. With a bearer-style secret, a captured request can be resent, and the dedupe key makes the resend a no-op.
- Keep the raw body. Authentic but unparseable requests are saved with
parsed_ok = 0and still get 200. - IDs stay text. Parse JSON with integers as strings so 19-digit transaction IDs don’t lose digits.
- Rotate with an overlap. Accept old and new together, switch the config, read it back, watch traffic move, retire the old one.
- Watch for silence. Hourly push coverage per channel, nightly backfill from the pull APIs, a per-surface quiet alarm.
- Never log the secret. Mask the path segment, drop the header, and treat
SMSApi/webhook/readoutput as a secret because it returns the full URL.
Five Ways a Push Reaches You
When people say “the webhook”, they usually mean one of five different things. They’re configured in different places, they carry different bodies, and they give you different options for proving who sent them.
1. The SMS delivery report webhook you register through the API. SMSApi/webhook/create takes smswebhook (the URL) and smswebhookrate (the TPS the reports are forwarded at, default 10), and that’s it. POST only, with the usual userid plus apikey header. There’s no field for headers or extra parameters, so whatever protection you want has to live in the URL itself. SMSApi/webhook/read hands the config back as smsWebhook and smsWebhookRate, the rate as a string ("50" in the sample). Same settings, different spelling and casing on the way back.
2. A delivery report webhook set up in the portal, for SMS. Webhooks, Add Webhook, product SMS, report type DLR. The form asks for a send method (POST, GET, JSON or XML), the URL, and then the parameter names you want for Transaction ID, Message ID, Error Code, Mobile Number, Received Time and Delivered Time (setup steps). You pick the names. You can also add custom parameters and custom headers (how).
3. The same thing for WhatsApp delivery reports. Same form, product WhatsApp, plus a WABA number, plus two more names to choose: Read Time and Status.
4. The WhatsApp incoming message (MO) webhook. Same form again, report type MO. The body follows Meta’s message shape: messages[] with from, id, type, timestamp (a string of seconds) and the content, plus contacts[] with the profile name (MO format). Button taps arrive here too, which the template buttons guide covers end to end.
5. The two-way SMS keyword forward. Set per keyword on a long code. You write the callback template yourself, something like phonecode=$vmn&location=$location&phoneno=$mobile&content=$message&carrier=$operator&time=$timestamp&keyword=$keyword&forwardMethod=GET, and the platform fills it in and calls you with a GET. No message ID, no header field. The keyword routing guide goes deep on this one.
The webhook FAQ also lists OBD voice calls among the products with webhook support. Everything below applies to a voice push as well. The payload just isn’t covered here.
What Each Surface Lets You Configure
Here’s the same information as a table you can work from.
| Surface | Configured with | Methods | You choose field names | Custom headers | Custom parameters | Backfill |
|---|---|---|---|---|---|---|
| SMS DLR via API | SMSApi/webhook/create and /update | Plan for GET or POST | No | No | No | SMSApi/reports/status with method=getDlr |
| SMS DLR via portal | Webhooks form, report type DLR | POST, GET, JSON, XML | Yes | Yes | Yes | getDlr |
| WhatsApp DLR | Webhooks form, report type DLR, WABA number | POST, GET, JSON, XML | Yes, plus Read Time and Status | Yes | Yes | WAApi/report |
| WhatsApp MO | Webhooks form, report type MO, WABA number | POST, GET, JSON, XML | No, Meta message shape | Yes | Yes | rest/wa/v1/inbox poll |
| Two-way SMS keyword | Keyword Callback URL | GET (forwardMethod=GET) | Yes, through the template | No | Through the template | None |
Two things in that table shape the whole design.
First, you get to choose the field names on the portal webhooks. That sounds like a convenience, and it’s actually a schema decision you’ll live with. Pick one set of names and use it on every webhook you create, for example txn_id, msg_id, err_code, mobile, recv_time, dlvr_time, read_time and status. Then add a custom parameter such as hook_v=1. When you change the config later, bump it to hook_v=2, and your receiver always knows which version of the form produced a request.
Second, the header column. Three of the five can carry a custom header, two can’t. That’s why the path secret is the baseline for every route, and the header secret is a second layer only where it exists.
The Threat Model in Plain Terms
You don’t need a long threat model for this. Four things go wrong in practice.
Someone finds the URL and sends fake events. Webhook URLs end up in logs, screenshots, support tickets and old config files. If your DLR handler marks a payment reminder as delivered, or your MO handler opens a support ticket, a forged request does exactly that. On two-way SMS it can trigger auto-replies that cost you money.
Someone captures a real request and sends it again. With a static secret in a header or path, a captured request is valid forever. The fix isn’t a cleverer secret. It’s making the second copy harmless.
The platform sends the same event twice, or not at all. Whether a failed push is retried isn’t pinned down: one webhook FAQ says retries “may depend on the implementation”, another says a 200 “avoids unnecessary retries” (retries, responses). So design for both. At-most-once means you lose events when you’re down. At-least-once means you get duplicates. Your receiver has to be correct under either.
Your receiver leaks the secret. Access logs record full URLs. Error trackers record headers. Debug endpoints echo requests. A secret that ends up in a log is a secret shared with everyone who can read that log.
The OWASP Webhook Security Cheat Sheet is a good reference for the general case. A lot of its advice assumes the sender signs each delivery with HMAC. Without that, you’re working with the extra layers it lists next to signatures, such as a static bearer token and IP allowlisting, on top of TLS. That’s why dedupe and reconciliation carry more of the weight here.
Where the Secret Lives
Generate one secret per route, from a proper random source, and never reuse it anywhere else. 32 random bytes is plenty. In Python, secrets.token_urlsafe(32) gives you 43 URL-safe characters, which drop straight into a path segment with no encoding.
Then decide where it goes:
| Placement | Works on | Leaks through | Notes |
|---|---|---|---|
| URL path segment | All five surfaces | Access logs, proxies, webhook/read output, screenshots of the config | The baseline. Mask it in logs. |
| Custom header | Portal webhooks (SMS DLR, WhatsApp DLR, WhatsApp MO) | Error trackers and debug dumps that record headers | The second layer. Easy to drop from logs by name. |
| Query parameter | Avoid | Everything a path leaks through, plus analytics tools | On two-way SMS the platform appends its own parameters to your URL. A path segment stays clear of that. |
| Custom body parameter | Portal webhooks | Whatever stores bodies | Fine for hook_v. Not for secrets, because you’ll store the body. |
Why both a path and a header where you can? Because they leak in different places. Logs tend to record URLs, error trackers tend to record headers, and it’s rare for one incident to expose both. An attacker needs both to get past the edge.
Use a header name that’s yours, like X-Hook-Secret. The webhook form’s example is Authorization: Bearer your_token, which works too, but a dedicated name is easier to strip from logs without touching anything else.
One Route per Configuration
Give every webhook config its own route: /hooks/<surface>/<path-secret>. Five surfaces, five routes. If you run separate WABA numbers or separate keywords, give each one its own route and secret too.
That buys you three things. A leak on one route doesn’t expose the others, so you rotate one secret instead of all of them. Each route knows exactly what body shape to expect, so parsing never has to guess. And per-route metrics fall out for free: you’ll see straight away that WhatsApp MO went quiet while SMS DLR is fine.
It also sidesteps a question you’d otherwise have to answer. The webhook/create family manages a single SMS webhook per account, while the portal FAQ says you can create several webhooks for the same product (multiple webhooks). With one route per config, it doesn’t matter how many configs point at you. Each one is identified by its own secret.
The Edge: TLS, Method and Size
The edge is everything that happens before you touch the body. Keep it cheap and strict.
TLS on your listener. Register only https:// URLs. The webhook FAQ recommends HTTPS (HTTPS), and a secret in a path or header is only as private as the connection carrying it. Accept TLS 1.2 and 1.3. The platform asks API clients for TLS 1.2 at minimum and recommends 1.3 (TLS guide), so a listener that takes both is right whichever one the outbound push uses.
Secrets first, before anything else. Check the path secret, then the header secret if the surface has one. Any miss gets a 404 with an empty body, before you read a byte of the request body. A route that doesn’t know the secret simply doesn’t exist.
Method. Allow GET and POST, answer 405 to anything else. The portal form offers POST, GET, JSON and XML as send methods, keyword forwards are GET, and a receiver that accepts both GET and POST handles all of them. Decide the parser by method and Content-Type, not by guessing.
Size. Cap the body. Pick a cap well above the largest real push you’ve captured (64 KB is a comfortable default for text-only events, since WhatsApp media arrives as IDs and URLs rather than bytes) and answer 413 above it. Log the rejection without the body.
Rate. On the API webhook you set the forwarding rate yourself with smswebhookrate, default 10. Size your receiver for that rate plus headroom, and put an edge rate limit somewhere above it so a flood from anywhere else can’t take the route down.
IP allowlists, later and as a layer. You can’t look up the source addresses pushes come from. If your security team wants an allowlist, collect the source addresses from a few weeks of real traffic first, add the allowlist at your load balancer, and keep the secrets in place. An allowlist built on guesses will quietly drop real pushes the day the platform adds a server.
The Ack Contract: Save, Then 200
The response you send is a promise, so make it a precise one. 200 means “I have this event saved and I’ll never need it again from you.” Nothing else should produce a 200, and everything that’s true should.
| Situation | Answer | Stored? |
|---|---|---|
| Path or header secret wrong or missing | 404, empty body | No |
| Method other than GET or POST | 405 | No |
| Body over your cap | 413 | No |
| Authentic, parsed, new event | 200 ok | Yes, one row |
| Authentic, parsed, duplicate event | 200 ok | No new row, dup_count goes up |
| Authentic, but the body doesn’t parse | 200 ok | Yes, raw body, parsed_ok = 0 |
| Your database is down | 503 | No |
Two rows in there go against instinct.
Unparseable but authentic gets a 200. If the secret checks out, the request came from the platform, and a body you can’t parse today is a bug on your side or a format change you haven’t seen yet. Returning 400 doesn’t fix that. It just throws the event away, or asks for a retry that will fail identically. Save the raw body, flag it, answer 200, and have a person look at parsed_ok = 0 rows.
Duplicates get a 200 too. The sender asked “did you get this?” and the answer is yes. A non-200 on a duplicate invites more retries for something you already have.
OWASP suggests a 401 for a failed signature. With the secret in the path, 404 is the more honest answer: without the secret, that URL really doesn’t exist.
Keep the handler short. Check, parse loosely, insert, answer. Routing, replies, CRM updates and anything else that could be slow happens in a worker that reads the saved rows. The delivery report ingestion guide covers what to do with DLR rows once they’re saved, and it’s the same pattern message idempotency uses on the sending side.
Dedupe Keys per Surface
A dedupe key is the answer to “is this the same event I already have?” Get it wrong in one direction and you merge two real events. Get it wrong in the other and retries pile up as separate rows. Each surface needs its own answer, because each one carries different identifiers.
| Surface | Key | Why |
|---|---|---|
| WhatsApp MO | wamid: + messages[].id, one row per message | The message ID is unique per incoming message. A body can hold more than one message, so split it. |
| WhatsApp DLR | message ID or transaction ID, mobile, status, read or delivered time | One message produces several reports as it moves from sent to delivered to read. Status is part of identity. |
| SMS DLR via portal | transaction ID, mobile, status, delivered time | Same reasoning. An interim status and a final one are two events. |
| SMS DLR via API | hash of the canonical parsed body, or of the raw bytes | You can’t pick the field names here, so don’t bet on any of them. A byte-identical retry hashes the same. |
| Two-way SMS keyword | long code, sender number, time, hash of content | There’s no message ID. Without time in your template, two identical texts from one person collapse into one. |
A couple of habits make those keys work.
Use the field names you chose on the portal form, not the labels in the form. If you named the transaction ID txn_id, your key reads txn_id. That’s the payoff for picking names once and reusing them.
Keep every identifier as text from the first byte. Transaction IDs on this platform are 18 or 19 digits, and a JSON parser that turns them into doubles will silently round them, so two different messages can end up with the same key. Python’s json.loads(text, parse_int=str) keeps them exact. The lossless JSON guide has the equivalent for Node, Java, Go and PHP.
Replays Are Just Duplicates
A shared secret in a path or header is a bearer credential. Anyone holding a captured request can send it again, and it’ll pass every check at the edge. Signed timestamps are the usual cure, and you can’t count on them here.
You don’t need them. A replayed request carries the same event, so it produces the same dedupe key, so the insert is a no-op and the only visible effect is dup_count going up by one. That’s the property worth having: a replay can’t do anything a retry couldn’t, and a retry is harmless.
What about rejecting old requests by their timestamp? Don’t, at least not as a hard rule. If the platform does retry, a late retry is a real event, and dropping it because it’s old loses data. The WhatsApp MO timestamp is useful as a signal, though. Record it, and alert on requests whose timestamp is far older than their arrival, since a burst of those means either a retry storm or someone replaying captured traffic.
Watch dup_count the same way. A steady trickle of duplicates is normal if pushes are retried. A sudden spike on one route, with no outage on your side, is worth a look.
What a replay or a forgery can do is be new. Someone holding both secrets can invent events with fresh IDs. That’s why the secrets matter, why you rotate them, and why the reconcile step in stage three compares pushes against what you actually sent.
The Receiver in Python, Tested
Here’s the whole receiver as a WSGI app with no dependencies outside the standard library, so you can drop it behind gunicorn or adapt it to Flask or Django. The trap it’s built around is ordering: every check that can reject a request happens before the body is read, and the 200 happens only after the insert commits.
Each route is /hooks/<surface>/<path-secret>. HEADER_CAPABLE lists the surfaces that also need X-Hook-Secret. Both secret lists accept several values, which is what makes rotation work.
"""hookrx: one hardened receiver for SMS and WhatsApp pushes.
WSGI, standard library only. Every route is /hooks/<surface>/<path-secret>.
Surfaces that support custom headers also need a header secret.
"""
import hashlib
import hmac
import json
import sqlite3
import time
from decimal import Decimal
from urllib.parse import parse_qs
MAX_BODY = 64 * 1024
HEADER = "HTTP_X_HOOK_SECRET" # WSGI name for the X-Hook-Secret header
# Which surfaces can carry a custom header. The others rely on the path.
HEADER_CAPABLE = {"sms-dlr-portal", "wa-dlr", "wa-mo"}
SURFACES = HEADER_CAPABLE | {"sms-dlr-api", "sms-keyword"}
SCHEMA = """
CREATE TABLE IF NOT EXISTS push_receipt (
surface TEXT NOT NULL,
dedupe_key TEXT NOT NULL,
received_at INTEGER NOT NULL,
parsed_ok INTEGER NOT NULL,
dup_count INTEGER NOT NULL DEFAULT 0,
raw_body TEXT NOT NULL,
PRIMARY KEY (surface, dedupe_key)
);
"""
def _digest(value):
return hashlib.sha256(value.encode("utf-8")).digest()
def secret_ok(presented, accepted):
"""Constant-time check against every accepted secret, no early exit."""
if not presented:
return False
probe = _digest(presented)
hit = False
for candidate in accepted:
hit |= hmac.compare_digest(probe, _digest(candidate))
return hit
def redact_path(path):
"""Never log the path secret."""
parts = path.rstrip("/").split("/")
if len(parts) >= 4:
parts[-1] = "***"
return "/".join(parts)
def parse_body(method, content_type, query, body):
"""Return (fields, ok). Integers stay strings, so 19-digit IDs survive."""
if method == "GET":
return {k: v[0] for k, v in parse_qs(query).items()}, True
ctype = (content_type or "").split(";")[0].strip().lower()
text = body.decode("utf-8", errors="replace")
if ctype == "application/json" or text.lstrip().startswith(("{", "[")):
try:
return json.loads(text, parse_int=str, parse_float=Decimal), True
except ValueError:
return {}, False
if ctype == "application/x-www-form-urlencoded":
return {k: v[0] for k, v in parse_qs(text).items()}, True
return {}, False # XML or anything else: keep the raw body, decide later
def body_hash(fields, raw):
if fields:
canon = json.dumps(fields, sort_keys=True, default=str)
return "body:" + hashlib.sha256(canon.encode("utf-8")).hexdigest()
return "raw:" + hashlib.sha256(raw).hexdigest()
def wa_message_ids(fields):
"""Message ids from a flat body or a Meta-style entry/changes body."""
if not isinstance(fields, dict):
return []
blocks = [fields]
for entry in fields.get("entry", []) or []:
for change in entry.get("changes", []) or []:
blocks.append(change.get("value", {}) or {})
ids = []
for block in blocks:
for msg in block.get("messages", []) or []:
if isinstance(msg, dict) and msg.get("id"):
ids.append(str(msg["id"]))
return ids
def dedupe_keys(surface, fields, raw):
"""One or more keys per request. Same event, same key, every time."""
if surface == "wa-mo":
ids = wa_message_ids(fields)
return ["wamid:" + i for i in ids] or [body_hash(fields, raw)]
if surface in ("sms-dlr-portal", "wa-dlr") and isinstance(fields, dict):
ident = fields.get("msg_id") or fields.get("txn_id")
if ident:
state = fields.get("status") or fields.get("err_code") or ""
when = fields.get("dlvr_time") or fields.get("read_time") or ""
return ["|".join([str(ident), str(fields.get("mobile", "")),
str(state), str(when)])]
if surface == "sms-keyword" and isinstance(fields, dict) and fields.get("time"):
text = hashlib.sha256(
str(fields.get("content", "")).encode("utf-8")).hexdigest()[:16]
return ["|".join([fields.get("phonecode", ""), fields.get("phoneno", ""),
fields["time"], text])]
return [body_hash(fields if isinstance(fields, dict) else {}, raw)]
class Receiver:
def __init__(self, db, path_secrets, header_secrets, clock=time.time):
self.db = db
self.db.executescript(SCHEMA)
self.path_secrets = path_secrets # surface -> [secrets]
self.header_secrets = header_secrets # surface -> [secrets]
self.clock = clock
self.log = []
def _reply(self, start, status, text=b"ok"):
start(status, [("Content-Type", "text/plain"),
("Content-Length", str(len(text)))])
return [text]
def __call__(self, environ, start):
path = environ.get("PATH_INFO", "")
method = environ.get("REQUEST_METHOD", "GET")
self.log.append((method, redact_path(path)))
parts = path.strip("/").split("/")
if len(parts) != 3 or parts[0] != "hooks" or parts[1] not in SURFACES:
return self._reply(start, "404 Not Found", b"")
surface, presented = parts[1], parts[2]
if not secret_ok(presented, self.path_secrets.get(surface, [])):
return self._reply(start, "404 Not Found", b"")
if surface in HEADER_CAPABLE and not secret_ok(
environ.get(HEADER, ""), self.header_secrets.get(surface, [])):
return self._reply(start, "404 Not Found", b"")
if method not in ("GET", "POST"):
return self._reply(start, "405 Method Not Allowed", b"")
length = int(environ.get("CONTENT_LENGTH") or 0)
if length > MAX_BODY:
return self._reply(start, "413 Payload Too Large", b"")
raw = environ["wsgi.input"].read(length) if length else b""
query = environ.get("QUERY_STRING", "")
if method == "GET":
raw = query.encode("utf-8")
fields, ok = parse_body(method, environ.get("CONTENT_TYPE"), query, raw)
now = int(self.clock())
with self.db:
for key in dedupe_keys(surface, fields, raw):
self.db.execute(
"INSERT INTO push_receipt (surface, dedupe_key, received_at,"
" parsed_ok, raw_body) VALUES (?, ?, ?, ?, ?)"
" ON CONFLICT (surface, dedupe_key)"
" DO UPDATE SET dup_count = dup_count + 1",
(surface, key, now, int(ok),
raw.decode("utf-8", errors="replace")))
return self._reply(start, "200 OK")
And the tests. They cover wrong secrets, a missing header, duplicates, a Meta-style wrapped body producing the same key as the flat one, rotation, size and method limits, form-encoded portal reports with your own field names, a 19-digit ID, keyword dedupe, unparseable and XML bodies, and a log that never holds the secret.
import io
import json
import sqlite3
import unittest
from hookrx import Receiver, MAX_BODY, redact_path
PATH = {"wa-mo": ["p-wa-mo-new"], "wa-dlr": ["p-wa-dlr"],
"sms-dlr-portal": ["p-sms-portal"], "sms-dlr-api": ["p-sms-api"],
"sms-keyword": ["p-kw"]}
HDR = {"wa-mo": ["h-wa-mo"], "wa-dlr": ["h-wa-dlr"],
"sms-dlr-portal": ["h-sms-portal"]}
MO = {"metadata": {"phone_number_id": "1", "display_phone_number": "91000"},
"messaging_product": "whatsapp",
"messages": [{"from": "919800000001", "id": "wamid.ABC123",
"text": {"body": "hi"}, "type": "text",
"timestamp": "1682397841"}],
"contacts": [{"profile": {"name": "A"}, "wa_id": "919800000001"}]}
def call(app, method, path, body=b"", ctype="application/json",
header=None, query=""):
env = {"REQUEST_METHOD": method, "PATH_INFO": path, "QUERY_STRING": query,
"CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(len(body)),
"wsgi.input": io.BytesIO(body)}
if header is not None:
env["HTTP_X_HOOK_SECRET"] = header
seen = {}
app(env, lambda status, headers: seen.setdefault("s", status))
return seen["s"]
class T(unittest.TestCase):
def setUp(self):
self.db = sqlite3.connect(":memory:")
self.app = Receiver(self.db, {k: list(v) for k, v in PATH.items()},
{k: list(v) for k, v in HDR.items()},
clock=lambda: 1700000000)
def rows(self):
return self.db.execute(
"SELECT surface, dedupe_key, parsed_ok, dup_count"
" FROM push_receipt ORDER BY dedupe_key").fetchall()
def test_wrong_path_secret_is_404_and_stores_nothing(self):
s = call(self.app, "POST", "/hooks/wa-mo/guess",
json.dumps(MO).encode(), header="h-wa-mo")
self.assertEqual(s, "404 Not Found")
self.assertEqual(self.rows(), [])
def test_missing_header_is_404(self):
s = call(self.app, "POST", "/hooks/wa-mo/p-wa-mo-new",
json.dumps(MO).encode())
self.assertEqual(s, "404 Not Found")
def test_mo_keyed_by_wamid_and_duplicate_counted(self):
body = json.dumps(MO).encode()
for _ in range(2):
s = call(self.app, "POST", "/hooks/wa-mo/p-wa-mo-new", body,
header="h-wa-mo")
self.assertEqual(s, "200 OK")
self.assertEqual(self.rows(), [("wa-mo", "wamid:wamid.ABC123", 1, 1)])
def test_wrapped_meta_shape_gives_same_key(self):
wrapped = {"entry": [{"changes": [{"value": MO}]}]}
call(self.app, "POST", "/hooks/wa-mo/p-wa-mo-new",
json.dumps(MO).encode(), header="h-wa-mo")
call(self.app, "POST", "/hooks/wa-mo/p-wa-mo-new",
json.dumps(wrapped).encode(), header="h-wa-mo")
self.assertEqual(self.rows(), [("wa-mo", "wamid:wamid.ABC123", 1, 1)])
def test_rotation_overlap_then_retire(self):
self.app.path_secrets["wa-mo"].append("p-wa-mo-old")
body = json.dumps(MO).encode()
self.assertEqual(call(self.app, "POST", "/hooks/wa-mo/p-wa-mo-old",
body, header="h-wa-mo"), "200 OK")
self.app.path_secrets["wa-mo"].remove("p-wa-mo-old")
self.assertEqual(call(self.app, "POST", "/hooks/wa-mo/p-wa-mo-old",
body, header="h-wa-mo"), "404 Not Found")
def test_oversize_and_method(self):
big = b"{" + b" " * MAX_BODY + b"}"
self.assertEqual(call(self.app, "POST", "/hooks/sms-dlr-api/p-sms-api",
big), "413 Payload Too Large")
self.assertEqual(call(self.app, "PUT", "/hooks/sms-dlr-api/p-sms-api",
b"{}"), "405 Method Not Allowed")
def test_portal_dlr_form_with_named_params(self):
form = (b"txn_id=6358884679059916409&mobile=919800000001"
b"&status=DELIVERED&dlvr_time=1700000000123&hook_v=1")
s = call(self.app, "POST", "/hooks/sms-dlr-portal/p-sms-portal", form,
ctype="application/x-www-form-urlencoded",
header="h-sms-portal")
self.assertEqual(s, "200 OK")
key = self.rows()[0][1]
self.assertEqual(
key, "6358884679059916409|919800000001|DELIVERED|1700000000123")
def test_json_19_digit_id_survives(self):
body = (b'{"txn_id": 6358884679059916409, "mobile": 919800000001,'
b' "status": "DELIVERED", "dlvr_time": 1700000000123}')
call(self.app, "POST", "/hooks/wa-dlr/p-wa-dlr", body, header="h-wa-dlr")
self.assertTrue(self.rows()[0][1].startswith("6358884679059916409|"))
def test_keyword_get_uses_time_and_content(self):
q1 = "phonecode=9190000&phoneno=919800000001&content=YES&time=1700000001"
q2 = "phonecode=9190000&phoneno=919800000001&content=YES&time=1700000060"
for q in (q1, q1, q2):
self.assertEqual(call(self.app, "GET", "/hooks/sms-keyword/p-kw",
query=q), "200 OK")
rows = self.rows()
self.assertEqual(len(rows), 2)
self.assertEqual(sorted(r[3] for r in rows), [0, 1])
def test_unparseable_but_authentic_is_kept(self):
s = call(self.app, "POST", "/hooks/sms-dlr-api/p-sms-api",
b"{not json", ctype="application/json")
self.assertEqual(s, "200 OK")
self.assertEqual(self.rows()[0][2], 0)
def test_xml_body_kept_raw(self):
s = call(self.app, "POST", "/hooks/sms-dlr-api/p-sms-api",
b"<dlr><id>1</id></dlr>", ctype="text/xml")
self.assertEqual(s, "200 OK")
self.assertTrue(self.rows()[0][1].startswith("raw:"))
def test_log_never_holds_the_secret(self):
call(self.app, "POST", "/hooks/sms-dlr-api/p-sms-api", b"{}")
self.assertNotIn("p-sms-api", repr(self.app.log))
self.assertEqual(redact_path("/hooks/sms-dlr-api/p-sms-api"),
"/hooks/sms-dlr-api/***")
if __name__ == "__main__":
unittest.main()
All 12 pass on Python 3.10:
Ran 12 tests in 0.004s
OK
secret_ok hashes both sides to SHA-256 before hmac.compare_digest, so secrets of different lengths compare in the same time, and it checks every accepted secret without stopping at the first match. The loop is what lets you hold old and new secrets at once during a rotation.
dedupe_keys returns a list, because one WhatsApp MO body can carry several messages. It also reads both the flat body and Meta’s entry[].changes[].value wrapper, so a format change upstream doesn’t double your rows.
The upsert uses ON CONFLICT ... DO UPDATE SET dup_count = dup_count + 1. It’s one statement, so two copies of the same event arriving at the same moment still end as one row.
A Node Header Check That Doesn’t Throw
If your receiver runs on Node, the trap is crypto.timingSafeEqual. It’s the right function, and it throws ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH when its two buffers differ in length. Compare a presented header straight against your secret and any wrong-length guess becomes a 500 and a stack trace in your logs, which tells the caller something about your secret and fills your error tracker.
Hash both sides first. Two SHA-256 digests are always 32 bytes, so the comparison never throws, and the time it takes doesn’t depend on what was sent.
'use strict';
const crypto = require('crypto');
const http = require('http');
// Old and new during a rotation; one value the rest of the time.
const ACCEPTED = (process.env.WA_MO_HEADER_SECRETS || '').split(',').filter(Boolean);
function sha(v) {
return crypto.createHash('sha256').update(String(v), 'utf8').digest();
}
// timingSafeEqual throws on unequal lengths, so compare fixed-size digests.
function headerOk(presented) {
if (typeof presented !== 'string' || presented.length === 0) return false;
const probe = sha(presented);
let hit = false;
for (const s of ACCEPTED) hit = crypto.timingSafeEqual(probe, sha(s)) || hit;
return hit;
}
function handler(req, res) {
if (!headerOk(req.headers['x-hook-secret'])) {
res.writeHead(404).end();
return;
}
let size = 0;
const chunks = [];
req.on('data', (c) => {
size += c.length;
if (size > 64 * 1024) { res.writeHead(413).end(); req.destroy(); return; }
chunks.push(c);
});
req.on('end', () => {
if (res.writableEnded) return;
const raw = Buffer.concat(chunks).toString('utf8');
// Save raw first (your durable insert goes here), then answer.
res.writeHead(200, { 'Content-Type': 'text/plain' }).end('ok');
});
}
module.exports = { headerOk, handler };
if (require.main === module) http.createServer(handler).listen(8080);
Run against a local server, the four cases come back as 200 for the right header, 404 for a wrong one, 404 for none, and 413 for a 70,000-byte body. headerOk also returns false for an array, which is what Node gives you when a header is sent twice, rather than passing a list to String() and comparing that.
The body handler stops reading at 64 KB and destroys the request, so a slow or huge upload can’t tie up the process. In your real handler, the durable insert goes where the comment is, before res.writeHead(200).
Drilling Your Own Endpoint With cURL
Before you save a webhook in the portal, probe the route yourself. Six requests cover the edge, and the expected answer for each is printed in the first line of the script.
#!/usr/bin/env bash
# Probe your own receiver before the platform does. Expect: 404 404 200 200 405 413
set -u
BASE="https://hooks.example.com/hooks/wa-mo"
GOOD="$WA_MO_PATH_SECRET"
HDR="X-Hook-Secret: $WA_MO_HEADER_SECRET"
BODY='{"messages":[{"from":"919800000001","id":"wamid.DRILL1","type":"text","text":{"body":"drill"},"timestamp":"1700000000"}]}'
code() { curl -s -o /dev/null -w '%{http_code} ' "$@"; }
code -X POST "$BASE/wrong-secret" -H "$HDR" -H 'Content-Type: application/json' --data-binary "$BODY"
code -X POST "$BASE/$GOOD" -H 'Content-Type: application/json' --data-binary "$BODY"
code -X POST "$BASE/$GOOD" -H "$HDR" -H 'Content-Type: application/json' --data-binary "$BODY"
code -X POST "$BASE/$GOOD" -H "$HDR" -H 'Content-Type: application/json' --data-binary "$BODY"
code -X PUT "$BASE/$GOOD" -H "$HDR" --data-binary '{}'
head -c 70000 /dev/zero | tr '\0' ' ' > /tmp/big.json
code -X POST "$BASE/$GOOD" -H "$HDR" -H 'Content-Type: application/json' --data-binary @/tmp/big.json
echo
Run against the Python receiver above, it prints 404 404 200 200 405 413: wrong path secret, missing header, a new event, the same event again (still 200, now a duplicate), a PUT, and an oversized body. The two 200s should leave exactly one row with dup_count = 1.
Then use the portal’s Test Webhook button (testing). It shows you the HTTP response your endpoint returned and should include any custom parameters and headers you set. Two things to check while you’re there. Your endpoint should answer the test with 200 ok and nothing else, because the response body is shown on screen. And the test event may carry IDs that don’t match anything you sent, so make sure your worker treats unknown IDs as “park and look later”, not as an error that blocks the queue.
For the API webhook, test it this way. After SMSApi/webhook/create or /update, call SMSApi/webhook/read and check that smsWebhook is exactly the URL you meant, then send one real SMS to a number you control and watch the route.
Rotating a Secret Without Dropping a Push
Rotate on a schedule and whenever a URL or header might have leaked (a shared screenshot, a log export, someone leaving the team). The rule that makes it safe is the same one behind API key rotation: accept old and new together for a while, move the config, confirm traffic moved, then retire the old one.
- Generate the new secret with
secrets.token_urlsafe(32)and store it next to the old one in your secrets manager. - Add it to the accepted list for that route and deploy. The receiver now takes both. Nothing has changed for the platform yet.
- Move the config. For a portal webhook, open Manage Webhooks, Edit, and change the URL or header value (managing webhooks). For the API webhook, call
SMSApi/webhook/updatewith the newsmswebhook. For a keyword, edit its Callback URL. - Read it back. Call
SMSApi/webhook/read, or reopen the portal entry, and check the stored value. A save you haven’t read back is a save you’re assuming. - Fire a test with Test Webhook, or one real message for the API webhook and keyword routes.
- Watch the split. Tag each accepted request with which secret matched (old or new, never the value) and wait until the old one has seen nothing for a full day. Pushes queued before the change may still arrive on the old URL.
- Retire the old secret, deploy, and confirm requests on it now get 404.
If you rotate both the path and the header secret on a portal webhook, do them one at a time. Two simultaneous changes make step six impossible to read.
Noticing the Push That Never Came
Everything so far protects you from requests you shouldn’t accept. This section is about requests that never arrive, which is the failure nobody notices. A webhook that stops firing doesn’t error. Your dashboards just get quieter.
There are three ways to catch it, and you want all three.
Push coverage against what you sent. For delivery reports you know exactly what to expect, because you sent the messages. Every hour, count the sends from two or more hours ago and how many of them have any push receipt yet. Here’s the query, with the receipt table from the receiver plus two small tables from your side:
-- Every push you accept, one row per event, raw body kept.
CREATE TABLE push_receipt (
surface TEXT NOT NULL, -- 'sms-dlr-api', 'wa-mo', ...
dedupe_key TEXT NOT NULL,
received_at INTEGER NOT NULL, -- epoch seconds, your clock
parsed_ok INTEGER NOT NULL, -- 0 = kept raw, look at it
dup_count INTEGER NOT NULL DEFAULT 0,
raw_body TEXT NOT NULL,
PRIMARY KEY (surface, dedupe_key)
);
-- What you sent, from your outbound table (trimmed for the example).
CREATE TABLE outbound (
provider_id TEXT PRIMARY KEY, -- transaction id as text
channel TEXT NOT NULL, -- 'sms' or 'whatsapp'
sent_at INTEGER NOT NULL
);
-- Which outbound rows got any push receipt, per hour.
CREATE TABLE dlr_seen (
provider_id TEXT PRIMARY KEY,
seen_at INTEGER NOT NULL
);
-- Push coverage per channel per hour, for sends at least 2 hours old.
-- :now is the current epoch second.
SELECT o.channel,
(o.sent_at / 3600) * 3600 AS hour_start,
COUNT(*) AS sent,
COUNT(d.provider_id) AS pushed,
ROUND(100.0 * COUNT(d.provider_id) / COUNT(*), 1) AS coverage_pct
FROM outbound o
LEFT JOIN dlr_seen d ON d.provider_id = o.provider_id
WHERE o.sent_at < :now - 7200
GROUP BY o.channel, hour_start
ORDER BY hour_start, o.channel;
Fed 200 SMS sends in one hour with 194 receipts, and 100 WhatsApp sends in the next hour with 61, it returns:
('sms', 1763697600, 200, 194, 97.0)
('whatsapp', 1763701200, 100, 61, 61.0)
The absolute number matters less than the change. Learn what normal coverage looks like for each channel over a couple of weeks, and alarm when an hour falls well below it. A drop like the WhatsApp hour above usually means your endpoint, your secret or the webhook config changed, not the network.
Silence per surface. For MO and keyword forwards you can’t predict volume, but you can learn it. Track the time since the last accepted request on each route, compare it with the usual gap for that hour of the day, and alarm when it’s several times longer. A quiet Sunday morning shouldn’t page anyone. A quiet Tuesday noon should.
A canary you control. For two-way SMS, send a text to your own long code from a handset you control once a day, using a reserved keyword your router ignores. If it doesn’t arrive within a few minutes, something in the chain is broken. On WhatsApp, send a message to your own business number from a test handset for the same reason.
The observability guide has the broader metric set. Coverage and silence are the two that catch a broken webhook before your customers do.
Backfill per Surface
Coverage tells you something’s missing. Backfill gets it back. Each surface has a different pull path, and one has none.
| Surface | Backfill call | Notes |
|---|---|---|
| SMS DLR (API or portal) | SMSApi/reports/status with method=getDlr | Date range plus pageLimit, cursor paging. Key the pulled rows exactly like the pushed ones, so a report that came both ways is one row. |
| WhatsApp DLR | WAApi/report | POST only, fromDate and toDate, pageLimit required, startCursor for the next page. uuId arrives unquoted, so parse it as text. |
| WhatsApp MO | rest/wa/v1/inbox | fromDate, toDate, page, limit up to 200, filter by waMsgId. Rows come newest first. Match on waMsgId against the messages[].id you stored from the push. |
| Two-way SMS keyword | None | Uptime, the silence alarm and the canary are your only protection. |
Run the backfill nightly for the previous day whether or not the alarm fired, and on demand after any incident. The delivery report ingestion guide walks through paging getDlr without losing rows, and the four-channel inbox comparison covers the inbox polls.
One detail that bites people: the same event looks different on the two paths. A WhatsApp MO push gives you timestamp as a string of seconds. The inbox poll gives you timestamp as a number of milliseconds. A DLR push uses the field names you chose. The pull uses the platform’s names (uuId, mobileNo, deliveryTime). Normalise both into the same key before you insert, or a backfilled event will sit next to its pushed twin as a second row.
Logging Without Leaking
Your receiver will be the most-logged code you own, so decide what it logs before the first request.
- Mask the path secret. Log
/hooks/wa-mo/***, never the real segment. Configure your load balancer and web server access logs the same way, because they log before your code runs. - Drop the secret header by name. Strip
X-Hook-Secret(or whatever you called it) in your logging middleware and in your error tracker’s scrubbing rules. - Log which secret matched, not its value. “old” or “new” is all the rotation needs.
- Keep bodies out of logs. The raw body belongs in
push_receipt, where access is controlled and retention is a decision. Logs get copied everywhere. MO bodies carry phone numbers and message text. - Treat
webhook/readoutput as a secret. It returnssmsWebhookwith the full URL, path secret included. Don’t print it in deploy scripts or CI output.
The OWASP Logging Cheat Sheet is the general reference. For how long to keep those raw bodies, and how to delete a person from them later, see the retention and erasure guide.
Decision Matrix
| If your situation is | Do this | Because |
|---|---|---|
| You only use the API webhook for SMS DLR | Path secret, body-hash dedupe, nightly getDlr backfill | There’s no header field and you can’t choose field names, so the path and the pull do the work |
| You can use the portal webhook for SMS DLR | Prefer it, with your own field names, hook_v, path and header secrets | Named fields give you a real dedupe key and the header gives you a second secret |
| You receive WhatsApp MO | Path and header secrets, messages[].id key, inbox poll backfill | The message ID is a natural key and the inbox gives you a way to recover |
| You run two-way SMS keywords | Path secret per keyword, time in the template, canary and silence alarm | No message ID, no header, no API backfill. Prevention is all you have |
| Security asks for IP allowlisting | Collect real source addresses first, then add it at the load balancer, keep secrets | Allowlists built on guesses drop real pushes |
| You see duplicates | Do nothing different, they’re absorbed by the key | That’s the design working. Alert only on a sudden spike |
| A URL or header may have leaked | Rotate that route only, with the seven-step overlap | One route per config keeps the blast radius to one surface |
| Coverage drops on one channel | Check the route, the secret and the config, then backfill | Coverage drops are almost always on the receiving side |
The Production Checklist
- One route per webhook config, shaped
/hooks/<surface>/<path-secret>. - Each path secret is
secrets.token_urlsafe(32)or equivalent, stored in a secrets manager, used nowhere else. - Portal webhooks also carry an
X-Hook-Secretcustom header with its own secret. - Portal webhooks use one fixed set of field names (
txn_id,msg_id,err_code,mobile,recv_time,dlvr_time,read_time,status) plus ahook_vcustom parameter. - Two-way SMS templates include
time=$timestamp. - Only
https://URLs are registered. The listener accepts TLS 1.2 and 1.3. - Secrets are checked in constant time against every accepted value, before the body is read.
- Any failed check answers 404 with an empty body and stores nothing.
- Only GET and POST are allowed. Bodies over the cap get 413.
- JSON is parsed with integers as text. IDs and phone numbers are never numbers in your code.
- Every authentic request is saved with its raw body before 200 is sent. Duplicates bump
dup_countand also get 200. - Unparseable but authentic bodies are kept with
parsed_ok = 0and reviewed. - Workers read saved rows. No routing, replies or CRM calls in the request handler.
- Pulled and pushed events are normalised into the same key before insert.
- Hourly coverage per channel, a silence alarm per route, a daily canary for two-way SMS and WhatsApp MO.
- Nightly backfill from
getDlr,WAApi/reportandrest/wa/v1/inbox. - Access logs, app logs and the error tracker mask the path secret and drop the secret header.
SMSApi/webhook/readoutput never reaches a log or CI output.- Rotation is rehearsed, and every config change is read back after saving.
- The six cURL drills pass before a webhook is saved in the portal.
Unspecified Behaviour and How to Code Around It
Some of what a receiver needs to know isn’t pinned down by anything you can read. Each item below gives the choice that’s safe either way, and none of them needs you to wait for an answer before you ship.
One. Assume a failed push may or may not be retried, and build for both. With a dedupe key and a nightly backfill, a retried push becomes a duplicate you absorb, and a push that’s never retried arrives by pull the next day. Either way you end with one row.
Two. Hash the body for the API webhook instead of guessing its field names. The API webhook’s report body isn’t something you can choose or look up. A canonical hash of the parsed body (or of the raw bytes when it won’t parse) is a correct key whatever the fields turn out to be, and you can switch to a field-based key later without losing history.
Three. Answer fast, and never make the answer wait on slow work. How long the platform waits for your response isn’t stated. A handler that only checks, inserts and answers is fast enough for any sensible timeout, and one that calls your CRM first isn’t safe under any of them.
Four. Accept GET and POST, and parse by method and Content-Type. What the JSON and XML send methods look like on the wire isn’t shown. A receiver that takes form bodies, JSON bodies and query strings, and keeps anything else raw, handles every one of them, including a format it hasn’t met yet.
Five. Keep the raw body of every authentic request. If a body changes shape upstream, the rows you saved before you noticed are still usable, because you can re-parse them. A receiver that kept only parsed fields can’t do that.
Six. Read both the flat and the wrapped WhatsApp MO shape. The MO sample is a flat body with messages[] at the top. Meta’s own webhooks wrap the same block in entry[].changes[].value. Reading message IDs from both places gives the same key either way, so a change upstream can’t double your rows.
Seven. Put the secret in the path even where a header is available. Whether custom headers are forwarded unchanged through every proxy between the platform and you isn’t something you can see. A path secret survives anything that delivers the request at all, and the header becomes a bonus layer rather than a single point of failure.
Eight. Accept TLS 1.2 and 1.3 on your listener. Which TLS version outbound pushes use isn’t stated. A listener that takes both works with either, and still refuses anything older.
Nine. Base IP allowlists on observed traffic, and never replace secrets with one. The source addresses of pushes aren’t published. An allowlist built from weeks of real traffic, layered on top of secrets, can only reject attackers. One built on a guess can reject the platform.
Ten. Treat a webhook config as unsaved until you’ve read it back. Whether an edit takes effect at once or after a delay isn’t stated. Reading the config back, then watching which secret matches, tells you what’s actually live without needing to know.
Eleven. Give every config its own route and secret, however many configs the platform allows. One SMS webhook through the API and several per product through the portal can both be true. Routes keyed by their own secret don’t care which.
FAQs
Do SMS or WhatsApp webhook pushes come with a signature I can verify?
Build as if they don’t. Put a random secret in the URL path of every route, add a custom header secret on portal webhooks, and check both in constant time. That gives you proof of origin without depending on a signature.
Should my webhook return 401 or 404 when the secret is wrong?
404, with an empty body. When the secret is part of the path, a URL without it really doesn’t exist, and a 404 gives a scanner nothing to work with. Don’t parse or store anything on a failed check.
What should I return when I get the same delivery report twice?
200, the same as the first time. You have the event, so the honest answer is yes. A non-200 on a duplicate only invites more retries.
Can I add custom headers to the SMS webhook created through the API?
Not through SMSApi/webhook/create, which takes only smswebhook and smswebhookrate. Put the secret in the URL path. If you want a header secret as well, set up the SMS delivery report webhook in the portal, where the form has Add Custom Headers.
How do I stop replay attacks without signed timestamps?
Make replays harmless instead of trying to detect them. A replayed request carries the same event, so it hits the same dedupe key and changes nothing. Record the WhatsApp MO timestamp and alert on requests that arrive much later than their timestamp, but don’t reject them outright.
What should the endpoint do if the body doesn’t parse?
If the secret checked out, save the raw body with parsed_ok = 0 and answer 200. The request is genuine, and rejecting it just loses the event. Then fix your parser and re-process the saved rows.
How do I know if pushes have stopped arriving?
Measure them. Count sends against push receipts every hour for delivery reports, track the time since the last request on each MO and keyword route, and send yourself a daily canary message. Any of the three catches a broken webhook long before a customer complains.
Can I recover WhatsApp incoming messages I missed while my endpoint was down?
Yes. Poll rest/wa/v1/inbox with fromDate and toDate for the outage window, page through with page and limit (up to 200), and match on waMsgId against the message IDs you already stored. Anything new goes through the same insert as a push.
Can I recover two-way SMS keyword messages I missed?
Not through the API. That’s why the keyword route needs the most uptime, a silence alarm and a daily canary text. Keep the receiver small and boring so it rarely goes down.
How often should I rotate webhook secrets?
On a schedule you’ll actually keep, and straight away if a URL or header might have leaked. Use the overlap: accept old and new, move the config, read it back, wait until the old secret sees nothing for a day, then retire it.
Make Every Push Count Once and Never Go Missing
Point your delivery reports and incoming messages at a receiver you can trust. Create a free SMSGatewayCenter account, register a test route with the Create Webhook API or the portal webhook form, and run the drills above before you go live. If you’d like a second pair of eyes on your webhook setup, get in touch with our team.
More from our blog
WhatsApp Template Buttons End to End: Quick Reply Payloads, Dynamic URL Buttons and Matching the Tap
Missed Call Verification and Lead Capture: Callback Design, Session Matching and the Lead Pipeline