Learning path: WhatsApp for agencies and software housesStep 3 of 5
One webhook endpoint for many WhatsApp numbers: routing by tenant
Read entry[].changes[].value.metadata.phone_number_id from every WhatsApp Cloud API webhook and look it up in a table that maps phone number IDs to tenants. Then hand the change to that tenant’s pipeline. Loop over every entry and every change, because one POST can carry events for several clients. When the ID is unknown, store the event, answer 200 and alert a person.
Where the receiving number sits in the payload
Every messages webhook, inbound or status, carries a metadata object with two fields: display_phone_number and phone_number_id (messages webhook reference). The entry[].id one level up is the WhatsApp Business Account ID, which Meta’s current docs call the Messaging account ID (status webhook reference).
"metadata": {
"display_phone_number": "15550783881",
"phone_number_id": "106540352242922"
}
Key your routing on phone_number_id. It is the ID you already use in the send path, POST /<WHATSAPP_BUSINESS_PHONE_NUMBER_ID>/messages, so one column serves inbound routing and outbound sending. display_phone_number is the number as people see it. Keep it for logs and dashboards.
Not every webhook has a phone number. Template webhooks such as message_template_status_update and account webhooks such as account_update carry the account ID in entry.id and no metadata. Map the account ID to the tenant as well, and fall back to it when metadata is missing. PARTNER_ADDED is the exception. When a client finishes Embedded Signup, Meta sends account_update with event set to PARTNER_ADDED. In that payload, entry.id is your business portfolio ID, and the client’s account ID is in waba_info.waba_id (Managing webhooks).
One endpoint, or one per client
By default all clients share your app’s callback URL. Meta’s partner guide says that if you subscribe your app to several Messaging accounts, “WhatsApp sends all webhook notifications to the app’s callback URL” unless you override it. You also “must individually subscribe to every Messaging account” with POST /<WABA_ID>/subscribed_apps (Managing webhooks).
Overrides give each client its own URL. You can set override_callback_uri on a Messaging account or on a single business phone number. Meta checks the number first, then the account, then the app (webhook overrides). The override covers messages and a list of related fields. Template and account webhooks are excluded. For those, “Meta always delivers these webhooks to your app’s default callback URL”. So even with per-client URLs, you need a shared endpoint that routes by account ID.
A single endpoint with a routing table is simpler to operate. You verify signatures in one place, deploy once and onboard a client by inserting a row. Per-client URLs suit you when a client runs their own backend and wants Meta’s webhooks directly.
The routing table and the loop
CREATE TABLE tenants (
id text PRIMARY KEY,
status text NOT NULL DEFAULT 'active', -- 'active' or 'offboarded'
workflow_id text, -- n8n sub-workflow for this client
waba_id text UNIQUE
);
CREATE TABLE tenant_numbers (
phone_number_id text PRIMARY KEY,
tenant_id text NOT NULL REFERENCES tenants (id)
);
Meta aggregates webhook POSTs “in a batch with a maximum of 1000 updates” and warns that “batching cannot be guaranteed” (Create a webhook endpoint). Code that reads only entry[0].changes[0] routes the first client’s event and drops the rest. Walk the whole payload:
def route(payload, tenant_by_phone_id, tenant_by_waba_id):
"""Yield (tenant_id or None, field, value) for every change in a Meta webhook."""
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
phone_id = value.get("metadata", {}).get("phone_number_id")
waba_id = value.get("waba_info", {}).get("waba_id") or entry.get("id")
if phone_id:
tenant = tenant_by_phone_id.get(phone_id)
else:
tenant = tenant_by_waba_id.get(waba_id)
yield tenant, change.get("field"), value
Run it after the signature check, and only then. Meta signs every payload with your app secret (Create a webhook endpoint). That secret belongs to your app and is the same for every client, so the signature proves Meta sent the event. Which client it belongs to comes from the ID lookup. Verify WhatsApp webhook signatures has the check in Node.js, Python and n8n.
Per-tenant secrets and data isolation
Three credentials differ per client. To send, Meta tells Tech Providers to use business tokens, which “are scoped to individual onboarded customers” (access tokens). Store one per tenant and pick it with the same tenant_id you routed on. A token from the wrong row sends from the wrong client’s number. If you use overrides, each URL has its own verify_token. If you forward events to a client’s backend, sign each forward with a secret issued to that client. A leak at one client then cannot forge traffic for another.
Put tenant_id on every table that holds messages or contacts. PostgreSQL row security makes a missing filter fail closed. Once enabled, “all normal access to the table for selecting rows or modifying rows must be allowed by a row security policy” (row security policies).
ALTER TABLE inbound_messages ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON inbound_messages
USING (tenant_id = current_setting('app.tenant_id', true));
Run SET LOCAL app.tenant_id = '...' at the start of each transaction. The table owner bypasses row security unless you add FORCE ROW LEVEL SECURITY, so connect your workers as a separate role.
Fan-out in n8n
- Webhook node, Respond set to Immediately, followed by the signature check.
- Postgres node, Execute Query, joining
tenant_numberstotenantson thephone_number_idfrom the payload. Turn on Always Output Data so an unknown number still produces an item. - Switch node in Rules mode, one rule per client on
{{ $json.id }}. Under Options, set Fallback Output to Extra Output so unmatched items get their own branch (Switch node). - On each client output, an Execute Sub-workflow node that calls that client’s workflow. Turn off Wait for Sub-Workflow Completion so one slow client does not hold up the rest (Execute Sub-workflow).
- On the fallback output, insert the payload into an
unrouted_eventstable and notify your team.
Editing the Switch for every new client stops scaling once you have many. Replace steps 3 and 4 with an If node on status and one Execute Sub-workflow node. Set Source to Database and take the Workflow ID from {{ $json.workflow_id }}. Onboarding a client becomes one insert.
Failure modes
An unknown number usually means a client was onboarded in Meta before your table was updated. Answer 200 anyway. A non-200 makes Meta retry for up to 7 days, and those retries go “to all apps that have subscribed to webhooks” for that Messaging account (webhooks overview). Keep the payload in unrouted_events and replay it once the row exists.
A removed client keeps sending events until you unsubscribe. Call DELETE /<WABA_ID>/subscribed_apps (Managing webhooks), then mark the tenant offboarded instead of deleting the row. Events still in Meta’s retry queue then find a tenant, match the offboarded status and get dropped with a log line. A deleted row would send them to unrouted_events and page someone for a client who left on purpose. Who keeps the number when a client leaves is a contract question, covered in One WhatsApp number per client.
On a QR connection
QR-connection providers send their own payloads, so metadata.phone_number_id does not exist there. Route on whatever field the provider uses to identify the connected number, with the same table and the same loop. Z-API Omni bills per number, US$29 per number per month for 1–10 numbers, US$26 for 11–50, US$23 for 51–100 and US$20 above 100. Webhooks are included, without limit (View documentation).
Z-API Omni team