Official server-side TypeScript SDK for the Wabery REST API.
Wabery covers the full production messaging workflow for WhatsApp Business: channels and routing, contacts and registration intents, conversations and message history, outbound text/templates/media/interactive messages, reactions, locations, stickers, contact cards, quoted replies, inbound media files with signed URLs, WhatsApp Flows, WhatsApp Groups, commerce and regional payment messages, hosted functions, submissions, dispatches, config-as-code, WhatsApp Calling control and signaling, signed webhooks, and Meta Business Agent API types.
Instagram Direct and Facebook Messenger are beta channels you can connect directly from the Channels page. They are intentionally limited in the SDK and API: use them for beta inbox visibility and simple replies, not WhatsApp Flows, WhatsApp templates, or proactive template-style outreach.
Read the full Wabery API documentation at www.wabery.com/docs, including the media messages guide for the channel matrix, inbound payloads, download policy, and provider limits; the WhatsApp management reference for every channel operation; and sending messages for commerce, Calling prompts, and regional Payments API shapes.
Requires Node.js 22.13 or later.
npm install @wabery/sdk
import { Wabery } from "@wabery/sdk";
const wabery = new Wabery();
const identity = await wabery.identity.retrieve();
console.log(identity.project.id);
const message = await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
text: "Thanks for your message",
});
const status = await wabery.messages.get(message.id);
console.log(status.delivery_status);
Manage the Meta assets behind a dedicated channel without handling its Meta access token:
const profile = await wabery.whatsappManagement.getBusinessProfile("channel_...");
await wabery.whatsappManagement.updateCommerceSettings("channel_...", {
is_cart_enabled: true,
is_catalog_visible: true,
});
await wabery.whatsappManagement.deleteMedia("channel_...", "media_...");
whatsappManagement also covers QR codes, phone registration and verification,
WABA assets and subscriptions, analytics, funding diagnostics, blocked users,
and Calling API configuration. Credit-line data is read-only so billing stays
directly between you and Meta.
Wabery handles Meta credentials, call control, and signed signaling webhooks. Your server still needs a WebRTC or SIP media implementation; the SDK does not capture a microphone, stream audio, or provide a browser softphone.
Enable calling on each eligible dedicated number:
await wabery.whatsappManagement.updateCallingSettings("channel_...", {
status: "ENABLED",
});
const settings = await wabery.whatsappManagement.getCallingSettings(
"channel_...",
);
Before a business-initiated call, request and verify the user's permission:
await wabery.messages.send({
channelId: "channel_...",
to: "+15551234567",
idempotencyKey: "call-permission-customer-123",
interactive: {
type: "call_permission_request",
body: { text: "Allow our support team to call you on WhatsApp." },
action: { name: "call_permission_request" },
},
});
const permission = await wabery.whatsappManagement.getCallPermissions(
"channel_...",
"WHATSAPP_USER_ID",
);
Use manageCall() for Meta call actions. For example, start an authorized
business call with an SDP offer or accept an inbound call with an SDP answer:
await wabery.whatsappManagement.manageCall("channel_...", {
to: "WHATSAPP_USER_ID",
action: "connect",
session: { sdp_type: "offer", sdp: offerSdp },
biz_opaque_callback_data: "support-case-123",
});
await wabery.whatsappManagement.manageCall("channel_...", {
call_id: callId,
action: "accept",
session: { sdp_type: "answer", sdp: answerSdp },
});
call.event delivers Meta's call or status item in payload.call. Verify it
with wabery.webhooks.constructEvent() and make repeated delivery safe. A
voice_call interactive message is only a button inviting the user to call;
it does not establish an outbound call.
The SDP examples describe WebRTC mode. With SIP enabled, your PBX or telephony
service handles SIP signaling and media while call.event remains available
for lifecycle and status handling.
Read the complete setup, WebRTC/SIP responsibilities, inbound and outbound sequences, REST and MCP examples, security guidance, and troubleshooting in the WhatsApp Calling guide.
Groups use opaque groupId values and support text, media, approved text/media
templates, and pin/unpin. A group template may contain only a text or media
header, a body, and a footer. Manage groups through wabery.groups:
const groups = await wabery.groups.list({ channelId: "channel_..." });
const creation = await wabery.groups.create({
channelId: "channel_...",
idempotencyKey: "create-support-group-2026-08-22",
subject: "Customer support",
});
if (creation.object === "api_operation" && creation.status === "processing") {
// Keep the exact same idempotencyKey and retry/reconcile this request.
console.log(`Group creation is ${creation.reconciliation}`);
} else if (creation.status === "pending") {
// Wait for group.lifecycle before using the authoritative group id.
console.log("Group creation accepted", creation.request_id);
}
await wabery.messages.send({
channelId: "channel_...",
groupId: groups.data[0].id,
idempotencyKey: "support-group-2026-08-22",
pin: { type: "pin", messageId: "wamid....", expirationDays: 7 },
});
Group sends reserve a durable intent before contacting Meta. Reuse the same
idempotencyKey for retries. If the SDK call receives a transient gateway
failure, its built-in retry attempts keep the same caller-provided key. A 202
response with object: "message_request" and status: "processing" means the
send is being reconciled; do not retry it with a new key.
Group creation uses the same caller-stable-key rule. The SDK never generates a
creation key; pass one once and reuse it whenever the request is retried.
groups.create() returns either the pending WhatsAppGroupOperation or a
WhatsAppGroupCreateProcessingResponse with object: "api_operation" and
status: "processing". A processing response has no group_id: keep the same
key, do not create a second group, and wait for the typed group.lifecycle
webhook. reconciliation is "provider" when Meta work has been claimed and
"local_persistence" while Wabery is still completing its durable acceptance.
Acceptance-unknown is a separate terminal HTTP 409 error, not a processing
state: the SDK throws WaberyConflictError with
code: "whatsapp_group_create_acceptance_unknown". Verify the group in
WhatsApp Manager before retrying with a new logical creation key.
The SDK also provides async iterators for cursor-paginated group resources:
for await (const group of wabery.groups.listAll({
channelId: "channel_...",
limit: 100,
})) {
console.log(group.id, group.subject);
}
for await (const request of wabery.groups.listJoinRequestsAll(
"channel_...",
"group_opaque_7f3a92",
{ limit: 100 },
)) {
await reviewJoinRequest(request.joinRequestId, request.wa_id);
}
Both iterators follow opaque provider cursors until the collection is exhausted. Do not construct cursors from IDs or page items.
Interactive commerce (product, product_list, catalog_message) is for
individual WhatsApp recipients only. See the
Groups guide.
Existing conversation methods remain individual-only. Use
conversations.listGroups(), getGroup(), and listGroupMessages() for group
response types. Before consuming the four new group management webhook events,
enable them with
projects.update(id, { groupWebhookEventsEnabled: true }) and parse with
webhooks.constructEventWithGroups().
The SDK reads WABERY_API_KEY, WABERY_BASE_URL, and WABERY_API_VERSION
from the environment. It ships a dual build, so both ESM (import) and CommonJS
(require("@wabery/sdk")) work.
For a new project, create or select the project in the Wabery dashboard, then run
wabery login and paste the one-time key shown in the browser back into the
terminal. The CLI stores the key locally; for your app process, export it as
WABERY_API_KEY.
Use the dashboard's WhatsApp button or manually text the project join code
(wab-ABC123 style) to the shared Wabery sandbox number. That join-code message
only registers your phone. From the CLI, wabery projects get "project_id"
returns join_code and enrollment_channel.phone_number. Send one normal
WhatsApp message next, then find the ids:
wabery projects get "project_id"
wabery channels list
wabery conversations list
wabery conversations messages "conversation_..."
Use the returned channel_id and conversation_id with the SDK:
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
text: "Thanks for your message",
});
Use conversationId when replying in an existing conversation. Sending directly
to to: "+14155550100" is supported only on dedicated WhatsApp channels after
you have recorded an active opt-in for that contact. Phone numbers are expected in
E.164 format (a leading + and country
code); Wabery normalizes and dedupes them per organization server-side.
Outbound content can be text, templates, media (image, video, document, audio),
interactive payloads, reactions, locations, stickers, or contact cards on
WhatsApp. Provide exactly one content field. Connected Instagram/Messenger beta
channels expose media replies through the same messages.send() method, but do
not support WhatsApp Flows, WhatsApp templates, or proactive sends. Reply with a
conversationId while that channel's 24-hour customer-service window is open.
replyTo is the exception: it quotes an existing message and combines with any
content field rather than replacing it.
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
reaction: { messageId: "wamid....", emoji: "👍" },
});
// Quote the message you are answering. Read the id from an inbound
// messages[].replied_to.message_id, or from a delivery's WhatsApp id.
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
replyTo: "wamid....",
text: "Yes, that one is still available",
});
// A link button, so a long URL does not sit in the body text. Free-form: no
// template approval, no per-message template fee. WhatsApp channels only.
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
interactive: {
type: "cta_url",
body: { text: "Your invoice is ready" },
display_text: "Open invoice",
url: "https://example.com/i/abc123",
},
});
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
media: { type: "audio", link: "https://example.com/reply.ogg" },
});
// Instagram: image, audio, or video by a directly fetchable HTTPS URL.
await wabery.messages.send({
channelId: "instagram_channel_...",
conversationId: "instagram_conversation_...",
media: { type: "image", link: "https://cdn.example.com/photo.jpg" },
});
// Messenger: image, document, audio, or video by HTTPS URL.
await wabery.messages.send({
channelId: "messenger_channel_...",
conversationId: "messenger_conversation_...",
media: { type: "document", link: "https://cdn.example.com/invoice.pdf" },
});
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
contacts: [
{
name: { formatted_name: "Ada Lovelace", first_name: "Ada" },
phones: [{ phone: "+15555550123", type: "WORK", wa_id: "15555550123" }],
},
],
});
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
location: {
latitude: 37.7749,
longitude: -122.4194,
name: "San Francisco office",
},
});
await wabery.messages.send({
channelId: "channel_...",
conversationId: "conversation_...",
sticker: { link: "https://example.com/sticker.webp" },
});
Media support differs by channel:
| Channel | Outbound media | Locator and metadata |
|---|---|---|
| image, document, audio, video | Public HTTPS link or WhatsApp media id; captions and document filenames supported |
|
| Instagram beta | image, audio, video | Public HTTPS link only; no caption or filename; send documents as text links |
| Messenger beta | image, document, audio, video | Public HTTPS link only; no caption or filename |
Instagram and Messenger links must be fetchable by Meta without custom headers. Unsupported combinations fail synchronously with HTTP 422 and are not queued. Provider size limits are image 5 MB, audio/video 16 MB, and document 100 MB on WhatsApp; image 8 MB and audio/video 25 MB on Instagram; and 25 MB per Messenger attachment. Meta can also reject an otherwise accepted URL for its MIME type or codec.
The media lifecycle maps to these SDK methods:
| Operation | REST | SDK |
|---|---|---|
| Send media | POST /v1/messages |
wabery.messages.send() |
| Check delivery | GET /v1/messages/{message_id} |
wabery.messages.get() |
| Read history or refresh a signed URL | GET /v1/conversations/{id}/messages |
wabery.conversations.listMessages() |
| Receive media | message.received webhook |
wabery.webhooks.constructEvent() |
Create single-use WhatsApp onboarding links from a browser-safe publishable key.
When the key starts with wab_pub_, the SDK sends it as
x-wabery-publishable-key instead of a Bearer token:
const wabery = new Wabery({ apiKey: "wab_pub_..." });
const intent = await wabery.registrationIntents.create({
customerReference: "user_42",
metadata: { plan: "starter" },
});
// Send the customer to intent.wa_link, then poll status:
const status = await wabery.registrationIntents.get(intent.id);
Server-side code may also create and poll intents with a wab_live_ key that
has the registrations:create scope.
Verify and parse a delivery into a typed, discriminated event with
constructEvent (Stripe-style). Pass the raw, unparsed request body and the
full x-wabery-signature header (formatted sha256=<hex>):
import { Wabery, type WaberyEvent } from "@wabery/sdk";
const wabery = new Wabery();
// rawBody must be the exact bytes received — do not JSON.parse then re-stringify.
const event: WaberyEvent = wabery.webhooks.constructEvent(
rawBody,
request.headers["x-wabery-signature"],
process.env.WABERY_WEBHOOK_SECRET,
);
switch (event.event) {
case "message.received":
await reply(event.payload.from, event.payload.text);
break;
case "flow.completed":
await save(event.payload.submission);
break;
case "message.status":
case "participant.joined":
break;
}
constructEvent throws WaberySignatureVerificationError on a bad signature.
If you only need a boolean, wabery.webhooks.verifySignature(rawBody, header, secret)
verifies without parsing.
Inbound message.received events include messages, assets, media,
location, and unsupported. WhatsApp, Instagram, and Messenger attachments
are normalized to the same MessageReceivedMediaAsset shape. When Meta Cloud
API cannot forward the original WhatsApp content, type is "unsupported",
text is null, and unsupported mirrors the official
messages[].unsupported / messages[].errors
envelope (error 131051 or 131060). Coexistence deletes and edits arrive as
type: "revoke" / type: "edit" with Meta's original_message_id object.
Meta also documents an outer "unsupported" envelope with nested
unsupported.type: "edit" and error 131051. Wabery recognizes the same
production-observed shape with the undocumented nested subtype "revoke".
Use getMessageReceivedItemDisposition to classify either shape. The returned
mutation disposition has shouldReply: false; do not answer it. Wabery applies
direct coexistence mutations to the original stored message and does not treat
them as a new customer turn. provider identifies the channel;
provider_media_id can be null when Meta supplies only a temporary source URL.
On Instagram/Messenger, from is null and user_id carries the
Instagram-scoped or Page-scoped sender id.
Cached media uses a short-lived Wabery signed URL. The authorization is embedded
in its token query parameter, so downloading it requires neither the Wabery API
key nor an Authorization header. The signed URL lasts about one hour by
default. expires_at is the separate retention deadline: 24 hours on free plans
and 7 days on paid plans. Fetch the conversation history again for a newly signed
URL while the asset remains retained. assets is a flattened list of inbound
files, media is the latest file, and messages[n].media is the file attached to
that specific message.
if (event.event === "message.received") {
for (const asset of event.payload.assets ?? []) {
if (asset.status !== "available" || !asset.url) continue;
const response = await fetch(asset.url);
if (!response.ok) throw new Error(`Failed to download ${asset.id}`);
await saveInboundFile({
id: asset.id,
messageId: asset.message_id,
fileName: asset.file_name,
contentType: asset.mime_type,
bytes: await response.arrayBuffer(),
retainedUntil: asset.expires_at,
});
}
}
Deliveries are at-least-once. Deduplicate on a stable id (message_id for
message.received, flow_token for flow.completed):
import { createDedupeStore } from "@wabery/sdk";
const seen = createDedupeStore({ ttlMs: 24 * 60 * 60 * 1000 });
if (seen.add(event.payload.message_id)) return; // already processed
createDedupeStore is single-instance. For multiple instances, implement the
DedupeStore interface over a shared store (Redis SET … NX PX, a unique DB
column) — add(key) returns true when the key was already seen.
The flow.completed submission is a Record<string, unknown>; coerce values with
asNumber / asString / asBoolean / asDate / asDateRange / asStringArray, or
coerceSubmission(submission, { budget: "number", … }) for the whole record at once.
Enroll a contact (records opt-in, returns a stable contact_id), optionally with a
preferredLanguage used to resolve locale-specific flows, and update it later:
const contact = await wabery.contacts.enroll({
phone: "+14155550100",
preferredLanguage: "es", // BCP-47; resolves locale flows on sendByConfigKey
referenceId: "user_42", // your id, echoed back on every event
optIn: { source: "checkout" },
});
// Set the language later, or mark enrollment state read by gated automations.
// `metadata` is shallow-merged; `preferredLanguage: null` clears it.
await wabery.contacts.update(contact.id, {
preferredLanguage: "id",
metadata: { linked: true },
});
Instagram Direct and Facebook Messenger can be connected directly from
Channels. Once connected, they appear in wabery.channels.list(). They
remain beta: no WhatsApp Flows, no WhatsApp templates, no proactive template
sends, and only limited structured reply support.
A channel's routing_mode decides what happens to inbound on it — AGENT runs
your Wabery-hosted agent with its automations and functions, EXTERNAL forwards
to your project webhook. For a dedicated number this overrides the project's
routing_mode, so inbound on a channel left in AGENT under an EXTERNAL
project goes to the hosted agent instead of your webhook. New channels inherit
the project routing at connect time.
list() / get() return a routing_warning when a channel bypasses the
project's configured webhook, and update() lets you fix it (or set it in CI):
const { data } = await wabery.channels.list();
for (const channel of data) {
if (channel.routing_warning) console.warn(channel.id, channel.routing_warning);
}
// Forward this dedicated number's inbound to your webhook.
await wabery.channels.update("channel_...", { routingMode: "EXTERNAL" });
// Or set the project-wide default that new channels inherit.
await wabery.projects.update("project_...", { routingMode: "EXTERNAL" });
WhatsApp channels and projects also expose publish_readiness. The sandbox can
publish Flows but cannot submit templates; dedicated WhatsApp channels must have
a Meta-verified business account before Flows or templates are submitted.
Template submission and proactive template sends also require a Meta payment
method; if NO_PAYMENT_METHOD is present, add one in Meta Business Settings
before sending templates. If readiness blockers such as BUSINESS_NOT_VERIFIED
or NO_PAYMENT_METHOD are present, publish/template calls return 412 with
the same publish_readiness object and do not queue work.
Author a flow's draft with the typed builders, apply it, then publish:
import { defineFlow, screen, textField, numberField, choiceField } from "@wabery/sdk";
const draft = defineFlow([
screen("intake", "Tell us about your project", [
textField("name", { label: "Your name", required: true }),
numberField("budget", { label: "Budget (USD)" }),
choiceField("timeline", {
label: "Timeline",
options: [
{ id: "asap", title: "ASAP" },
{ id: "this_month", title: "This month" },
],
}),
]),
]);
await wabery.config.apply({
flows: [{ key: "lead_intake", name: "Lead intake", draft }],
automations: [],
});
// config.apply works in flow keys; publish/send work in flow_ids. Bridge them:
const flow = await wabery.flows.findByConfigKey("lead_intake");
await wabery.flows.publish(flow.id); // queues the publish job
// Meta reviews asynchronously; poll until it is sendable:
await wabery.flows.waitUntilPublishable(flow.id, { timeoutMs: 120_000 });
// Or force a one-off live status refresh:
await wabery.flows.status(flow.id);
const { flow_token } = await wabery.flows.send(flow.id, {
channelId: "channel_...",
contactId: "contact_...", // exactly one recipient: contactId | conversationId | to
});
// Inspect, debug, and clean up:
const full = await wabery.flows.get(flow.id); // includes the compiled flow_json
const { data: events } = await wabery.flows.events(flow.id); // publish/submission/reconcile log
await wabery.flows.delete(flow.id); // draft → delete on Meta, published → deprecate
Prefer hand-written Meta Flow JSON? Set flow_json (typed as MetaFlowJson)
instead of draft, and check it locally before publishing with validateFlowJson(json)
— a structural-only check (missing version, no terminal screen, dangling/unreachable
screens). A clean result does not guarantee Meta will accept it (e.g. flow-name
uniqueness is only enforced at publish). The completed submission arrives on your
flow.completed webhook — there is no onSubmit URL — with valid and, when
invalid, validation_errors. Correlate it via the flow_token returned from
flows.send, or via contact_reference echoed on every event.
WhatsApp Flows have no native locale switch. For fixed copy, translate a draft into
one draft per language with localizeFlow, publish each as a flow that shares one
config_key with a distinct locale (omit locale for the group default), then
send by config key — Wabery resolves the variant for the contact's language:
import { localizeFlow } from "@wabery/sdk";
const byLocale = localizeFlow(draft, {
en: {}, // group default (no locale)
es: { "Your name": "Tu nombre", Submit: "Enviar" },
});
await wabery.config.apply({
flows: [
{ key: "lead_intake", name: "Lead intake", draft: byLocale.en },
{ key: "lead_intake", name: "Lead intake (es)", locale: "es", draft: byLocale.es },
],
automations: [],
});
// publish each variant, then let Wabery pick by the contact's preferredLanguage
// (explicit locale -> contact language -> "" default), falling back gracefully:
const { flow_token, locale } = await wabery.flows.sendByConfigKey("lead_intake", {
channelId: "channel_...",
contactId: "contact_...", // uses this contact's preferredLanguage
locale: "es", // optional override
});
For per-user copy, drive translations through the data-exchange endpoint instead.
An interactive flows.send only works inside the 24-hour customer-service window.
To reach a contact proactively, send an approved flow-type message template (a
template with a FLOW button) and pass the flow token via a button action:
await wabery.messages.send({
channelId: "channel_...",
to: "+14155550100",
template: {
name: "daily_reminder",
language: "en",
components: [
{
type: "button",
sub_type: "flow",
index: "0",
parameters: [{ type: "action", action: { flow_token: "..." } }],
},
],
},
});
For DATA_EXCHANGE flows, Wabery POSTs each call to your data_exchange_url,
signed with the same x-wabery-signature scheme and secret as webhooks. Verify
the request and build the reply with the typed helpers:
import {
dataExchangeComplete,
dataExchangeError,
dataExchangeScreen,
flowOptions,
} from "@wabery/sdk";
const req = wabery.webhooks.verifyDataExchange(rawBody, signatureHeader, secret);
const projects = await projectsFor(req.contact_reference, req.data?.workspace);
return dataExchangeScreen("SELECT", {
...flowOptions("project", projects), // -> { project_options: [{ id, title }] }
});
// Show a message instead of advancing:
// return dataExchangeError("SELECT", "No active projects in this workspace.");
// Close the flow; params arrive as the flow.completed submission:
// return dataExchangeComplete({ workspace: "ws_1", project: "proj_a" });
data you return becomes the screen's whole data
model, so resend every <field>_options list and prefill the screen needs.2xx JSON object of at most
64 KB, no redirects. screen must be a screen in the flow, or SUCCESS via
dataExchangeComplete. Wabery answers WhatsApp's ping health checks itself.SUCCESS; validateFlowJson flags it.See Dynamic flows for the full request and reply reference.
Hosted functions are Wabery-hosted TypeScript handlers for message-triggered logic, Business Agent tools, and external MCP/tool invocation. Create metadata, deploy source, test, then expose as a tool if needed:
const fn = await wabery.functions.create({
slug: "quote-customer",
name: "Quote customer",
triggerType: "ANY_MESSAGE",
});
await wabery.functions.deploy(fn.id, {
source: `
export default async function handler(ctx) {
ctx.log("received", ctx.event.type);
return { output: { ok: true } };
}
`,
});
await wabery.functions.update(fn.id, { isActive: true });
await wabery.functions.test(fn.id, { text: "I need a quote" });
await wabery.functions.update(fn.id, {
exposeAsMcpTool: true,
inputSchema: { type: "object" },
});
await wabery.functions.invoke(fn.id, {
arguments: { orderId: "ord_123" },
});
const logs = await wabery.functions.logs(fn.id);
Use API scopes functions:read, functions:write, and functions:invoke for
least-privilege keys.
Exercise your webhook and data-exchange handlers without deploying. signPayload
produces the x-wabery-signature header so you can POST fixtures to your local server:
import { signPayload } from "@wabery/sdk";
const body = JSON.stringify(myFakeEvent);
await fetch("http://localhost:3000/webhooks", {
method: "POST",
headers: { "x-wabery-signature": signPayload(body, secret) },
body,
});
Or use the CLI: wabery webhooks send-test --url <url> --secret <s> and
wabery flows test --url <url> --secret <s> --action data_exchange.