Skip to main content
Version: v0.31.0

Use the JavaScript/TypeScript SDK

Drive OpenWA from Node with the official @rmyndharis/openwa client: authenticate once, manage session lifecycle, send messages and media, branch on typed errors, and receive inbound events through webhooks. Every method maps to one REST endpoint, so what you learn here transfers directly to the API reference.

Prerequisites
  • OpenWA running and reachable (default http://localhost:2785/api). See Installation.
  • An API key for the X-API-Key header. See Authentication for how to obtain one.
  • The SDK installed: npm install @rmyndharis/openwa (Node 18+). See the SDK overview.

The Python and PHP SDKs expose the same resources and methods in their language's idiom (snake_case + dicts in Python, camelCase + arrays in PHP), so these recipes carry over. That convention covers method names only — the dict and array keys stay camelCase in both, exactly as they go on the wire, so a Python call reads client.chats.mute(session_id, {"chatId": ..., "muteUntil": ...}), never chat_id or mute_until.

Gateway and package versions

These examples target gateway v0.31.0 and released SDK 0.13.0. SDK 0.6.0 and later carry the gateway's message filters, chat last-message type, poll typing, webhook redrive, event.response typing and per-send idempotency arguments; SDK 0.5.1 and earlier do not, and the raw requests below are the way to call those routes from them. SDK 0.7.0 adds the message.receipt and poll.vote event names (gateway v0.26.0+), SDK 0.8.0 adds groups.setMemberLabel, search.search match, and customLinkPreview thumbnailUrl / thumbnailBase64 (gateway v0.27.0+), SDK 0.9.0 adds contacts.lid (getLid in Java, Contacts.Lid in Go, gateway v0.27.1+) and idempotency_key on Python's client.request(...), SDK 0.10.0 adds messages.receipts (getReceipts in Java, Messages.Receipts in Go, gateway v0.28.0+, whatsapp-web.js only), SDK 0.11.0 adds passkey_required on AccountRestrictionKind (gateway v0.30.0+) and isForwarded / forwardingScore on ChatHistoryMessage (gateway v0.29.1+), SDK 0.12.0 adds the linkPreview session config key (gateway v0.30.3+), and SDK 0.13.0 adds phone on the chat summary (gateway v0.31.0+) and a null secret on webhook updates in the JavaScript and Python types. On an older SDK, call a newer route via client.request(...). See the migration notes.

Construct the client​

Create one OpenWAClient and reuse it across requests (including in Java, where OpenWAClient is thread-safe and wraps an internal HttpClient connection pool). baseUrl and apiKey are required — the constructor throws synchronously if either is missing.

import { OpenWAClient } from '@rmyndharis/openwa';

const client = new OpenWAClient({
baseUrl: 'http://localhost:2785',
apiKey: process.env.OPENWA_API_KEY!,
});

const sessionId = '8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a'; // from POST /sessions, or the dashboard

Every session-scoped call on this page takes that sessionId — the server-generated UUID a session is addressed by. The session's name is a label you choose at creation time and the API never accepts it in place of the id.

The client sends X-API-Key on every request; you never set it per call. Pass baseUrl without the /api suffix — every SDK path already includes the /api prefix, so your baseUrl must not. In production, point baseUrl at your domain over TLS (for example https://wa.example.com); a path prefix such as /v1 behind a reverse proxy is preserved.

OptionTypeRequiredDefaultPurpose
baseUrlstringYes—Gateway base URL, e.g. http://localhost:2785. Trailing slash trimmed; path prefix kept.
apiKeystringYes—Sent as X-API-Key on every request.
timeoutMsnumberNo30000Per-request timeout in milliseconds.
defaultHeadersRecord<string,string>No{}Headers merged onto every request. The X-API-Key and JSON Content-Type always win.
fetchFetchLikeNoglobal fetchInjectable transport — the place to add retry or observability middleware.

Verify your API key​

Call auth() to confirm the key is valid and discover the role it resolves to. The role decides which write operations you may call.

const result = await client.auth();
console.log(result);
// { valid: true, role: 'operator', engineType: 'baileys', scoped: false }

SDK 0.7.0 types role as 'admin' | 'operator' | 'viewer' in JavaScript and Python; earlier versions type it as a plain string.

Any operation that creates or mutates server state requires an OPERATOR-level key — including sending any message (text, media, location, contact, reply, forward, react, delete, bulk), creating sessions and webhooks, cancelling a bulk batch, and group admin actions. A VIEWER key is read-only: it can call the plain GET reads (listing and fetching sessions, messages, contacts, groups) but nothing that sends or changes state. Some GET routes still need an OPERATOR key, among them the two whose payload is a credential for WhatsApp itself rather than data: a session's QR code, and, from v0.23.5, a group's invite code (groups.inviteCode). A VIEWER key calling a write, or one of those reads, throws OpenWAForbiddenError (HTTP 403). See Authentication for how keys, roles, and per-session scoping work.

Since v0.23.6 a key can carry allowedChats, an allowlist of groups and contacts. An operation naming a chat outside it answers 403, and routes without explicit chat-scope support are refused. The chat list filters before pagination from the same release; from gateway v0.24.0 the contact and group lists do too, labels.chats returns only allowed chats, and messages.list requires an explicit allowed chatId. SDK 0.5.1 already exposes that query: client.messages.list(sessionId, { chatId: '628123456789@c.us' }).

The open surface includes sends, message actions, history, reactions, and per-recipient delivery receipts (messages.receipts, gateway v0.28.0+ / SDK 0.10.0+), chats methods, single-contact reads and writes, group subject/description/picture/own-member-label changes and leave, chat-label assignments, and sessions.get. Forward checks both chats and bulk sends check every recipient. Gateway v0.25.0 also opens groups.get, getGroupSettings and updateGroupSettings for allowed groups (and v0.27.0 opens groups.setMemberLabel, added in SDK 0.8.0) and scopes built-in search before totals and pagination; plugin search remains forbidden. A quotedMessageId on an ordinary send is still forbidden: use reply, which resolves the quoted message inside the authorized chat.

Session discovery, auth(), message batch status/cancel, webhooks, status, channels, contact number checks and LID lookups (contacts.lid, gateway v0.27.1+ / SDK 0.9.0+), the label catalogue (labels.list, labels.get, labels.upsert and labels.delete), and group creation, joins, participant administration, membership requests and invite codes remain closed to chat-restricted keys. Health checks need no key. See Authentication for the role and scope rules.

Bring a session online​

A session is one WhatsApp connection. Before it can send anything it has to be created, started, and authenticated by scanning a QR code or entering a pairing code on the phone.

Every state-changing call here requires an OPERATOR-level key — create, start, stop, forceKill, getQrCode, and requestPairingCode. Only the plain GET reads (get, list) work with a VIEWER key.

// Create the session (OPERATOR key). The name is 3–50 chars, alphanumeric + hyphens.
const session = await client.sessions.create({ name: 'my-session' });

// Start it and bring the WhatsApp connection up. Every call after `create` takes
// the generated id, never the name — keep it from the create response.
await client.sessions.start(session.id);
Note

The name exists only to create the session and to keep it unique. Everything afterwards is addressed by the server-generated id, a UUID, and no route takes a name in its place. The session routes reject a name in the path as a non-UUID, and the routes that act through the engine fail the lookup as for a session that is not started (Session '<name>' is not active on the messages routes). Both answer 400, except the catalog routes and the status posts and delete, which report the same mistake as 404. webhooks.create answers 404 as well, and so does templates.create since v0.23.6 (it answered 500 before). Routes that only read stored rows never look the session up, so messages.list, status.list, templates.list and webhooks.list, among others, answer with an empty result rather than an error. The media routes do neither: they never check that the session exists, so with a name conversionStatus answers as usual and convertVoice and convertVideo convert as usual. Since v0.23.6 a url conversion leaves through the egress proxy of the session in the path, but a name finds no session, so the url is then fetched from the gateway's own address.

start resolves to a SessionResponse. Its status walks through created → initializing → qr_ready → authenticating → ready as the connection comes up.

{
"id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"name": "my-session",
"status": "qr_ready",
"phone": null,
"createdAt": "2026-06-26T10:00:00.000Z",
"updatedAt": "2026-06-26T10:00:05.000Z"
}

Authenticate with a QR code​

getQrCode returns the current code straight from the engine. qrCode is a PNG data URL — render it as an image for the user to scan.

const qr = await client.sessions.getQrCode(session.id);
console.log(qr);
// { qrCode: 'data:image/png;base64,iVBORw0KGgo...', status: 'qr_ready' }

The code rotates; re-fetch it if the user is slow. Once scanned, the session's status advances to ready. Poll client.sessions.get(session.id) until status === 'ready' before sending.

Authenticate with a pairing code​

For headless setups, request an 8-character pairing code instead of a QR. The user types it into WhatsApp under Link a device → Link with phone number. Request it only while the session reads qr_ready: before that the API answers 409 and the SDK throws OpenWAConflictError, and once a code has been accepted the same 409 answers until the session reaches ready. On the Baileys engine a socket that has begun closing answers it while status still reads qr_ready, for up to 30 s, so retry once before treating it as a bad state (since v0.23.3).

On whatsapp-web.js the gateway retries the request itself while WhatsApp Web reloads its QR page, and since v0.23.6 a request that runs out of attempts answers 503 (OpenWAServiceUnavailableError), where it answered 500 before. Four attempts of up to 15 s each, 3 s apart, can take over a minute, longer than the default timeoutMs of 30 s: when the attempts hang, the SDK throws OpenWATimeoutError before the 503 arrives, and the gateway keeps trying after the client has given up. Raise timeoutMs on the client that requests pairing codes to receive the gateway's answer. The 503 is retryable, but an attempt that timed out may still have reached WhatsApp, and a retry starts the linking flow again. On that engine, request a code only for a number you are prepared to re-link: a request for a number that already has a linked session has been observed to end with WhatsApp unlinking that device. If that session must stay up, link the new one by QR. Since v0.26.0 the gateway refuses a request on this engine with 409 (OpenWAConflictError), without asking WhatsApp, when the number is the stored phone of another session of this gateway: delete that session, or log it out while it runs, first. The gateway cannot see a link made on another gateway or only on the phone, so the caution above still holds for those.

const pairing = await client.sessions.requestPairingCode(session.id, {
phoneNumber: '628123456789', // digits only, international format
});
console.log(pairing);
// { pairingCode: 'ABCD1234', status: 'qr_ready' }

Stop a session​

await client.sessions.stop(session.id); // graceful disconnect

Use client.sessions.forceKill(session.id) only when a session is stuck and stop does not return. See the Sessions guide and First session for the full lifecycle.

Read and change a session's config​

getConfig reads the configuration a session is actually running with, and updateConfig patches it in place — no restart, no re-link, no second QR scan. Four keys are read: autoRejectCalls, maxReconnectAttempts (0–20), reconnectBaseDelay (1000–300000 ms), and linkPreview (a boolean; gateway v0.30.3+, SDK 0.12.0+). getConfig works with a VIEWER key; updateConfig needs an OPERATOR one.

const config = await client.sessions.getConfig(sessionId);
console.log(config);
// { autoRejectCalls: false, maxReconnectAttempts: null, reconnectBaseDelay: 5000, linkPreview: null }

await client.sessions.updateConfig(sessionId, { autoRejectCalls: true });

Both calls report the effective configuration, so maxReconnectAttempts: null on the way out means unlimited, not unset. autoRejectCalls is re-read on every incoming call and linkPreview on every send-text or send-template, so both apply immediately; the two reconnect settings are read once per start and apply from the next start.

autoRejectCalls works on Baileys only. A rejection sent by whatsapp-web.js does not stop the call ringing, so since v0.23.6 that engine logs each auto-reject as failed, where it used to log a rejection that had no effect. The reconnect settings bound the gateway's own reconnect: on Baileys the engine retries a transient drop by itself, from 1 s doubling to 60 s with no attempt cap, and neither setting applies to those retries.

linkPreview is the preview of a send-text or send-template that sets neither linkPreview nor customLinkPreview; a value in the request wins. false sends without a preview on both engines. true asks for one: whatsapp-web.js builds one by default, and on Baileys it makes the gateway fetch the first https:// link with a domain-name host in the text before the message is sent. null, read back or sent in an update, means the engine's own default: a preview on whatsapp-web.js, none on Baileys.

The update body has three states per field, not two: leave the key out and the value is untouched, send a value and it is set, send null and it is cleared back to the default. The null is not decoration — restoring maxReconnectAttempts to unlimited is the one thing no in-range number can express.

// Cap reconnects at 5, then later restore unlimited.
await client.sessions.updateConfig(sessionId, { maxReconnectAttempts: 5 });
await client.sessions.updateConfig(sessionId, { maxReconnectAttempts: null });
Go and Java need an explicit clear flag to send that null

Neither language can express the null case by leaving a field nil: Go's omitempty omits a nil pointer rather than writing null, and Gson drops nulls by default — so in both, an unset field sends nothing and the server leaves the value unchanged. Each carries a matching clear* flag, and a clear wins over a value set on the same field.

_, err := client.Sessions.UpdateConfig(ctx, sessionId, openwa.UpdateSessionConfigRequest{
ClearMaxReconnectAttempts: true, // sends {"maxReconnectAttempts": null}
})
client.sessions.updateConfig(sessionId,
UpdateSessionConfigRequest.builder()
.clearMaxReconnectAttempts()
.build());

ClearAutoRejectCalls / clearAutoRejectCalls(), ClearReconnectBaseDelay / clearReconnectBaseDelay() and, since SDK 0.12.0, ClearLinkPreview / clearLinkPreview() do the same for the other three fields. JavaScript, Python, and PHP send null directly — no flag involved.

The proxy body below has the same three states. SDK 0.5.1 and later expose UpdateSessionProxyRequest in Go with ClearProxyURL, which wins over ProxyURL when both are set. In Java pass new UpdateSessionProxyRequest(null) to clear the proxy; this request record is serialized with explicit nulls.

Read and change a session's proxy (v0.23.4+)​

Gateway v0.23.4 added GET and PATCH /api/sessions/{sessionId}/proxy. SDK 0.5.1 and later wrap them as sessions.getProxy and sessions.updateProxy. The GET never returns the URL: it reports whether a proxy is set, the host:port, the type derived from the scheme, and whether credentials are stored.

const proxy = await client.sessions.getProxy(sessionId);
// { enabled: true, proxyType: 'socks5', proxyHost: 'proxy.example.com:1080', hasCredentials: true }

await client.sessions.updateProxy(sessionId, { proxyUrl: 'socks5://user:pass@proxy.example.com:1080' });
await client.sessions.updateProxy(sessionId, { proxyUrl: null }); // clear it

The PATCH needs an admin key that is not session-scoped; a scoped key is refused with 403 whatever its role. Nothing restarts, so the change takes effect on the session's next start: stop and start the session to apply it now.

Write a literal % in the proxy credentials as %25. Since v0.23.6 a bare % that starts no valid escape is refused with 400, where it used to be stored and then fail every later start. From the same release the proxy also carries the gateway's own fetch of a media url you pass to a send, status, picture, or conversion route, and on Baileys the link preview of a text send, unless the operator sets SESSION_PROXY_URL_FETCH=false.

List calls are bounded-paginated

The list endpoints, sessions.list, messages list, chats, groups, and contacts, accept limit and offset query parameters. limit is capped server-side: sessions, groups, chats, and contacts at 1-1000 (default 1000), messages at 1-100 (default 50). A larger limit is clamped rather than refused, so a message list returns at most 100 rows however large the limit you send. Page through large result sets with offset rather than fetching everything in one call. sessions.list also takes name (v0.23.5+), an exact, case-sensitive lookup that returns an empty list when nothing matches; an empty value or a repeated name key is a 400. SDK 0.5.1 and later expose it as client.sessions.list({ name: 'my-session' }).

For message history, prefer after over offset (v0.23.4+). It takes the id of the previous page's last message and anchors the window to that row, so a message arriving mid-walk cannot shift the page and make you re-read or skip one; offset counts rows and still shifts. after replaces offset when both are sent, and a cursor naming no message in the session is a 400 rather than a silently empty page. The same call takes inlineMedia: false to drop every inline base64 payload while keeping each row's { omitted, sizeBytes } marker, which is usually what you want on a walk: the inline-media budget is spent per response, so every page pays it again. SDK 0.5.1 and later declare both options, so client.messages.list(sessionId, { after: lastId, inlineMedia: false }) works directly.

Filter stored messages (v0.25.0+)​

Gateway v0.25.0 adds since (inclusive) and until (exclusive) in epoch milliseconds, direction (incoming or outgoing), type, messageId, and orderBy (createdAt or timestamp). chatId, from, after, inlineMedia, limit and offset remain available. SDK 0.6.0 declares the new filters in JavaScript, Python, Java and Go, and unknownTimestampTotal in the response; PHP forwards these keys through messages->list(). SDK 0.5.1 and earlier have no declarations for them, so call the raw method there.

const page = await client.messages.list(sessionId, {
chatId: '628123456789@c.us',
direction: 'incoming',
type: 'poll',
since: Date.parse('2026-10-14T00:00:00Z'),
until: Date.parse('2026-10-15T00:00:00Z'),
orderBy: 'timestamp',
inlineMedia: false,
limit: 50,
});
console.log(page.total, page.unknownTimestampTotal);

timestamp ordering omits rows without a known message time. With a time bound or that ordering, unknownTimestampTotal counts unknown-time rows matching the other filters. Continue with the last row's id as after, preserving the filters and ordering. See Sending messages for the stored-message contract.

Chat lists can return optional lastMessageType; lastMessage remains preview text, not an object. Poll data can carry { name, options, allowMultipleAnswers } in message events, storage and live history, and since gateway v0.29.1 forwarded messages carry isForwarded: true and (when positive) forwardingScore in message events (message.received, message.sent) and live history (GET /api/sessions/{sessionId}/messages/{chatId}/history). SDK 0.6.0 declares the chat field and the live-history poll shape in JavaScript, Python, Java and Go, and SDK 0.11.0 declares isForwarded and forwardingScore on ChatHistoryMessage; on older SDKs use a local response type or raw decoded data.

Since gateway v0.31.0 a Baileys chat held under a privacy id (@lid) that has no saved, verified or push name lists name as "", where v0.30.3 listed the id's own digits, and carries phone, the digits to show, when the session can map the id. Title such a chat by phone, else by id. whatsapp-web.js lists no phone and lists an unnamed chat under its id. Every Baileys chat name is also trimmed, and a blank name of a chat not held under a privacy id lists the contact's name or the id's digits. SDK 0.13.0 declares phone as optional in the JavaScript, Python, Go and Java types; PHP returns decoded arrays.

Send messages​

Each send method takes the session id first, then a typed body. The methods that dispatch a message — sendText, the media senders, sendLocation, sendContact, reply, and forward — resolve to a MessageResponse: { messageId, timestamp }, where timestamp is a Unix time in seconds. The two that act on an existing message, react and delete, instead resolve to { success: boolean }.

const sent = await client.messages.sendText(sessionId, {
chatId: '628123456789@c.us',
text: 'Hello from OpenWA!', // max 4096 characters
});
console.log(sent);
// { messageId: 'true_628123456789@c.us_3EB0123456789', timestamp: 1706868000 }

chatId is a WhatsApp JID: <number>@c.us for an individual, <id>@g.us for a group. Since v0.26.0 a send or message-action chatId that is not localpart@host, such as a bare phone number, answers 400; earlier gateways passed it on to the engine. WhatsApp text formatting works inline: *bold*, _italic_, ~strikethrough~, and `monospace`.

Reply to or react to a specific message by its id:

// Reply, quoting an earlier message — returns a MessageResponse.
const replied = await client.messages.reply(sessionId, {
chatId: '628123456789@c.us',
quotedMessageId: 'true_628123456789@c.us_3EB0123456789',
text: 'Replying to that',
});
console.log(replied);
// { messageId: 'true_628123456789@c.us_3EB0987654321', timestamp: 1706868060 }

// React (an empty emoji string removes the reaction) — returns { success }.
const reacted = await client.messages.react(sessionId, {
chatId: '628123456789@c.us',
messageId: 'true_628123456789@c.us_3EB0123456789',
emoji: '👍',
});
console.log(reacted);
// { success: true }

// Any send can quote as well — quotedMessageId turns it into a reply.
const quotedImage = await client.messages.sendImage('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', {
chatId: '628123456789@c.us',
url: 'https://example.com/photo.jpg',
quotedMessageId: 'true_628123456789@c.us_3EB0123456789',
});
console.log(quotedImage);
// { messageId: 'true_628123456789@c.us_3EB0555555555', timestamp: 1706868120 }

Since v0.17.0 every send request type carries an optional quotedMessageId — text, the five media senders, location, contact, and poll — so a media, location, contact, or poll reply no longer has to go through reply(). It is typed in the JavaScript, Python, Go, and Java SDKs; the PHP client takes untyped arrays, so you add the key to the array and it reaches the wire unchanged. On reply() the field stays required; everywhere else it is optional. The value is engine-specific: whatsapp-web.js takes the serialized message id, Baileys the raw key id of a message it has already stored.

See the Sending messages guide for the complete set.

Retry a single send with an idempotency key (v0.25.0+)​

Gateway v0.25.0 accepts an optional Idempotency-Key header on twelve single-recipient routes: text, image, video, audio, document, sticker, location, contact, template, poll, reply and forward. Use one caller-owned key per logical send, persist it before sending, and reuse the same route, body and key for retries. The key must contain 1-255 visible ASCII characters and is retained per session for 24 hours. Omit it to keep the existing behavior.

SDK 0.6.0 takes the key as a send argument. JavaScript, PHP and Java accept it as an optional trailing idempotencyKey argument on the twelve routes above, and Python as the keyword-only idempotency_key. Go reads it from the context with openwa.WithIdempotencyKey(ctx, key), which sends the header only on those routes. A key outside 1-255 visible ASCII characters is refused before the request is sent.

const result = await client.messages.sendText(
sessionId,
{ chatId: '628123456789@c.us', text: 'Order 123 confirmed' },
'order-123-confirmation',
);
// If a retry is needed, call again with the same body and key.
result = client.messages.send_text(
session_id,
{"chatId": "628123456789@c.us", "text": "Order 123 confirmed"},
idempotency_key="order-123-confirmation",
)
ctx := openwa.WithIdempotencyKey(context.Background(), "order-123-confirmation")
result, err := client.Messages.SendText(ctx, sessionID, openwa.SendTextRequest{
ChatID: "628123456789@c.us",
Text: "Order 123 confirmed",
})

In PHP the call is $client->messages->sendText($sessionId, $body, 'order-123-confirmation'), and in Java client.messages.sendText(sessionId, request, "order-123-confirmation").

SDK 0.5.1 and earlier have no per-send idempotency argument. JavaScript and PHP ignore an extra send argument; TypeScript rejects it. In JavaScript, use the raw request's headers option:

import type { MessageResponse } from '@rmyndharis/openwa';

const send = {
method: 'POST' as const,
path: `/api/sessions/${sessionId}/messages/send-text`,
headers: { 'Idempotency-Key': 'order-123-confirmation' },
body: { chatId: '628123456789@c.us', text: 'Order 123 confirmed' },
};
const result = await client.request<MessageResponse>(send);
// If a retry is needed, reuse `send` unchanged.

PHP 0.5.1's raw request() also lacks per-call headers. Use a direct Guzzle request for this call, with the same gateway URL and API key:

$response = (new \GuzzleHttp\Client())->request('POST',
'http://localhost:2785/api/sessions/' . rawurlencode($sessionId) . '/messages/send-text', [
'allow_redirects' => false,
'timeout' => 30,
'headers' => [
'X-API-Key' => getenv('OPENWA_API_KEY'),
'Idempotency-Key' => 'order-123-confirmation',
],
'json' => ['chatId' => '628123456789@c.us', 'text' => 'Order 123 confirmed'],
]);

Do not put a send key in a shared client's defaultHeaders, where unrelated calls would reuse it. A completed request replays its original response. 409 with IDEMPOTENCY_KEY_IN_PROGRESS means wait and retry with the same key; 409 with IDEMPOTENCY_OUTCOME_UNKNOWN means inspect the chat before deciding whether to send again with a new key. 422 with IDEMPOTENCY_KEY_REUSED means the route or body differs. SDK 0.5.1 exposes these codes as err.code. Bulk sends, product sends, button replies, and status posts do not have this guarantee. See Sending messages for the retry contract.

Send media and location​

sendImage, sendVideo, sendAudio, sendDocument, and sendSticker share one body shape. Provide a url or a base64 payload, and give base64 a mimetype; if both are sent, the base64 payload is used. filename is optional on every one of them, documents included; omit it and the engine substitutes a generic name, so set it whenever the recipient should see a real one.

// Image by URL with a caption.
await client.messages.sendImage(sessionId, {
chatId: '628123456789@c.us',
url: 'https://example.com/photo.jpg',
caption: 'Check this out', // max 1024 characters
});

// Document from base64 bytes.
await client.messages.sendDocument(sessionId, {
chatId: '628123456789@c.us',
base64: 'JVBERi0xLjQKJ...', // raw base64, no data-URL prefix
mimetype: 'application/pdf',
filename: 'invoice.pdf',
});

The gateway downloads a url itself before sending. Since v0.23.6 it checks the URL first: one that is not an absolute http:// or https:// URL answers 400. Before, a value that passed as a URL without that scheme, such as example.com/photo.jpg or an ftp:// link, was decoded as base64 and sent garbled. When base64 carries data, the url is neither fetched nor checked. A url that carries a user name or password answers 400 too since v0.31.0, before any connection is made, where it answered 500. Since v0.23.6 a download that fails answers 400, or 413 above the media byte cap, where both answered 500 before; all three arrive as a plain OpenWAApiError. From the same release, on a session with an egress proxy the download goes through the proxy rather than leaving from the gateway's own address (unless the operator sets SESSION_PROXY_URL_FETCH=false), and a failure there before any response arrives answers 503 (OpenWAServiceUnavailableError). Nothing was sent at that point, so that 503 is safe to retry. Behind a proxy, though, the gateway cannot tell a failing proxy from a media host that is unreachable or does not respond before the download times out, so such a url can answer 503 there, where a session without a proxy answers 400; if the 503 repeats, check that the URL itself answers. A host the gateway cannot resolve, or one that resolves to a blocked address, still answers 400 behind a proxy, because the gateway checks the name before the request leaves, and so does an http:// URL for which an http or https proxy returns an error status of its own, such as 502. A 407, which the proxy sends when the credentials in the session's proxy URL are missing or wrong, answers 503 instead, whatever the URL's scheme. A download that times out is the exception on default settings: the gateway gives it up to 30 s (MEDIA_DOWNLOAD_TIMEOUT_MS), the same as the SDK's default timeoutMs, and its clock starts only once the request has arrived, so the SDK throws OpenWATimeoutError first and neither the 503 nor the 400 reaches you. Set timeoutMs above the gateway's download timeout to receive them.

Location takes coordinates and an optional label:

await client.messages.sendLocation(sessionId, {
chatId: '628123456789@c.us',
latitude: -6.2,
longitude: 106.8,
description: 'Our office',
});

All three resolve to the same { messageId, timestamp } shape. In the Go SDK, SendLocationRequest.Latitude and Longitude are float64 fields without omitempty, so valid 0, 0 coordinates are always serialized on the wire.

Send polls, voice notes, and mentions​

Native polls​

POST /messages/send-poll posts a native WhatsApp poll. Pass 2–12 options; the poll is single-choice unless you set allowMultipleAnswers: true. Both engines support it.

const poll = await client.messages.sendPoll(sessionId, {
chatId: '628123456789@c.us',
name: 'Where should we meet?', // the poll question, max 255 chars
options: ['Park', 'Beach', 'Downtown'], // 2–12, each max 100 chars
allowMultipleAnswers: true, // optional; default single choice
});
console.log(poll);
// { messageId: 'true_628123456789@c.us_3EB0...', timestamp: 1706868120 }

Inbound polls arrive as message type poll. Since v0.23.2 the poll question fills the message body on both engines, so a webhook body filter or a search can read it without opening the poll payload.

PTT voice notes​

sendAudio accepts an optional ptt boolean. When true, the audio is delivered as a real WhatsApp voice note — the microphone bubble with a waveform — instead of a plain audio file. Voice notes require audio/ogg; codecs=opus; when ptt is set without a mimetype, the server defaults to that, so supply OGG/Opus bytes for reliable playback. The message is stored as type voice.

await client.messages.sendAudio(sessionId, {
chatId: '628123456789@c.us',
url: 'https://example.com/clip.ogg',
ptt: true, // deliver as a voice note
});

@mentions​

sendText and the media senders accept an optional mentions array of individual WIDs, for example 628123456789@c.us. The text (or caption for media) must also contain the literal @<number> token for each mention, or WhatsApp will not render the mention.

await client.messages.sendText(sessionId, {
chatId: '1203630000@g.us', // a group
text: 'Hey @628123456789, can you take this?',
mentions: ['628123456789@c.us'],
});

On inbound messages, both engines surface the tagged WIDs as mentionedIds when the message carries any. In the PHP SDK, since 0.13.0 the resource methods send options on sendPoll, mentions on sends and recipients on status posts as JSON arrays whatever their keys, so the result of array_filter() or array_unique() can be passed as it is. On 0.12.1 and earlier, pass 0-indexed lists (wrap such arrays in array_values()) so json_encode serializes them as JSON arrays rather than objects. A body passed to the raw request() is sent as given in every version, so pass its lists through array_values().

Answer a WhatsApp Business prompt (v0.23.6+)​

On a Baileys session, a WhatsApp Business prompt that offers buttons or list rows arrives on message.received with a buttons: [{ id, text }] array. Buttons that open a URL or dial a number are left out, since they cannot be clicked. The prompt arrives as type: "text" with its text in body, and a button, template, or list reply arrives as text too, with button: { id, text? } naming the choice; before v0.23.6 a list prompt and those replies arrived as unknown. A native-flow reply arrived as text before v0.23.6 as well, and since then it also carries button when its payload names the choice's id. POST /messages/click-button answers one of those choices with a button or list reply quoted to the prompt. SDK 0.5.1 exposes it as messages.clickButton:

const answer = await client.messages.clickButton(sessionId, {
chatId: '628123456789@c.us',
messageId: '3EB0C767D26A1D8B4F2A', // the prompt's id from message.received
buttonId: 'yes', // one of the prompt's buttons[].id
// text: 'Yes', // optional; read from the stored prompt when omitted
});
console.log(answer);
// { messageId: '3EB0A1B2C3D4E5F60718', timestamp: 1706868180 }

It needs an OPERATOR-level key, and whatsapp-web.js answers 501 (OpenWANotImplementedError). The prompt must still be in the engine's message store and in the named chat, or the call answers 404; a buttonId the prompt does not offer, or a message that is not a clickable prompt, answers 400. The reply is a structured reply message, not a tap in the WhatsApp UI, so the business may treat it differently: classic button, template, and list prompts are supported, and replies to native-flow prompts are unverified.

Post a Status update​

Status posting works on both engines. The status resource exposes text, image, video, and voice status posts under POST /api/sessions/:id/status/send-text|send-image|send-video|send-voice, on client.status as sendText, sendImage, sendVideo, and sendVoice. recipients is an optional array of up to 256 JIDs (@c.us or @lid) and is engine-conditional: Baileys posts to exactly that allow-list and rejects an omitted or empty one with 400, while whatsapp-web.js ignores it and broadcasts to the account's status-privacy audience.

// Text status to up to 256 recipients.
await client.status.sendText(sessionId, {
text: 'Out for the holidays 🌴',
recipients: ['628123456789@c.us', '628987654321@c.us'],
});

sendImage and sendVideo take the same media body shape as the message senders plus recipients.

Send in bulk​

For high-volume sends, sendBulk enqueues a batch (up to 100 messages) and returns immediately with a batch id and a poll URL — the messages are dispatched asynchronously with a pacing delay. Each item carries a type and a content object keyed by that type.

A media item carries its url or base64 under content.<type>, as in content: { image: { url } }. Since v0.23.6 that url must be an absolute http:// or https:// URL, as on the single senders, unless base64 carries data. One that is not fails the whole request with 400, and nothing is queued. Since v0.31.0 a url that carries a user name or password is refused the same way; before, the batch was accepted and the item failed. A url holding a placeholder such as {{name}} is checked only once the item's variables are rendered into it, and a bad result fails that item alone, counted under failed in batchStatus.

const batch = await client.messages.sendBulk(sessionId, {
messages: [
{ chatId: '628111111111@c.us', type: 'text', content: { text: 'Hi A' } },
{ chatId: '628222222222@c.us', type: 'text', content: { text: 'Hi B' } },
],
options: {
delayBetweenMessages: 3000, // ms, minimum 1000; default 3000
randomizeDelay: true,
},
});
console.log(batch);
// {
// batchId: 'batch_01HZ...',
// status: 'processing',
// totalMessages: 2,
// estimatedCompletionTime: '2026-06-26T10:00:06.000Z',
// statusUrl: '/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/messages/batch/batch_01HZ...'
// }

Poll progress with batchStatus:

const status = await client.messages.batchStatus(sessionId, batch.batchId);
console.log(status.progress);
// { total: 2, sent: 1, failed: 0, pending: 1, cancelled: 0 }

To stop an in-flight batch, call client.messages.cancelBatch(sessionId, batch.batchId) — this requires an OPERATOR-level key.

Chats, presence, calls, and channel admin (v0.16.0+)​

Ten client methods landed in v0.16.0, spread across six resources. Each maps to one REST route; the eight that change state need an OPERATOR-level key.

MethodBody / argumentsResolves to
chats.pin(sessionId, body)PinChatRequest { chatId: Jid; pin: boolean }SuccessResult
chats.mute(sessionId, body)MuteChatRequest { chatId: Jid; muteUntil: number | null }SuccessResult
sessions.setOnlinePresence(sessionId, body)SetOwnPresenceRequest { available: boolean }SuccessResult
groups.getMembershipRequests(sessionId, groupId)—GroupMembershipRequest[]
groups.approveMembershipRequests(sessionId, groupId, participants?)string[], optionalParticipantsResult
groups.rejectMembershipRequests(sessionId, groupId, participants?)string[], optionalParticipantsResult
contacts.listBlocked(sessionId)—string[]
calls.createLink(sessionId, body)CreateCallLinkRequest { type: 'audio' | 'video'; startTime: number }CallLinkResponse { link: string }
channels.demoteAdmin(sessionId, channelId, body)DemoteChannelAdminRequest { userId: Jid }SuccessResult
channels.transferOwnership(sessionId, channelId, body)TransferChannelOwnershipRequest { newOwnerId: Jid }SuccessResult

SuccessResult is { success: boolean; message?: string }. ParticipantsResult is { success: boolean; message: string; results: ParticipantResult[] }, with one outcome per participant in results; before SDK 0.7.0 it extended SuccessResult in JavaScript and Python.

Pin and mute a chat​

// Pin the chat to the top of the list; pass false to release it.
await client.chats.pin('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', {
chatId: '628123456789@c.us',
pin: true,
});

// Mute for the next eight hours — muteUntil is epoch MILLISECONDS.
await client.chats.mute('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', {
chatId: '628123456789@c.us',
muteUntil: Date.now() + 8 * 60 * 60 * 1000,
});

// Unmute: send null.
await client.chats.mute('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', {
chatId: '628123456789@c.us',
muteUntil: null,
});
muteUntil is milliseconds, and it is required

A seconds-scale timestamp is an instant in 1970, so the mute expires the moment it is set while the call still answers 200 — the failure is silent. The field is also required rather than optional, because the two readings of an omitted value, unmute now and mute indefinitely, are opposites: null means unmute. To mute indefinitely, send a far-future timestamp; since v0.26.0 one above 9007199254740991 (Number.MAX_SAFE_INTEGER) is refused with 400.

Set the account's presence​

// The ACCOUNT's presence, not a chat's — returns { success }.
await client.sessions.setOnlinePresence('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', {
available: false,
});

available: false hands notification delivery back to the phone. This is the linked account's global presence; per-chat typing and recording indicators are still client.chats.sendState.

const blocked = await client.contacts.listBlocked('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a');
console.log(blocked);
// ['628987654321@c.us']

const call = await client.calls.createLink('8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a', {
type: 'video',
startTime: Date.now(), // absolute epoch milliseconds; Date.now() means "now"
});
console.log(call.link);

Both type and startTime are required, and startTime is a whole number of milliseconds: a fraction answers 400, and Python types it int since SDK 0.13.0. A refusal on WhatsApp's side answers 403.

Resolve a contact's LID or phone and read per-recipient message receipts (v0.27.1+ / v0.28.0+)​

Gateway v0.27.1 added GET /api/sessions/{sessionId}/contacts/{number}/lid (wrapped in SDK 0.9.0+ as contacts.lid in JavaScript, Python, and PHP, contacts.getLid in Java, and Contacts.Lid in Go) as the companion to contacts.phone (GET .../contacts/{lid}/phone). Gateway v0.28.0 added GET /api/sessions/{sessionId}/messages/{chatId}/{messageId}/receipts (whatsapp-web.js only; Baileys answers 501), wrapped in SDK 0.10.0+ as messages.receipts (messages.getReceipts in Java, Messages.Receipts in Go):

// Resolve a phone number or @c.us JID to its Linked Identity (@lid), or null when unknown.
const { lid } = await client.contacts.lid(sessionId, '628123456789');

// Read per-recipient delivery, read, and played timestamps (Unix seconds) on whatsapp-web.js.
const { receipts } = await client.messages.receipts(
sessionId,
'120363021234567890@g.us',
'true_120363021234567890@g.us_3EB0123456789_628111111111@c.us',
);
for (const r of receipts) {
console.log(r.participantId, r.deliveredAt, r.readAt, r.playedAt);
}

Membership requests and channel admin​

getMembershipRequests, approveMembershipRequests, and rejectMembershipRequests wrap the group join queue. Omitting participants acts on every pending request, and a partial refusal still resolves — read results rather than trusting success alone. See Groups.

const pending = await client.groups.getMembershipRequests(
'8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a',
'120363021234567890@g.us',
);

await client.groups.approveMembershipRequests(
'8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a',
'120363021234567890@g.us',
pending.map((request) => request.participantId),
);

channels.demoteAdmin and channels.transferOwnership administer a channel this account owns. Both throw OpenWANotImplementedError (501) on a whatsapp-web.js session — they are implemented on Baileys only — and the transfer is irreversible: the account cannot take the channel back through the API afterwards. See Channels.

await client.channels.demoteAdmin(
'8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a',
'120363000000000000@newsletter',
{ userId: '628123456789@c.us' },
);

Handle errors​

The SDK throws a typed error on any non-2xx response and does not retry automatically, so backoff stays under your control. The same holds for the Python, PHP, and Java SDKs; the Go SDK is the one exception and ships an opt-in retry policy, described below. Every error extends OpenWAError, and the API-error classes carry .status (HTTP code), .body (the parsed JSON envelope), .code, .retryAfterSeconds and .headers in SDK 0.5.1 and later, so you can branch with instanceof or inspect the fields directly.

import {
OpenWAConflictError,
OpenWANotFoundError,
OpenWARateLimitError,
OpenWATimeoutError,
OpenWAApiError,
} from '@rmyndharis/openwa';

try {
await client.messages.sendText(sessionId, {
chatId: '628123456789@c.us',
text: 'Hello!',
});
} catch (err) {
if (err instanceof OpenWAConflictError) {
// 409 — engine not ready; the session may still be connecting.
} else if (err instanceof OpenWANotFoundError) {
// 404 — session or chat does not exist.
} else if (err instanceof OpenWARateLimitError) {
// 429 — back off and retry yourself.
} else if (err instanceof OpenWATimeoutError) {
// request exceeded timeoutMs.
} else if (err instanceof OpenWAApiError) {
console.error(`API error ${err.status}:`, err.body);
} else {
throw err; // network/transport error
}
}
Error classStatusWhen it's thrown
OpenWAAuthError401Missing or invalid API key
OpenWAForbiddenError403Key's role is insufficient (e.g. an OPERATOR-only route), or a chat-restricted key (v0.23.6+) calls a route not open to it, names a chat outside its list, or sends a quotedMessageId on anything but reply; or the client IP or the session is outside the key's allowedIps or allowedSessions (v0.24.0+); or WhatsApp refused a well-formed operation (for example a group or channel write the account has no admin rights for). The error message says which
OpenWANotFoundError404Resource not found
OpenWAConflictError409Conflict: typically the engine is not ready; on a send with an Idempotency-Key, IDEMPOTENCY_KEY_IN_PROGRESS or IDEMPOTENCY_OUTCOME_UNKNOWN; since v0.31.0, ENGINE_PAGE_RELOADING on whatsapp-web.js, and a send cut short while it ran, which has no code and a message that says it may or may not have been sent (inspect code and the message before retrying)
OpenWARateLimitError429Rate limited
OpenWANotImplementedError501The active engine doesn't support this operation; on whatsapp-web.js, since v0.31.0, also when the WhatsApp Web build the session runs has no job for a group join, invite preview, invite code, group info or setting write, profile picture or status write, or message pin, and nothing was asked of WhatsApp
OpenWAServiceUnavailableError503The engine did not confirm the operation in time; on Baileys, WhatsApp throttled the request (code 429) or timed out a query it awaits (code 408), which a send, reaction, edit, delete, pin or status post answers with 503 since v0.26.0 and with 500 before; or (v0.23.6+) a media url fetched through the session's egress proxy failed before any response arrived; also when the gateway has too much request body data in flight
OpenWAApiErrorany otherGeneric non-2xx (e.g. 400 validation)
OpenWATimeoutError—Request exceeded the configured timeout

OpenWATimeoutError extends OpenWAError directly, not OpenWAApiError, so it has no .status or .body. A timeout means the client stopped waiting for the response, not that the gateway aborted the operation: on a send, reuse the same Idempotency-Key or check the chat before sending again.

Since v0.31.0 the 409 of a page reload carries a code, and a send cut short while it ran has a 409 of its own. The reload 409 is whatsapp-web.js only: while WhatsApp Web reloads its page and the session still reads ready, a request that is safe to repeat answers it with code ENGINE_PAGE_RELOADING; the SDK error carries it as err.code, and err.retryAfterSeconds is the interval to ask again at. Most reloads last seconds and some a few minutes, and no event marks the end, so repeat the request at that interval; a repeat of a channel delete that the first attempt had already applied may meet a channel that is gone, which answers 403, and a repeat of an unsubscription may meet a channel that is no longer followed. No SDK retries it for you by default. A send or status post that was cut short while it ran, by a page reload on whatsapp-web.js or by a connection replaced or stopped while it was written on Baileys, answers a 409 with no code whose message says it may or may not have been sent or posted. On Baileys a status delete, reaction, edit, message delete for everyone or pin is cut short the same way. Check the chat, or your status, before sending or posting it again: a keyed send retried with the same Idempotency-Key answers 409 with IDEMPOTENCY_OUTCOME_UNKNOWN.

Add your own retries

Because this SDK does not retry, wrap calls in your own backoff for 429. The injectable fetch option is the place to slot in retry or observability middleware.

Since gateway v0.23.6 every 429 from the gateway's rate limiter carries a plain Retry-After in seconds next to the Retry-After-<window> header that names the window that shed the request; before, only the suffixed header was sent. SDK 0.5.1 and later expose the delay as err.retryAfterSeconds and the original header as err.headers?.get('Retry-After'). SDK 0.7.0 caps retryAfterSeconds at 2147483 (about 24.8 days), so err.retryAfterSeconds * 1000 is always a valid setTimeout delay. With the default in-memory limiter the value is not the time left in the window: the first refused request starts a block one full window long (1 s, 60 s, or an hour for the default short, medium and long windows) and the value counts it down. With Redis-backed limiting (REDIS_ENABLED=true) there is no separate block, so the value is the time left in the current window (at least 1 s) and counts down as well. Either way it can be up to an hour when the long window is the one exhausted. If several windows are exhausted at once, the header gives the shortest, so a retry after it can still answer 429. A send refused by send pacing is also a 429 but carries no Retry-After: read retryAfterSeconds from err.body, where code is SEND_PACING_LIMITED. The rate limiter counts each client IP separately, and since v0.23.6 it counts an IPv6 client by its /64: workers on different addresses in one IPv6 /64 now share one count and can meet 429 sooner than before, and raising the RATE_LIMIT_* limits is up to the gateway operator. The gateway's in-flight upload budget is charged differently: since gateway v0.24.0 a request that carries an active API key, as SDK calls do, is charged to that key, so workers sharing one key draw on one half of the budget (INFLIGHT_BODY_BUDGET_BYTES, by default four times BODY_SIZE_LIMIT) however many addresses they use. A request that would take the key's bodies in flight past that half is refused with 503 (OpenWAServiceUnavailableError) and Retry-After: 1 before its body is read or any route runs, so parallel base64 media sends on one key can meet it. Only requests without a recognised key are charged to the client address, an IPv6 client on its /64. A body that the budget or the key's share could never admit is refused with 413 and no Retry-After. Nothing has been processed by then, so a 503 is safe to retry, and raising the budget is up to the operator.

OpenWAServiceUnavailableError (503) can mean an operation was refused before it ran, a media fetch or recipient lookup failed, an engine confirmation never arrived, or, on Baileys, WhatsApp throttled the request (code 429) or timed out a query it awaits (code 408). Back off and retry later instead of at once, because repeating a throttled request straight away prolongs the throttle. Repeat reads and writes that converge on the same state; for a non-idempotent send use the same Idempotency-Key or inspect the chat before deciding to send again. A throttled send or single write was turned away before it ran, so nothing was sent or applied, and a keyed send frees its Idempotency-Key (and since gateway v0.27.0 a 503 on a send also proves nothing was sent when its recipient lookup failed, its connection closed before the message was written, or its media or preview image URL could not be fetched through the session's proxy, and any other pre-send refusal such as a not-ready session, an unsupported engine operation, a failed media or thumbnail download or decode, an unregistered Baileys recipient, or a missing or wrong-chat Baileys quote or forward frees Idempotency-Key as well). Any other timeout proves nothing: the write may have been applied, and a keyed send keeps its key taken. A group settings update with several fields applies them one at a time, so a 503 on a later field, a throttle included, leaves the earlier ones applied; its message lists them after already applied:, so re-read the settings before retrying, or send one field per request. A 503 from the multi-node forwarding layer itself means the owner was never reached, but an owner response is relayed unchanged, including 503. Forwarding failures after the request was sent can be 502 or 504; those also leave the outcome uncertain. See Retry a single send.

The Go SDK can do this for you

Go is the deliberate exception to "no automatic retries". Pass openwa.WithRetry at construction and the client retries on its own; leave it out and it never does.

client, err := openwa.New(baseURL, apiKey, openwa.WithRetry(openwa.DefaultRetryPolicy()))

DefaultRetryPolicy() is 3 retries after the first attempt, a 200 ms base delay doubling to a 5 s cap, on 429, 500, 502, 503 and 504, honouring Retry-After. RetryPolicy is a plain struct, so every one of those is yours to change.

The 5 s cap bounds computed backoff, while a longer Retry-After can increase the delay. Since SDK 0.5.1, if the required wait exceeds the remaining request deadline (30 s by default), the client returns the current typed 429 or 503 error immediately instead of waiting for a timeout. RespectRetryAfter: false uses only computed backoff. A SEND_PACING_LIMITED response is never retried automatically; read its retryAfterSeconds body field and decide when to try again.

Two rules narrow that policy for a POST (which is every send) and a PATCH (Sessions.UpdateConfig and Sessions.UpdateProxy), and neither is reachable through RetryableStatuses:

  • After a network error a POST or PATCH is never replayed. The SDK cannot tell whether the gateway processed the request before the connection dropped, and a key from WithIdempotencyKey does not widen the policy. Only GET, HEAD, OPTIONS, PUT and DELETE are retried there.
  • On a retryable status a POST or PATCH is replayed only for 429 and 503, the two statuses the SDK permits for writes. Since SDK 0.10.0, a POST on 503 is replayed only when the request context carries an Idempotency-Key (openwa.WithIdempotencyKey) or the 503 response carries a Retry-After header (which the gateway sends when a request is shed before execution by the in-flight body budget or an ingress preflight); an unkeyed POST that gets a 503 without Retry-After is not replayed automatically because 503 can also report an unconfirmed write or relay an owner response after work began. A 500, 502 or 504 can arrive after the message was already sent, so a POST or PATCH is not replayed on those even if you list them.

Enabling Go retries can replay a POST on 503 up to three more times. On Baileys a 503 can be WhatsApp throttling a send, and the default backoff (three retries from 200 ms) replays it within about a second and a half: for sends raise BaseDelay or lower MaxRetries, or retry the throttled send yourself later. Use a client without WithRetry for non-idempotent sends when you cannot preserve a send key or reconcile an uncertain outcome. On whatsapp-web.js, retries of Sessions.RequestPairingCode start the linking flow again; use a client without retries for that operation too. Custom retry middleware must preserve these boundaries.

Receive events with webhooks​

The SDK is a request/response client — there is no client.on(...) and no streaming. To receive inbound messages, delivery acks, and session events, register a webhook that points at an HTTP endpoint you host, then read the delivered payloads there.

Create a webhook with the webhooks resource (requires an OPERATOR-level key):

const webhook = await client.webhooks.create(sessionId, {
url: 'https://my-app.example.com/openwa/events',
events: ['message.received', 'message.ack', 'session.disconnected'],
secret: process.env.WEBHOOK_SECRET, // optional; with it, deliveries carry X-OpenWA-Signature
});
console.log(webhook.id, webhook.active);
// '3f8a1c2e-9b47-4d61-a0f2-7c5e8d904b13' true

// Send a test delivery to confirm your receiver is reachable.
const test = await client.webhooks.test(sessionId, webhook.id);
console.log(test);
// { success: true, statusCode: 200 }

SDK 0.13.0 declares the following events, including event.response (since 0.6.0) and message.receipt and poll.vote (since 0.7.0, gateway v0.26.0 or later); the PHP client takes event strings and has no event list. Use '*' for all of them except message.receipt, which must be named:

EventFires when
message.receivedAn inbound message arrives
message.sentAn outbound message is sent
message.ackA delivery/read receipt updates (for messages the account sent since v0.27.0; on Baileys since v0.28.0 also delivered and read for a group message the account sent once every non-self group participant has delivered or read it)
message.receiptOne recipient delivers, reads or plays a message the account sent to a group or posted to Status (v0.26.0+). Baileys only. Not part of '*': name it
message.failedAn outbound message fails
message.revokedA message is deleted for everyone
message.reactionA reaction is added or removed
message.editedA message is edited (v0.9.0+, both engines)
status.receivedA contact's Status (Story) is received
session.statusThe session lifecycle status changes
session.qrA new QR code is available
session.authenticatedThe session authenticates
session.disconnectedThe session disconnects
session.reconnect_loopA session is stuck reconnecting; fires once per 5 consecutive attempts (v0.10.0+)
session.restrictionWhatsApp imposes or lifts an account restriction (v0.14.0+)
presence.updateA subscribed contact's presence changes (v0.14.0+). Baileys only.
event.responseA guest RSVPs to a WhatsApp event invitation (v0.25.0+). Baileys only.
poll.voteA voter changes their selection on a poll (v0.26.0+ on whatsapp-web.js; on Baileys since v0.30.2, which reports a vote only while the poll's creation message is still in the session's message store)
group.joinA participant joins a group the session belongs to
group.leaveA participant leaves a group the session belongs to
group.updateA group's metadata changes; a roster change is group.join or group.leave
group.join_requestSomeone requests to join a group the session administers (v0.15.0+)
call.receivedAn incoming call is detected. Not reliable on whatsapp-web.js
call.acceptedAn incoming call is picked up (v0.14.0+). Baileys only.
call.rejectedAn incoming call is declined (v0.14.0+). Baileys only.
call.missedAn incoming call rings out (v0.14.0+). Baileys only.

Six of these have no producer on the whatsapp-web.js engine: message.receipt, presence.update, event.response and the three call outcomes. Subscribing to them there is accepted and then never fires. See the Webhooks guide for why. call.received does have a producer there but is not reliable: a WhatsApp Web build can leave the engine's call hook uninstalled, so calls go unreported while messages keep flowing, and since v0.23.6 the session logs a warning when it detects that.

webhooks.create and update also take filters, conditions every message event must meet to be delivered. Since v0.23.6 a condition can match chatId, which scopes a webhook to chosen groups or chats: filters: { conditions: [{ field: 'chatId', operator: 'is', value: ['120363000000000000@g.us'] }] }. Write a group as its full @g.us id. Gateway v0.25.0 adds chatId to message.ack and message.failed, so chatId and kind filters can scope delivery events too; older gateways did not carry that field on those events. See the Webhooks guide for every filter field.

The secret is optional and the gateway never generates one. When a webhook has a non-empty secret, each delivery is signed as X-OpenWA-Signature: sha256=<hmac>, and you should verify it before trusting the payload; without one no X-OpenWA-Signature header is sent, so there is nothing to verify. The read responses from webhooks.list/get deliberately omit the secret, so store it yourself. To clear a stored secret, webhooks.update takes secret: '' or secret: null: the JavaScript and Python types declare the null since SDK 0.13.0, and in Go and Java use the empty string, since their update types leave an unset field out. See the Webhooks guide for payload shapes, signature verification, and retry behavior.

Audit webhooks across sessions​

webhooks.list(sessionId) covers one session. webhooks.listAll() returns every webhook the key can see across all of them, paginated with limit and offset — it requires an OPERATOR-level key.

const all = await client.webhooks.listAll({ limit: 50, offset: 0 });

When a webhook stops arriving, webhooks.deliveryFailures() reads the delivery-failure log. It requires an ADMIN-level key and accepts a sessionId filter alongside limit and offset.

const failures = await client.webhooks.deliveryFailures({
sessionId,
limit: 20,
});
The log records failures, not filter suppressions

It includes exhausted deliveries and zero-attempt failures such as capacity or shutdown refusals. A delivery a webhook's own filters suppressed never appears here, an empty log is not evidence the event was delivered. Check the webhook's active flag, its events, and its filters first. SDK 0.6.0 declares WebhookDeliveryFailure records, with replayable, in the typed clients; PHP returns decoded arrays.

Redrive retained failures (v0.25.0+)​

The gateway can replay eligible delivery failures when the operator enables WEBHOOK_FAILURE_PAYLOAD_RETENTION_HOURS above zero. SDK 0.6.0 wraps the call as webhooks.redriveDeliveryFailures (redrive_delivery_failures in Python, Webhooks.RedriveDeliveryFailures in Go) and marks the rows it can replay with replayable in the failure log. It needs an ADMIN key:

const redrive = await client.webhooks.redriveDeliveryFailures({ sessionId, limit: 10 });
console.log(redrive.delivered, redrive.failed, redrive.skipped, redrive.remaining);

On SDK 0.5.1 and earlier use a raw request:

const redrive = await client.request({
method: 'POST',
path: '/api/webhooks/delivery-failures/redrive',
body: { sessionId, limit: 10 },
});

The batch makes direct POSTs, reuses each stored receiver idempotency key, and returns delivered, failed, skipped and remaining counts (enqueued is always zero). A client timeout does not cancel it. Inspect the failure log before repeating a batch; receivers must deduplicate deliveries. See Webhooks for payload-retention, eligibility and scope rules.

Prefer no-code? Use n8n

If you'd rather not host a receiver, the n8n integration manages the webhook for you and exposes incoming events as a workflow trigger.

Troubleshooting​

SymptomCauseFix
OpenWAAuthError (401) on every callMissing or wrong API keyCheck apiKey; confirm with client.auth().
OpenWAForbiddenError (403)Key lacks the OPERATOR role for a write, or for a credential read (QR code, group invite code); or, for a key with allowedChats (v0.23.6+), the route or the chat is outside its scope, or the call sends a quotedMessageId on anything but reply; or the client IP or the session is outside the key's allowedIps or allowedSessions (v0.24.0+); or WhatsApp refused a well-formed operation, for example a group or channel write the account has no admin rights forRead the error message to see which. Use an operator key, or scope the action; for a chat-restricted key, use one whose scope covers the call, and quote only through reply; for an IP or session refusal, call from an allowed address or session; for a WhatsApp refusal the key is not the cause, so check the account's rights in that group or channel. See Authentication.
OpenWAConflictError (409) on sendSession not ready yetPoll sessions.get(id) until status === 'ready', then send.
OpenWAConflictError (409) on send, no code, and a message that says it may or may not have been sentThe send was cut short while it ran: a page reload on whatsapp-web.js, or a connection replaced or stopped while it was written on Baileys (v0.31.0+)Check the chat before sending again. A keyed send retried with the same Idempotency-Key answers IDEMPOTENCY_OUTCOME_UNKNOWN, so send again only with a new key and only if the message is not there.
OpenWAConflictError (409), code ENGINE_PAGE_RELOADINGwhatsapp-web.js: WhatsApp Web is reloading its page while the session still reads ready (code since v0.31.0)Repeat the request after err.retryAfterSeconds. A reload can last a few minutes and no event marks its end.
OpenWAConflictError (409) on send, code IDEMPOTENCY_KEY_IN_PROGRESSThe first request with this Idempotency-Key is still runningRetry with the same key once it finishes.
OpenWAConflictError (409) on send, code IDEMPOTENCY_OUTCOME_UNKNOWNAn earlier request with this key failed and the message may have been sentCheck the chat. Send again only with a new key: the same key keeps answering 409. See Retry a single send with an idempotency key.
OpenWAConflictError (409) on requestPairingCodeThe session is not at qr_ready: still connecting, or a code was already accepted; or, on whatsapp-web.js (v0.26.0+), the number is the stored phone of another session of this gatewayPoll sessions.get(id) until status === 'qr_ready', then request the code; after a code is accepted, wait for ready. For the number case, delete the other session or log it out first.
OpenWANotFoundError (404) on sendSession id or chatId is wrongVerify the session exists and the JID ends in @c.us or @g.us.
OpenWATimeoutErrorRequest exceeded timeoutMsRaise timeoutMs, or add backoff via the injectable fetch.
Webhook never firesReceiver unreachableRun webhooks.test(sessionId, id) and check the returned statusCode.

Next steps​