Visitar URL original
WhatsApp Business Cloud | Chat SDK

WhatsApp Business Cloud

Connect to WhatsApp Business Cloud for customer messaging and automated conversations.

Create a new bot

Scaffold a Next.js bot with the WhatsApp Business Cloud adapter using create-chat-sdk:

pnpm create chat-sdk@latest my-bot --adapter whatsapp memory -y

The generated app uses the Memory state adapter for local development. To add the adapter to an existing app, start at Install.

Install

pnpm add @chat-adapter/whatsapp @chat-adapter/state-memory

Quick start

The adapter auto-detects WHATSAPP_ACCESS_TOKEN, WHATSAPP_APP_SECRET, WHATSAPP_PHONE_NUMBER_ID, and WHATSAPP_VERIFY_TOKEN from the environment.

lib/bot.ts
import { Chat } from "chat";
import { createWhatsAppAdapter } from "@chat-adapter/whatsapp";
import { createMemoryState } from "@chat-adapter/state-memory";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    whatsapp: createWhatsAppAdapter(),
  },
  state: createMemoryState(),
});

bot.onNewMention(async (thread, message) => {
  await thread.post("Hello from WhatsApp!");
});

The memory state adapter keeps subscriptions and locks in process memory, which suits local development. Use Redis or PostgreSQL in production.

app/api/webhooks/whatsapp/route.ts
import { after } from "next/server";
import { bot } from "@/lib/bot";

export async function GET(request: Request) {
  return bot.webhooks.whatsapp(request);
}

export async function POST(request: Request) {
  return bot.webhooks.whatsapp(request, {
    waitUntil: (task) => after(() => task),
  });
}

Platform setup

Create a Meta app

  1. Go to developers.facebook.com/apps and create a Business app.
  2. Add the WhatsApp product to your app.

Get credentials

From your Meta app dashboard, copy:

  • App Secret (under App Settings then Basic) to WHATSAPP_APP_SECRET.
  • Access Token (under WhatsApp then API Setup) to WHATSAPP_ACCESS_TOKEN. The token shown there is temporary. For production, generate a permanent System User Token instead.
  • Phone Number ID (under WhatsApp then API Setup) to WHATSAPP_PHONE_NUMBER_ID.

Choose your own random string for WHATSAPP_VERIFY_TOKEN. You enter the same value in the next step.

Configure webhooks

Deploy the GET and POST route shown above to a public HTTPS URL first, then:

  1. Open WhatsApp then Configuration.
  2. Set the callback URL to https://your-domain.com/api/webhooks/whatsapp.
  3. Set Verify Token to the same value as WHATSAPP_VERIFY_TOKEN.
  4. Subscribe to the messages webhook field. Also subscribe to user_id_update so the adapter can follow user ID rotations.

Configuration

PropTypeDefaultDescription
accessToken?string
Meta access token. Auto-detected from `WHATSAPP_ACCESS_TOKEN`.
appSecret?string
App secret for webhook verification. Auto-detected from `WHATSAPP_APP_SECRET`.
phoneNumberId?string
Bot's phone number ID. Auto-detected from `WHATSAPP_PHONE_NUMBER_ID`.
verifyToken?string
Webhook verification secret. Auto-detected from `WHATSAPP_VERIFY_TOKEN`.
apiVersion?string"v25.0"
Graph API version.
userName?string"whatsapp-bot"
Bot username for self-message detection. Auto-detected from `WHATSAPP_BOT_USERNAME`.
apiUrl?string
Override the Meta Graph API base URL. Auto-detected from `WHATSAPP_API_URL`.

Environment variables

VariableRequiredDescription
WHATSAPP_ACCESS_TOKENYesMeta access token, ideally a System User Token in production
WHATSAPP_APP_SECRETYesApp secret used to verify webhook signatures
WHATSAPP_PHONE_NUMBER_IDYesDefault phone number ID. Thread replies use the number in the thread id
WHATSAPP_VERIFY_TOKENYesYour chosen secret for the webhook verification handshake
WHATSAPP_BOT_USERNAMENoBot username. Defaults to whatsapp-bot
WHATSAPP_API_URLNoMeta Graph API base URL override

Webhooks

The route handles two kinds of request from Meta:

  • GET verification handshake: Meta sends a hub.verify_token challenge that must match WHATSAPP_VERIFY_TOKEN.
  • POST event delivery: incoming messages, reactions, and interactive responses, signed with X-Hub-Signature-256 and verified against WHATSAPP_APP_SECRET.

Message formatting

Pass { markdown: text } to convert standard Markdown to WhatsApp formatting: **bold** becomes *bold*, _italic_ stays _italic_, and ~~strike~~ becomes ~strike~. Literal text such as (~80 % easy) is sent as written, and code content and intentional backslashes are preserved. WhatsApp has no escape syntax, so when escaped text like \_word\_ or a line starting with \> would otherwise turn into formatting, the adapter keeps the backslash and it shows in the message.

Interactive messages

The adapter converts card elements to WhatsApp interactive messages:

  • A card with buttons renders as WhatsApp reply buttons. Titles longer than 20 characters are truncated.
  • Only the first 3 buttons are sent. Extra buttons are dropped.
  • Body text is truncated to 1024 characters.
  • A card without buttons is sent as formatted text, unless it qualifies as a CTA URL message.

WhatsApp reply buttons cannot open URLs, so when a card with reply buttons also contains link buttons, each link button is appended to the interactive message body as a Label: url line.

A card whose only interactive element is a single LinkButton is sent as a native WhatsApp CTA URL message with a tappable link button. The card is promoted only when all of these hold:

  • The LinkButton is the card's only action across every actions row, including rows nested in sections. Reply buttons, selects, radio selects, or a second populated actions row keep the text fallback.
  • The URL starts with http:// or https:// and the label is non-empty. Other schemes (mailto:, tel:, relative paths) keep the text fallback because the Cloud API rejects them.
  • The card has no header imageUrl and no image, table, chart, or inline link children. The interactive body cannot carry those, so such cards keep the text fallback to avoid losing content. Text, fields, sections, and dividers are fine.
  • The post has no files or attachments. When media accompanies the card, the adapter keeps the single captioned media send.

The button label is truncated to 20 characters, the header (card title) to 60, and the body to 1024. Cards that do not match these rules fall back to formatted text, where link buttons render as Label: url.

Template messages

Outside the 24-hour customer service window, WhatsApp only accepts pre-approved template messages. Use sendTemplate to start business-initiated conversations:

const threadId = await adapter.openDM("15551234567");

await adapter.sendTemplate(threadId, {
  name: "appointment_reminder",
  language: "en",
  components: [
    {
      type: "body",
      parameters: [{ type: "text", text: "Tomorrow at 2pm" }],
    },
  ],
});

Templates must be created and approved in WhatsApp Manager before they can be sent. Quick reply button taps on a template arrive as button responses and are dispatched to your onAction handlers.

Contextual replies

Use thread.reply() to quote a specific message in WhatsApp:

bot.onDirectMessage(async (thread, message) => {
  await thread.reply(message, {
    markdown: "I can help with that.",
  });
});

You can pass either a Message or a message ID as the target. Text, cards, files, and buffered streams are supported. When one logical reply produces multiple WhatsApp messages, only the first message includes the contextual reference.

Replies are outbound only. When a user quote-replies to one of your messages, the adapter does not yet surface what they quoted, so message.replyTo is undefined on inbound WhatsApp messages.

WhatsApp does not display the quoted bubble when the target was deleted or moved to long-term storage, when the reply is a template message, or for some media replies on KaiOS. Reaction messages cannot be contextual replies. See Meta's contextual replies documentation.

File uploads

postMessage accepts both files and attachments (typed media with optional data, fetchData, or a public URL). See the file uploads guide for the shared API.

lib/bot.ts
await thread.post({
  markdown: "Here's the report:",
  files: [
    {
      data: reportBuffer,
      filename: "report.pdf",
      mimeType: "application/pdf",
    },
  ],
});

WhatsApp allows one media item per message, which shapes how the adapter sends files:

  • Multiple files or attachments in a single post() are sent as sequential messages, and the last message ID is returned.
  • Markdown, or card fallback text, is attached as a caption on the first media message when supported, up to 1024 characters. Text is sent as a separate message first when the caption is too long or when the first media is audio, because audio does not support captions.
  • Buffers are uploaded through the Cloud API /media endpoint. attachments with only a url use HTTPS link passthrough without an upload. URLs must use https://.
  • When a card renders as reply buttons, media is sent first without a caption, and the interactive message that follows carries the title, body, and buttons. When the card falls back to plain text, the fallback text captions the first media, and the caption includes a Label: url line for each link button. A card with only a link button is not promoted to a CTA URL message when media is attached, so it takes this captioned path too.
  • To send a photo with buttons, pass the image through files or attachments. Card-embedded images (imageUrl or <Image> children) are not sent as native media.

Inbound attachments

Incoming media attachments expose a lazy fetchData(). Media is downloaded only from Meta's fbcdn.net and fbsbx.com hosts or the configured Graph origin. Downloads refuse private and internal addresses, are limited to 25 MB, and time out after 30 seconds, and the access token never follows a redirect off those hosts. Pass a custom transport to downloadMedia() to route downloads through a proxy.

Typing indicators

WhatsApp supports typing indicators through thread.startTyping() or adapter.startTyping(threadId). Use it when the bot is about to respond and may take a few seconds:

bot.onDirectMessage(async (thread, message) => {
  await thread.startTyping();

  await thread.post({
    markdown: "Thanks, I am checking that now.",
  });
});

The adapter sends Meta's read-plus-typing payload for the most recent inbound message ID in the thread history, so the indicator only works after the bot has received a message. Without that inbound context, startTyping() does nothing. The indicator is dismissed when the bot sends its reply, or after the WhatsApp platform timeout.

Read receipts

Mark the current inbound message as read before starting work:

bot.onDirectMessage(async (thread) => {
  await thread.markAsRead();
  await thread.post("Thanks, I am checking that now.");
});

You can also pass an inbound Message or its ID to thread.markAsRead(). WhatsApp marks that message and earlier messages in the conversation as read. It does not allow outgoing message IDs to be marked as read and recommends acknowledging inbound messages within 30 days.

User identity

WhatsApp messages include a business-scoped user ID (BSUID) in from_user_id and contacts[].user_id. Users with a username may omit the phone-based from and wa_id fields.

The adapter accepts either identifier. When both are available, it preserves an existing phone-based thread ID and stores the BSUID as an alias. Replies include both to and recipient, with the phone number taking precedence according to Meta's API. BSUID-only threads send through recipient.

Meta does not support BSUID recipients for one-tap, zero-tap, or copy-code authentication templates. Those templates require the user's phone number.

Use a persistent state adapter in production so identity aliases survive restarts. The adapter preserves the canonical thread when Meta rotates a BSUID by consuming user_changed_number and user_changed_user_id system messages plus the user_id_update webhook, which carries the previous and current BSUID. Subscribe your Meta app to the user_id_update webhook field so rotations reach the adapter. Current phone, BSUID, parent BSUID, and username fields remain available through message.raw.

API errors

A non-2xx Graph API response throws WhatsAppApiError, exported from @chat-adapter/whatsapp. It extends AdapterError, so existing instanceof AdapterError checks continue to work.

import { WhatsAppApiError } from "@chat-adapter/whatsapp";

try {
  await thread.post("Hello");
} catch (error) {
  if (error instanceof WhatsAppApiError) {
    console.error(error.code, error.errorCode, error.details, error.status);
  }
  throw error;
}
  • code: the shared AdapterError code when the failure maps onto one: RATE_LIMITED (HTTP 429, or Meta throttling codes such as 130429 and 80007), AUTH_FAILED (HTTP 401, or Meta codes 0 and 190), PERMISSION_DENIED (HTTP 403, or Meta codes 3, 10, and 200 to 299), NOT_FOUND (HTTP 404). Otherwise undefined.
  • errorCode: Meta's numeric error code, such as 130429
  • providerMessage and type: Meta's error.message and error.type, when present
  • details: Meta's error_data.details, when present
  • status: HTTP response status
  • subcode and traceId: Meta's error_subcode and fbtrace_id, when present
  • raw: the full parsed response body (see the WhatsAppGraphErrorBody type), or the original text if it is not valid JSON

Meta recommends using error codes and details for error handling. Subcodes are optional and deprecated in the Cloud API. Missing or malformed provider fields stay undefined, and numeric codes that a proxy serializes as strings are accepted. The error message combines the operation, the HTTP status, and Meta's error.message, or a bounded excerpt of a non-JSON body.

This covers non-2xx responses from message sends, templates, reactions, read receipts, typing requests, media uploads, and media metadata requests. Transport failures and unparseable response bodies throw NetworkError, as do binary media download failures. A 2xx response that reports success: false for a typing request or read receipt throws a plain AdapterError. A successful API response can still be followed by an asynchronous delivery failure; those webhook errors are not thrown as WhatsAppApiError.

Thread IDs

whatsapp:{phoneNumberId}:{userWaId}

Example: whatsapp:1234567890:15551234567.

phoneNumberId is the bot's phone number ID. The final segment is the adapter's canonical user identifier. It may contain a phone number, a BSUID such as US.13491208655302741918, or a previously observed identifier retained for thread continuity.

Replies, reactions, read receipts, typing indicators, and media uploads for a thread go out from that phoneNumberId. openDM still uses the configured number, because that call has no inbound thread yet.

Limitations

  • Outgoing messages longer than 4096 characters are split into multiple messages automatically.
  • Outside the 24-hour customer service window, only approved template messages can be sent.

Feature support

Messaging

FeatureSupported
Post message
Message repliesOutbound only
Edit message
Delete message
File uploadsImages, audio, docs
StreamingBuffered
Scheduled messages

Rich content

FeatureSupported
Card formatInteractive messages
ButtonsInteractive replies
Link buttonsSingle CTA URL
Select menus
Tables
Charts
FieldsFormatted text
Images in cards
Modals

Conversations

FeatureSupported
Slash commands
Mentions
Add reactions
Remove reactions
Typing indicator
Mark as read
Message edit events
Message delete events
DMs
Ephemeral messages
User lookup
Parent subject
Native client
Custom API endpoint

Message history

FeatureSupported
Fetch messagesPersisted history
Fetch single message
Fetch thread info
Fetch channel messages
List threads
Fetch channel info
Post channel message

More adapters