# Wabery — Full Documentation > Wabery helps you build, reuse, and manage WhatsApp AI agents for your clients. > Start with Wabery's runtime, or use scoped Wabery actions with an eligible > Meta Business Agent pilot. The messaging API remains available for developers. REST base URL: https://api.wabery.com/v1 Dashboard: https://app.wabery.com OpenAPI: https://api.wabery.com/v1/openapi.json Index: https://wabery.com/llms.txt Wabery developer resources: https://wabery.com/developers/ CLI on npm: https://www.npmjs.com/package/@wabery/cli MCP: https://mcp.wabery.com MCP manifest: https://wabery.com/.well-known/mcp.json Privacy: https://wabery.com/privacy/ Deprecation policy: https://wabery.com/docs/api-versioning/ This file concatenates every page of the Wabery docs so an AI agent can load the full reference in one fetch. Do not crawl the marketing site. ## Pricing Wabery is priced by production connections, not message volume alone. The tiers are: - Free — 1 production connection, 1,000 messages/mo, hard pause on overage — $0 - Wabery Pro — 1 production connection + 50K shared messages/mo included — $15/mo - Additional production connections (2–9) — $5/mo each - Additional production connections (10–100) — $3/mo each - Additional message capacity — each extra 50K messages/mo — $15/mo - Enterprise (100+ projects or high throughput) — contact sales@wabery.com Full breakdown: https://wabery.com/pricing.md Use the dashboard or the limits API for the current project's active quota and capabilities. Imported WhatsApp chat history does not count toward the monthly message allowance. Neither do messages Meta shares with Wabery while another app, such as a Meta Business Agent, controls a conversation. For dedicated WABAs, Meta bills message and template fees to the customer directly. For shared-sandbox delivery, Wabery deducts Meta's published destination-market service rate from the testing organization's wallet without markup. AI usage is billed separately. New accounts receive $1 of wallet credit to test a Wabery-hosted AI agent without a card. The first successful wallet top-up of $10 or more adds $2 bonus credit. Automatic top-ups are off by default. --- # Introduction Build an agent once, adapt it for each client, and keep their access, data, channels, and versions separate. You manage the client relationship and your service price; Wabery provides the agent, action, and WhatsApp infrastructure. Marketplace discovery, seller payouts, and guaranteed earnings are not included. Use Wabery's agent directly, or explore the limited Meta Business Agent pilot: Meta handles the conversation while Wabery connects your client's business actions. Your client needs Meta Business Agent access and must authorize their WhatsApp account. Native Meta Flow and MCP connections are not supported yet. Choose Reservations in the same agent setup when the client needs Wabery to manage availability. Tables reserve one whole table or an explicit table bundle per party; Classes reserve places and configured named resources in dated group sessions, such as yoga classes. Private appointments allocate configured staff and resource bundles. Configure business hours, inventory, rules and a responsible operator without an external booking system or hosted function. Wabery records a confirmed allocation only after exact customer confirmation. Keep phone bookings and walk-ins in the same agenda. Appointment requests remain intake that needs business confirmation; they do not hold inventory. Reservations supports explicit table combinations, named class rooms or equipment, private appointments with staff schedules, waitlists, business-issued service credits and read-only iCalendar sharing. Service credits are not money or proof of payment. Payments, deposits and two-way external calendar or booking-system synchronization are not included. Reservations uses frozen synthetic WhatsApp demos, client-owned asset connection, cost/runtime review and deliberate launch in the same workspace. Booking rules can be published for manual calendar use without WhatsApp; customer-facing agent booking actions are launched separately. AI can propose supported configuration changes for review; applying a draft cannot launch it or create arbitrary integrations. Operators see actual booking states and failed or uncertain customer notices for manual follow-up. Pausing live automation and revoking a demo are independent. Each client retains separate inventory, versions and access. Known Wabery costs are visible; unavailable external costs are unknown. Reservas también está disponible en la configuración unificada. Admite mesas y combinaciones explícitas, plazas de clases con salas o equipos asignados, y citas privadas con horarios del personal y recursos concretos. Configura horarios, inventario, reglas y responsable sin otro sistema de reservas ni una función propia. La IA propone cambios para revisar; guardar un borrador no activa el agente. La demostración de WhatsApp es simulada, y cada cliente conecta su propio número cuando lo necesita; el propietario o administrador revisa los costes y publica de forma deliberada. El acceso del cliente es opcional. Una entrada u oferta en lista de espera no guarda capacidad. El negocio puede emitir créditos de servicio que no son dinero ni prueba de pago. Registra las reservas telefónicas en la misma agenda y revisa los avisos fallidos o inciertos. No incluye pagos, depósitos ni sincronización bidireccional con calendarios o sistemas externos. Las solicitudes de cita siguen pendientes de confirmación del negocio. Choose Leads in the same setup when the client needs approved enquiry details for human follow-up. Configure the exact fields and responsible person. The prospect WhatsApp demo uses frozen synthetic data and never writes production leads. After client-owned connection, current cost approval and deliberate launch, the verified sender must confirm the exact details before Wabery stores them. The enquiry remains qualifying until an operator changes its stage; Wabery does not invent a score or promise a sale. Elige Leads en la misma configuración cuando el cliente necesite datos de consulta aprobados para seguimiento humano. Configura los campos exactos y la persona responsable. La demostración de WhatsApp usa datos sintéticos congelados y no escribe leads de producción. Tras la conexión propiedad del cliente, la aprobación de costes actual y el lanzamiento deliberado, el remitente verificado debe confirmar los datos exactos antes de que Wabery los guarde. La consulta permanece en calificación hasta que una persona cambie su etapa; Wabery no inventa una puntuación ni promete una venta. Choose Appointment requests while setting up the agent. The template guides business details, request fields and a responsible person. It prepares an agent and form without a custom hosted function or manual action credentials. Requests go to Wabery's inbox; a routing note does not connect an external booking platform. Publish and test the form, obtain the client's own WhatsApp connection when that channel is needed, review costs and runtime readiness, then deliberately publish. Installation, connection, and invitation acceptance do not activate the agent. Client access is optional, uses View-only or Editor roles, and is not a publication approval gate. Reuse keeps each client's configuration and data separate. Packaged WhatsApp demo invitations need no agency membership for the prospect. They use frozen synthetic business data, one participant, expiry, revocation, attempt limits and delivery limits. A submitted sample request is simulated; it never books a slot or calls a production business system. The creator organization pays actual AI use. Shared-sandbox delivery is free through September 30, 2026; from October 1, that organization's wallet pays Meta's published destination-market service rate without Wabery markup. Demo limits do not change automatic top-ups or cap other projects. Expiry, revocation, exhausted allowance or insufficient credit never triggers another paid runtime. Inspect recorded requests before retrying a failure; an absent notification does not mean a request was lost. The business must confirm an appointment separately, and recording that decision does not automatically contact the customer. Pause production and revoke demo access independently. Wabery runtime AI uses the Wabery wallet. Meta and external backend charges remain separate; unavailable usage is not zero. A Wabery wallet limit does not cap Meta's bill, and stopping one runtime does not silently switch you to another paid runtime. The developer API also covers channels, signed webhooks, broadcasts, WhatsApp Flows, and hosted functions. Use it when your client's workflow needs custom logic. ## Current project and channel workflows ### Projects and safe copies Use one project for each business or independent operation. A project copy starts as an inactive draft and includes saved agent configuration, automations, forms, appointment-request settings, Leads settings, and Reservations configuration. Reusable knowledge is optional and becomes an independent copy. Customer data, conversations, leads, requests, bookings, client access, credentials, channel connections, live deployments, and spending history are never copied. Full guide: https://wabery.com/docs/projects/ ### Client project access Invite a verified email as View only or Editor. View-only members can inspect the assigned project's inbox, calendar, leads, and details. Editors can also reply, update leads and project details, and handle appointment requests. Manage bookings is a separate Editor grant. Invitations expire after 72 hours. Clients cannot publish, see organization billing or credentials, or access other projects. They can opt into email alerts for leads, appointment requests, and booking changes. Full guide: https://wabery.com/docs/client-project-access/ ### Website chat Configure a welcome message, brand colors, launcher position, and up to 20 exact allowed origins. Add www and non-www hosts separately when both should work, then install the project-specific script. Website visitors enter the same project inbox and hosted-agent routing; the widget grants no workspace access. Full guide: https://wabery.com/docs/website-chat/ ### Shopify products Attach up to three public Shopify stores to an agent. Wabery reads public product titles, descriptions, URLs, variants, prices, currencies, and availability. It cannot read customers or orders, create carts, change products or inventory, or access Shopify Admin. Full guide: https://wabery.com/docs/shopify-connector/ ### Agent languages and private browser testing New agent instructions, saved replies, and generated Flows can use English, Spanish, or Indonesian. Smart Replies can follow the sender's language or use one fixed supported language. A private browser test link can expire after one hour, 24 hours, or seven days and allow 10 or 30 messages. A replacement link disables the old one. It sends no WhatsApp message, exposes no business action, and still uses the project's model and Wabery Wallet. Full guide: https://wabery.com/docs/hosted-agent/ ## What you get - [Unified channels](https://wabery.com/docs/channels): Send and receive on WhatsApp Business through one clean API. - [Signed webhooks](https://wabery.com/docs/webhooks): Every message, status, and submission delivered as a typed, signed event. - [WhatsApp Flows](https://wabery.com/docs/flows): Native in-chat forms that return clean, validated submissions. - [Hosted functions](https://wabery.com/docs/hosted-functions): Server-side TypeScript handlers for workflow and agent tool logic. - [Registration intents](https://wabery.com/docs/registration-intents): Single-use WhatsApp onboarding links safe to create from your app. - [WhatsApp broadcasts](https://wabery.com/docs/broadcasts): Send approved templates to a prepared, consent-eligible audience immediately or on a schedule. - [CLI](https://wabery.com/docs/cli): Manage channels, contacts, broadcasts, Flows, and hosted functions from your terminal. - [WhatsApp MCP Server](https://wabery.com/docs/mcp): Hosted and local MCP servers so Claude, ChatGPT, Cursor, or Codex can build on WhatsApp. - [SDK API reference](https://wabery.com/sdk-reference): Generated reference for every `@wabery/sdk` method, type, and helper. ## If you just signed up Start here. You do not need a production WhatsApp number for the first test. 1. Open your first project in the dashboard and copy the sandbox join code. 2. Send that join code to the shared Wabery sandbox number from your test phone. 3. Send one normal WhatsApp message after the join code; that creates a conversation. 4. Run `wabery login`, then `wabery doctor`, or create a key under [**Access → API keys**](https://app.wabery.com/access?tab=api-keys). 5. Follow the [Quickstart](https://wabery.com/docs/quickstart) to send your first reply. After that first loop works, choose the next layer: signed webhooks for inbound events, WhatsApp Flows for structured forms, hosted functions for server-side workflow logic, or a dedicated WhatsApp channel for production traffic. ## Find features in the dashboard The left sidebar follows the current project and groups work by purpose: | Sidebar | Use it for | | --- | --- | | **Daily work → Inbox** | Read and reply to conversations, including human handoff. | | **Daily work → Bookings** | When enabled, manage the calendar, appointment requests, waitlist, and service credits. | | **Daily work → Leads** | When enabled, review customer-confirmed enquiries, heat signals, and stages. | | **Daily work → Contacts** | Browse customer records, consent, and suppressions. | | **Manage → Agent** | Edit the hosted-agent Draft, knowledge, automations, modules, model, language, voice, and publication state. | | **Manage → Channels** | Connect WhatsApp, Messenger, Instagram, or website chat and inspect routing. | | **Manage → Settings** | Update project details, staff alerts, and optional client project access. | | **Developer → Access** | Manage connected apps and agents, project API keys, and browser-safe registration. | | **Developer → Webhooks** | Configure the endpoint and signing secret, then inspect delivery history and retries. | | **Workspace → Projects** | Switch, add, and safely copy projects. | | **Workspace → Usage & billing** | Review plan, wallet, usage, and spending controls. | Some entries appear only when their module is enabled or the current user has permission. Flows, templates, broadcasts, and advanced functions remain available from their relevant product and developer surfaces. ## How it fits together 1. **Start with a channel** — use the shared sandbox immediately, or connect a dedicated WhatsApp Business account later. 2. **Send & receive** — call the API (or SDK) to send messages; receive inbound messages, files, and statuses as signed webhooks, and pull thread history from the conversations API. 3. **Register customers** — use registration intents to link a customer's WhatsApp identity to your own user id without exposing a secret key. 4. **Collect structured data** — define a WhatsApp Flow once and get back clean submissions at your endpoint. 5. **Broadcast safely** — prepare a frozen, consent-eligible audience, review its counts, then send or schedule an approved WhatsApp template. 6. **Run workflow logic** — deploy hosted functions when an automation or agent tool needs server-side TypeScript. ## Capability map Wabery's public API, SDK, CLI, and MCP server cover the full messaging workflow: | Area | What you can do | | --- | --- | | [Channels](https://wabery.com/docs/channels) | Connect and route WhatsApp, Messenger, Instagram, and website chat; provider requirements differ. | | [Messages](https://wabery.com/docs/sending-messages) | Send text, approved templates, outbound media (image, video, document, audio), interactive WhatsApp messages (reply buttons, lists, `cta_url` link buttons, location and contact-info prompts), reactions, locations, stickers, contact cards, and WhatsApp Flows. Quote any message with `reply_to`. Track delivery with `message.status` webhooks. | | [Inbound events](https://wabery.com/docs/webhooks#inbound-media-files) | Receive signed `message.received` webhooks for text, media files, locations, contacts, and other inbound message types. Media files include short-lived Wabery download URLs. | | [Conversations](https://wabery.com/docs/conversations) | List conversations and message history; retained inbound media is re-signed when read through the conversation history API. | | [Contacts & registration](https://wabery.com/docs/contacts) | Enroll opted-in contacts server-side, or mint browser-safe [registration intents](https://wabery.com/docs/registration-intents) that link a customer's WhatsApp identity to your own user id. | | [Broadcasts](https://wabery.com/docs/broadcasts) | Import or select consented contacts, freeze an audience snapshot, then send or schedule approved localized WhatsApp templates with frequency limits, suppressions, and delivery counts. | | [WhatsApp Flows](https://wabery.com/docs/flows) | Author static or dynamic Flows, publish them to Meta, localize by config key, run data-exchange endpoints, inspect dispatches, submissions, and flow event logs. | | [Hosted functions](https://wabery.com/docs/hosted-functions) | Deploy project-scoped TypeScript handlers, test them, expose them as Business Agent or MCP-callable tools, and inspect invocation logs. | | [Templates](https://wabery.com/docs/templates) | Create, submit, inspect, and send WhatsApp templates, including flow-type templates for proactive Flow entry points. | | [Automations](https://wabery.com/docs/automations) | Handle conversations with no code: trigger on welcome, keyword, or any message, then chain actions — send replies, send flows, run a function inline, delay, wait for a reply, branch on a condition, or hand off to a human. Switch to external routing when your webhook owns the reply logic. | | [Reservations](https://wabery.com/docs/reservations) | Own availability for tables, classes, or private appointments; manage waitlists, service credits, and read-only calendar sharing. | | [Leads](https://wabery.com/docs/leads) | Collect customer-confirmed details, show a simple heat signal, and let people own the sales stage. | | [Website chat](https://wabery.com/docs/website-chat) | Embed the project agent on explicitly allowed website origins and route conversations to the same inbox. | | [Shopify connector](https://wabery.com/docs/shopify-connector) | Read public catalog data from up to three stores without order, customer, cart, Admin, or write access. | | Config as code | Export, validate, diff, and apply project configuration for webhooks, flows, and automations. | | Business Agents | Use the REST/OpenAPI surface to provision Meta Business Agents, connectors, tools, thread control, tests, evals, and skills where available for your Meta setup. | > **New here?** Start with the [Quickstart](https://wabery.com/docs/quickstart) — from API key to your first message in one file. > Start building — free: https://app.wabery.com/login?join=true --- # Let an AI agent set up Wabery Your AI agent can create your Wabery account, build and test your WhatsApp setup, and take it live for you. You don't need to work in the dashboard. You stay in control: the agent asks you to approve its access, sends you a link for each step only you can do, and publishes to Live only after you confirm. This works with any agent that can make HTTP requests or use MCP, such as Claude Code, Codex, or Cursor. Ask it to set up WhatsApp with Wabery, or point it to [wabery.com/auth.md](https://wabery.com/auth.md). ## Who does what | Step | Your agent | You | | --- | --- | --- | | Create your account | Asks for your email and sends you a link with a 6-digit code | Sign in or create your account, check the code, choose a project, and approve | | Build the setup | Sets your webhook or builds the hosted agent's Draft | Nothing | | Test on the sandbox | Sends you a WhatsApp link | Open it on your phone and send the prefilled code | | Connect your number | Sends you a connection link | Sign in to Facebook and connect your number with Meta | | Publish the hosted agent | Shows you the changes and asks you to confirm | Confirm, or ask for changes | | Go live | Tells you anything Meta still needs | Finish it in your Meta account | ## 1. Approve your agent's access Your agent asks for the email you use for Wabery, or want to use. It then sends you a link like `https://app.wabery.com/authorize-agent?code=123456` and a 6-digit code. 1. Open the link. Sign in with that email, or create your account with it. Wabery emails you a sign-in code. If the account is new, Wabery creates your workspace and a first project, then returns you to the request. 2. Check that the page shows the same code as your agent. 3. Choose the project the agent can work on, then select **Approve access**. Your agent then receives an API key for that project. It can manage channels, flows, contacts, and functions, send messages from the project, and publish your agent to Live after you confirm the changes. It cannot erase contacts or create other API keys. The link expires after 15 minutes. If it expires, ask your agent to start again. Only workspace owners and admins can approve. If the page says you're signed in with a different email, sign in with the email your agent asked for. > **Only approve requests you started:** Approve only when you asked your own agent to connect to Wabery. Wabery never asks you to approve a request someone else sent you. `wabery login --email you@example.com` uses the same approval flow, so the [CLI](https://wabery.com/docs/cli/) no longer asks you to copy and paste a key. ## 2. Your agent follows the setup checklist After you approve, your agent reads a checklist of the remaining steps. For each step, Wabery tells the agent whether it can do the step itself through the API, or whether it needs you, and gives it any link to send you. You'll hear from your agent only when there's something for you to do. The steps depend on who answers your customers: - **Your own app or agent answers:** your agent sets the HTTPS webhook that receives inbound messages. See [external automations](https://wabery.com/docs/external-automations/). - **Wabery's hosted agent answers:** your agent builds the hosted agent's Draft and assigns your channel to it. See [hosted agent](https://wabery.com/docs/hosted-agent/). If your number already answers through your own app, your agent asks before switching to the hosted agent. It keeps your number on your app while you test the hosted agent on the sandbox, and moves the number over only when you confirm the publish. ## 3. Test on the sandbox Your agent sends you a WhatsApp link. Open it on your phone and send the prefilled message. It contains your project's join code, and your next messages to the shared Wabery number reach your project. Your agent can then check the replies with you. See [Wabery sandbox](https://wabery.com/docs/sandbox/). ## 4. Connect your WhatsApp number When you're ready for real customers, your agent sends you a connection link. It asks first whether you use the WhatsApp Business app on that number, so you can keep using the app if you do. Open the link, sign in to Facebook, and connect your number with Meta. You don't need to sign in to Wabery. The link works once and expires after 7 days. Anyone with the link can finish this setup, so don't forward it. Your agent can create links for a new number or a number that uses the Business app. If another WhatsApp API provider already uses the number, the number stays there: you share the same WhatsApp account with Wabery during setup. See [Connect WhatsApp](https://wabery.com/docs/connect-whatsapp/). Meta charges you directly for WhatsApp conversations on your own number. See [WhatsApp pricing](https://wabery.com/docs/whatsapp-pricing/). ## 5. Confirm each publish This step applies when Wabery's hosted agent answers your customers. Your agent edits only the Draft. Your customers keep getting the Live version until you confirm a publish. Before publishing, your agent shows you what changed and which channels it affects. Reply to confirm, or ask for changes. Your agent publishes only after you confirm, and every later change needs your confirmation again. Publishing runs the same checks as **Agent → Review and publish** in the dashboard. Your agent may also ask you to approve: - moving a channel from your webhook to the hosted agent - applying the Draft to every channel that is already live - going live with automations only while AI replies are unavailable, for example before you add wallet credit > **You decide what goes live:** Wabery relies on your agent to show you the changes and ask before it publishes. It can't see your conversation with your agent, so you are responsible for what you confirm. Apps connected through the hosted MCP server, such as Claude, must also show you an approval prompt before they publish. Wabery refuses the publish if the app can't ask you. You can still review and publish yourself on **Agent** at any time. ## 6. Go live After your number connects, Meta may still need something from you before real customers can message it, such as a payment method on your WhatsApp Business Account. Your agent tells you exactly what's missing. Finish it in your Meta account, and your agent confirms when you're live. ## Remove your agent's access Open [**Access → API keys**](https://app.wabery.com/access?tab=api-keys) and revoke the key named after your agent and project. Your agent loses access immediately. Apps connected through the hosted MCP server are listed under **Access → Connections**. ## For AI agents - Registration, claim, and the full onboarding walkthrough: [auth.md](https://wabery.com/auth.md) - Checklist: `GET https://api.wabery.com/v1/onboarding` - Customer connection links: `POST /v1/onboarding/handoffs`, then poll `GET /v1/onboarding/handoffs/{id}` - Publishing: `GET /v1/agent/publish-review`, then `POST /v1/agent/publish` with `customer_confirmed: true` after the customer confirms - MCP tools: `wabery_get_onboarding`, `wabery_create_onboarding_handoff`, `wabery_get_onboarding_handoff`, `wabery_get_agent_publish_review`, `wabery_publish_agent` - CLI: `wabery login --email`, `wabery onboard`, `wabery onboard connect-whatsapp`, `wabery onboard publish-review`, `wabery onboard publish` - [OpenAPI spec](https://api.wabery.com/v1/openapi.json) --- # Quickstart From a new project to your first WhatsApp reply. This guide starts from an empty Wabery project and sends your first WhatsApp reply. A new project can use the shared Wabery sandbox immediately: register your test phone with the project's join code, send one normal inbound message, then reply from the SDK, CLI, or API. ## Before you start You need: - a Wabery project; new signups get one during onboarding - the sandbox join code for that project - a phone with WhatsApp installed - either `wabery login` completed, or a server-side key from [**Access → API keys**](https://app.wabery.com/access?tab=api-keys) You do **not** need a dedicated WhatsApp Business number for this quickstart. The shared sandbox is enough to send your first reply. > The join-code message only connects your phone to the project. It is not shown as a chat bubble. After WhatsApp confirms the code was sent, send a normal message like "hello from quickstart"; that creates the conversation you can reply to. ## 1. Create or pick a project If you just signed up, Wabery creates your first project during onboarding and shows: - the project join code, formatted like `wab-ABC123` - a default API key, shown once - the shared sandbox WhatsApp number If you skipped that step, open the dashboard, create a project, then find its join code in **Project settings**. From the CLI, `wabery projects list` and `wabery projects get "project_id"` also return `join_code` plus the effective `enrollment_channel.phone_number` to message. ## 2. Sign in or set the API key Install the CLI and run `wabery login`. It shows an approval link and a 6-digit code. Sign in, or create your account, check the code, choose a project, and approve. The CLI receives a key scoped to that project and stores it in your local config: ```bash npm i -g @wabery/cli wabery login --email you@example.com # use --no-open on a headless box wabery doctor # confirms the saved key, project, and base URL work ``` No global install needed — run it on demand instead: `npx wabery login` (or `pnpm dlx wabery login`, `bunx wabery login`). Want files for your app too? After login, run: ```bash wabery init --name "My project" ``` That creates `.env.wabery`, `wabery.config.json`, and a `wabery-webhook-handler.ts` stub without overwriting existing files. You can skip it for this quickstart; it is just a scaffold for your real app. > Prefer to manage the key yourself? Create one under [**Access → API keys**](https://app.wabery.com/access?tab=api-keys) (live keys are prefixed `wab_live_`) and set `WABERY_API_KEY` — it overrides the CLI config. Never ship a `wab_live_` key to the browser or commit it to git. See [Authentication](https://wabery.com/docs/authentication). ## 3. Connect a test phone Send the project's join code to the shared Wabery sandbox number from the phone you want to test with. If the dashboard gives you a WhatsApp button, use it; it opens WhatsApp with the code prefilled. CLI/agent path: ```bash wabery projects list wabery projects get "project_id" # read join_code + enrollment_channel.phone_number ``` After the phone is connected, send a normal message to the same sandbox chat: ```text hello from quickstart ``` Now verify that the project has a channel and inspect the latest conversation: ```bash wabery channels list wabery conversations list wabery conversations messages "conversation_..." ``` Use the sandbox `channel_id` and the new `conversation_id` in the send call below. If the conversation exists but has no inbound message yet, the join code registered the phone but the normal test message has not arrived; send one more WhatsApp message to the sandbox chat. > Building customer onboarding instead of testing your own phone? Use [registration intents](https://wabery.com/docs/registration-intents) to mint browser-safe WhatsApp links, or [contacts.enroll](https://wabery.com/docs/contacts#enroll-a-contact) when your server already has the phone number and opt-in evidence. ## 4. Install the SDK ```bash npm install @wabery/sdk ``` ## 5. Reply to the conversation Use the `conversation_id` from the inbound message you just sent. WhatsApp free-form replies require an open messaging window; outside that window, send an approved template instead. **SDK:** ```ts title="send.ts" import { Wabery } from "@wabery/sdk"; const wabery = new Wabery(); await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", text: "Thanks for your message", }); ``` **CLI:** ```bash wabery messages send \ --channel-id "channel_..." \ --conversation-id "conversation_..." \ --text "Thanks for your message" ``` **curl:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "text": "Thanks for your message" }' ``` A successful call returns `202 Accepted` with the queued message id. Delivery happens asynchronously. Within a few seconds, the reply should appear in the same WhatsApp sandbox chat where you sent the normal test message. Inspect it with `wabery.messages.get("msg_...")`, `wabery messages get "msg_..."`, or the `message.status` webhook. For proactive WhatsApp sends to a phone number, use a dedicated channel and record contact opt-in first. ## 6. Receive the next message Replies (and delivery statuses) arrive at your webhook as signed events — no polling required: ```json { "event": "message.received", "payload": { "object": "message", "content": "do you ship internationally?" } } ``` Point an endpoint at Wabery and verify the signature — see [Webhooks](https://wabery.com/docs/webhooks). ## Next steps - [Authentication](https://wabery.com/docs/authentication): API keys and webhook signing secrets. - [Sending messages](https://wabery.com/docs/sending-messages): Text, templates, and the full send reference. - [Registration intents](https://wabery.com/docs/registration-intents): Link customers from your app with single-use WhatsApp onboarding links. - [WhatsApp Flows](https://wabery.com/docs/flows): Collect structured data with in-chat forms. - [Hosted functions](https://wabery.com/docs/hosted-functions): Run server-side TypeScript for workflow and tool logic. - [CLI](https://wabery.com/docs/cli): Ship from your terminal. - [WhatsApp MCP Server](https://wabery.com/docs/mcp): Ship by describing it to Claude, ChatGPT, Cursor, or Codex. > Get your API key — free: https://app.wabery.com/login?join=true --- # PHP, Python, and API clients Wabery's REST API works from any server-side HTTP client. The TypeScript SDK is optional. PHP and Python use the same base URL, Bearer authentication, JSON bodies, idempotency keys, and response objects: ```text Base URL: https://api.wabery.com/v1 Authorization: Bearer Content-Type: application/json ``` Keep `wab_live_` keys in server-side environment variables. Never put them in browser code, mobile applications, source control, URLs, or shared API-client environment values. ## OpenAPI-compatible clients Import Wabery's canonical OpenAPI 3.1 contract into any compatible graphical, CLI, local, or hosted API client: ```text https://api.wabery.com/v1/openapi.json ``` Choose import from URL, select `https://api.wabery.com/v1` as the server if prompted, and configure Bearer authentication with `WABERY_API_KEY`. Wabery does not require or endorse a particular API client. ## PHP PHP 8.1 or newer with the cURL extension needs no Wabery package: ```php "channel_...", "conversation_id" => "conversation_...", "text" => "Thanks for your message", ], JSON_THROW_ON_ERROR); $handle = curl_init("https://api.wabery.com/v1/messages"); curl_setopt_array($handle, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("WABERY_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => $payload, ]); $responseBody = curl_exec($handle); $status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE); if ($responseBody === false || $status !== 202) { throw new RuntimeException("Wabery request failed with HTTP {$status}"); } ``` ## Python Install Requests with `python -m pip install requests`, then: ```python import os import requests response = requests.post( "https://api.wabery.com/v1/messages", headers={ "Authorization": f"Bearer {os.environ['WABERY_API_KEY']}", }, json={ "channel_id": "channel_...", "conversation_id": "conversation_...", "text": "Thanks for your message", }, timeout=(10, 30), ) response.raise_for_status() message = response.json() ``` Complete reusable clients, media examples, history reads, error handling, and constant-time webhook signature verification are at: https://wabery.com/docs/api-clients --- # Authentication API keys for requests and signing secrets for webhooks. Wabery uses API keys to authenticate requests and a **signing secret** to verify the webhooks Wabery sends you. ## Get a project key with the CLI The fastest way to get a project-scoped key is the CLI: ```bash npm i -g @wabery/cli wabery login # opens the browser, choose a project, paste the shown key once ``` `wabery login` creates an API key for the project you select and stores it in your local CLI config, so the CLI and the [MCP server](https://wabery.com/docs/mcp) are authenticated automatically after that first paste. Use `wabery doctor` to confirm it works. Create projects in the dashboard, then open [**Access → API keys**](https://app.wabery.com/access?tab=api-keys) to create, reveal, scope, or revoke a project key. ## API keys Keys are prefixed by capability: | Prefix | Use | | --- | --- | | `wab_live_` | Server-side API access in the shared sandbox and on connected channels. | | `wab_pub_` | Browser-safe publishable key for [registration intents](https://wabery.com/docs/registration-intents). | For your own services, set `WABERY_API_KEY` (it overrides the CLI config) and authenticate every request with a Bearer token: ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "text": "Hi" }' ``` The SDK reads the key for you: ```ts import { Wabery } from "@wabery/sdk"; const wabery = new Wabery(); ``` > `wab_live_` keys are server-side secrets. Don't expose them in client code, mobile apps, or git history. Rotate immediately if one leaks. ## Publishable keys Publishable keys (`wab_pub_...`) are safe to use in browser widgets, but only on the [registration-intent endpoints](https://wabery.com/docs/registration-intents). Send them in the `x-wabery-publishable-key` header, not as a Bearer token: ```bash curl https://api.wabery.com/v1/registration-intents \ -H "x-wabery-publishable-key: $WABERY_PUBLISHABLE_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_reference": "user_123" }' ``` The SDK and CLI do this automatically when `apiKey` / `WABERY_API_KEY` starts with `wab_pub_`. ## Webhook signing secret Each webhook endpoint has a signing secret. Wabery signs every delivery so you can confirm it really came from Wabery and wasn't tampered with — the signature arrives in the `x-wabery-signature` header as `sha256=`. See [Webhooks](https://wabery.com/docs/webhooks) for verification. ## Scopes API keys carry a set of scopes that limit blast radius. A request missing the required scope returns `403` with `error: "insufficient_scope"` and the `required_scope` in the body. Grant the narrowest set each integration needs: | Scope | Grants | | --- | --- | | `messages:send` | Send messages. | | `conversations:read` | List conversations and read message history. | | `contacts:read` / `contacts:write` | Read / enroll and update contacts. | | `contacts:erase` | Erase a contact's retained personal data. | | `broadcasts:read` / `broadcasts:write` / `broadcasts:send` | Read / create and manage / deliver broadcast campaigns. | | `templates:read` / `templates:write` | Read / create WhatsApp templates. | | `channels:read` / `channels:write` | List and inspect / update channel routing. | | `business_agents:read` / `business_agents:write` | Inspect / provision and manage Meta Business Agents, connectors, tools, settings, thread control, and skills. | | `flows:read` / `flows:send` / `flows:publish` | Read / send / publish WhatsApp Flows. | | `agents:publish` | Publish the hosted agent's Draft to Live. Only do this after the customer confirms the changes. | | `functions:read` / `functions:write` / `functions:invoke` | Read, deploy/manage, and invoke [hosted functions](https://wabery.com/docs/hosted-functions). | | `submissions:read` / `dispatches:read` | Read Flow submissions / dispatches. | | `projects:read` / `projects:write` | Read / update project settings (webhook URL, routing). | | `config:read` / `config:write` | Read / apply config-as-code. | | `registrations:create` | Mint [registration intents](https://wabery.com/docs/registration-intents) (also granted to `wab_pub_` keys). | | `limits:read` | Read the key's [rate limits and quota](https://wabery.com/docs/errors#rate-limits). | A wildcard (`*`) key grants every scope — use it only for trusted server-side automation. --- # Channels Connect and manage WhatsApp Business channels. A **channel** is a connected messaging account you send and receive through. Wabery focuses on WhatsApp Business channels. API calls target a concrete `channel_id` returned by `channels.list()`. | Surface | Channel | | --- | --- | | WhatsApp | WhatsApp Business numbers | ## Connect a channel Link an account from the dashboard under **Channels**, or bring an existing WhatsApp Business number. Once connected, your `wab_live_` key can send and receive on it. The sandbox gives you a shared test number with no Meta setup. Shared-sandbox delivery is free through September 30, 2026; from October 1, the published destination-market service rate is deducted from the testing organization's Wabery wallet without markup. AI usage is billed separately to that organization. ## Targeting a channel Every send takes a `channelId`: **SDK:** ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", text: "Thanks for reaching out!", }); ``` **curl:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "text": "Thanks for reaching out!" }' ``` > Use the `channel_id` returned by the API. For WhatsApp dedicated channels you can send to an E.164 phone number (`+14155550100`); otherwise send on an existing `conversationId`. ## Routing inbound messages Each channel has a `routing_mode` that decides what happens to inbound messages on it — `AGENT` runs your Wabery-hosted agent with its automations and functions, and `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's routing at connect time. See [Webhooks → Channel routing](https://wabery.com/docs/webhooks#channel-routing-overrides-the-project) for the full precedence rules. `channels.list()` / `channels.get(id)` include a `routing_warning` when a channel bypasses the project's configured webhook. Set a channel's routing in code: **SDK:** ```ts const { data } = await wabery.channels.list(); data.forEach((c) => c.routing_warning && console.warn(c.id, c.routing_warning)); await wabery.channels.update("channel_...", { routingMode: "EXTERNAL" }); ``` **CLI:** ```bash wabery channels list wabery channels update channel_... --routing-mode EXTERNAL ``` ## Publish readiness WhatsApp channels include `publish_readiness` on `channels.list()`, `channels.get(id)`, and project responses. Use it before publishing Flows or submitting templates: ```json { "can_publish_flows": false, "can_submit_templates": false, "business_verification_status": "not_verified", "account_review_status": "APPROVED", "phone_number_status": "CONNECTED", "blockers": ["BUSINESS_NOT_VERIFIED", "NO_PAYMENT_METHOD"] } ``` The shared Wabery sandbox can publish Flows when the sandbox WhatsApp Business Account is verified, but it cannot submit templates because templates belong to Wabery's sandbox account. Dedicated WhatsApp numbers must pass Meta's business and account readiness checks before Flows can be published. Templates have one extra billing prerequisite: template submission and proactive template sending require a Meta payment method on the WhatsApp Business Account. Without it, `can_publish_flows` can still be true, but `can_submit_templates` is false and `blockers` includes `NO_PAYMENT_METHOD`. Read [why WhatsApp templates need a payment method](https://wabery.com/blog/whatsapp-template-payment-method) for the billing context. Wabery returns `412` with the same `publish_readiness` blockers instead of queueing work that cannot succeed. ## Broadcast channel availability The broadcast composer lists only connected, dedicated WhatsApp numbers. Unavailable numbers remain visible with their exact blocker so an operator can fix the account instead of guessing. Common blockers include missing Meta billing, an unverified business, a restricted or disconnected number, poor quality, and a readiness check that must be retried. Wabery allows only one active dedicated WhatsApp channel for a normalized phone number across the platform. Reconnecting the same number reuses its eligible channel in the current organization and project; it never transfers a channel from another tenant. Disconnected rows are retained because historical messages refer to them, but they are not selectable for new broadcasts. This is why an older number can appear in channel history without representing another active sender. If a channel says **Payment method required**, add billing to the WhatsApp Business Account in Meta Business Manager and then refresh its status in Wabery. If it says the payment status could not be checked, retry the check before changing billing—the unknown state is not treated as proof that billing is missing. ## The 24-hour window WhatsApp restricts free-form messages to a 24-hour window after the user's last message. Outside the window you must use an approved template. Wabery returns a clear error when a send falls outside the window — see [Errors & rate limits](https://wabery.com/docs/errors). --- # WhatsApp usernames & user IDs Meta identifies WhatsApp users with a Business Scoped User ID (BSUID). The ID is scoped to the business portfolio that owns the WhatsApp number. In Wabery webhooks, `from` is the E.164 phone when disclosed (otherwise `null`), `user_id` is the BSUID when Meta supplies one, and `contact_id` remains the stable application-facing key. No API version change is required and existing phone-number sends remain unchanged. The public `to` input remains E.164-only. For sends addressed by `conversation_id`, Wabery maps a known phone to Meta's `to` field and a phone-hidden BSUID to Meta's dedicated `recipient` field, and prefers the phone whenever it is available. Webhook consumers must still accept `from: null` and `recipient_id: null`, join on `contact_id`, tolerate additive or unknown event types, and safely acknowledge `contact.identity.updated`. Do not parse a BSUID as a phone or compare it across portfolios. Wabery follows Meta identity-change system events on the existing `messages` subscription and emits `contact.identity.updated`. The nullable identity properties already exist in Wabery's webhook shape; the rollout populates them when Meta supplies the corresponding values. Manage a business username with GET, POST, or DELETE `/v1/channels/{id}/whatsapp-username`; retrieve Meta suggestions at `/v1/channels/{id}/whatsapp-username/suggestions`. SDK methods are available on `wabery.channels`. Current status is `approved` or `reserved`; POST accepts an optional `transfer_action` of `none` or `force_transfer`. Meta's `business_username_updates` events emit `channel.username.updated` with `approved`, `reserved`, or `deleted` status. Meta's current contract does not support canceling a pending username request. Meta business usernames use 3–35 English letters, digits, periods, or underscores and must contain a letter. They improve discovery but do not hide the business phone number. Use interactive type `request_contact_info` or a template `REQUEST_CONTACT_INFO` button with the fixed `Share Contact Info` text to request a phone. Meta rejects authentication templates sent to a BSUID (error `131062`), so Wabery only sends them to a phone number. Wabery only backfills a sender phone from a contact card when Meta marks it with `origin: "contact_request"`. --- # Contacts & opt-in Enroll opted-in WhatsApp contacts, manage language and metadata, and satisfy the opt-in requirement for proactive sends. A **contact** is an end user reachable on one of your channels, identified by a stable Wabery `id` (aliased as `contact_id`). A phone number is optional: Meta can represent a WhatsApp username user only by a Business Scoped User ID (BSUID). Wabery namespaces that identity to the owning Meta business portfolio and updates it when Meta sends an identity-change system event. Before you can send **proactively** to a WhatsApp number — a `to` send outside an existing conversation — that contact needs an **active opt-in record**. Replies inside the [24-hour window](https://wabery.com/docs/channels#the-24-hour-window) do not. > Inbound-only? You don't need to enroll anyone. When a contact messages you first, Wabery creates the contact and conversation automatically and the `message.received` webhook carries the `contact_id`. Enrollment is for server-side, proactive sends. ## Enroll a contact Record the contact and its opt-in in one call. `phone` is E.164. `optIn.source` is required when you pass an `optIn` block — capture where and how consent was given so it holds up to a WhatsApp quality review. **SDK:** ```ts const contact = await wabery.contacts.enroll({ phone: "+14155550100", name: "Ada Lovelace", preferredLanguage: "en", // BCP-47; resolves locale-specific flows referenceId: "user_123", // your own id; echoed back as contact_reference metadata: { plan: "pro" }, optIn: { source: "checkout_form", // required within optIn method: "web_form", occurredAt: "2026-06-20T14:00:00Z", consentText: "I agree to receive order updates on WhatsApp.", }, }); ``` **CLI:** ```bash wabery contacts enroll --project-id "project_id" \ --phone "+14155550100" \ --preferred-language "en" \ --metadata '{"plan":"pro"}' ``` **curl:** ```bash curl https://api.wabery.com/v1/contacts \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "phone": "+14155550100", "name": "Ada Lovelace", "preferred_language": "en", "reference_id": "user_123", "metadata": { "plan": "pro" }, "opt_in": { "source": "checkout_form", "method": "web_form", "occurred_at": "2026-06-20T14:00:00Z", "consent_text": "I agree to receive order updates on WhatsApp." } }' ``` Requires the `contacts:write` scope. `project_id` is optional — API keys are project-scoped, so it defaults to the key's project and must match it if set. A contact response: ```json { "object": "contact", "id": "contact_...", "contact_id": "contact_...", "phone": "+14155550100", "preferred_language": "en", "reference_id": "user_123", "project_id": "project_...", "status": "active" } ``` Use `id` in new code; `contact_id` is a backward-compatible alias with the same value. `reference_id` is your correlation key — it surfaces as `contact_reference` on every [webhook](https://wabery.com/docs/webhooks) for this contact. > Sending to a contact without an active opt-in returns `409` with `error: "contact_opt_in_required"`. Enroll with an `optIn` block, or send only inside the 24-hour window opened by the contact's own inbound message. ## Import a CSV Import up to 100,000 rows (25 MB) asynchronously. The required `phone` column must contain E.164 values. Optional mappings cover name, preferred language, tags, and metadata; tags are separated with `|` or `;`. ```bash wabery contacts import contacts.csv \ --phone-column phone --name-column name \ --language-column language --tags-column tags \ --consent '{"categories":["MARKETING"],"source":"signup_form","method":"web_form"}' wabery contacts imports wabery contacts import-status "import_id" ``` The optional consent declaration applies to every row. A phone number is not consent: include the declaration only when its wording, timestamp, source, and evidence are supportable for every imported contact. Poll until `completed`; rejected rows are available at `GET /contact-imports/{id}/errors`. ## Record consent or suppression Consent is category-specific: ```ts await wabery.contacts.addConsent("contact_...", { categories: ["MARKETING"], source: "account_preferences", method: "web_form", occurredAt: "2026-07-20T12:00:00Z", consentText: "Send me product announcements on WhatsApp.", evidence: { formVersion: "v3" }, }); ``` Suppress globally by omitting `category`, or suppress a single category: ```ts await wabery.contacts.suppress("contact_...", { category: "MARKETING", reason: "Requested by customer", }); ``` Inbound `STOP`, `UNSUBSCRIBE`, `CANCEL`, `END`, or `QUIT` creates a suppression automatically. Only genuine, newly recorded consent should lift it. ## Update language or metadata `metadata` is **shallow-merged** into the existing value; `preferredLanguage: null` clears it. Requires `contacts:write`. **SDK:** ```ts await wabery.contacts.update("contact_...", { preferredLanguage: "es", metadata: { linked: true }, // merged, not replaced }); ``` **CLI:** ```bash wabery contacts update "contact_..." --preferred-language "es" \ --metadata '{"linked": true}' ``` **curl:** ```bash curl -X PATCH https://api.wabery.com/v1/contacts/contact_... \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "preferred_language": "es", "metadata": { "linked": true } }' ``` ## List contacts Cursor-paginated with `limit` and `startingAfter` (see [Pagination](https://wabery.com/docs/errors#pagination)). Requires `contacts:read`. ```ts const { data, has_more } = await wabery.contacts.list({ limit: 50 }); // Or stream every page without managing the cursor: for await (const contact of wabery.contacts.listAll()) { console.log(contact.id, contact.phone); } ``` ## Remove a contact `unenroll` deletes the project contact record. Pass `erase: true` to also erase retained personal data, including stored broadcast personalization, flow submissions and dispatches, flow-event details, and connector invocation payloads (requires the `contacts:erase` scope) — use it for GDPR / right-to-be-forgotten requests. ```ts await wabery.contacts.unenroll("contact_...", { erase: true }); ``` ## Registration intents vs. enrollment Enrollment is a **server-side** action with a secret key — you already hold the number and consent. To let a customer opt in **from your app** without a secret key, mint a browser-safe [registration intent](https://wabery.com/docs/registration-intents) instead: they tap a `wa.me` link, message your number, and Wabery links the WhatsApp identity to your `customer_reference`. ## Next steps - [Sending messages](https://wabery.com/docs/sending-messages): Send text, media, templates, and interactive messages to a contact. - [Registration intents](https://wabery.com/docs/registration-intents): Browser-safe opt-in links that link a WhatsApp identity to your user id. - [Conversations & history](https://wabery.com/docs/conversations): List a contact's threads and read message history. --- # Sending messages The messages.send reference — text, templates, media, interactions, reactions, locations, stickers, and flows. Send a message with `wabery.messages.send()` (or `POST /v1/messages`). Set the `channelId` returned by the API, target either an existing conversation or a dedicated-channel WhatsApp phone number with opt-in, and provide exactly one content field. ## Send text **SDK:** ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", text: "Thanks for your message", }); ``` **curl:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "text": "Thanks for your message" }' ``` ## Send a template Outside the [24-hour window](https://wabery.com/docs/channels#the-24-hour-window), use an approved template instead of free-form text. Create and get one approved first — see [WhatsApp templates](https://wabery.com/docs/templates) — then send it by `id`, or by `name` plus `language`: Templates can only be submitted and approved on dedicated WhatsApp channels whose Meta business account is verified and has a Meta payment method. The Wabery sandbox cannot submit your templates. Check `channel.publish_readiness.can_submit_templates` before creating templates; readiness failures return `412` with blockers such as `BUSINESS_NOT_VERIFIED` or `NO_PAYMENT_METHOD`. See [why WhatsApp templates need a payment method](https://wabery.com/blog/whatsapp-template-payment-method) for the Meta billing reason. Send authentication templates to a phone number. Meta doesn't deliver them to a business-scoped user ID (BSUID), so Wabery returns `422 authentication_template_requires_phone_number` instead of sending. A template that isn't approved for the channel returns `409 template_not_approved`. Templates are never blocked because another app, such as a Meta Business Agent, controls the conversation. **SDK:** ```ts await wabery.messages.send({ channelId: "channel_...", to: "+14155550100", template: { name: "order_shipped", language: "en", components: [ { type: "body", parameters: [{ type: "text", text: "AB-2291" }], }, ], }, }); ``` **curl:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "to": "+14155550100", "template": { "name": "order_shipped", "language": "en", "components": [ { "type": "body", "parameters": [{ "type": "text", "text": "AB-2291" }] } ] } }' ``` ## Send a Flow Trigger a [WhatsApp Flow](https://wabery.com/docs/flows) to collect structured data in-chat: **SDK:** ```ts await wabery.flows.send("flow_...", { channelId: "channel_...", contactId: "contact_...", bodyText: "Tell us about your project", }); ``` **curl:** ```bash curl https://api.wabery.com/v1/flows/flow_.../send \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "contact_id": "contact_...", "body_text": "Tell us about your project" }' ``` `flows.send` sends an interactive flow message, which Meta only allows **inside** the 24-hour window. To send by the contact's language, use `flows.sendByConfigKey("config_key", { … })` — see [Localization](https://wabery.com/docs/flows#localization-multi-language-flows). ### Proactive flows (outside the 24-hour window) To reach a contact proactively, send an approved **flow-type template** (a template with a `FLOW` button) and pass the flow token via a button `action`: ```ts 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: "..." } }], }, ], }, }); ``` ## Send media Send an image, document, video, or audio file by **public link**. `type` is required; `caption` (≤ 1024 chars) and `filename` (documents, ≤ 240 chars) are optional. Audio takes neither — Meta drops both, so sending either returns `400`. **SDK:** ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", media: { type: "document", link: "https://example.com/invoice.pdf", filename: "invoice-2291.pdf", caption: "Your invoice", }, }); ``` **curl:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "media": { "type": "document", "link": "https://example.com/invoice.pdf", "filename": "invoice-2291.pdf", "caption": "Your invoice" } }' ``` Provide exactly one of `media.link` or `media.id`. `link` must be a publicly reachable HTTPS URL — Meta fetches it. `id` is a **Meta-hosted media handle** you uploaded to the WhatsApp Cloud API yourself; Wabery does not host uploads, so use `link` unless you already manage media ids on Meta. ## Send a reaction React to an existing WhatsApp message with `reaction`. Use an empty emoji string to remove a previous reaction. **SDK:** ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", reaction: { messageId: "wamid....", emoji: "👍", }, }); ``` **curl:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "reaction": { "message_id": "wamid....", "emoji": "👍" } }' ``` ## Send a location Send a WhatsApp location pin with latitude and longitude. `name` and `address` are optional. ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", location: { latitude: 37.7749, longitude: -122.4194, name: "San Francisco office", }, }); ``` ## Send a sticker Send a WhatsApp sticker by public HTTPS link or Meta media id: ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", sticker: { link: "https://example.com/sticker.webp", }, }); ``` Provide exactly one of `sticker.link` or `sticker.id`. ## Send an interactive message Interactive **reply buttons** (up to 3) and single-select **lists** are sent with the `interactive` field. The SDK types match this wire shape exactly: ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", interactive: { type: "button", body: { text: "Confirm your order?" }, buttons: [ { id: "confirm", title: "Confirm" }, { id: "cancel", title: "Cancel" }, ], }, }); ``` The full wire shape, with limits: **Buttons:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "interactive": { "type": "button", "body": { "text": "Confirm your order?" }, "buttons": [ { "id": "confirm", "title": "Confirm" }, { "id": "cancel", "title": "Cancel" } ] } }' ``` `buttons`: 1–3 entries; `title` ≤ 20 chars. Optional `header` (`{ "type": "text", "text": "…" }`, ≤ 60) and `footer` (`{ "text": "…" }`, ≤ 60). **List:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "interactive": { "type": "list", "body": { "text": "Pick a delivery slot" }, "button": "View slots", "sections": [ { "title": "Today", "rows": [ { "id": "slot_am", "title": "Morning", "description": "9am–12pm" }, { "id": "slot_pm", "title": "Afternoon", "description": "1pm–5pm" } ] } ] } }' ``` `button` is the list's CTA label (≤ 20). `sections`: 1–10, each with 1–10 `rows`; row `title` ≤ 24, `description` ≤ 72. **Link button (`cta_url`):** ```json { "interactive": { "type": "cta_url", "body": { "text": "Your invoice is ready" }, "display_text": "Open invoice", "url": "https://example.com/i/abc123" } } ``` Maps a URL to a button so a long or opaque link does not sit in the body text. One button only; `display_text` ≤ 20 chars; `url` must be http(s). Free-form: it sends inside the 24-hour window with no template approval and no per-message template fee. **Prompts:** `{ "type": "location_request_message", "body": { "text": "…" } }` asks the customer to share their location; `{ "type": "request_contact_info", "body": { "text": "…" } }` asks for the phone number on their WhatsApp account. Both take only `body`. A tap on a reply button or list row comes back as a `message.received` [webhook](https://wabery.com/docs/webhooks) carrying the `id` you set — deduplicate and branch on it. The other three send nothing back to route on: a `cta_url` tap only opens the URL and produces no webhook, a location request arrives as an inbound `location` message, and a contact info request as an inbound `contacts` message. `cta_url`, `location_request_message` and `request_contact_info` are WhatsApp only. Sending them to an Instagram or Messenger channel returns `422` `interactive_type_unsupported_on_channel` naming the channel platform. ## Reply to a specific message Set `reply_to` (`replyTo` in the SDK) to a WhatsApp message id to quote it. It works with any content type and is a modifier, not a content field, so it does not count toward the exactly-one-of rule. ```json { "channel_id": "channel_...", "conversation_id": "conversation_...", "reply_to": "wamid....", "text": "Yes, that one is still available" } ``` Inbound replies carry `messages[].replied_to` with the quoted `message_id` and `from` on `message.received`; pass that `message_id` straight back as `reply_to`. ## Send a contact card `contacts` takes 1–20 cards in Meta's shape. `name.formatted_name` is required plus at least one of `first_name`, `last_name`, `middle_name`, `suffix` or `prefix`; a card without one returns `400`. Set `phones[].wa_id` to make a number tappable as a WhatsApp contact. Optional: `birthday` (`YYYY-MM-DD`), `emails`, `urls`, `addresses`, `org`. ```json { "contacts": [ { "name": { "formatted_name": "Ada Lovelace", "first_name": "Ada" }, "phones": [ { "phone": "+15555550123", "type": "WORK", "wa_id": "15555550123" } ] } ] } ``` ## Parameters | Field | Type | Notes | | --- | --- | --- | | `channelId` | `string` | Required channel id from `channels.list()`. | | `to` | `string` | E.164 phone for dedicated WhatsApp channels (requires opt-in). | | `conversationId` | `string` | Existing conversation id. | | `text` | `string` | Free-form message, ≤ 4096 chars (within the window). | | `template` | `object` | Approved WhatsApp template id, or name plus language. | | `media` | `object` | Image, document, video, or audio by public `link` or Meta media `id`. Audio takes no `caption` or `filename`. | | `interactive` | `object` | WhatsApp `button`, `list`, `cta_url`, `location_request_message`, or `request_contact_info` payload. | | `reaction` | `object` | React to an existing WhatsApp message by `messageId`/`message_id` and `emoji`. | | `location` | `object` | WhatsApp location pin with `latitude`, `longitude`, optional `name` and `address`. | | `sticker` | `object` | WhatsApp sticker by public HTTPS `link` or Meta media `id`. | | `contacts` | `array` | 1–20 contact cards. Each needs `name.formatted_name` plus one other name part. | | `replyTo` | `string` | WhatsApp message id to quote. A modifier — combines with any content field. | | `idempotencyKey` | `string` | Optional; safe-retry key (see [Errors](https://wabery.com/docs/errors#retries--idempotency)). | > Provide exactly one of `text`, `template`, `media`, `interactive`, `reaction`, `location`, `sticker`, or `contacts`. `replyTo` is not a content field and combines with any of them. Use `wabery.flows.send()` for WhatsApp Flows. A successful send returns `202 Accepted` with the queued message id; inspect it with `wabery.messages.get("msg_...")`, `wabery messages get "msg_..."`, or `message.status` [webhooks](https://wabery.com/docs/webhooks). > `to` sends are for dedicated WhatsApp channels with active opt-in. For the shared sandbox and inbound conversations, send with `conversationId`. --- # WhatsApp templates Create, submit, and track approval of WhatsApp message templates for proactive sends outside the 24-hour window. Outside the [24-hour window](https://wabery.com/docs/channels#the-24-hour-window), WhatsApp only allows **approved templates**. A template is submitted to Meta for review, moves through an approval lifecycle, and — once `APPROVED` — can be sent to opted-in contacts. This page covers creating and tracking templates; see [Sending messages](https://wabery.com/docs/sending-messages#send-a-template) for sending an approved one. Read paths need `templates:read`; create needs `templates:write`. ## Prerequisites Templates can only be submitted on a **dedicated** WhatsApp channel whose Meta business account is **verified** and has a Meta payment method. The shared Wabery sandbox cannot submit templates — they belong to Wabery's own account. Read [why WhatsApp templates need a payment method](https://wabery.com/blog/whatsapp-template-payment-method) if Wabery reports `NO_PAYMENT_METHOD`. Check readiness first: ```ts const channel = await wabery.channels.get("channel_..."); if (!channel.publish_readiness?.can_submit_templates) { console.log("Blocked by:", channel.publish_readiness?.blockers); // e.g. ["BUSINESS_NOT_VERIFIED", "NO_PAYMENT_METHOD"] } ``` Submitting when not ready returns `412` with the same `publish_readiness` blockers — Wabery rejects it rather than queueing work that Meta will refuse. ## Create and submit Open **Templates** to create and monitor templates in the dashboard, or use the SDK or API below. One call creates the template and submits it to Meta. `category` is one of `UTILITY`, `MARKETING`, or `AUTHENTICATION`; `components` follow Meta's template component schema (header, body, footer, buttons). **SDK:** ```ts const template = await wabery.templates.create({ channelId: "channel_...", name: "order_shipped", // a-z, 0-9, underscores language: "en", category: "UTILITY", components: [ { type: "BODY", text: "Your order {{1}} has shipped." }, ], }); console.log(template.status); // "PENDING" — review has started ``` **curl:** ```bash curl https://api.wabery.com/v1/templates \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "name": "order_shipped", "language": "en", "category": "UTILITY", "components": [ { "type": "BODY", "text": "Your order {{1}} has shipped." } ] }' ``` A template response: ```json { "object": "whatsapp_template", "id": "tmpl_...", "channel_id": "channel_...", "meta_template_id": "1234567890", "name": "order_shipped", "language": "en", "category": "UTILITY", "status": "PENDING", "submitted_at": "2026-06-20T14:00:00Z" } ``` ## Approval lifecycle Review is asynchronous and can take up to 24 hours. `status` moves through: | Status | Meaning | | --- | --- | | `PENDING` | Submitted to Meta; awaiting review. | | `APPROVED` | Ready to send. | | `REJECTED` | Meta declined it; see `rejection_reason`. | | `DISABLED` | Previously approved, later disabled (e.g. quality drop). | Track it in one of three ways — prefer the first two in production over blocking a request: **1. Webhook (recommended).** Meta status changes arrive as a signed `template.status` [webhook](https://wabery.com/docs/webhooks) — no polling. **2. On-demand refresh.** `status(id)` forces a live Meta status check: ```ts const latest = await wabery.templates.status("tmpl_..."); // GET with refresh ``` ```bash wabery templates status "tmpl_..." ``` **3. Block until resolved.** For scripts and CI, `waitUntilApproved` polls until `APPROVED`, throwing if the template is `REJECTED`/`DISABLED` or the timeout elapses: ```ts const approved = await wabery.templates.waitUntilApproved("tmpl_...", { timeoutMs: 60 * 60 * 1000, // default 24h intervalMs: 60_000, }); ``` ```bash wabery templates wait "tmpl_..." --wait=86400 ``` ## List templates Filter by `channelId` and/or `status`. Requires `templates:read`. ```ts const { data } = await wabery.templates.list({ channelId: "channel_...", status: "APPROVED", }); ``` Once a template is `APPROVED`, send it — including flow-type templates for proactive [WhatsApp Flows](https://wabery.com/docs/flows) — from [Sending messages](https://wabery.com/docs/sending-messages#send-a-template). ## Templates you can send from the dashboard Wabery syncs every template in your WhatsApp Business Account, including types it can't fill in for you yet. The inbox template picker and broadcasts offer an approved template when every part of it is one Wabery can complete: - a text, image, video, or document header; - the body and footer; and - URL, phone number, quick reply, or request contact info buttons. Broadcasts also accept Flow buttons. Other templates stay listed on the **Templates** page with a note that you can't send them from the inbox or broadcasts. These include authentication templates, carousels, limited-time offers, coupon (copy code) buttons, location or product headers, catalog and product buttons, voice call buttons, and call permission requests. Broadcasts only use marketing and utility templates. To send one of these templates, use `POST /v1/messages` and pass the components yourself. A `coupon_code` parameter can be up to 20 characters. Send authentication templates to a phone number. Meta doesn't deliver them to a business-scoped user ID (BSUID), so Wabery returns `422 authentication_template_requires_phone_number` before contacting Meta. ## If Meta restricts your templates When Meta restricts utility templates on your WhatsApp Business Account, you can keep sending the templates you already have. Meta moves your approved utility templates to marketing while the restriction lasts, so Meta charges them as marketing messages. Only creating new utility templates is paused: Wabery returns `409 whatsapp_utility_templates_restricted` until Meta lifts the restriction. A Direct Send restriction only limits Meta's Direct Send API. Wabery doesn't use it, so your template sends continue as normal. ## Next steps - [Sending messages](https://wabery.com/docs/sending-messages#send-a-template): Send an approved template by id, or by name plus language. - [WhatsApp Flows](https://wabery.com/docs/flows): Flow-type templates open a Flow proactively, outside the 24-hour window. - [Webhooks](https://wabery.com/docs/webhooks): Track approval with signed `template.status` events. --- # Conversations & history List conversations and read message history — the pull-based counterpart to webhooks, with re-signed media URLs. [Webhooks](https://wabery.com/docs/webhooks) **push** each event to you in real time. Conversations let you **pull**: list threads, page back through message history, and re-fetch inbound media after the webhook's signed URL has expired. Use them to backfill after downtime, reconcile against your own store, or power an agent that needs prior context. All endpoints require the `conversations:read` scope. ## List conversations Cursor-paginated. Filter by `contactId`, or by `active` to get only threads inside their messaging window. **SDK:** ```ts const { data, has_more } = await wabery.conversations.list({ contactId: "contact_...", active: true, limit: 50, }); // Or iterate every page without managing the cursor: for await (const convo of wabery.conversations.listAll({ active: true })) { console.log(convo.id, convo.last_message_at); } ``` **curl:** ```bash curl "https://api.wabery.com/v1/conversations?contact_id=contact_...&active=true&limit=50" \ -H "Authorization: Bearer $WABERY_API_KEY" ``` A conversation: ```json { "object": "conversation", "id": "conv_...", "contact_id": "contact_...", "phone": "+14155550100", "last_channel_id": "channel_...", "is_active": true, "started_at": "2026-06-20T14:00:00Z", "last_message_at": "2026-06-20T14:21:10Z" } ``` `is_active` reflects whether the 24-hour window is currently open. Reply with `messages.send({ conversationId: "conv_...", ... })`; outside the window use an approved [template](https://wabery.com/docs/templates). ## Read message history `listMessages` is cursor-paginated and ordered by `order` — `desc` (newest first, the default) for a live view, `asc` to replay a thread from the start. **SDK:** ```ts const { data } = await wabery.conversations.listMessages("conv_...", { order: "asc", limit: 100, }); ``` **curl:** ```bash curl "https://api.wabery.com/v1/conversations/conv_.../messages?order=asc&limit=100" \ -H "Authorization: Bearer $WABERY_API_KEY" ``` A message: ```json { "object": "message", "id": "msg_...", "conversation_id": "conv_...", "contact_id": "contact_...", "channel_id": "channel_...", "direction": "inbound", "type": "image", "status": "received", "content": null, "media": { "type": "image", "file_name": "msg_...-image.jpg", "file_size": 248913, "mime_type": "image/jpeg", "whatsapp_media_id": "wamid...", "url": "https://storage.wabery.com/assets/inbound/asset_...?token=...", "expires_at": "2026-06-27T14:21:10Z", "status": "available", "accessible": true }, "timestamp": "2026-06-20T14:21:10Z" } ``` `direction` is `inbound` or `outbound`. For outbound messages that failed, `failure` carries the provider error (`provider`, `code`, `message`, `fbtrace_id`). ## Re-fetching inbound media The media `url` in a `message.received` [webhook](https://wabery.com/docs/webhooks#inbound-media-files) is a short-lived signed URL (~1 hour). Reading the same message through history **re-signs a fresh URL** as long as the retained object still exists — its lifetime is bounded by `expires_at` (24h on the free plan, 7 days on paid). Check before downloading: ```ts const { data } = await wabery.conversations.listMessages("conv_..."); for (const message of data) { const media = message.media; if (media?.status !== "available" || !media.url) continue; // expired / not cached const response = await fetch(media.url); await storeFile({ messageId: message.id, body: await response.arrayBuffer() }); } ``` If retention has lapsed, `status` is `expired` and `url` is `null` — the object is gone and cannot be re-signed. Store files on your side promptly. > Webhooks are the primary, real-time path; history is for backfill and reconciliation. Don't poll history in a tight loop to substitute for a webhook endpoint — it counts against your [rate limit](https://wabery.com/docs/errors#rate-limits). ## Next steps - [Webhooks](https://wabery.com/docs/webhooks): The real-time push path — verify signatures and handle inbound media. - [Sending messages](https://wabery.com/docs/sending-messages): Reply inside the window with text, media, or interactive messages. - [Errors & rate limits](https://wabery.com/docs/errors#pagination): Cursor pagination, rate limits, and idempotency. --- # Registration intents Create single-use WhatsApp registration links with publishable keys. Registration intents let you enroll end customers from your own product without exposing a secret API key. Wabery returns a single-use `wa.me` link. The customer taps it, sends the prefilled token to your Wabery WhatsApp number, and Wabery links that WhatsApp identity to your `customer_reference`. Use this for self-serve onboarding, account linking, or "connect your WhatsApp" flows in your app. ## Authentication Registration intents support two key types: | Key | Header | Use | | --- | --- | --- | | `wab_pub_...` | `x-wabery-publishable-key` | Browser-safe widget calls. Metadata is treated as untrusted. | | `wab_live_...` | `Authorization: Bearer ...` | Server-side minting with the `registrations:create` scope. | Polling an intent with `GET /registration-intents/{id}` works with either key type. The SDK and CLI automatically send `x-wabery-publishable-key` when the key starts with `wab_pub_`; otherwise they use Bearer auth. ## Create an intent **SDK:** ```ts import { Wabery } from "@wabery/sdk"; const wabery = new Wabery({ apiKey: "wab_pub_..." }); const intent = await wabery.registrationIntents.create({ customerReference: "user_123", metadata: { plan: "starter" }, }); console.log(intent.wa_link); ``` **CLI:** ```bash WABERY_API_KEY="wab_pub_..." wabery registration-intents create \ --customer-reference "user_123" \ --metadata '{"plan":"starter"}' ``` **curl:** ```bash curl https://api.wabery.com/v1/registration-intents \ -H "x-wabery-publishable-key: $WABERY_PUBLISHABLE_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_reference": "user_123", "metadata": { "plan": "starter" } }' ``` The response includes: ```json { "object": "registration_intent", "id": "reg_...", "token": "wjr_...", "status": "PENDING", "wa_link": "https://wa.me/...", "expires_at": "2026-06-27T00:00:00.000Z" } ``` Send the customer to `wa_link`. Do not edit the prefilled message; Wabery uses the token to match the customer to the intent. ## Poll status **SDK:** ```ts const status = await wabery.registrationIntents.get(intent.id); if (status.status === "JOINED") { // The customer is connected. Future message.received events include // customer_reference/contact_reference for correlation. } ``` **CLI:** ```bash wabery registration-intents get "reg_..." ``` **curl:** ```bash curl https://api.wabery.com/v1/registration-intents/reg_... \ -H "x-wabery-publishable-key: $WABERY_PUBLISHABLE_KEY" ``` Server-side polling can use a scoped secret key instead: ```bash curl https://api.wabery.com/v1/registration-intents/reg_... \ -H "Authorization: Bearer $WABERY_API_KEY" ``` Statuses are: | Status | Meaning | | --- | --- | | `PENDING` | The customer has not completed the WhatsApp step yet. | | `JOINED` | The customer sent the token and is connected. | | `REJECTED` | Wabery rejected the registration, with `rejection_reason` when available. | | `EXPIRED` | The intent expired before the customer joined. | ## Webhooks When the customer joins, Wabery emits a signed `participant.joined` webhook. The payload includes your `customer_reference` and metadata so you can link the WhatsApp contact to your own user record. Use [Webhooks](https://wabery.com/docs/webhooks) to verify the signature and handle the event. --- # Webhooks Receive every message, status, and Flow submission as a signed event. Wabery delivers everything that happens on your channels to your endpoint as **typed, signed events** — inbound messages, delivery statuses, and Flow submissions. No polling, with automatic retries on failure. The dashboard's **Webhooks** page is the single home for both configuration and delivery activity. Endpoint setup is collapsed by default; select **Manage** to edit the URL, send a test event, copy or rotate the signing secret, and review verification requirements. **Recent deliveries** remains visible underneath, with event and status filters, automatic refresh, response codes, retry counts, and expandable payloads. ## Register an endpoint Add your HTTPS endpoint in the dashboard under **Webhooks**, or fully from code so your setup stays scriptable: ```sh # Set the webhook URL and a bring-your-own signing secret on a project wabery projects update "proj_id" \ --webhook-url "https://yourapp.com/webhooks/wabery" \ --webhook-secret "$WABERY_WEBHOOK_SECRET" # Read it back any time (also includes webhook_url) wabery projects get "proj_id" # → includes webhook_secret wabery env --project-id "proj_id" # → ready-to-paste WABERY_* block ``` Each project has one signing secret used to verify deliveries (and outbound [data-exchange](https://wabery.com/docs/flows) calls). It's revealed by `GET /projects/{id}`, settable on create/update (bring-your-own), and rotatable with `POST /projects/{id}/rotate-webhook-secret`. The list endpoint never returns it. ## Routing mode: your API vs your Wabery agent A project's `routing_mode` decides what happens to each **inbound** message: | `routing_mode` | Inbound handling | | --- | --- | | `EXTERNAL` | Every inbound message is forwarded to your webhook as `message.received`. You own the reply logic and call the REST API to respond. This is the default for API-first projects. | | `AGENT` | Inbound messages are handled by your Wabery-hosted agent, including its automations and functions. | > The two are mutually exclusive. While `routing_mode` is `EXTERNAL`, **built-in automations are never evaluated** — every message is forwarded to your webhook instead. A `config apply` that defines automations on an EXTERNAL project still stores them and reports `active: true`, but they will not fire; the apply response returns a warning saying so, and the automations canvas shows a banner. Either move the trigger logic into your webhook handler, or switch the project's `routing_mode` to `AGENT` to run the automations natively. ### Channel routing overrides the project Each **dedicated** channel also carries its own `routing_mode`, and for that channel it takes precedence over the project's. A dedicated number sitting in `AGENT` does **not** forward inbound to your webhook even if the project is `EXTERNAL` with a webhook configured — inbound is handled by the Wabery-hosted agent. Newly linked channels **inherit the project's routing mode** at connect time, so a number added under an `EXTERNAL` project forwards from the start. To diagnose or fix an existing channel, `channels.list()` and `channels.get(id)` return a `routing_warning` whenever a channel bypasses the project's configured webhook (e.g. `AGENT` under an `EXTERNAL` project). The inbound worker also logs the same warning per message. Flip the channel to `EXTERNAL` programmatically: **SDK:** ```ts await wabery.channels.update("channel_...", { routingMode: "EXTERNAL" }); ``` **CLI:** ```bash wabery channels update channel_... --routing-mode EXTERNAL ``` **curl:** ```bash curl -X PATCH https://api.wabery.com/v1/channels/channel_... \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "routing_mode": "EXTERNAL" }' ``` > The shared sandbox channel is the exception: it routes per-participant (by the project each tester joined), so its channel-level `routing_mode` is ignored and cannot be set via `channels.update` — set routing on the project instead. ## Event shape Every delivery is `{ event, payload, sentAt }`. An inbound `message.received` looks like this: ```json { "event": "message.received", "payload": { "agent_id": "agent_...", "organization_id": "org_...", "channel_id": "channel_...", "conversation_id": "conv_...", "contact_id": "contact_...", "from": "+15551234567", "text": "do you ship internationally?", "message_id": "msg_...", "type": "text", "messages": [ { "id": "msg_...", "type": "text", "text": "do you ship internationally?", "received_at": "2026-06-20T14:21:10Z", "media": null, "location": null, "interactive": null, "replied_to": null } ], "assets": [], "media": null, "location": null, "contact_reference": "your-own-user-id", "customer_reference": "your-own-user-id", "metadata": { "plan": "pro" } }, "sentAt": "2026-06-20T14:21:10Z" } ``` `from` is the sender's E.164 number when Meta discloses it. For a phone-hidden WhatsApp username user it is `null`, and `user_id` carries the portfolio-scoped BSUID. `contact_id` is Wabery's stable contact key; `contact_reference` echoes the `externalId` you set in the contact's metadata. Reply by calling `POST /v1/messages` with the `channel_id` and `conversation_id` from this event. Wabery processes Meta's identity-change system events on the existing `messages` webhook and emits `contact.identity.updated` when a stored BSUID changes. Contact-info responses use `messages[n].type: "contacts"` and `messages[n].contacts`; WhatsApp system notices use `type: "system"` and `messages[n].system`. `message.status` reports `sent`, `delivered`, `read`, or `failed`. When a customer plays a voice message you sent, you receive `read`. For a failed message, `failure.message` holds Meta's specific reason when Meta supplies one, and `failure.title` holds Meta's short error title. Group statuses arrive once per participant and identify the participant with `recipient_participant_user_id` (BSUID); `recipient_participant_id` (phone) is omitted when the participant's phone number is unavailable. When a customer shares a single product from your catalog, `message.received` arrives with `type: "interactive"` and `interactive.type: "product"`. `interactive.id` is the product's `retailer_id`, and `interactive.product` carries its title, description, `currency_code`, `price_amount`, `sale_price_amount`, and `url`. Prices use Meta's format: the amount multiplied by 1,000, so `1000` with `currency_code: "USD"` is 1.00 USD. When handoff is on, Wabery does not deliver new `message.received` events and rejects automated `POST /v1/messages` replies with `409 ai_handoff_active`. When another app, such as a Meta Business Agent, controls a WhatsApp conversation, Wabery stores the messages Meta shares in the inbox for context but does not deliver them as `message.received`. ## Quoted replies When a customer replies to a specific message, that message carries `replied_to`: ```json { "id": "msg_...", "type": "text", "text": "yes, that one", "replied_to": { "message_id": "wamid....", "from": "+15551234567" } } ``` `message_id` is the quoted message's WhatsApp id. Pass it back as `reply_to` on `POST /v1/messages` to answer in the same thread. `replied_to` is `null` when nothing is quoted. ## Inbound media files When a contact sends an image, voice note, audio file, video, document, or sticker, the `message.received` webhook includes file metadata and a Wabery-hosted download URL: - `messages[n].media` is the media attached to that specific inbound message. - `assets` is a flattened list of all media files in the delivery. - `media` is the latest media file in the delivery, for convenience. - `location` carries latitude/longitude for location messages. Locations do not have a file URL. The `url` is a short-lived signed URL, valid for about 1 hour by default and capped by the asset's remaining retention. The `expires_at` field is the asset retention deadline, not the signed URL deadline: 24 hours on the free plan and 7 days on paid plans. Store files on your side promptly. If you read the same message later through `GET /conversations/{id}/messages`, Wabery re-signs a fresh URL as long as the retained object still exists. Wabery starts caching inbound WhatsApp media as soon as the webhook is ingested and retries before delivery. WhatsApp customers can send files up to Meta's 100 MB maximum. If caching still fails, or the retained object has expired, the webhook is still delivered with `status` set to `unavailable` or `expired` and `url: null`. Example image payload: ```json { "event": "message.received", "payload": { "agent_id": "agent_...", "organization_id": "org_...", "channel_id": "channel_...", "conversation_id": "conv_...", "contact_id": "contact_...", "from": "+15551234567", "text": null, "message_id": "msg_...", "type": "image", "messages": [ { "id": "msg_...", "type": "image", "text": null, "received_at": "2026-06-20T14:21:10Z", "media": { "id": "asset_...", "message_id": "msg_...", "type": "image", "url": "https://storage.wabery.com/assets/inbound/asset_...?token=...", "expires_at": "2026-06-27T14:21:10Z", "mime_type": "image/jpeg", "file_name": "msg_...-image.jpg", "file_size": 248913, "provider": "whatsapp", "provider_media_id": "wamid...", "status": "available" }, "location": null } ], "assets": [ { "id": "asset_...", "message_id": "msg_...", "type": "image", "url": "https://storage.wabery.com/assets/inbound/asset_...?token=...", "expires_at": "2026-06-27T14:21:10Z", "mime_type": "image/jpeg", "file_name": "msg_...-image.jpg", "file_size": 248913, "provider": "whatsapp", "provider_media_id": "wamid...", "status": "available" } ], "media": { "id": "asset_...", "message_id": "msg_...", "type": "image", "url": "https://storage.wabery.com/assets/inbound/asset_...?token=...", "expires_at": "2026-06-27T14:21:10Z", "mime_type": "image/jpeg", "file_name": "msg_...-image.jpg", "file_size": 248913, "provider": "whatsapp", "provider_media_id": "wamid...", "status": "available" }, "location": null, "contact_reference": "your-own-user-id", "customer_reference": "your-own-user-id", "metadata": { "plan": "pro" } }, "sentAt": "2026-06-20T14:21:10Z" } ``` Handle files by checking `status` and downloading only when `url` is present: ```ts 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 storeFile({ waberyAssetId: asset.id, messageId: asset.message_id, contentType: asset.mime_type, fileName: asset.file_name, body: await response.arrayBuffer(), retainedUntil: asset.expires_at }); } } ``` > `message.received` carries both `contact_reference` and `customer_reference` with the **same value**. `contact_reference` is the canonical name used across all events (`flow.completed`, data-exchange); `customer_reference` is a backward-compatible alias. Prefer `contact_reference` in new code. Common event types: | Type | When | | --- | --- | | `message.received` | A contact sent you a message. | | `message.status` | A message you sent was delivered / read / failed. | | `flow.completed` | A contact completed a [WhatsApp Flow](https://wabery.com/docs/flows). See its payload in the [Flows guide](https://wabery.com/docs/flows#receive-the-submission). | | `flow.status` | Meta reported a Flow status change such as `PUBLISHED`, `BLOCKED`, or `DEPRECATED`. | | `template.status` | Meta reported a WhatsApp template review/status change such as `APPROVED` or `REJECTED`. | | `participant.joined` | A sandbox participant joined a project. | ## Verify the signature Every delivery includes an `x-wabery-signature` header formatted as `sha256=`. Verify it over the raw request body with your endpoint's signing secret and reject anything that doesn't match: **SDK:** ```ts import { Wabery } from "@wabery/sdk"; const wabery = new Wabery(); const valid = wabery.webhooks.verifySignature( rawBody, request.headers["x-wabery-signature"], process.env.WABERY_WEBHOOK_SECRET, ); ``` **Manual:** ```ts import crypto from "node:crypto"; function verify(rawBody: string, signature: string, secret: string) { const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex"); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)); } ``` > Always verify against the **raw** request body before parsing JSON, and use a constant-time comparison. Respond `2xx` quickly; Wabery retries non-2xx responses with exponential backoff. ## Parse into a typed event `constructEvent` verifies the signature **and** returns a typed, discriminated event in one step — switch on `event.event` and the payload narrows automatically. It throws `WaberySignatureVerificationError` on a bad signature, so a caught error always means "reject". ```ts import { Wabery, type WaberyEvent } from "@wabery/sdk"; const wabery = new Wabery(); // rawBody must be the exact bytes received (not re-stringified JSON). 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; } ``` ## Idempotency Deliveries are **at-least-once**. Deduplicate on a stable id — `message_id` for `message.received`, `flow_token` for `flow.completed` (one `flow.completed` per `flow_token`, even if Meta retries): ```ts 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** (state lives in one process). For multiple instances, implement the `DedupeStore` interface over a shared store — `add(key)` returns `true` when the key was already seen: ```ts import type { DedupeStore } from "@wabery/sdk"; const store: DedupeStore = { async add(key) { // SET key NX with a TTL; null reply means it already existed → duplicate. const ok = await redis.set(`wh:${key}`, "1", "PX", 86_400_000, "NX"); return ok === null; }, }; if (await store.add(event.payload.message_id)) return; // already processed ``` ## Test locally Exercise your handler without deploying. The [CLI](https://wabery.com/docs/cli) signs a fake payload with your secret and POSTs it to your local server: ```bash wabery webhooks send-test --url http://localhost:3000/webhooks \ --secret "$WABERY_WEBHOOK_SECRET" --event message.received ``` In code, `signPayload` produces the same `x-wabery-signature` header for fixtures and tests: ```ts import { signPayload } from "@wabery/sdk"; const body = JSON.stringify(myFakeEvent); const res = await fetch("http://localhost:3000/webhooks", { method: "POST", headers: { "x-wabery-signature": signPayload(body, secret) }, body, }); ``` --- # WhatsApp Flows Collect structured, validated data with native in-chat forms. Static options or dynamic, per-user data fetched from your server. WhatsApp Flows are forms inside the chat. Define the fields once and receive validated JSON. Wabery handles Meta's Flow JSON, encryption, and data exchange. ## Static vs. dynamic flows Pick a mode per flow: | Mode | `runtime_mode` | When to use | Where options come from | | --- | --- | --- | --- | | **Static** | `STATIC` (default) | Options are the same for everyone and known when you publish (e.g. a fixed `timeline` list). | Hardcoded in the flow definition. Rendered entirely on-device, no server round-trip. | | **Dynamic** | `DATA_EXCHANGE` | Options differ per user, change over time, or one field depends on another (cascading dropdowns), or you need to prefill / branch based on who's filling it in. | Fetched from **your** HTTPS endpoint at runtime, mid-conversation. | > Do not deploy one flow per user. Publish one `DATA_EXCHANGE` flow and return their options from your server at runtime. ## Define a flow Flows are authored as **config-as-code** in `wabery.config.json` or from **Connections → WhatsApp → Flows**. Both compile to the same Flow JSON. A flow's `draft` is a set of screens; each screen holds typed fields and explicit navigation. ```json title="wabery.config.json" { "$schema": "https://api.wabery.com/v1/config/schema", "version": "2026-06-18", "project_id": "project_...", "flows": [ { "key": "lead_intake", "name": "Lead intake", "runtime_mode": "STATIC", "draft": { "entryScreenId": "START", "screens": [ { "id": "START", "title": "Tell us about your project", "fields": [ { "name": "name", "label": "Your name", "type": "text", "required": true }, { "name": "budget", "label": "Budget (USD)", "type": "number" }, { "name": "timeline", "label": "Timeline", "type": "choice", "options": [ { "id": "asap", "title": "ASAP" }, { "id": "this_month", "title": "This month" } ] } ], "primary": { "label": "Submit", "target": { "kind": "complete" } } } ] } } ] } ``` Authoring in TypeScript? The SDK ships typed builders that return the same `draft` data — handy for editor autocomplete and compile-time checks: ```ts import { defineFlow, screen, textField, numberField, choiceField } from "@wabery/sdk"; const draft = defineFlow([ screen("START", "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: [], }); ``` > The builders are pure helpers — flows are still **data**, not a runtime engine. Prefer to hand-write canonical Meta Flow JSON? Use `flow_json` (typed as `MetaFlowJson`) instead of `draft` and Wabery stores it as-is. Hand-writing `flow_json` is the most error-prone path — a malformed document is only rejected at publish time, after a round-trip to Meta. The SDK ships full `MetaFlowJson` types (screens / components / actions / data-model) **and** a local validator that catches the common structural mistakes (missing version, no terminal screen, dangling navigation targets) before you call the API: ```ts import { validateFlowJson, type MetaFlowJson } from "@wabery/sdk"; const flowJson: MetaFlowJson = { /* ...your hand-written Flow JSON... */ }; const issues = validateFlowJson(flowJson); if (issues.length) { throw new Error(issues.map((i) => `${i.path}: ${i.message}`).join("\n")); } ``` > `validateFlowJson` (and `wabery config validate`) are **structural checks only** — they catch missing versions, dangling/unreachable screens (Meta's `INVALID_ROUTING_MODEL`), and array fields missing their `items` schema. A clean result means "no obvious structural problem", **not** "Meta will accept it". Some rejections are only knowable at publish — notably **flow-name uniqueness** (names must be unique per WhatsApp Business Account) and account/permission errors. When a publish does fail, Wabery surfaces Meta's real reason and `validation_errors` (with line pointers) on `meta_status_reason` — see [Versioning & publishing](#versioning--publishing). ## Deploy it ```bash wabery config validate wabery.config.json wabery config diff wabery.config.json wabery config apply wabery.config.json ``` Publishing a `DATA_EXCHANGE` flow also registers an encryption key with Meta and wires the flow's endpoint to Wabery — you don't manage keys yourself. Flow publishing requires a Meta-verified WhatsApp Business Account. The shared Wabery sandbox can publish Flows once Wabery's sandbox account is verified, but customer-owned dedicated WhatsApp channels must be verified on Meta before publishing. Check `project.publish_readiness` or `channel.publish_readiness` first; if `can_publish_flows` is `false`, `flows.publish()` returns `412` with blockers such as `BUSINESS_NOT_VERIFIED` and does not queue a Meta publish job. ## Send it **SDK:** ```ts await wabery.flows.send("flow_...", { channelId: "channel_...", contactId: "contact_...", // or conversationId, or a raw `to` phone number bodyText: "Tell us about your project", flowCta: "Start", // button label, ≤ 20 chars // Static flows open on a specific screen and may prefill it: firstScreen: "START", screenData: { name: "Alex" }, }); ``` **curl:** ```bash curl https://api.wabery.com/v1/flows/flow_.../send \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "contact_id": "contact_...", "body_text": "Tell us about your project", "flow_cta": "Start", "first_screen": "START", "screen_data": { "name": "Alex" } }' ``` Provide exactly one recipient: `contact_id`, `conversation_id`, or `to` (an E.164 phone). `first_screen` is required for static flows and ignored for dynamic ones (the endpoint decides the opening screen). The call returns a `flow_dispatch` with a **`flow_token`** — your correlation key for this send. ## Receive the submission When the contact submits the form, Wabery validates it against the flow's declared field schema and delivers a single **`flow.completed`** [webhook](https://wabery.com/docs/webhooks): ```json { "event": "flow.completed", "payload": { "object": "flow_submission", "id": "fsub_...", "flow_token": "b1c2...", "flow_id": "flow_...", "flow_version": 3, "organization_id": "org_...", "agent_id": "agent_...", "conversation_id": "conv_...", "contact_id": "contact_...", "contact_reference": "your-own-user-id", "from": "+15551234567", "valid": true, "validation_errors": [], "submission": { "name": "Alex", "budget": 2000, "timeline": "asap" }, "submitted_at": "2026-06-22T14:21:09.000Z" } } ``` > **`flow.completed` is the single source of truth.** There is no separate `onSubmit` URL on the flow and Wabery does not POST anywhere else on completion. (If you need to react *during* the form — to populate options or branch screens — that's the data-exchange endpoint below, which is a different mechanism and only applies to dynamic flows.) Submissions are idempotent: one delivery per `flow_token`, even if Meta retries. Validation runs before the webhook fires, so `submission` is already typed and checked against your field rules. `valid` is `true` when every reached field passed; when something fails, `valid` is `false` and `validation_errors` lists the offending fields (`{ field, message }`). The array is **always present** — `[]` when valid — so you never have to guess why a submission was rejected. The raw answers are still delivered either way. > **`valid` is path-aware for branched flows.** Wabery validates only the screens the run actually reached, not the union of every screen's required fields. So a flow that branches (e.g. a chooser routing to a *GROWER* or a *LAYER* path) is `valid: true` for a complete run down one branch — the other branch's required fields are not counted as "missing". `validation_errors` tells you exactly which fields failed when `valid` is `false`, so `valid === false` is a safe signal to gate on. `submission` is a `Record` on the wire. The SDK ships coercion helpers so you don't hand-cast every field: ```ts import { asNumber, asDate, coerceSubmission } from "@wabery/sdk"; const budget = asNumber(event.payload.submission.budget); // number | undefined const when = asDate(event.payload.submission.preferred_date); // Date | undefined // …or coerce the whole thing against your field types at once: const data = coerceSubmission(event.payload.submission, { budget: "number", preferred_date: "date", interests: "stringArray", }); ``` ## Correlating submissions to your users You get three stable handles back, in order of preference: - **`flow_token`** — unique per send (returned by `flows.send`). The most precise key: it ties this exact submission to the exact send you made. Store it when you send and look it up on completion. - **`contact_reference`** — *your own* id for this person. Set it as `externalId` in the contact's `metadata` when you create/enroll the contact, and Wabery echoes it on every `flow.completed` (and `message.received`) event, so you never have to store a `contact_id` → user mapping. - **`contact_id`** + **`from`** — `contact_id` is stable for a given WhatsApp number within your organization (numbers are normalized to E.164 and deduped). `from` is that E.164 number. Either is a durable fallback. > WhatsApp's raw `flow_token` is generated by Wabery at send time and is never exposed to the end user, so it can't be tampered with. You don't pass a custom token into the flow — use `contact_reference` to carry your own identifier. ## Dynamic flows (data-exchange) A dynamic flow calls your server while the person fills it in, so you can load options for them, prefill answers, choose the next screen, and close the flow. Set `runtime_mode: "DATA_EXCHANGE"` and a `data_exchange_url`: ```json title="wabery.config.json (excerpt)" { "key": "ticket_intake", "name": "Support ticket", "runtime_mode": "DATA_EXCHANGE", "data_exchange_url": "https://api.example.com/wabery/flow", "draft": { "entryScreenId": "SELECT", "screens": [ { "id": "SELECT", "title": "Where's the issue?", "fields": [ { "name": "workspace", "label": "Workspace", "type": "choice", "dropdown": true, "dynamicOptions": true, "refreshOnSelect": true }, { "name": "project", "label": "Project", "type": "choice", "dropdown": true, "dynamicOptions": true } ], "primary": { "label": "Next", "target": { "kind": "complete" } } } ] } } ``` - `dynamicOptions: true`: your endpoint supplies the field's options at runtime. - `refreshOnSelect: true`: changing the field calls your endpoint again, so you can repopulate other fields on the same screen (cascading dropdowns). Each call works like this: WhatsApp sends an encrypted request to Wabery, Wabery decrypts it and POSTs plain JSON to your URL, then checks your reply and sends it back to WhatsApp encrypted. You don't handle any keys or encryption. ### The request Wabery sends `POST ` with these headers: | Header | Value | | --- | --- | | `Content-Type` | `application/json` | | `User-Agent` | `Wabery-FlowExchange/1` | | `X-Wabery-Signature` | `sha256=`: HMAC-SHA256 of the raw body, keyed with your project's webhook secret. Verify it exactly as for a [webhook](https://wabery.com/docs/webhooks). | ```json { "version": "3.0", "action": "data_exchange", "screen": "SELECT", "data": { "workspace": "ws_42" }, "triggered_by": "field_change", "changed_field": "workspace", "flow_token": "b1c2...", "flow_id": "flow_...", "agent_id": "agent_...", "organization_id": "org_...", "contact_id": "contact_...", "contact_reference": "your-own-user-id", "from": "+15551234567" } ``` | Field | Type | Description | | --- | --- | --- | | `action` | `"INIT"` \| `"data_exchange"` \| `"BACK"` | Why WhatsApp called. See the table below. | | `screen` | `string` | The screen the person is on. Not set for `INIT`. | | `data` | `object` | Values the current screen sends, without Wabery's internal `__wabery_*` keys. For a `refreshOnSelect` field, this holds the screen's current answers. | | `triggered_by` | `"footer"` \| `"field_change"` \| `null` | `"footer"` when the person pressed the screen's button, `"field_change"` when a `refreshOnSelect` field changed. `null` for `INIT`, `BACK`, and hand-written Flow JSON. | | `changed_field` | `string` \| `null` | The field that changed, when `triggered_by` is `"field_change"`. | | `version` | `string` | WhatsApp's data API version. | | `flow_token` | `string` | Identifies this send. It's the value `flows.send` returned and the one on `flow.completed`. | | `flow_id`, `agent_id`, `organization_id` | `string` | The flow and project this send belongs to. | | `contact_id` | `string` \| `null` | The Wabery contact. | | `contact_reference` | `string` \| `null` | Your own id for the person: the `referenceId` you set when you [enrolled the contact](#starting-the-conversation). | | `from` | `string` \| `null` | The person's phone number in E.164 format. | Wabery sets the identity fields (`flow_token` through `from`) after merging WhatsApp's payload, so a request can't spoof them. | `action` | When WhatsApp sends it | | --- | --- | | `INIT` | The flow opens. Return the first screen. | | `data_exchange` | A `refreshOnSelect` field changed, or the person pressed the button on a screen that can lead to more than one screen. A screen with a single next screen navigates on the phone without calling you. | | `BACK` | The person went back to a screen that has `refresh_on_back: true` (hand-written Flow JSON only). | WhatsApp also sends health checks (`ping`) and error notifications. Wabery answers those itself, so your endpoint never receives them. Verify the signature and parse the body with the SDK: ```ts const req = wabery.webhooks.verifyDataExchange( rawBody, request.headers["x-wabery-signature"], process.env.WABERY_WEBHOOK_SECRET, ); // req.action, req.screen, req.data, req.flow_token, req.contact_reference, … ``` ### The reply Return HTTP `200` with a JSON object naming the next `screen` and its `data`: ```json { "screen": "SELECT", "data": { "project_options": [ { "id": "proj_a", "title": "Project A" }, { "id": "proj_b", "title": "Project B" } ], "project": "proj_a" } } ``` `screen` must be a screen in the flow, or `SUCCESS` to close it (see [Close the flow from your endpoint](#close-the-flow-from-your-endpoint)). `data` does three things: - **Options:** `_options` arrays of `{ id, title }` fill `dynamicOptions` fields. - **Prefills:** a field's name with a value (`"project": "proj_a"`) preselects it. - **Errors:** `error_message` shows a message on the screen instead of advancing. Return the same `screen` to stay on it (for example, to refresh options), or a different screen to move on. To branch per person, return a different screen; it must be one the current screen can lead to. When you move to another screen in a flow built from a `draft`, include the earlier answers in `data`. Each screen's data model carries the answers from the screens before it, and the final submission reads them from there. `req.data` already holds them, so spread it into your reply. > **Replace, not merge.** The `data` you return becomes the screen's whole data model. Wabery doesn't merge it with what you sent before, so return every `_options` list and prefill the screen needs on every reply. Answers the person typed are kept separately and aren't affected. The SDK builds these replies: ```ts import { dataExchangeError, dataExchangeScreen, flowOptions } from "@wabery/sdk"; return dataExchangeScreen("SELECT", { ...flowOptions("project", projects), // { project_options: [{ id, title }] } project: "proj_a", }); return dataExchangeError("SELECT", "No active projects in this workspace."); // { "screen": "SELECT", "data": { "error_message": "No active projects in this workspace." } } ``` ### Close the flow from your endpoint A flow usually closes on the phone: when the person presses a button whose target is `complete`, WhatsApp sends their answers to Wabery and you receive [`flow.completed`](#receive-the-submission). Your endpoint isn't involved. Close it from your endpoint when your server decides the form is done, for example after a loop where the person adds items until they pick "Done". Reply with WhatsApp's reserved `SUCCESS` screen and put the answers in `extension_message_response.params`: ```json { "screen": "SUCCESS", "data": { "extension_message_response": { "params": { "customer_name": "Alex", "service": "hemming" } } } } ``` ```ts import { dataExchangeComplete } from "@wabery/sdk"; return dataExchangeComplete({ customer_name: "Alex", service: "hemming" }); ``` WhatsApp closes the flow and sends `params` back to Wabery, and you receive `flow.completed` with `params` as `submission`: - **`flow_token`:** Wabery adds the session's `flow_token` to `params`. If you include it yourself, it must equal `req.flow_token`; a token from another send is rejected. - **Answers:** WhatsApp returns only what's in `params`, not the answers from earlier screens. When the flow declares fields, Wabery keeps and validates only those fields, so use the field names. A required field on a screen the person reached must be present, or `valid` is `false`. Without declared fields, `submission` contains every param except `flow_token`. - **Hand-written Flow JSON:** mark the screen your endpoint closes from as `terminal: true`. Don't give any screen the id `SUCCESS`: WhatsApp reserves it, and Wabery rejects it in `config apply`, `config validate`, and publishing. ### Reply rules Wabery checks every reply. If a check fails, WhatsApp shows the person an error and the screen doesn't change. They can press the button again, which sends the same request a second time, so make your handler idempotent. | Rule | Failure `code` | | --- | --- | | Respond within 8 seconds. | `timeout` | | Accept the connection. | `unreachable` | | Use a public HTTPS URL on port 443. | `blocked_url` | | Don't redirect. Wabery doesn't follow redirects, so set the final URL. | `redirect` | | Return a `2xx` status. | `http_error` | | Keep the body at 64 KB or less. | `response_too_large` | | Return valid JSON. | `invalid_json` | | Return an object with a string `screen` and an object `data`. `screen` is a screen in the flow or `SUCCESS`. A `SUCCESS` reply's `params` is an object, and any `flow_token` in it is this send's. | `invalid_response` | The 8 seconds cover your whole handler. If finishing involves slow work, such as generating a document or sending another message, reply first and do that work afterwards or when `flow.completed` arrives. ### Debug endpoint failures Each failed call is recorded as an `endpoint.failed` [flow event](#event-log-debugging-without-worker-logs) with the failure `code` and a message that says what to fix: ```bash wabery flows events flow_123 ``` ```jsonc { "object": "flow_event", "type": "endpoint.failed", "level": "warn", "message": "Your endpoint did not respond within 8 seconds.", "data": { "code": "timeout", "action": "data_exchange", "screen": "ADD_ITEM", "flow_token": "b1c2..." }, "created_at": "2026-10-13T02:01:46.000Z" } ``` For `http_error` and `redirect`, `data.status` holds the HTTP status your endpoint returned. Before you publish, check your endpoint with [`wabery flows test`](#test-locally), which applies the same rules, or with the endpoint panel's **Live** mode in the dashboard's flow builder. ## Field types & validation Every type below is validated **server-side** before `flow.completed` fires, mirroring WhatsApp's on-device checks. | `type` | Renders as | Value shape | Options & validation | | --- | --- | --- | --- | | `text` | TextInput | `string` | `required`, `minChars`, `maxChars`, `pattern` (regex; needs `helperText`), `inputType`: `text` \| `email` \| `phone` \| `password` \| `passcode` | | `textarea` | TextArea | `string` | `required`, `maxChars` | | `number` | numeric TextInput | `number` | `required`, `minChars`, `maxChars` | | `boolean` | OptIn checkbox | `boolean` | `required` | | `date` | DatePicker, or CalendarPicker when `range: true` | `string`, or `{ start_date, end_date }` | `required`, `range` | | `choice` | RadioButtonsGroup, `Dropdown` when `dropdown: true`, or CheckboxGroup when `multi: true` | `string`, or `string[]` when `multi` | `required`, static `options` **or** `dynamicOptions`, `minSelected`, `maxSelected`, `refreshOnSelect` (dynamic) | | `photo` | PhotoPicker | `string[]` (media handles) | `required`, `minFiles`, `maxFiles`, `maxFileSizeKb` | | `document` | DocumentPicker | `string[]` (media handles) | `required`, `minFiles`, `maxFiles`, `maxFileSizeKb` | You can also place non-input **display items** (`heading`, `subheading`, `body`, `caption`) on a screen for instructions. ### Conditional fields & multiple screens - **Conditional fields** — give any field or display item a `visibleWhen` condition so it only appears when a prior answer on the **same screen** matches: ```json { "name": "other_detail", "label": "Tell us more", "type": "text", "visibleWhen": { "field": "reason", "op": "eq", "value": "other" } } ``` - **Multiple screens** — navigation is a graph, not a fixed list. Each screen has a primary button (and up to two link buttons) whose `target` is either another screen (`{ "kind": "screen", "screenId": "..." }`) or the end of the flow (`{ "kind": "complete" }`). Leave navigation unset for a linear walk (next screen in order; the last screen completes). In dynamic flows, branching screens let your endpoint choose which screen comes next. ## Starting the conversation A Flow is delivered as an interactive WhatsApp message, so the same initiation rules as any message apply: - **Opt-in is required.** Sending to a contact (by `contact_id`, `conversation_id`, or `to`) needs an active WhatsApp opt-in on record, or the send is rejected with `409 contact_opt_in_required`. Capture opt-in when you enroll the contact. - **The 24-hour window applies.** You can send a Flow freely while the [customer-service window](https://wabery.com/docs/channels#the-24-hour-window) is open (the contact messaged you within the last 24h). To **proactively** prompt — e.g. a daily check-in Flow when no one has messaged — first re-open the window with an approved [template](https://wabery.com/docs/sending-messages#send-a-template), then send the Flow. That template step requires a Meta payment method; see [why WhatsApp templates need payment](https://wabery.com/blog/whatsapp-template-payment-method). `flows.send` itself sends a plain interactive flow message; it does not wrap a template. **Enroll the contact first** so `contact_reference` is populated from the very first interaction (it's the `externalId` echoed on data-exchange, `flow.completed`, and `message.received`): ```ts const contact = await wabery.contacts.enroll({ phone: "+15551234567", projectId: "project_...", referenceId: "user-42", // becomes contact_reference / externalId metadata: { plan: "pro" }, optIn: { source: "app-onboarding", method: "checkbox" }, }); await wabery.flows.send("flow_...", { channelId: "channel_...", contactId: contact.id, }); ``` ## Why a send didn't land A `flows.send` returning a `flow_dispatch` means Wabery accepted the send, not that WhatsApp delivered it. Failures surface in two places: - **Synchronously, on send.** Pre-flight problems reject the request: `409 contact_opt_in_required` (no opt-in on record), `409 flow_not_published` / `flow_blocked` / `flow_throttled` / `flow_deprecated` (Meta status), or a messaging window error. The SDK throws a typed `WaberyConflictError` / `WaberyApiError` with the `code` and `message`. - **Asynchronously, after send.** Delivery outcomes arrive on the [`message.status`](https://wabery.com/docs/webhooks) webhook — watch for `status: "failed"` and read `failure.code` / `failure.title` for Meta's reason. Inspect a specific send anytime with its `flow_token`: ```ts const dispatch = await wabery.dispatches.get(flowToken); // status: SENT | COMPLETED | EXPIRED ``` ```bash wabery dispatches get ``` ## Versioning & publishing - **`config apply` updates the draft.** It upserts the flow's definition; it does not change what end-users see until you publish. - **Publishing snapshots a version.** Publishing to Meta freezes the current Flow JSON and field schema as a new `FlowVersion` and pushes it to Meta. Each send is bound to the version that was live at send time, so a submission is always validated against the schema it was collected with. - **In-flight sessions are unaffected by edits.** An open Flow keeps running on the version it started with; re-applying or re-publishing a new version only affects sends made *after* the publish. (Sessions still expire after 7 days.) - **Meta reviews flows.** Publishing queues an async job that goes through Meta's draft → publish step and can take time; the flow becomes sendable only once Meta reports it `PUBLISHED`. Wabery tracks Meta's status and blocks sends for `PUBLISHING`, `PUBLISH_FAILED`, `DRAFT`, `BLOCKED`, `THROTTLED`, or `DEPRECATED` flows with a clear error. Draft flows can only be test-sent to the phone numbers that own the flow on Meta. ### The full lifecycle in code `config.apply` works in flow **keys** (your stable `config_key`); `publish` and `send` work in **`flow_id`s**. The bridge is `flows.findByConfigKey`: ```ts // 1. Apply the draft (creates/updates the flow as DRAFT). await wabery.config.apply({ flows: [{ key: "lead_intake", name: "Lead intake", draft }], automations: [], }); // 2. Resolve the flow_id from your config key. const flow = await wabery.flows.findByConfigKey("lead_intake"); if (!flow) throw new Error("flow not found"); // 3. Queue the publish job… await wabery.flows.publish(flow.id); // 4. …and wait until Meta reports PUBLISHED (polls; throws on PUBLISH_FAILED/BLOCKED/DEPRECATED/timeout). await wabery.flows.waitUntilPublishable(flow.id, { timeoutMs: 120_000 }); // 5. Now it's sendable. await wabery.flows.send(flow.id, { channelId: "channel_...", contactId: "contact_..." }); ``` To check status yourself instead of blocking, read `flow.meta_status` from `wabery.flows.status(flow.id)` or `wabery.flows.get(flow.id)` — it is `PUBLISHED` when sendable. Project webhooks also receive `flow.status` when Meta reports a status change. ### When a publish fails A failed publish sets `meta_status` to `PUBLISH_FAILED` and carries the actionable detail: `meta_status_reason` (Meta's human-facing title/message) and `validation_errors` (with line/field pointers when present). The CLI prints both: ```bash wabery flows publish flow_123 --wait # waits up to 5 min by default wabery flows publish flow_123 --wait=600 # or set your own timeout (seconds) wabery flows status flow_123 # re-check anytime; prints the reason if failed ``` `--wait` polls until Meta reports `PUBLISHED`. Because publishing is asynchronous on Meta's side, a timeout is **not** an error — the CLI prints "still publishing, re-check with `flows status`" and exits 0. It only errors on a terminal `PUBLISH_FAILED` / `BLOCKED` / `DEPRECATED` state, and prints Meta's reason. Wabery makes publishing **idempotent**: it validates the compiled JSON locally before creating anything on Meta, persists the Meta flow id as soon as the asset exists, and — if a name was already taken by a prior failed attempt — adopts that existing flow instead of dead-ending on "Flow name is not unique". So a transient failure no longer permanently burns a flow name; just retry the publish. ### Inspecting and deleting flows - **Get the compiled Flow JSON.** `wabery flows get ` (or `GET /flows/{id}?include=flow_json`, or `wabery.flows.get(id)` in the SDK) returns `flow_json` — the compiled Meta WhatsApp Flow JSON (the published version if any, else the current draft), including `screens`, `routing_model`, and data-source bindings. Use it to align your data-exchange endpoint to the compiler's screen ids and navigation. It's opt-in (`?include=flow_json`) because it can be large, so status polls stay lean; `field_schema` (what `flow.completed` is validated against) is always returned. - **Delete a flow.** `wabery flows delete ` (SDK: `wabery.flows.delete(id)`) removes a flow. A draft Meta asset is hard-deleted; a published one is deprecated (Meta forbids deleting published flows). The local record is removed regardless, so this is how you clean up failed/test/orphaned flows. - **Reconcile with Meta.** `wabery flows reconcile ` (or `flows status`) pulls Meta's current status + validation_errors, and — if a prior failed publish left the flow's Meta id unset but a flow by that name exists on Meta — re-adopts it so the record stops drifting. ### Event log (debugging without worker logs) Every publish attempt, submission outcome, reconciliation, and failed data-exchange call is recorded as a flow event with the raw detail. Read them with `wabery flows events ` (`GET /flows/{id}/events`, SDK `wabery.flows.events(id)`): ```jsonc { "object": "list", "has_more": false, "data": [ { "object": "flow_event", "type": "publish.failed", "level": "error", "message": "Create flow: Flow name is not unique", "data": { "code": "meta_error", "validation_errors": [{ "error": "INVALID_ROUTING_MODEL", "line_start": 12 }] }, "created_at": "2026-06-24T10:00:00.000Z" }, { "object": "flow_event", "type": "submission.rejected", "level": "warn", "message": "Submission rejected: brooder", "data": { "valid": false, "validation_errors": [{ "field": "brooder", "message": "required field missing" }], "reached_screens": ["select", "grower"] } } ] } ``` | `type` | Recorded when | | --- | --- | | `publish.queued`, `publish.succeeded`, `publish.failed` | A publish to WhatsApp is queued, succeeds, or fails. | | `publish.blocked` | A required flow can't go live until it's tested in the Sandbox. | | `submission.validated`, `submission.rejected` | A `flow.completed` submission passes or fails validation. The same `validation_errors` are on each submission in `GET /submissions`. | | `flow.reconciled` | Wabery syncs the flow's status or id from WhatsApp. | | `endpoint.failed` | A call to your `data_exchange_url` fails. `data.code` says why; see [Reply rules](#reply-rules). | ## Localization (multi-language flows) WhatsApp Flows have **no built-in locale switch** — Flow JSON is single-language, and Meta only localizes message *templates*, not Flows. There are two supported patterns: ### Static copy → one flow per language (resolved by config key) Author the flow once, then translate its user-facing strings and publish one flow per locale **sharing a single `config_key`**, each with a distinct `locale` (omit `locale` for the group default). `localizeFlow` does the translation step: give it a draft and a dictionary per locale (mapping the source string to its translation), and it returns one draft per locale (missing keys fall back to the source string). ```ts 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 send by config key. Wabery resolves the variant for the contact — explicit `locale` → the contact's `preferred_language` → the `""` group default — and skips any variant Meta hasn't approved: ```ts const { flow_token, locale } = await wabery.flows.sendByConfigKey("lead_intake", { channelId: "channel_...", contactId: "contact_...", // uses this contact's preferred_language locale: "es", // optional override }); ``` > If this throws `WaberyEndpointNotAvailableError` (a `404`/`405` with no `Wabery-Version` response header), the route isn't served by the instance you're connected to — a deployment/version gap, not a usage bug. See [Errors → version skew](https://wabery.com/docs/errors) for the fallback (the list endpoints carry the same data). Set the contact's language with `contacts.enroll({ preferredLanguage })` or `contacts.update(id, { preferredLanguage })`. In automations, the **Send Flow** node has a "use contact's language" toggle that resolves by config key at send time. (WhatsApp doesn't report a user's language, so you supply it.) > `locale` is part of the `WaberyConfig` flow-entry type in `@wabery/sdk` — no cast needed. Each `(key, locale)` pair must be unique: two entries sharing a `key` with the **same** locale (or both omitting it) are **rejected** by `config.apply` / `config validate`, so a typo can't silently overwrite a variant. Give each variant a distinct `locale` (leave exactly one without, the group default). ### Dynamic copy → translate via data-exchange For `DATA_EXCHANGE` flows, bind user-facing strings to `${data.*}` and return the right language from your endpoint based on the contact. Wabery echoes `contact_reference` (your own id) on every data-exchange call, so you know whose language to use: ```ts const locale = await localeFor(req.contact_reference); // "en" | "id" | … return dataExchangeScreen("SELECT", { ...flowOptions("timeline", optionsFor(locale)), heading: t(locale, "tell_us_about_your_project"), }); ``` Use the first pattern for fixed copy (simplest), the second when copy is per-user or already dynamic. ## Test locally You don't need a deploy or a Meta publish to exercise your handlers. Sign a fake payload with your webhook secret and POST it to your local server — the [CLI](https://wabery.com/docs/cli) does this for you: ```bash # Drive your webhook handler: wabery webhooks send-test --url http://localhost:3000/webhooks \ --secret "$WABERY_WEBHOOK_SECRET" --event flow.completed # Send one data-exchange request and check the reply: wabery flows test --url http://localhost:3000/flow \ --secret "$WABERY_WEBHOOK_SECRET" \ --action data_exchange --screen SELECT --data '{"workspace":"ws_1"}' \ --triggered-by field_change --changed-field workspace # Walk the whole journey (open, field changes, branch), then fire flow.completed: wabery flows simulate --url http://localhost:3000/flow \ --webhook-url http://localhost:3000/webhooks \ --secret "$WABERY_WEBHOOK_SECRET" \ --steps '[{"action":"INIT"},{"action":"data_exchange","screen":"SELECT","data":{"workspace":"ws_1"}}]' \ --submission '{"workspace":"ws_1","project":"proj_a"}' ``` Both commands check each reply against the [reply rules](#reply-rules) and exit with an error that lists what Wabery would reject. They can't check that `screen` exists in your flow; Wabery checks that when the flow runs. In `simulate`, a `SUCCESS` reply ends the walk, and its `params` become the `flow.completed` submission unless you pass `--submission`. In code, `signPayload` produces the same `x-wabery-signature` header so you can write your own fixtures and integration tests: ```ts 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, }); ``` The shared **sandbox number** is the other half of the loop: enrolling a contact on a sandbox project returns a `channel_id` you can send real flows through, and joining emits a [`participant.joined`](https://wabery.com/docs/webhooks) webhook — useful for end-to-end tests against a real WhatsApp client without a dedicated number. ## End-to-end example: cascading dropdowns, a branch, and your database A dynamic flow whose options depend on the person, that branches on an answer, and whose submission lands in your database. It's one `DATA_EXCHANGE` flow plus two handlers you own. ```ts title="flow definition" import { defineFlow, screen, dropdown, radio, textField, completeFlow, goToScreen } from "@wabery/sdk"; const draft = defineFlow([ screen("SELECT", "Where's the issue?", [ dropdown("workspace", { label: "Workspace", dynamic: true, refreshOnSelect: true }), dropdown("project", { label: "Project", dynamic: true }), radio("severity", { label: "Severity", options: [ { id: "low", title: "Low" }, { id: "high", title: "High" }, ] }), ], { // Two possible next screens, so pressing Next calls your endpoint // (triggered_by: "footer") and your reply picks the screen. primary: { label: "Next", target: goToScreen("DETAILS") }, links: [{ label: "Callback", target: goToScreen("CALLBACK") }], }), screen("DETAILS", "Anything else?", [ textField("notes", { label: "Notes" }), ], { primary: { label: "Submit", target: completeFlow() } }), screen("CALLBACK", "We'll call you back", [ textField("callback_number", { label: "Phone number", required: true }), ], { primary: { label: "Submit", target: completeFlow() } }), ]); ``` ```ts title="data-exchange endpoint (cascading options + branch)" import { dataExchangeScreen, flowOptions } from "@wabery/sdk"; const req = wabery.webhooks.verifyDataExchange(rawBody, sigHeader, secret); const user = await userByRef(req.contact_reference); if (req.action === "INIT") { return dataExchangeScreen("SELECT", { ...flowOptions("workspace", await workspacesFor(user)), ...flowOptions("project", []), // empty until a workspace is chosen }); } if (req.triggered_by === "footer") { // Next on SELECT: pick the screen, and carry the answers forward. const next = req.data?.severity === "high" ? "CALLBACK" : "DETAILS"; return dataExchangeScreen(next, { ...req.data }); } // The workspace changed: repopulate projects. Replace semantics, so resend both lists. const projects = await projectsFor(user, req.data?.workspace as string); return dataExchangeScreen("SELECT", { ...flowOptions("workspace", await workspacesFor(user)), ...flowOptions("project", projects), }); ``` ```ts title="webhook handler (write the final submission)" const event = wabery.webhooks.constructEvent(rawBody, sigHeader, secret); if (event.event === "flow.completed" && event.payload.valid) { if (seen.add(event.payload.flow_token)) return; // idempotent per flow_token await db.tickets.insert({ userId: await userIdByRef(event.payload.contact_reference), ...event.payload.submission, // { workspace, project, severity, notes | callback_number } }); } ``` --- # Automations Handle most WhatsApp conversations with no code — trigger-and-action workflows for welcome messages, keyword replies, flows, delays, human handoff, and inline function calls. Automations are the no-code way to handle inbound WhatsApp conversations. Each automation is a **trigger** plus a chain of **actions**, built visually on the automations canvas in the dashboard under **Agent → Automations** (`/automations`). They run inside Wabery, so you don't need a server, a webhook, or a deploy to reply to customers. **Start with automations.** They cover most of what an agent needs — welcome messages, keyword menus, collecting details with a Flow, waiting for a reply, following up after a delay, and handing off to a human. Reach for a [hosted function](https://wabery.com/docs/hosted-functions) only when a step genuinely needs custom code, and prefer running that function *from* an automation (see [Run Function](#run-function)) rather than making the whole agent code-first. ## Triggers An automation fires on the first trigger that matches an inbound message. Evaluation order is first-match-wins: | Trigger | Fires when | | --- | --- | | **Welcome** | The contact's first-ever message to this project. | | **Keyword** | The message matches one of the automation's keywords (e.g. `book`, `hours`, `price`). | | **Any message** | A catch-all for any inbound message that no keyword caught. | ## Actions After a trigger matches, Wabery walks the chain of actions in order. | Action | What it does | | --- | --- | | **Send Reply** | Sends a text reply. Supports [variables](#variables) like `{{customer_name}}` and up to three quick-reply buttons. | | **Send Flow** | Sends a published [WhatsApp Flow](https://wabery.com/docs/flows) to collect structured input (booking details, an order form, lead questions). | | **Run Function** | Calls a [hosted function](https://wabery.com/docs/hosted-functions) inline and uses its result. See [Run Function](#run-function). | | **Delay** | Waits a set time, then continues the chain later (e.g. a next-day follow-up). | | **Wait for Reply** | Pauses until the contact replies, captures what they said, and can branch on matched options. | | **Pause Replies** | Turns on [handoff](https://wabery.com/docs/handoff): stops automated replies and hands the conversation to a human. | | **Condition** | Branches the chain based on the contact or the message. | ## Examples - **Keyword reply** — Keyword `hours` → Send Reply with your opening times. - **Menu** — Keyword `help` → Send Reply with quick-reply buttons (`Book`, `Prices`, `Talk to a human`). - **Collect details** — Welcome → Send Reply (a greeting) → Send Flow (a booking form). - **Ask and branch** — Keyword `book` → Send Reply ("Are you a new customer?") → Wait for Reply → Condition → different paths for yes / no. - **Follow up later** — After a Flow submission → Delay 1 day → Send Reply ("How did everything go?"). - **Escalate** — Keyword `refund` → Pause Replies so a teammate takes over. ## Run Function The **Run Function** action calls one of your project's deployed [hosted functions](https://wabery.com/docs/hosted-functions) in the middle of an automation. This is how you bring in live data — real availability, an order status, a price quote — without turning the whole agent into code. The function runs with a timeout, and if it fails the automation simply continues, so a broken function never wedges the conversation. A function returns an `output` object. What the automation does with it depends on the action's **result mode**: | Result mode | Behavior | | --- | --- | | **Set variables** (default) | Merges `output` into the conversation's [variables](#variables) so later replies can use them. Give it a name like `order` to expose `{{order_status}}`, `{{order_eta}}`; leave the name empty to use the output field names directly. | | **Reply with output** | Sends a field from `output` back to the customer. Defaults to `reply`, then `message`, then `text`, or name the field explicitly. | | **Side effect** | Runs the function for its effect only (log a lead, notify a system) and ignores the output. | A typical shape: Keyword `status` → Run Function `lookupOrder` (set variables as `order`) → Send Reply `Your order is {{order_status}}, arriving {{order_eta}}.` ## Variables Send Reply and the reply text of a Run Function support `{{variable}}` placeholders: | Variable | Value | | --- | --- | | `{{business_name}}` | Your organization name. | | `{{customer_name}}` | The contact's name (falls back to "there"). | | `{{business_phone}}` | Your business phone, if set. | | `{{business_address}}` | Your business address, if set. | | `{{captured_reply}}` | The customer's message captured by a Wait for Reply action. | | `{{captured_option}}` | The matched option label from a Wait for Reply action. | Any field returned by a Run Function action in **Set variables** mode is also available as a `{{...}}` placeholder in later actions. ## Routing mode Automations only run when the project routes inbound messages to Wabery's in-app handling. If a project is set to **external routing**, every inbound message is forwarded to your webhook instead and automations are paused — your webhook owns the reply logic. See [routing modes](https://wabery.com/docs/channels) to switch. The automations canvas shows a banner when a project is on external routing. ## Config as code Automations are part of a project's configuration and can be exported, validated, diffed, and applied alongside webhooks and flows. See the [CLI](https://wabery.com/docs/cli) for the config export/apply workflow, or build and edit them visually from **Agent → Automations** in the dashboard. --- # Human handoff Pause the hosted or external reply path for one conversation while a teammate handles it in Inbox. Handoff pauses automation for one conversation so a teammate can reply. It does not affect the rest of the inbox. ## The two states A conversation is always in one of two states: | State | Who replies | | --- | --- | | **Automation active** (default) | The project's hosted agent or external webhook can answer. | | **Handoff on** | Automations, external webhooks, and public API outbound sends are paused. A teammate handles the conversation in the inbox. | ## What handoff pauses When handoff is on for a conversation, Wabery will not: - Run native automations or auto-replies for new inbound messages. - Forward new inbound messages to an external project webhook. - Queue outbound automated replies through `POST /v1/messages`; the API returns `409 ai_handoff_active` instead. Manual teammate replies from **Inbox** still work. Handoff stays active until someone turns it off, so a human conversation is never taken back by an automation mid-reply. ## Turning handoff on Handoff turns on automatically when either happens: - **A teammate replies manually** in the inbox (`/inbox`). Sending a manual message means a human is now handling the thread, so the configured agent steps back. - **An automation runs Pause Replies.** Use the [Pause Replies](https://wabery.com/docs/automations#actions) action to escalate on a keyword or condition, for example keyword `refund` → Pause Replies, so a teammate takes over. A teammate can also flip it on directly from the **Handoff** toggle in the conversation's details panel. ## Turning handoff off Open the conversation in the inbox and switch **Handoff** off (or use **Turn off handoff** in the conversation banner). The project's hosted agent or external webhook can answer new messages again. ## Where you see it - **Inbox banner**: an open conversation on handoff shows a banner, *"Handoff on: you're handling this,"* with a one-click way to hand it back. - **Conversation list**: threads on handoff are tagged with a **Handoff** badge so your team can spot what needs a human. - **Details panel**: the **Handoff** toggle shows and controls the current state. ## Handoff emails Wabery emails the organization's owners and admins who have a verified email address, so a customer who needs a person is not left waiting: - **When a customer needs a person.** When your agent or a Pause Replies automation requests a handoff, owners and admins get an email about 2 minutes later, unless a teammate has already replied. The short wait lets the email include the messages the customer sends around the handoff. - **When a customer is waiting for a reply.** While handoff is on, if the customer writes and nobody on your team replies within 2 minutes, owners and admins get one reminder with the customer's latest messages. More messages before you reply do not send more emails. After you reply, the next unanswered message can send a new reminder. Replies from your agent or automations do not count as a reply from your team, and a customer's emoji reaction does not count as a new message. Sandbox and browser test chats never send handoff emails. Both switches are on by default. Turn handoff emails off for a whole project in **Project settings → Inbox notifications**, or for one contact with the **Handoff emails** switch in the conversation's details panel. ## When another app handles the conversation Your WhatsApp number can also be connected to another app that answers customers, such as a Meta Business Agent. Meta lets one app control a conversation at a time. While another app controls a conversation: - **You still see it.** Meta shares the customer's messages, the other app's replies, and delivery receipts with Wabery. They appear in **Inbox** so your team has the full context. - **Wabery stays quiet.** Your agent and automations do not answer those messages, and Wabery does not forward them to your external webhook as `message.received`. - **It doesn't use your plan.** These shared messages do not count toward your plan's monthly message allowance. - **Templates still send.** Meta never blocks template messages or broadcasts because another app controls a conversation, and neither does Wabery. Wabery takes the conversation back when Meta delivers the customer's next message to Wabery. After 24 hours with no activity, Wabery also stops treating the other app as the owner. Until the customer writes again, Meta can still reject a free-form reply with error `131070`. When that happens, the message fails with a reason that says another app controls the conversation, instead of a generic Meta error. > Handoff is managed in **Inbox**. External services should treat `409 ai_handoff_active` from `POST /v1/messages` as a hard stop and wait until a teammate turns handoff off. ## Next steps - [Automations](https://wabery.com/docs/automations): Trigger handoff automatically with the Pause Replies action. - [Conversations & history](https://wabery.com/docs/conversations): Pull thread history to give a teammate context before they reply. --- # Hosted functions Deploy server-side TypeScript handlers that Wabery can run for message triggers, Business Agent tools, and MCP tool calls. Hosted functions are project-scoped TypeScript handlers hosted by Wabery. Use them when a WhatsApp workflow needs server-side logic close to the conversation: quote calculators, order lookups, enrichment, routing decisions, or small tools that a Business Agent can call. Functions are created as metadata first, then deployed from source. Deployments always remain inactive until you review and explicitly activate them. A function must be active and have a successful deployment before Wabery can invoke it. > New to Wabery? Complete the [Quickstart](https://wabery.com/docs/quickstart) first. Hosted functions assume you already have a project, an API key or CLI login, and a test conversation or workflow that needs server-side logic. ## Create and deploy Open **Agent → Functions** to inspect deployments and logs in the dashboard, or create and deploy from the CLI, SDK, or API: **CLI:** ```bash wabery functions create \ --slug quote-customer \ --name "Quote customer" \ --trigger-type ANY_MESSAGE wabery functions deploy fn_... --source ./quote-customer.ts wabery functions update fn_... --active true wabery functions test fn_... --text "Can you quote this?" wabery functions logs fn_... ``` **SDK:** ```ts 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: { reply: "Thanks, we will follow up." } }; } `, }); await wabery.functions.update(fn.id, { isActive: true }); await wabery.functions.test(fn.id, { text: "Can you quote this?" }); ``` **curl:** ```bash curl https://api.wabery.com/v1/functions \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "slug": "quote-customer", "name": "Quote customer", "trigger_type": "ANY_MESSAGE" }' curl https://api.wabery.com/v1/functions/fn_.../deploy \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{"source":"export default async function handler(ctx) { return { output: { ok: true } }; }"}' curl -X PATCH https://api.wabery.com/v1/functions/fn_... \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Content-Type: application/json" \ -d '{"is_active":true}' ``` `trigger_type` matches automation triggers: `KEYWORD`, `WELCOME`, or `ANY_MESSAGE`. ## Function source Export a default async handler. Wabery passes the normalized event and a scoped context object. ```ts export default async function handler(ctx) { const profile = await ctx.data.get("profile"); await ctx.kv.put("last_event", ctx.event.type); ctx.log("message", ctx.event.text); return { output: { ok: true, profile }, }; } ``` Context access is scoped to the authenticated project and contact. Functions are request/response handlers; keep them bounded and use logs for debugging rather than long-running work. ## Expose as a tool Hosted functions can back a Meta Business Agent connector tool, or be exposed as an external MCP/tool call. External invocation is opt-in: ```bash wabery functions update fn_... \ --expose-as-mcp-tool true \ --input-schema '{"type":"object","properties":{"orderId":{"type":"string"}}}' wabery functions invoke fn_... --arguments '{"orderId":"ord_123"}' ``` SDK equivalent: ```ts await wabery.functions.update("fn_...", { exposeAsMcpTool: true, inputSchema: { type: "object", properties: { orderId: { type: "string" } }, }, }); await wabery.functions.invoke("fn_...", { arguments: { orderId: "ord_123" }, }); ``` To wire a Business Agent tool to hosted logic, create a connector tool with `backing_type: "HOSTED_FUNCTION"` and `backing_function_id: "fn_..."`. ## API scopes Use scoped API keys where possible: | Scope | Allows | | --- | --- | | `functions:read` | List functions, fetch source, read invocation logs. | | `functions:write` | Create, update, deploy, test, and delete functions. | | `functions:invoke` | Invoke an exposed function as a tool. | The CLI and MCP server use the same REST endpoints. MCP write tools require write mode and confirmation tokens for create, deploy, update, invoke, and delete actions. --- # CLI Manage channels, contacts, broadcasts, Flows, and hosted functions from your terminal. The Wabery CLI manages channels, registration intents, contacts, imports, broadcasts, messages, flows, hosted functions, automations, and webhooks from your terminal. It also ships the Wabery MCP server (see the "WhatsApp MCP Server" section below), so you can hand Wabery to an AI coding agent (Claude, Codex, OpenCode) and build by describing the feature. ## Install & sign in Install it globally, then sign in: **npm:** ```bash npm i -g @wabery/cli wabery login ``` **pnpm:** ```bash pnpm add -g @wabery/cli wabery login ``` **bun:** ```bash bun add -g @wabery/cli wabery login ``` `wabery login` authorizes the CLI in your browser (`--no-open` prints a URL instead), asks you to choose a project, creates a key scoped to that project, then shows the key once. Paste it back into the waiting terminal; the CLI stores it locally so future CLI and MCP commands are authenticated. Run `wabery doctor` to confirm. To override, set `WABERY_API_KEY` (and optionally `WABERY_BASE_URL`, which defaults to the API base `https://api.wabery.com/v1` — not the dashboard origin). ### Run without installing Prefer not to install globally? Run any `wabery` command on demand through your package runner — handy for CI or a one-off `wabery login`: **npx:** ```bash npx wabery login npx wabery doctor ``` **pnpm:** ```bash pnpm dlx wabery login pnpm dlx wabery doctor ``` **bun:** ```bash bunx wabery login bunx wabery doctor ``` ### Scaffold app files After login, `wabery init` creates starter files for your app without overwriting existing files: ```bash wabery init --name "My project" ``` It writes `.env.wabery`, `wabery.config.json`, and a `wabery-webhook-handler.ts` stub. Load `.env.wabery` in your app, edit the webhook URL in `wabery.config.json`, then apply it with `wabery config apply wabery.config.json`. ## Common commands ```bash # verify your API key and base URL; also flags channels that drop inbound # (the `channels` check lists any `routing_warnings`) wabery doctor # confirm the project this key is scoped to wabery projects list # for a new sandbox project: text the join code to the sandbox, # send one normal WhatsApp message, then inspect the conversation wabery projects get "project_id" # read join_code + enrollment_channel.phone_number wabery channels list wabery conversations list wabery conversations messages "conversation_id" # reply inside the open messaging window wabery messages send --channel-id "channel_id" \ --conversation-id "conversation_id" \ --text "Thanks for your message" # send richer WhatsApp payloads wabery messages send --channel-id "channel_id" \ --conversation-id "conversation_id" \ --latitude 37.7749 --longitude -122.4194 --location-name "Office" wabery messages send --channel-id "channel_id" \ --conversation-id "conversation_id" \ --sticker-link "https://example.com/sticker.webp" # create a starter config, then validate it wabery config init wabery.config.json --project-id "project_id" wabery config validate wabery.config.json # enroll a WhatsApp contact for testing (optionally with a language) wabery contacts enroll --project-id "project_id" --phone "+14155550123" \ --preferred-language "es" # update a contact's language or metadata later (metadata is shallow-merged) wabery contacts update "contact_id" --preferred-language "id" \ --metadata '{"linked": true}' # import and poll a consented CSV audience wabery contacts import contacts.csv --phone-column phone \ --name-column name --language-column language --tags-column tags \ --consent '{"categories":["MARKETING"],"source":"signup_form","method":"web_form"}' wabery contacts import-status "import_id" # mint a single-use WhatsApp registration link wabery registration-intents create --customer-reference "user_123" \ --metadata '{"plan": "starter"}' wabery registration-intents get "intent_id" # send a flow; use --config-key to pick the variant for the contact's language wabery flows send "flow_id" --channel-id "channel_id" --contact-id "contact_id" wabery flows send --config-key "lead_intake" --locale "es" \ --channel-id "channel_id" --contact-id "contact_id" # check a queued message or wait for a template approval in scripts wabery messages get "message_id" wabery templates wait "template_id" --wait=86400 # inspect channels; `routing_warning` flags a channel that silently drops inbound wabery channels list wabery channels get "channel_id" # forward a dedicated number's inbound to your webhook (overrides project routing) wabery channels update "channel_id" --routing-mode EXTERNAL # or set the project-wide default that new channels inherit wabery projects update "project_id" --routing-mode EXTERNAL # deploy hosted logic for tools or message-triggered workflows wabery functions create --slug quote-customer \ --name "Quote customer" --trigger-type ANY_MESSAGE wabery functions deploy "function_id" --source ./quote-customer.ts wabery functions update "function_id" --active true wabery functions test "function_id" --text "I need a quote" wabery functions update "function_id" \ --expose-as-mcp-tool true \ --input-schema '{"type":"object"}' wabery functions invoke "function_id" --arguments '{"orderId":"ord_123"}' wabery functions logs "function_id" ``` ## WhatsApp Groups command reference Group IDs are opaque and every group command requires `--channel-id`: ```text wabery groups list --channel-id [--limit <1-1024>] [--starting-after ] [--ending-before ] [--after ] [--before ] wabery groups get --channel-id wabery groups create --channel-id --subject [--description ] [--join-approval-mode auto_approve|approval_required] --idempotency-key wabery groups delete --channel-id wabery groups settings --channel-id [--subject ] [--description ] [--profile-picture ] wabery groups invite-link --channel-id [reset|--reset] wabery groups join-requests --channel-id [list|approve|reject] [--join-request-ids ] [--limit <1-1024>] [--starting-after ] [--ending-before ] wabery groups remove-participants --channel-id --users wabery messages send --channel-id --group-id --text --idempotency-key ``` Settings, management actions, and sends also accept `--body ''` where the command implementation exposes it. Group creation and sends reuse the same stable idempotency key after `processing`; CLI writes execute without the MCP confirmation gate. ## Broadcast workflow ```bash wabery broadcasts create --body @broadcast.json wabery broadcasts prepare "broadcast_id" --body @audience.json wabery broadcasts get "broadcast_id" # poll until ready wabery broadcasts recipients "broadcast_id" # only after reviewing the frozen counts: wabery broadcasts send "broadcast_id" \ --idempotency-key "august-launch-send" # or schedule instead: wabery broadcasts schedule "broadcast_id" \ --scheduled-at "2026-08-01T10:00:00Z" \ --timezone "Europe/Amsterdam" wabery broadcasts list --status sending wabery broadcasts duplicate "broadcast_id" wabery broadcasts cancel "broadcast_id" ``` `audience.json` must contain exactly one of `contactIds`, `importId`, or `filter`. The CLI generates idempotency keys for broadcast mutations when none is supplied. Duplicate copies template configuration into a new draft, not the audience. Cancel stops only recipients that have not been dispatched. ## MCP server The CLI also prints config for the local Wabery MCP server, so Claude Code, Codex, and OpenCode can call Wabery directly: ```bash wabery mcp-config claude --raw wabery mcp-config codex --raw wabery mcp-config opencode --raw ``` Prefer no install? Wabery also has a hosted MCP server with OAuth sign-in. See the "WhatsApp MCP Server" section below for the hosted setup, the full list of exposed tools, and a worked example prompt. --- # WhatsApp broadcasts Send an approved WhatsApp template to a consented contact audience, immediately or on a schedule. A broadcast is a one-time send to as many as 100,000 contacts through a dedicated Meta Cloud API channel. Wabery resolves each contact's preferred language and freezes the eligible audience before delivery. ## Prerequisites and safeguards - A connected dedicated channel with acceptable quality and a confirmed Meta payment method (not the shared sandbox). - Approved marketing or utility template variants and a fallback language. Each template needs a text or media header and only URL, phone number, quick reply, request contact info, or Flow buttons. - Active consent for the `MARKETING` or `UTILITY` category. - No active suppression. Marketing broadcasts default to at most one send per contact in 24 hours and three in seven days. Wabery rechecks consent, blocks, suppression, language, and frequency during preparation and immediately before dispatch. Dispatch is also limited independently per WhatsApp channel. A number also used in the WhatsApp Business app shares Meta's fixed 20 messages per second with app and inbox traffic, so Wabery sends broadcasts on it at up to 10 messages per second. An imported phone number is never proof of consent. Meta's messaging limit also applies: the number of people you can start conversations with in any rolling 24 hours, shared by every phone number in your Meta business portfolio. Replies to people who messaged you in the last 24 hours don't count toward it. The **Templates** page shows the current limit. The dashboard explains why a channel cannot be selected. API clients receive `meta_payment_method_required` after a successful check confirms billing is missing, or `meta_payment_status_unavailable` when Wabery could not verify the current state. Refresh channel status for the latter rather than assuming billing is absent. ## Create and prepare ```ts const broadcast = await wabery.broadcasts.create({ name: "August launch", channelId: "channel_...", category: "MARKETING", templateName: "august_launch", fallbackLanguage: "en_US", variants: [{ templateId: "template_...", language: "en_US", parameterMappings: [{ component: "body", index: 0, parameterType: "text", source: "name", fallback: "there", }], }], }); await wabery.broadcasts.prepareAudience(broadcast.id, { filter: { tags: ["launch-list"], languages: ["en", "es"] }, }); ``` The audience body contains exactly one of: ```json { "contactIds": ["contact_1", "contact_2"] } ``` ```json { "importId": "import_..." } ``` ```json { "filter": { "tags": ["launch-list"], "languages": ["en", "es"], "isBlocked": false }, "excludeContactIds": ["contact_..."] } ``` Preparation is asynchronous. Poll `GET /broadcasts/{id}` until `ready`, review the total/skipped counts, and audit `GET /broadcasts/{id}/recipients`. The prepared audience is frozen; later tag or import changes do not change it. ## Lifecycle `draft` → `preparing` → `ready` → `scheduled` or `sending` → `completed`. Campaigns can also end as `canceled` or `failed`. Cancel stops only messages not yet dispatched; provider-accepted messages cannot be recalled. Duplicate creates a new draft with the template configuration but no audience. ## Send or schedule ```ts await wabery.broadcasts.send(broadcast.id); await wabery.broadcasts.schedule(broadcast.id, { scheduledAt: "2026-08-01T10:00:00Z", timezone: "Europe/Amsterdam", }); ``` Mutating broadcast API calls require `Idempotency-Key`; the SDK and CLI generate one automatically. Wabery marks the provider attempt before sending. An ambiguous provider acceptance is recorded for reconciliation instead of automatically retrying a message that may already have been accepted. If Meta pauses, disables, or recategorizes the broadcast's template while it is sending, Wabery stops the remaining sends and marks the broadcast `failed` with `failure.code: "template_not_approved"`, so no recipient is sent under the wrong category's consent and frequency rules. Duplicate the broadcast once the template is approved in the right category. Creating a broadcast with a template Wabery can't fill returns `422 unsupported_template_type`. When Meta accepts a message but holds it before delivery, Wabery keeps the recipient pending until Meta sends it or reports it failed (Meta error `132015`). ## MCP safety MCP tools cover list/get/create/prepare/recipients/send/schedule/cancel/ duplicate, plus completed contact import discovery. Agents must review a ready snapshot before requesting confirmation. Hosted MCP uses person-controlled elicitation whenever the client advertises it, including local clients. Local clients without elicitation use `send_broadcast:`, `schedule_broadcast:`, or `cancel_broadcast:` in explicit write mode as confirmation-token fallbacks; hosted clients without elicitation fail closed. The REST API additionally supports `DELETE /broadcasts/{id}` for drafts only. ## Webhooks and opt-outs Exact inbound `STOP`, `UNSUBSCRIBE`, `CANCEL`, `END`, or `QUIT` suppresses future broadcasts. Project webhooks receive `broadcast.started`, `broadcast.completed`, `broadcast.canceled`, and `broadcast.failed`. `message.status` includes `broadcast_id` and `broadcast_recipient_id`. Reference: https://wabery.com/docs/broadcasts --- # WhatsApp MCP Server Wabery's hosted WhatsApp MCP server lets Claude, ChatGPT, Cursor, and Codex send messages, manage WhatsApp Flows, and build on the WhatsApp Business API. Wabery ships a WhatsApp MCP server so any MCP-capable AI agent, Claude, ChatGPT, Cursor, Codex, or your own, can build on the WhatsApp Business API by describing what you want instead of wiring up the Meta Cloud API yourself. There are two ways to connect: a hosted server with no install, or a local server printed by the Wabery CLI (see the "CLI" section above). The dashboard groups both paths under **Access → Connections**. Use **Hosted AI apps** for ChatGPT, Claude, or Codex with OAuth. Use **Local agents** for Claude Code, Codex, or OpenCode through the Wabery CLI. Active OAuth connections appear under **Connected apps & agents**, where you can disconnect them at any time. ## Hosted MCP server The no-install path. Point any MCP client at the hosted server and sign in with OAuth: there is no API key to copy and no CLI to install. ``` https://mcp.wabery.com ``` | Client | Setup | | --- | --- | | Claude | Open [**Customize → Connectors**](https://claude.ai/new#settings/customize-connectors), click **+**, then add `https://mcp.wabery.com`. | | Claude Code | `claude mcp add --transport http wabery https://mcp.wabery.com`, then `/mcp` to sign in. | | Cursor | Customize → MCP → add a server with URL `https://mcp.wabery.com`, then click "Needs login". | | Codex CLI | Add `[mcp_servers.wabery]` with `url = "https://mcp.wabery.com"` and `auth = "oauth"` to `~/.codex/config.toml`, then run `codex mcp login wabery`. | Unlike the local server below, the hosted server has **write tools enabled**. Your OAuth scopes decide what an agent is allowed to change. High-risk tools use person-controlled MCP elicitation and fail closed when the client cannot show it. Hosted OAuth credentials work only through the hosted MCP connector; copying one into a direct REST request does not authenticate. ## Local MCP server (CLI) Prefer a local process? Install the Wabery CLI (see the "CLI" section above), then print an MCP server config for your agent and drop it into its config file — Claude Code, Codex, and OpenCode are supported: ```bash wabery mcp-config claude --raw wabery mcp-config codex --raw wabery mcp-config opencode --raw ``` Then just describe what you want: > "Read https://wabery.com/llms.txt, use my Wabery MCP server, register my test phone on the sandbox, send one normal WhatsApp message, then add a signed webhook handler and reply with `messages.send`." The agent has enough context to build the first loop end to end. The MCP server exposes the core Wabery primitives an agent needs to build an integration: projects, channels, routing, contacts, registration intents, conversations, message history, outbound messages, inbound media metadata, templates, broadcasts, WhatsApp Flows, hosted functions, submissions, dispatches, automations, webhooks, config-as-code, and Meta Business Agent tools. The local server starts **read-only** by default; pass `--write` (or set `WABERY_MCP_MODE=write`) to allow mutations in a trusted local session. Hosted function MCP tools let an agent list, create, deploy, test, expose, invoke, tail logs, and delete project-scoped server-side handlers. Function write tools require confirmation tokens in write mode, matching the CLI's safety model for config apply and flow publish. For media-aware agents, use `wabery_list_conversation_messages` to inspect history. Retained inbound WhatsApp files appear as media/assets metadata with short-lived signed URLs; download them promptly and treat `expires_at` as the retention deadline. For template and locale-aware workflows, agents should inspect `publish_readiness` on `wabery_get_channel` before creating templates. Templates need a dedicated non-sandbox WhatsApp channel, Meta business verification, and a Meta payment method; blockers such as `BUSINESS_NOT_VERIFIED` or `NO_PAYMENT_METHOD` mean the template should not be submitted yet. When enrolling contacts, set `preferred_language` if later flow sends should resolve a locale-specific config key. After `wabery_send_message`, use `wabery_get_message` to inspect queued/provider status and Meta failure details. Use `wabery_get_template` with `refresh: true`, or `wabery_wait_template` in scripts, to track template approval. ## WhatsApp Groups MCP tools The 13 group tools are divided into reads — `wabery_list_groups`, `wabery_get_group`, `wabery_get_group_invite_link`, and `wabery_list_group_join_requests` — and confirmed writes — `wabery_create_group`, `wabery_update_group_settings`, `wabery_update_group_profile_picture`, `wabery_reset_group_invite_link`, `wabery_approve_group_join_requests`, `wabery_reject_group_join_requests`, `wabery_remove_group_participants`, `wabery_delete_group`, and `wabery_send_group_message`. Create and send require caller-generated stable idempotency keys; a processing create result has no group ID and must be retried with the same key. Any client advertising MCP elicitation uses client-controlled confirmation, including local clients; local clients without elicitation use write mode and the `confirmation_token` fallback. ## Broadcast campaigns | Stage | Tools | Required scope | | --- | --- | --- | | Find an audience | `wabery_list_contacts`, `wabery_list_contact_imports`, `wabery_get_contact_import` | `contacts:read` | | Inspect | `wabery_list_broadcasts`, `wabery_get_broadcast`, `wabery_list_broadcast_recipients` | `broadcasts:read` | | Build | `wabery_create_broadcast`, `wabery_prepare_broadcast_audience`, `wabery_duplicate_broadcast` | `broadcasts:write` | | Deliver | `wabery_send_broadcast`, `wabery_schedule_broadcast` | `broadcasts:send` | | Stop remaining work | `wabery_cancel_broadcast` | `broadcasts:write` | Safe sequence: verify a dedicated channel, approved variants, and category-specific consent; create a draft; prepare exactly one of `contact_ids`, `import_id`, or `filter`; poll until `ready`; show the user exact counts and exclusions; ask for explicit confirmation; only then send or schedule. Send requires `send_broadcast:`, schedule requires `schedule_broadcast:`, and cancel requires `cancel_broadcast:`. CSV files are uploaded through the dashboard or `wabery contacts import`, not through an MCP prompt. MCP can list and inspect completed imports. Preparation freezes recipients; duplicate copies only template configuration. --- # Security model Wabery tenant-scopes every API key, OAuth grant, project, channel, contact, and real-time subscription. Authentication and API scopes authorize each resource. - Hosted MCP grants and refresh tokens are bound to the canonical MCP resource. Refresh tokens rotate, and hosted MCP tokens cannot be used as REST API credentials. - High-risk MCP actions use person-controlled elicitation whenever the client advertises it, including local clients. Local clients without elicitation require explicit write mode and documented confirmation tokens; hosted clients without elicitation fail closed. - WebSocket subscriptions validate organization and conversation ownership and use organization-specific event channels. - A contact or imported number is not consent. Broadcasts require active category-specific consent, recheck suppressions immediately before dispatch, enforce frequency caps, and recognize mandatory opt-outs. - CSV requests, files, rows, columns, cells, mappings, and concurrent imports are bounded. Erasure removes broadcast personalization, flow dispatch/submission records, linked flow-event details, and connector invocation payloads. - Only the active hosted-function deployment can run. Requests, results, logs, subrequests, CPU, and wall-clock execution are bounded. For your production integration, keep `wab_live_` keys in a server-side secret manager, grant narrow scopes, verify `x-wabery-signature` over the raw webhook body, protect webhook/SIP/payment/function secrets, use encrypted connections and least-privilege credentials for services you connect, rotate exposed credentials, and avoid logging customer message bodies. Wabery platform security controls require no customer setup. Reference: https://wabery.com/docs/security --- # Errors & rate limits HTTP status codes, retries, and idempotency. The API uses conventional HTTP status codes and returns a JSON error body: ```json { "error": "contact_opt_in_required", "message": "An active WhatsApp opt-in record is required before sending to this contact." } ``` ## Status codes | Code | Meaning | | --- | --- | | `200` | Success. | | `400` | Invalid request (missing/!malformed fields). | | `401` | Missing or invalid API key. | | `403` | Key lacks the required [scope](https://wabery.com/docs/authentication#scopes). | | `404` | Resource not found. | | `409` | Conflict or current-state block (e.g. duplicate idempotency key, outside the messaging window, contact opt-in required, template not approved). | | `412` | Channel/project readiness failed (e.g. WhatsApp `publish_readiness` blockers such as `BUSINESS_NOT_VERIFIED` or `NO_PAYMENT_METHOD`). | | `422` | Valid shape but semantically invalid for the operation. | | `429` | Rate limited — back off and retry. | | `503` | A required safety dependency is unavailable. Honor `Retry-After` and retry with the same idempotency key. | | `5xx` | Transient server error — safe to retry. | ## WhatsApp template and conversation errors These codes tell you why Wabery refused a WhatsApp send or template change. Fix the cause before retrying; repeating the same request returns the same error. | Status | `error` | When it happens | | --- | --- | --- | | `400` | `invalid_request` | The request body failed validation, for example a template `coupon_code` parameter longer than Meta's 20-character maximum. `issues` lists each field. | | `409` | `template_not_approved` | The template isn't approved for this channel. A broadcast also stops with this `failure.code` when Meta pauses, disables, or recategorizes its template while it is sending. | | `409` | `whatsapp_utility_templates_restricted` | You tried to create a `UTILITY` template while Meta restricts utility templates on the WhatsApp Business Account. Sending existing templates still works. | | `409` | `ai_handoff_active` | Handoff is on for the conversation, so automated `POST /v1/messages` sends are paused until a teammate turns it off. | | `409` | `contact_in_human_handoff` / `thread_not_owned` | A Flow send was refused because handoff is on, or because another app, such as a Meta Business Agent, controls the conversation. | | `422` | `authentication_template_requires_phone_number` | An authentication template was addressed to a business-scoped user ID (BSUID). Meta only delivers them to a phone number. | | `422` | `unsupported_template_type` | A broadcast uses a template Wabery can't fill, such as a carousel or a template with coupon buttons. | | `422` | `whatsapp_group_template_type_unsupported` | A group send used an authentication template or a template with buttons. Groups accept text and media templates only. | | `502` | `thread_control_failed` with `reason: "thread_state_save_failed"` | Business Agent thread control only, where available: Meta applied the action, but Wabery couldn't save the new owner. Don't repeat the action. Read the thread state again before your next step. | ## Version skew & unavailable endpoints A `404` or `405` can mean one of two different things: - **The resource doesn't exist** — a genuine `404` from a real handler (e.g. an unknown flow id). These carry a JSON error body and a `Wabery-Version` response header. - **The endpoint isn't served by the connected instance** — the method/path isn't deployed (your SDK is newer than the API build). These come from the framework/proxy, so they have **no** `Wabery-Version` header. The SDK distinguishes the two for you: a `404`/`405` with no `Wabery-Version` header is raised as a `WaberyEndpointNotAvailableError` (a subclass of `WaberyApiError`) with a message that names the method and path and points at the likely capability gap — rather than a bare "request failed with HTTP 404". ```ts import { WaberyEndpointNotAvailableError } from "@wabery/sdk"; try { await wabery.flows.sendByConfigKey("lead_intake", { channelId, to }); } catch (err) { if (err instanceof WaberyEndpointNotAvailableError) { // This build doesn't serve POST /flows/send. The list endpoints carry the // same data, so fall back to them (e.g. flows.list() / projects.list()). } } ``` If you call the REST API directly, treat a `404`/`405` **without** a `Wabery-Version` response header as "endpoint not available on this instance" and fall back to the list endpoint (`GET /flows`, `GET /projects`) that exposes the same data. ## Retries & idempotency Retry `429` and `5xx` responses with exponential backoff. To make retries safe, send an `Idempotency-Key` header on writes — Wabery returns the original result for a repeated key instead of sending twice: **SDK:** ```ts await wabery.messages.send({ channelId: "channel_...", conversationId: "conversation_...", text: "Hi", idempotencyKey: "7c3f-order-2291", }); ``` **curl:** ```bash curl https://api.wabery.com/v1/messages \ -H "Authorization: Bearer $WABERY_API_KEY" \ -H "Idempotency-Key: 7c3f-order-2291" \ -H "Content-Type: application/json" \ -d '{ "channel_id": "channel_...", "conversation_id": "conversation_...", "text": "Hi" }' ``` ## Rate limits Two limits apply per API key: a **rate limit** (default 600 requests / 60 seconds) and a **monthly quota** (default 100,000 requests / calendar month). Both scale with your plan. Read the live values for your key from `GET /limits`: ```ts const limits = await wabery.limits.retrieve(); // { object: "public_api_limits", // rate_limit: { requests: 600, window_seconds: 60, scope: "api_key" }, // monthly_quota: { requests: 100000, scope: "api_key", period: "2026-06" } } ``` Exceeding either returns `429` with a JSON body and headers. `X-Wabery-Limit-Type` tells you which limit tripped (`rate_limit` vs `monthly_quota`): ```json { "error": "rate_limit", "message": "Public API rate limit exceeded", "limit": 600, "remaining": 0, "reset_at": "2026-06-20T14:22:00Z" } ``` | Header | Meaning | | --- | --- | | `RateLimit-Limit` | The ceiling for the window that tripped. | | `RateLimit-Remaining` | Requests left in the current window. | | `RateLimit-Reset` | Unix timestamp when the window resets. | | `Retry-After` | Seconds to wait before retrying — respect this. | | `X-Wabery-Limit-Type` | `rate_limit` or `monthly_quota`. | > Webhook deliveries are retried automatically with backoff on non-2xx responses, so a brief outage on your endpoint won't drop events. ## Pagination List endpoints (`contacts.list`, `conversations.list`, `conversations.listMessages`, `templates.list`, …) return a `WaberyList`: ```json { "object": "list", "data": [ /* … */ ], "has_more": true } ``` Page with `limit` and a `starting_after` cursor set to the last id you saw: ```ts let startingAfter: string | undefined; do { const page = await wabery.contacts.list({ limit: 100, startingAfter }); for (const contact of page.data) process(contact); startingAfter = page.has_more ? page.data.at(-1)?.id : undefined; } while (startingAfter); ``` Or let the SDK manage the cursor with the `listAll()` async iterator: ```ts for await (const contact of wabery.contacts.listAll()) process(contact); ``` ## WhatsApp Groups and commerce Groups require an eligible Official Business Account Cloud API number. Manage them through `wabery.groups` and send with opaque `groupId`/`group_id` values, never `to`. Group creation and group sends require caller-generated stable idempotency keys, reused for every retry. Supported group content is text, media, approved text/media templates (a text or media header, body, and footer, with no buttons), and pin/unpin. Other templates return `422 whatsapp_group_template_type_unsupported` before Wabery contacts Meta. Pin duration is `expirationDays` in the SDK and `expiration_days` in REST (1–30 days). Group commerce, interactive and authentication messages, calls, ephemeral/view-once, edit, and delete are unsupported. Individual WhatsApp recipients support `product`, `product_list` (up to 10 sections and 30 products total), and `catalog_message`; inbound order, referral, CTWA, referred-product, and identity attribution fields are preserved in history and webhooks. Creation may return `object: "api_operation", status: "processing"` with the stable `idempotency_key` and `reconciliation: "provider"` or `"local_persistence"`. It has no group ID: retry the same request with the same key and wait for `group.lifecycle`; never create a second group with a new key. Acceptance-unknown is separate: HTTP 409 with `whatsapp_group_create_acceptance_unknown` requires verification in WhatsApp Manager before using a new logical key. Management webhook `payload.occurred_at` can be null when Meta omits its timestamp, and aggregate `payload.data.errors` does not invalidate successful participant entries or settings fields; apply only individually failed entries/fields selectively. The SDK returns either this processing response or the pending group operation, and provides `groups.listAll()` plus `groups.listJoinRequestsAll()` async iterators for opaque cursor pagination. Management webhooks are `group.lifecycle`, `group.participants`, `group.settings`, and `group.status`; enable them explicitly and process the original provider item in `payload.data`, including partial-operation errors. Any client advertising MCP elicitation uses client-controlled confirmation, including local clients; local clients without elicitation use the `confirmation_token` fallback. --- # WhatsApp Calling Wabery connects Meta's WhatsApp Calling API to your own WebRTC or SIP voice application. Wabery handles Meta credentials, call settings, call-control requests, and signed `call.event` webhooks. It does not provide a browser softphone, PBX, media relay, microphone access, or live audio streaming. Before calling, use a dedicated eligible Meta Cloud number, enable calling on the individual phone number, configure the Wabery project webhook, and operate a WebRTC or SIP media application. Wabery configures provider event delivery during normal channel connection, so customers do not create a separate Meta webhook. The shared Wabery sandbox cannot host calling. SDK control methods: - `whatsappManagement.getCallingSettings(channelId, options)` - `whatsappManagement.updateCallingSettings(channelId, input)` - `whatsappManagement.getCallPermissions(channelId, userWaId)` - `whatsappManagement.manageCall(channelId, input)` Before a business-initiated call, send a `call_permission_request` interactive message and verify the permission. Then use `manageCall()` with `action: "connect"` and your SDP offer. For user-initiated calls, process the signed `call.event`, create an SDP answer, optionally send `pre_accept` with that answer, then send `accept` with the same answer. `reject` declines a call and `terminate` ends it. A `voice_call` interactive message is a button inviting the user to call; it does not start a business-initiated call. MCP uses `wabery_get_whatsapp_management` for `calling_settings` and `call_permissions`, `wabery_manage_whatsapp` for `update_calling_settings` and `manage_call`, and `wabery_send_message` for permission requests or call buttons. MCP carries signaling, not audio. Call-control writes require human approval. Wabery preserves Meta's original item in `call.event.payload.call`. `payload.kind` is `call` for Meta `calls[]` entries and `status` for Meta `statuses[]` entries. Verify the `x-wabery-signature`, keep call setup fast, and deduplicate retries using the call ID, event/status, and timestamp. Complete SDK, REST, MCP, permission, webhook, WebRTC/SIP, security, and troubleshooting guide: https://wabery.com/docs/whatsapp-calling/ --- # WhatsApp management The channel-scoped management API uses the connected channel's Meta credentials without returning its access token. It is available through `wabery.whatsappManagement`, REST at `/v1/channels/{id}/whatsapp-management`, and the MCP tools `wabery_get_whatsapp_management` and `wabery_manage_whatsapp`. Read operations: `business_profile`, `commerce_settings`, `qr_codes`, `qr_code`, `webhook_subscriptions`, `phone_number`, `phone_numbers`, `waba`, `owned_wabas`, `shared_wabas`, `assigned_users`, `analytics`, `credit_lines`, `credit_line_allocation`, `calling_settings`, `call_permissions`, and `blocked_users`. Write operations: `update_business_profile`, `update_commerce_settings`, `create_qr_code`, `update_qr_code`, `delete_qr_code`, `delete_media`, `register_phone`, `deregister_phone`, `request_verification_code`, `verify_code`, `set_two_step_verification`, `subscribe_webhooks`, `unsubscribe_webhooks`, `override_webhook_callback`, `assign_waba_user`, `unassign_waba_user`, `update_calling_settings`, `manage_call`, `block_users`, and `unblock_users`. List reads accept `limit` 1–100 plus opaque `after`/`before` cursors. Analytics accepts one `analytics`, `pricing_analytics`, `template_analytics`, `call_analytics`, or `group_analytics` expression. Meta retired `conversation_analytics` on November 1, 2026, so Wabery no longer accepts it; use `pricing_analytics` for message costs. Credit and allocation data is read-only. SIP credentials, verification PINs, and webhook verify tokens are secrets. Deregistration, unsubscribing webhooks, callback overrides, deletions, assignments, blocking, and call-control actions change Meta immediately. Complete SDK method, operation, parameter, consequence, REST, MCP, and error reference: https://wabery.com/docs/whatsapp-management/ Eligible regional payment messages are sent through `POST /messages`, not the management endpoint. India uses `order_details` with a `review_and_pay` action; Singapore uses its nested `order_details` object; `order_status` uses a `review_order` action. Wabery preserves Meta's country-specific payment fields. See https://wabery.com/docs/sending-messages/#regional-payment-messages. --- # Wabery API versioning and deprecation The canonical REST base URL is `https://api.wabery.com/v1`. Pin tested behavior with the `Wabery-Version` request header. The current dated version is `2026-06-18`, and every handled REST response echoes the effective version. Within `/v1`, additions remain backward compatible. A breaking behavior change requires a new dated version; a broader incompatible contract requires a new URL major such as `/v2`. Wabery gives at least 180 days' notice before retiring a public version unless an urgent security or legal requirement makes that unsafe or impossible. Affected responses use the RFC 9745 `Deprecation` header, the RFC 8594 `Sunset` header, and a `Link` with `rel="deprecation"` to migration guidance. The OpenAPI document also marks deprecated operations. No public REST version is currently scheduled for sunset. Read the canonical policy at https://wabery.com/docs/api-versioning/.