Receive events with webhooks
Webhooks push OpenWA events to your server over HTTP as they happen — an inbound message, a delivery receipt, a session going online — so you never have to poll the API. Each webhook belongs to one session and receives a POST for every subscribed event.
This guide shows you how to register, list, update, test, and delete webhooks; what a delivery looks like on the wire; how to verify its signature; and how to filter events before they ever reach your endpoint.
- A running session — see Connect a session.
- An API key with the operator role or higher. Every webhook route is operator-guarded, except the delivery-failure log, which requires admin. The key must also carry no chat allowlist: a key restricted to selected chats (
allowedChats, v0.23.6+) is refused with403on every webhook route, whatever its role. See Authentication to mint one, and Scope a key to chats. - A publicly reachable HTTPS endpoint that returns
2xxon success.
The examples assume these shell variables:
export BASE="http://localhost:2785/api"
export API_KEY="YOUR_API_KEY"
export ADMIN_API_KEY="YOUR_ADMIN_API_KEY"
export SESSION="8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a"
In production, BASE is your own domain over TLS; the /api prefix is unchanged. ADMIN_API_KEY is an admin-role key, used only by the delivery-failure examples.
How delivery works
An event flows from the WhatsApp engine to the dispatcher, which keeps only the webhooks whose events list and filters match. Each match is POSTed to your URL with tracing headers, and with an HMAC signature when the webhook has a secret. A non-2xx response, a timeout, or a network error triggers a retry, until the delivery has been attempted retryCount times in total. Backoff is exponential on both the queued path (QUEUE_ENABLED=true) and the direct path OpenWA uses otherwise: WEBHOOK_RETRY_DELAY doubles with each retry, so the waits are 5, 10, 20 and 40 seconds at the default delay, as many as retryCount allows (the default retryCount of 3 gives 5 and 10). The direct path backed off linearly before v0.24.0.
Since v0.24.0, once a webhook's last attempt has failed, the same session's further deliveries to it take a per-session slot, at most WEBHOOK_DEGRADED_SESSION_CONCURRENCY at a time per node (by default a quarter of the worker or dispatch pool), until its first 2xx. One dead receiver therefore cannot take every delivery slot from the session's healthy webhooks. With the queue on, the excess waits in the delayed set without spending an attempt; with it off, a session's backlog past a quarter of WEBHOOK_DISPATCH_MAX_QUEUED is recorded as a delivery failure with attempts: 0 and replayed by the outbox. A delivery already running when the failure lands is not capped. Configuration lists the defaults.
The serialized delivery body is capped at WEBHOOK_MAX_PAYLOAD_BYTES (default 1 MiB, validated as a positive integer at boot). An oversized body first sheds any inline media — the event is delivered with the omitted marker instead of being dropped — and is re-checked. A body still over the cap is not sent: the delivery is recorded as undelivered (queryable at GET /api/webhooks/delivery-failures). This is a breaking change from releases that sent oversized bodies as-is.
Since v0.25.0 the durable outbox keeps queued deliveries until the worker completes delivery or persists a terminal failure. The reconciler inspects queued jobs before replaying: completed jobs retire their outbox copy while Redis still retains the job, and an unavailable Redis leaves the copy pending. Recovery before the outbox write remains best effort, so receivers must deduplicate repeated POSTs.
On shutdown, parked direct deliveries and deliveries stopped during retry backoff leave their outbox row pending for the next start. A backoff that ends within WEBHOOK_SHUTDOWN_DRAIN_MS (default 5 seconds) records attempts: 0, even if earlier attempts were sent; a delivery still asleep when the drain ends is only logged as abandoned. The drain is bounded, so a receiver may already have processed an interrupted delivery. Deduplicate on X-OpenWA-Idempotency-Key across restarts and redrives. A later successful delivery removes its failure rows; terminal replay failures replace the provisional zero-attempt row without losing the event's record.
Register a webhook
Send a POST to /api/sessions/{sessionId}/webhooks. Only url is required; events defaults to ["message.received"] when omitted.
curl -X POST "$BASE/sessions/$SESSION/webhooks" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-server.com/webhook",
"events": ["message.received", "session.status"],
"secret": "a-long-random-string",
"retryCount": 3
}'
| Field | Type | Required | Notes |
|---|---|---|---|
url | string | yes | Endpoint that receives deliveries. Validated as a URL and SSRF-guarded — an internal or blocked host is rejected with 400, as is a URL embedding credentials (user:pass@host), on create and update (v0.19.0+). Since v0.31.0 the blocked addresses also include the documentation ranges (such as 203.0.113.0/24 and 2001:db8::/32), 2001:2::/48 and 192.88.99.2; a receiver on one of them needs SSRF_ALLOWED_HOSTS (see Configuration). |
events | string[] | no | Event names to subscribe to (see the event catalog), or ["*"] for every event except message.receipt, which must be named explicitly (v0.26.0+). At least one entry and at most 27 entries (WEBHOOK_EVENTS.length + 1, the 26 named events plus "*", v0.28.0+). Defaults to ["message.received"]. |
secret | string | no | HMAC signing key (a webhook without one is delivered unsigned), 16–255 characters. Since v0.20.0 a secret shorter than 16 characters is rejected when the webhook is created, and since v0.21.0 the update route enforces the same floor (an empty string or null still clears signing); secrets saved by earlier releases keep signing. Write-only — never returned by any response. |
headers | object | no | Custom headers added to every delivery. Write-only. Reserved names are dropped: Content-Type, any X-OpenWA-*, User-Agent (v0.24.0+), and the connection-level names Connection, Content-Length, Expect, Keep-Alive, TE, Trailer, Transfer-Encoding and Upgrade (v0.23.7+) — you cannot forge a system header. |
filters | object | no | Optional pre-dispatch filter (see Filter events before delivery). Omit or set null to fire on every subscribed event. |
retryCount | integer | no | Total delivery attempts, 0–5. Defaults to 3, meaning one attempt plus two retries. 0 and 1 both mean a single attempt with no retry. |
The response (201 Created) echoes the saved webhook. Note that secret and headers are intentionally absent:
{
"id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
"sessionId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"url": "https://your-server.com/webhook",
"events": ["message.received", "session.status"],
"filters": null,
"active": true,
"retryCount": 3,
"lastTriggeredAt": null,
"createdAt": "2026-06-25T10:00:00.000Z",
"updatedAt": "2026-06-25T10:00:00.000Z"
}
Save the id — you need it to get, update, test, or delete the webhook.
A session can hold at most WEBHOOK_MAX_PER_SESSION webhooks (default 16). A new registration above the cap is rejected with 400; webhooks that already exceed the cap are grandfathered — they keep working and are not deleted. Set the variable to 0 for no cap.
List, update, test, and delete
All management routes are scoped to a session, so one session cannot read or act on another session's webhooks by id — a wrong-session id resolves to 404.
| Action | Method + path | Role |
|---|---|---|
| List for a session | GET /api/sessions/{sessionId}/webhooks | operator |
| List across your key's sessions | GET /api/webhooks | operator |
| List failed deliveries | GET /api/webhooks/delivery-failures | admin |
| Get one | GET /api/sessions/{sessionId}/webhooks/{id} | operator |
| Update | PUT /api/sessions/{sessionId}/webhooks/{id} | operator |
| Send a test delivery | POST /api/sessions/{sessionId}/webhooks/{id}/test | operator |
| Delete | DELETE /api/sessions/{sessionId}/webhooks/{id} | operator |
Cross-session diagnostics
Two routes sit outside the per-session tree and answer questions about every webhook at once.
GET /api/webhooks returns every webhook the calling key can see as a bare array, newest first, with limit (1–1000, default 1000) and offset for paging. A session-scoped key sees only the webhooks of its allowed sessions; an admin or otherwise unscoped key sees all. Each entry is the same shape a create returns — secret and headers stay write-only here too.
GET /api/webhooks/delivery-failures lists deliveries that exhausted their retry budget and deliveries not sent (attempts: 0, including overflow, oversize and shutdown refusals). It requires an admin key; operator keys get 403. Results are constrained by allowedSessions; chat-restricted keys are refused. A zero-attempt row may still be pending in the outbox, so this list is not proof that an event will never be delivered.
curl -H "X-API-Key: $ADMIN_API_KEY" \
"$BASE/webhooks/delivery-failures?sessionId=$SESSION&limit=20"
| Query parameter | Notes |
|---|---|
sessionId | Narrow to one session. A value outside the key's allowedSessions returns [] rather than an error, so the route is not an existence oracle for other sessions. |
limit | 1–1000, default 1000. |
offset | Records to skip, default 0. An offset of 2^63 or more answers an empty page (v0.26.0+; it answered 500 before), here and on GET /api/webhooks. |
Response 200 — a bare array ordered by createdAt descending:
[
{
"id": "8c0b1f2e-3d4a-5b6c-7d8e-9f0a1b2c3d4e",
"webhookId": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
"sessionId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"event": "message.received",
"url": "https://your-server.com/webhook",
"idempotencyKey": "msg_8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a_true_628123456789@c.us_3EB0ABC123_f1e2d3c4-b5a6-7890-1234-567890abcdef",
"deliveryId": "dlv_0f8c1a2b-3c4d-5e6f-7a8b-9c0d1e2f3a4b",
"attempts": 3,
"lastStatusCode": 502,
"lastError": "HTTP 502: Bad Gateway",
"createdAt": "2026-06-25T11:59:00.000Z",
"replayable": false
}
]
lastStatusCode is null when the failure was a network or timeout error rather than a non-2xx response. Since v0.20.0 the lastError text redacts the target's host:port. idempotencyKey and deliveryId let you correlate a lost event against your own receiver logs. Rows older than WEBHOOK_FAILURE_RETENTION_DAYS (default 90; set it to 0 or less to keep everything) are pruned daily.
replayable reports whether a terminal row (attempts > 0) still holds retained event data and its webhook still exists (since v0.27.0 a row whose webhook was deleted reads replayable: false); the data itself is never returned. WEBHOOK_FAILURE_PAYLOAD_RETENTION_HOURS=0 (the default) retains none, so no row can be manually redriven. With a positive value, terminal failures recorded during that setting remain replayable until their retention window expires or their webhook is deleted. Zero-attempt rows belong to automatic outbox recovery, not manual redrive. Oversize or preflight-failed first dispatches are final rather than automatically replayed.
Redrive retained failures (v0.25.0+)
An admin key can call POST /api/webhooks/delivery-failures/redrive after fixing a receiver. Every body field is optional:
| Field | Limit |
|---|---|
sessionId | String, at most 128 characters; narrows within the key's session scope. |
webhookId | String, at most 128 characters. |
ids | At most 500 failure-row IDs, each at most 128 characters. |
limit | Integer 1-500, default 100. |
curl -X POST "$BASE/webhooks/delivery-failures/redrive" \
-H "X-API-Key: $ADMIN_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "sessionId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a", "limit": 20 }'
{ "redriven": 2, "delivered": 2, "enqueued": 0, "failed": 0, "skipped": 0, "remaining": 0 }
The call selects eligible rows with the fewest attempts, then oldest first. Each gets one direct POST, even with queue delivery enabled; enqueued is always zero and redriven equals delivered. It reuses the original idempotency key and runs webhook:before hooks again against retained pre-hook data. Success removes the failure and closes any pending outbox copy; failure raises its attempt count. A sweep already replaying that event can still deliver another POST with the same key.
Missing, disabled, unsubscribed or reassigned webhooks are excluded before the limit; a webhook subscribed only through "*" is not subscribed to message.receipt. skipped counts selected rows cancelled by a hook or invalidated during the call. Since v0.26.0 a row cancelled during its replay also has its attempt count raised, which ranks it behind untried rows, so it no longer heads every batch; it keeps its retained data. remaining counts eligible rows in the same requested scope, so resolve persistent errors before calling again. A client timeout does not cancel the batch. Shutdown stops at the next row and bounds running replays by WEBHOOK_SHUTDOWN_DRAIN_MS; untouched rows stay for a later call.
Update a webhook
PUT accepts the same fields as create, plus active to enable or disable delivery without deleting the webhook. Every field is optional — send only what changes. Pausing a webhook stops dispatch immediately:
curl -X PUT "$BASE/sessions/$SESSION/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "active": false }'
The response (200 OK) is the updated webhook in the same shape as create.
A delivery already waiting in the queue (QUEUE_ENABLED=true, v0.23.6+), or between retries on the direct path that the queue-off default uses (v0.24.0+), follows the webhook as it stands when each attempt runs. After a url, headers or secret change it goes to the new URL with the new headers and the new secret. Once the webhook is deleted, disabled, or no longer subscribed to that event, the delivery is dropped: no further retries and no delivery-failure row. The drop is logged at warn level with action=webhook_skipped_stale and the delivery's webhookId, event, deliveryId and idempotencyKey. It fires no webhook:error hook, and on the queued path the queue dashboard (/api/admin/queues) lists the job as completed, not failed, with success: false in its result, until completed-job retention (one hour or the latest 1000 jobs, applied as later jobs complete) removes it. A filters change does not reach deliveries already queued or in retry. A retryCount change does not reach a queued delivery, which keeps the attempt count it was queued with, but a direct delivery reads the current retryCount before each further retry. Earlier releases sent every queued attempt to the URL, headers and secret captured when the event was queued, even after the webhook was disabled or deleted, and before v0.24.0 direct retries did the same with the webhook as it stood at dispatch.
Test a webhook
Fire a synthetic delivery to confirm your endpoint is reachable and your signature check works. The test sends a payload with event: "test" and reports the outcome:
curl -X POST "$BASE/sessions/$SESSION/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef/test" \
-H "X-API-Key: $API_KEY"
{ "success": true, "statusCode": 200 }
On failure, success is false and error carries the reason (for example a timeout, a refused connection, or a 3xx redirect refused by the SSRF guard).
Delete a webhook
curl -X DELETE "$BASE/sessions/$SESSION/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
-H "X-API-Key: $API_KEY" -i
A successful delete returns 204 No Content with an empty body.
Since v0.31.0 a successful create, update or delete writes a webhook_created, webhook_updated or webhook_deleted row to the audit log (GET /api/audit, admin key) with the acting API key, the session, the webhook id, the URL host, the events and the active flag. An update row also names the fields that changed and, when the URL changed, the previous host; an update that changes nothing writes no row. The secret, the headers, the filters and the URL's user name, path and query are never recorded.
Event catalog
A webhook fires for an event when its events array contains the event name or "*". The one exception is message.receipt (v0.26.0+): "*" does not cover it, because it fires once per recipient and would multiply the traffic of every catch-all webhook, so a webhook receives it only when it names it. These are the events OpenWA emits:
| Event | Fires when |
|---|---|
message.received | An inbound message arrives. Since v0.28.0 whatsapp-web.js drops WhatsApp system notices (e2e_notification, notification_template, broadcast_notification) instead of delivering them as empty unknown messages. Since v0.30.2 it also drops an entry of a kind the library does not list that carries neither text nor media, and since v0.30.3 the header of an album (its photos and videos arrive as messages of their own, as on Baileys). On Baileys, since v0.30.2, a message that decrypts only in part and is left with no content is dropped too, so the redelivery that carries the content is not skipped as a duplicate. |
message.sent | An outbound message is sent from this session. |
message.ack | A delivery or read receipt updates an outbound message the account sent (since v0.27.0 reading a received message on the phone no longer fires message.ack or moves its stored status to read, and since v0.28.0 Baileys also fires delivered and read on outbound group messages once every current non-sender group member has received or read the message, using the cached group roster when available). |
message.receipt | One recipient receives, reads or plays a group or status message the account sent (v0.26.0+, Baileys only). Opt-in: named explicitly, never delivered through "*". See Receipt payloads. |
message.failed | A receipt resolves to failed. |
message.revoked | A message is deleted or recalled. Since v0.28.0 Baileys ignores a non-admin group member's attempt to delete another member's message instead of marking the message revoked and emitting message.revoked. |
message.edited | A message's text, or a media message's caption, is edited (v0.9.0+; both engines). The payload carries the new text and a hasMedia flag, never replacement media: WhatsApp cannot edit the attachment itself. |
message.reaction | A reaction is added, changed, or removed. Since v0.23.6, on Baileys, a reaction the account makes from its phone in a one-to-one chat carries the account's own id in senderId. Earlier releases put the contact's id there, so the account's reaction replaced the contact's entry in the reactions snapshot, and removing it deleted that entry. |
status.received | A contact's Status (Story) is received. Since v0.30.2 this includes a status that WhatsApp delivers to some Baileys accounts as a top-level <status> stanza, which earlier releases did not store or announce. |
session.qr | A new pairing QR is generated. |
session.authenticated | The session pairs and is ready. |
session.disconnected | The session disconnects. |
session.status | The session status transitions. Since v0.23.6 a stop, logout or force-kill announces disconnected only after the engine is released, so a session read on that event already reports engineLoaded: false. Earlier releases could announce it while the engine was still shutting down, which on whatsapp-web.js lasted as long as Chromium took to close. |
session.reconnect_loop | A session is stuck in a reconnect loop; fires once per 5 consecutive scheduled attempts (v0.10.0+). |
session.restriction | WhatsApp imposes (or lifts) an account restriction on the session (v0.14.0+, including kind: "passkey_required" with code: "passkey_prologue_request" when WhatsApp asks for a passkey during Baileys linking since v0.30.0). |
group.join | A participant joins a group the session belongs to. Since v0.23.6 Baileys also fires it when the session itself is added to or joins a group, as whatsapp-web.js already did. On Baileys that event's participantIds holds only the session's own id, not the members added with it. A group the session creates itself fires none. |
group.leave | A participant leaves a group the session belongs to. |
group.update | A group's metadata changes (subject, description, settings). A participant joining or leaving is group.join or group.leave instead, and an admin promotion or demotion produces no event at all, so do not wait on this one for roster activity. |
group.join_request | Someone requests to join a group the session administers (v0.15.0+). Fires only when the group has admin-approval enabled. |
event.response | A guest RSVPs to a WhatsApp event invitation (v0.25.0+, Baileys only). See RSVP payloads. |
poll.vote | A voter changes their selection on a poll (v0.26.0+; on Baileys since v0.30.2). See Poll vote payloads. |
presence.update | A subscribed contact's presence changes (online/offline/typing) (v0.14.0+). Baileys only. |
call.received | An incoming WhatsApp call is detected. Fires on both engines, but is not reliable on whatsapp-web.js (see below). |
call.accepted | An incoming call is picked up (v0.14.0+). Baileys only. |
call.rejected | An incoming call is declined (v0.14.0+). Baileys only. |
call.missed | An incoming call rings out (v0.14.0+). Baileys only. |
Six of these have no producer on the whatsapp-web.js engine: presence.update, event.response, message.receipt and the three call outcomes. Subscribing to an event the engine cannot produce is accepted and then simply never fires. presence.update at least announces itself, its prerequisite, POST /api/sessions/{sessionId}/presence/subscribe, answers 501 on that engine, while the three call outcomes give no signal at all, because whatsapp-web.js sees a call ring but never learns how it ended.
call.received does have a producer on whatsapp-web.js, but not a dependable one: the library detects a ringing call through a hook it installs into the WhatsApp Web page, and a WhatsApp Web build can leave that hook out while messages keep flowing, so the event can stop firing while the session looks healthy. Since v0.23.6 a session whose page visibly lacks the hook logs a call_hook_missing warning when it reaches ready; an inconclusive check stays silent, so no warning is not a guarantee. For call automation you can rely on, run the gateway with ENGINE_TYPE=baileys.
Since v0.23.6 a Baileys session that reconnects after an outage also dispatches what WhatsApp queued while it was down: message.received for inbound messages, message.sent for messages the account sent from its phone in that window, and the reactions, edits and revokes from the same window. Earlier releases dropped all of them. Expect a burst of older events right after a reconnect. On message.received and message.sent, data.timestamp is the message's original time; the envelope timestamp is when the event was dispatched.
Delivery payload
Every delivery is a POST with this JSON body:
{
"event": "message.received",
"timestamp": "2026-02-02T10:00:00.000Z",
"sessionId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"idempotencyKey": "msg_8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a_true_628123456789@c.us_3EB0ABC123_f1e2d3c4-b5a6-7890-1234-567890abcdef",
"deliveryId": "dlv_550e8400-e29b-41d4-a716-446655440000",
"data": {
"id": "true_628123456789@c.us_3EB0ABC123",
"from": "628123456789@c.us",
"to": "628987654321@c.us",
"chatId": "628123456789@c.us",
"body": "Hello from OpenWA!",
"type": "text",
"timestamp": 1719312000,
"fromMe": false,
"isGroup": false,
"kind": "individual",
"author": "628123456789@c.us"
}
}
event, timestamp, sessionId, idempotencyKey, and deliveryId are always present. For message.received, message.sent, and message.revoked the key is composed <prefix>_<sessionId>_<messageId>_<webhookId>; other events put their own fields between the prefix and the webhook id (message.ack and message.failed add the delivery status, message.receipt adds the recipient and the status, poll.vote adds the poll, the voter, the time of the change and a hash of the selection, session.status adds the new status and an occurrence id). A message whose id the engine could not read (an empty id on whatsapp-web.js) has no message id to put there, so since v0.31.0 its key carries an occurrence id minted once per dispatch and reused by every retry: each such event is its own event, where they all shared one key and a receiver that deduplicated on it kept only the first. Every key ends with the webhook's own id, so two subscriptions to the same event cannot collide at your dedup boundary, which also means the same message delivered to two webhooks carries two different keys. Treat the key as opaque and compare it whole. data holds the event-specific payload — for message events that is the message object shown above. For session.reconnect_loop, data is { "sessionId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a", "attempts": 5, "nextDelayMs": 300000 }: the consecutive attempt count and the delay before the next scheduled retry. The HMAC signature, sent only when the webhook has a secret, is not in the body; it rides in the X-OpenWA-Signature header.
Events that can repeat with identical content (message.edited, message.reaction, presence.update, every session.* event except session.qr, and the group.* events) carry an occurrence id in their key. Since v0.26.0 it is a random id minted once per dispatch and reused by every retry of it, so two occurrences in the same millisecond no longer share a key. Earlier releases put an ISO timestamp in that position; a receiver that read a time out of the key must dedupe on the whole key instead.
Since v0.25.0 message.ack and message.failed include data.chatId when it can be resolved. This lets webhook chatId and kind filters scope delivery/read failures to a chat. Handle older retained payloads that lack it.
Poll creation messages carry data.poll: { name, options, allowMultipleAnswers } in v0.25.0, alongside the poll question in body; persisted rows store it as metadata.poll. Since v0.26.0 an inbound poll is cut to 32 options, and the question and each option to 1024 characters, on both engines; WhatsApp's own limits are far lower, so nothing a client can send is cut. Votes on a poll arrive as poll.vote on both engines (on Baileys since v0.30.2).
Since v0.29.1 message.received and message.sent on both engines carry data.isForwarded: true when WhatsApp marks the message as forwarded, together with data.forwardingScore (how many times it has been forwarded) when the engine reports a positive value. Both fields are absent on non-forwarded messages (so a receiver never sees false), and both are stripped if the message is later revoked. Stored-message responses (GET /api/sessions/{sessionId}/messages) do not carry them; the live chat-history route (GET /api/sessions/{sessionId}/messages/{chatId}/history, whatsapp-web.js only) does.
RSVP payloads
event.response has this data shape on Baileys:
{
"sessionId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"eventMessageId": "3EB0EVENT",
"chatId": "120363021234567890@g.us",
"responderId": "628123456789@c.us",
"fromMe": false,
"response": "going",
"extraGuestCount": 1,
"eventName": "Game night",
"responseMessageId": "3EB0ANSWER",
"timestamp": 1792022400,
"contact": { "name": "Ada", "pushName": "Ada" }
}
response is going, not_going, maybe or unknown. Optional fields are extraGuestCount, eventName and contact (with name and/or pushName when known). A changed answer has a new responseMessageId; keep the latest guest-clock timestamp per responder, rather than using delivery order. Second-resolution timestamps cannot order two answers in the same second. eventName is the original name, not a later rename.
Only events still held in the Baileys message store can be decrypted. Events from before linking, evicted past BAILEYS_MESSAGE_STORE_LIMIT, or received from a contact in a disappearing-messages chat while STORE_EPHEMERAL_MESSAGES=false (since v0.31.0) yield no RSVP. In a one-to-one chat an event creator's own answer cannot be decrypted. Offline answers replay after reconnect. Since v0.31.0 answers to one event that arrive in the same Baileys buffer window are each reported; earlier releases reported only the last one, even across different guests. whatsapp-web.js accepts the subscription and never emits it. Webhook filter conditions do not narrow this event; check chatId in the receiver. Its base idempotency key is rsvp_<sessionId>_<responseMessageId>, salted with the webhook ID as usual.
Poll vote payloads
poll.vote (v0.26.0+; on Baileys since v0.30.2) reports each change of a voter's selection on a poll, sent with send-poll or from the phone. It has the same fields on both engines; the example is from whatsapp-web.js, where pollMessageId is the serialized message id, while on Baileys it is the bare id of the poll's creation message, such as 3EB0POLL:
{
"sessionId": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"pollMessageId": "true_628123456789@c.us_3EB0POLL",
"chatId": "628123456789@c.us",
"voterId": "628123456789@c.us",
"selectedOptions": ["Done"],
"pollName": "Did you finish the report?",
"timestamp": 1792022400,
"timestampMs": 1792022400123
}
selectedOptions is the voter's whole current selection as the option texts exactly as they appear on the poll, the strings vote-poll takes; it is not a delta, and [] means the voter cleared the vote. Since v0.30.2 selectedOptions is cut to 32 entries of 1024 characters each, and pollName to 1024 characters, on both engines, as an inbound poll already is. timestamp is the voter's clock in seconds and timestampMs the same instant in milliseconds. Changes within one second share timestamp, so keep the latest timestampMs per voterId rather than using delivery order. On whatsapp-web.js, pollName is present only when WhatsApp Web still holds the poll creation message; without it whatsapp-web.js cannot name the options, so a vote on such a poll is not reported (a cleared vote still is, with []). On Baileys a vote is read with the poll creation message in the session's message store (BAILEYS_MESSAGE_STORE_LIMIT), and votes cast before the store held the poll are not backfilled. A Baileys vote is not reported, a cleared vote included, when the store no longer holds its poll (a poll received in a disappearing-messages chat while STORE_EPHEMERAL_MESSAGES=false is never kept, since v0.31.0), when it does not authenticate against the poll, when it names an option the poll does not have, or when it is sent from a chat other than its poll's. The one exception to that last rule is a poll the account sent to a broadcast list, whose votes arrive in the voters' one-to-one chats and are reported only from there (since v0.31.0; before, a vote from a group, the list or the status chat was reported too). The gateway keeps no vote counts: tally them from these events. Webhook filter conditions do not narrow this event; check chatId in the receiver. Its base idempotency key is vote_<sessionId>_<pollMessageId>_<voterId>_<timestampMs>_<hash of selectedOptions>, salted with the webhook ID as usual.
Receipt payloads
message.receipt (v0.26.0+) reports each recipient's receipt for a message the account sent to a group or to Status, and only on Baileys. One-to-one receipts keep arriving as message.ack. data has this shape:
{
"id": "3EB0ABC123",
"messageId": "3EB0ABC123",
"chatId": "120363021234567890@g.us",
"participant": "628123456789@c.us",
"status": "read",
"timestamp": 1792022400
}
status is delivered, read or played, with one event per recipient and status; timestamp is epoch seconds. Receipts from the account's own linked devices are not reported, and nothing is stored: the gateway forwards the event as it arrives. On Baileys 7.0.0-rc14, the release v0.26.0 ships, a voice note that was played reports read. Webhook chatId and kind conditions can scope the event to a chat; it has no sender, body or type. Its base idempotency key is receipt_<sessionId>_<messageId>_<participant>_<status>, salted with the webhook ID as usual.
A message to a group of 1,000 members can produce about 2,000 receipts, in bursts. Each webhook that names message.receipt has a queue of its own in front of the shared dispatch pool: a quarter of WEBHOOK_DISPATCH_CONCURRENCY deliveries run at once, shared by the session's receipt webhooks, up to three quarters of WEBHOOK_DISPATCH_MAX_QUEUED receipts wait for each webhook, and any further receipt is dropped for that webhook. A dropped receipt leaves no outbox or failure row, is never replayed, and is counted once per webhook in openwa_webhook_delivery_failures_total; the gateway logs webhook_opt_in_dropping at warn level when a webhook starts dropping and webhook_opt_in_dropped with the count once its queue has drained. A session never runs more than that quarter of receipt deliveries at once, however many of its webhooks name the event. Receipts still waiting at shutdown are dropped without being counted. Treat the event as best effort.
Media in the payload
For message events with media, data.media.data carries the file as inline base64 only up to WEBHOOK_MEDIA_INLINE_MAX_BYTES (default 1 MiB, measured on the decoded bytes). Above that, the media travels as the omitted marker — the same shape as an undownloaded inbound media item:
{ "mimetype": "image/jpeg", "omitted": true, "sizeBytes": 1572864 }
A receiver that expects media.data to always hold base64 must handle the marker instead: fetch the media when you need it, or raise the caps. The two caps compound: WEBHOOK_MAX_PAYLOAD_BYTES is measured on the serialized JSON body after WEBHOOK_MEDIA_INLINE_MAX_BYTES has been applied, and base64 inflates media by a third, so at the shipped defaults (1 MiB each) media above roughly 768 KiB of decoded bytes already reaches you as the marker. With the payload cap left at its default, raising the inline cap alone changes nothing, because the payload gate then sheds the media anyway: raise both, keeping the payload cap at least 4/3 of the inline cap plus room for the rest of the event, for example WEBHOOK_MEDIA_INLINE_MAX_BYTES=5242880 with WEBHOOK_MAX_PAYLOAD_BYTES=7340032. Set the inline cap to 0 to never inline media.
Fetch it from the per-message media route rather than the message list. The list carries its own inline budget (MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES) and honours inlineMedia=false, so it can hand you the very same omitted marker; the per-message route serves the bytes.
The payload-size gate in How delivery works reuses this marker: an oversized body sheds its inline media before enqueue, so the event is delivered as a marker rather than dropped. Since v0.21.0 the same cap and marker also bound the message.received and message.sent events broadcast on the Socket.IO channel: a large blob is shed to the marker instead of being broadcast in full to every subscribed socket.
Delivery headers
| Header | Meaning |
|---|---|
X-OpenWA-Event | The event name (mirrors event in the body). |
X-OpenWA-Idempotency-Key | Content-derived key, stable across retries — deduplicate on this. |
X-OpenWA-Delivery-Id | Fresh dlv_<uuid> per delivery — for tracing, not deduplication. |
X-OpenWA-Retry-Count | Attempt number; 0 is the first attempt. |
X-OpenWA-Signature | sha256=<hex> HMAC — present only when the webhook has a secret. |
User-Agent | OpenWA-Webhook/1.0.0. |
The webhook:before plugin hook can transform data, but event, sessionId, and timestamp are re-asserted to the server's values after the hook runs — the delivered body, signed when the webhook has a secret, always matches the X-OpenWA-* headers. Since v0.23.6 a hook result without a plain-object payload (a primitive, an array, null, or no payload at all) is skipped: the event goes out with the last usable payload, an earlier hook's rewrite included. Before, a string, number, or boolean payload failed the delivery, an array was sent as the whole body without event, sessionId, or timestamp, and a null or missing payload in a returned data, or a data of null, sent the original payload, dropping an earlier hook's returned rewrite. A result with no data at all, such as { continue: true }, left the previous payload in place, as it still does.
Design for at-least-once delivery
Delivery is at-least-once, not exactly-once. The WhatsApp engine can re-fire an event, and a failed delivery is retried, so the same logical event can reach your endpoint more than once.
Make your handler idempotent by deduplicating on X-OpenWA-Idempotency-Key. The key is content-derived: every retry of the same event reuses the same key, while a distinct occurrence (a new message, a fresh session transition) gets a distinct key. Record processed keys and skip a key you have already handled.
A delivery that returns non-2xx, times out (default 10 seconds), or fails at the network level is retried until it has been attempted retryCount times in total, so the default 3 gives your endpoint one attempt plus two retries, not four POSTs. Backoff is exponential, doubling WEBHOOK_RETRY_DELAY with each retry (see How delivery works). Each retry carries the same X-OpenWA-Idempotency-Key and an incremented X-OpenWA-Retry-Count. Return 2xx only once you have safely accepted the event.
Once your endpoint answers 2xx, the delivery is successful. A bookkeeping failure on OpenWA's side afterwards (for example, recording lastTriggeredAt) is logged but does not flip the outcome — earlier releases could re-POST such a delivery and file a dead-letter row for an event you had already received.
The delivery is also durable across a hard crash (v0.23.0+): it is recorded before it is attempted, and a bounded sweep replays whatever a crash stranded, under the same stored X-OpenWA-Idempotency-Key. A replay after a restart is therefore the same logical event, one more reason the deduplication above is not optional. Settled delivery records are pruned after WEBHOOK_OUTBOX_RETENTION_DAYS (default 7 days); a record that can still be replayed is never pruned on age. Since v0.26.0, once a replay to a webhook has failed in a sweep, that webhook's further stranded rows in the same sweep get one direct attempt each, so an unreachable receiver does not hold the sweep for a full retry schedule per row; the next sweep is their retry. A stranded row whose stored payload does not parse (imported or hand-edited history on SQLite) is logged as webhook_outbox_row_unreadable and left untouched, and the rows behind it are replayed. Since v0.31.0 the sweep sets such a row aside for an hour (it remembers up to 1000 of them, and a restart forgets them), where it read the row again and logged it on every pass.
Verify the HMAC signature
When a webhook has a secret, every delivery includes:
X-OpenWA-Signature: sha256=<hex>
The hex is an HMAC-SHA256 over the exact raw request body bytes, keyed with your secret. To verify, recompute the HMAC over the raw body you received — not a re-serialized parse, which can reorder keys and break the comparison — and compare in constant time. Reject anything that does not match before processing the event.
const crypto = require('crypto');
const express = require('express');
const app = express();
const WEBHOOK_SECRET = process.env.OPENWA_WEBHOOK_SECRET;
function verifyOpenWASignature(rawBody, signature, secret) {
if (!signature || !secret) return false;
const expected =
'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
const received = Buffer.from(signature);
const computed = Buffer.from(expected);
if (received.length !== computed.length) return false;
return crypto.timingSafeEqual(received, computed);
}
// express.raw keeps req.body as the exact bytes received, so the HMAC matches.
app.post('/openwa/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.header('X-OpenWA-Signature');
if (!verifyOpenWASignature(req.body, signature, WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
// Deduplicate before doing real work.
const key = req.header('X-OpenWA-Idempotency-Key');
// if (alreadyProcessed(key)) return res.status(200).send('OK');
// Handle event.data here, then acknowledge.
return res.status(200).send('OK');
});
app.listen(3000);
- Verify
X-OpenWA-Signaturebefore trusting or parsing the body. - Compute the HMAC over the exact raw body bytes your server received.
- Compare in constant time.
- Return
401for an invalid signature, and2xxonly once the event is safely accepted. - Deduplicate on
X-OpenWA-Idempotency-Key.
If no secret is configured, the X-OpenWA-Signature header is omitted entirely and you cannot tell a real delivery from a forged one. Always set a long, random secret for production webhooks.
Filter events before delivery
A webhook can carry a filters object so OpenWA only delivers events that match — keeping noise off your endpoint and saving you the verification round-trip. Filters are evaluated before dispatch. All conditions are combined with AND: every condition must match for the webhook to fire. Omitting filters (or setting it to null) delivers every subscribed event.
{
"url": "https://your-server.com/webhook",
"events": ["message.received"],
"filters": {
"conditions": [
{ "field": "sender", "operator": "is", "value": ["628123456789@c.us"] },
{ "field": "body", "operator": "contains", "value": "invoice" }
]
}
}
Filters apply to message events only in this release. A condition on a non-message event is skipped, so the webhook still fires for those events.
Filter fields are resolved out of the event's own payload, and not every message event carries every field. On an absent field a condition's result is fixed: an is condition on an id or type field (sender, recipient, chatId, mentions, type, kind), a boolean compared with true, and a body condition with a non-empty value cannot match and drop the event, while an isNot condition always passes, and so does a boolean compared with false, because an absent boolean reads as false. An absent body reads as an empty string, so a body condition with an empty value (equals "", contains "") always passes too. Since every condition must match, only a failing one settles the event; a passing one leaves the outcome to the filter's other conditions. message.ack and message.failed carry { id, messageId, status, ack, chatId? } and message.reaction carries { messageId, chatId, reaction, senderId }, plus a reactions map holding the post-apply snapshot of every reaction on the message whenever that message is in the store. None of the three has a sender or a body, so a sender is condition suppresses all of them, while a sender isNot condition passes all of them and leaves the rest of the filter to decide: a type is condition next to it still drops all three, which carry no type. Since v0.25.0 receipts include chatId when resolved, so chatId and derived kind filters can scope them. Earlier retained receipts without it still have the absent-field behavior. message.receipt (v0.26.0+) carries { id, messageId, chatId, participant, status, timestamp }, with no sender, body or type, so only chatId and the kind derived from it can scope it. poll.vote is outside the message family and no condition narrows it.
Scope the subscription with events rather than relying on a filter to be ignored on the events it cannot read.
Each condition is { field, operator, value, caseSensitive? }. The allowed operators and value type depend on the field:
| Field | Type | Operators | value |
|---|---|---|---|
sender | contact id | is, isNot | array of ids or bare phone numbers |
recipient | contact id | is, isNot | array of ids or bare phone numbers |
chatId | chat id | is, isNot | array of chat ids; a group as its full <id>@g.us (v0.23.6+) |
mentions | contact id list | is, isNot | array of ids — matches if any mentioned id is in the list |
type | message type | is, isNot | array of text, image, video, audio, voice, document, sticker, location, contact, poll, call, revoked, order, product, masked, unknown (order and product v0.23.5+) |
body | text | contains, equals | a string; set "caseSensitive": true to match case |
isGroup | boolean | is | true or false |
kind | chat kind | is, isNot | array of individual, group, channel, status, broadcast, unknown (v0.23.4+) |
fromMe | boolean | is | true or false |
hasMedia | boolean | is | true or false |
Id matching is dialect-aware: a bare phone number, a @c.us JID, and the underlying @lid for the same contact all match each other, so "628123456789" and "628123456789@c.us" are equivalent. A phone and an @lid match only through a pair an engine has reported to the gateway (v0.26.0+): a mapping inherited from an older release, including one restored from a backup made on an older release, counts as unknown until an engine reports it again, and two different @lids never match through a shared phone. Since v0.23.6 an @lid written in the condition itself goes through the same resolution as the one in the event, so a condition naming a contact or chat by its @lid keeps matching once the gateway learns that identity's phone number. In earlier releases that moment silently flipped the condition: an isNot exclusion started delivering the chat it was meant to keep out, and an is inclusion stopped delivering, while the filter still read correctly in the dashboard.
chatId (v0.23.6+) matches the conversation rather than a person, which makes it the field for scoping a webhook to specific groups or chats: in a group, sender is the participant who wrote, not the group. { "field": "chatId", "operator": "is", "value": ["120363000000000000@g.us"] } delivers only that group's messages. Write a group as its full <id>@g.us JID; bare digits are read as a phone number (<digits>@c.us) and match no group. message.ack and message.failed also support this filter when chatId is resolved in v0.25.0; a gateway older than v0.23.6 refuses a chatId condition on save as an unrecognized field.
kind is the full discriminator isGroup cannot be. Everything that is not a group collapses to isGroup: false, so a channel (newsletter), a status update and a broadcast list are indistinguishable from a one-to-one chat there. Excluding channel traffic while keeping direct messages needs { "field": "kind", "operator": "isNot", "value": ["channel"] }. The value is read from the event payload when it carries one, and derived from chatId otherwise, which is what makes it work on the message.edited, message.reaction and message.revoked events that carry only the chat id. isGroup is unchanged and still supported.
hasMedia widened in v0.23.4 without any change to the filter itself: a message whose media download failed now keeps its media envelope with omitted: true instead of losing the field, so it matches hasMedia: true where it used to be skipped. A rule written to catch every media message catches more of them than before.
type gained order and product in v0.23.5: a cart the customer placed and a shared product card used to arrive as unknown, so a rule written on unknown stops catching them.
On Baileys, since v0.23.6, a WhatsApp Business list prompt and a contact's reply to a button, template quick-reply or list row arrive as text instead of unknown. A filter on unknown stops catching them, and one on text starts to. A list reply's body now holds the row title and a list prompt's body its description (else its title); both arrived empty before, so a body condition can match them as well. A native-flow reply with no body text of its own, whose parameters carry a button label next to its id, now takes that label as body, where it arrived empty before. The same release adds two Baileys-only fields to the message object, neither of them a filter field: a prompt that offers choices carries buttons: [{ id, text }] (URL and call buttons are left out), and a tap carries button: { id, text? }, which is left out when WhatsApp sent no id. See Inbound message types and Answer a WhatsApp Business prompt.
A filter is validated on save. An unknown field, an operator the field does not support, a wrong value type, more than 20 conditions, more than 100 values in one condition, an id entry over 128 characters on sender, recipient, chatId, or mentions (v0.28.0+), or a body string over 1000 characters returns 400 with a field-level message. poll became a valid type value in v0.23.2; before that the dashboard offered it in its picker while the save was refused as invalid, so a rule or webhook built on it on an older gateway never saved.
A suppressed delivery says so
A subscribed webhook that a filter drops used to leave no trace at all: the filter runs before dispatch, so nothing is delivered, no metric moves, and the delivery-failure list gets no row. Since v0.14.6 each suppression is logged at debug level, so a webhook that has gone quiet can be explained without guessing:
Webhook filters suppressed a delivery
action=webhook_filter_suppressed event=message.ack
subscribed=1 suppressed=1 payloadFields=ack,chatId,id,messageId,status
payloadFields is the alphabetically sorted list of fields the event's payload actually carried — usually the answer on its own, because the common cause is a condition naming a field that is not in that list. Set LOG_LEVEL=debug while investigating; the line is not emitted at the default level, since a filter suppressing an event is the normal outcome of a filter doing its job.
The log line changes nothing about matching: it only reports a suppression the filter had already decided.
The dashboard ships a condition builder for these filters, so you can compose and preview them without hand-writing the JSON.
Use the SDK
The @rmyndharis/openwa JavaScript SDK wraps the session-scoped webhook routes — create, list, get, update, test, and delete — and, since v0.14.6, the two cross-session routes as well. Pass the host as baseUrl (without /api — the SDK adds it):
import { OpenWAClient } from '@rmyndharis/openwa';
const client = new OpenWAClient({
baseUrl: 'http://localhost:2785',
apiKey: process.env.OPENWA_API_KEY,
});
const webhook = await client.webhooks.create('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', {
url: 'https://your-server.com/webhook',
events: ['message.received', 'session.status'],
secret: process.env.OPENWA_WEBHOOK_SECRET,
});
await client.webhooks.test('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', webhook.id);
await client.webhooks.update('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', webhook.id, { active: false });
// client.webhooks.list / get / delete are also available.
// Cross-session: every webhook the key can see, and the dead-letter log (admin key).
await client.webhooks.listAll({ limit: 100 });
await client.webhooks.deliveryFailures({ sessionId: '8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', limit: 20 });
Common errors
| Status | Cause | Fix |
|---|---|---|
400 Bad Request | URL is internal or SSRF-blocked, embeds credentials (user:pass@host, v0.19.0+), an invalid event name, a malformed filter, an unknown body field, or the session is at its webhook cap (WEBHOOK_MAX_PER_SESSION, default 16). | Use a public HTTPS URL with no credentials in it; check the message array for the offending field; delete a webhook before registering another. |
401 Unauthorized | Missing, invalid, expired or revoked X-API-Key. | Send a valid, active key. See Authentication. |
403 Forbidden | Since v0.24.0 a valid key outside its session/IP scope; also a key whose role is below operator, or below admin on the delivery-failure list or redrive route. Since v0.23.6, also a key restricted to selected chats (allowedChats), which every webhook route refuses. | Use an operator or admin key; use an admin key for the delivery-failure log; manage webhooks with a key that carries no chat allowlist. |
404 Not Found | The session or webhook id does not exist, or the webhook belongs to a different session. | Confirm both sessionId and the webhook id. |
429 Too Many Requests | Global rate limit exceeded. | Honor Retry-After and back off; releases before v0.23.6 send only the per-throttler Retry-After-* header. See Rate limiting. |
Your own endpoint must return 2xx to acknowledge a delivery. Anything else — including a 401 from your signature check — counts as a failure and is retried.
Next steps
- Authentication — issue the operator key these routes require.
- Sending messages — act on the events you receive.
- n8n integration — consume OpenWA webhooks in a no-code workflow.
- API reference — the full webhook endpoint schemas.