# Sendable > Sendable is a WhatsApp API: link a WhatsApp number as a session, then send and read messages, manage groups, and receive events over HTTP. - API base URL: https://wav1-api.recrav.com - OpenAPI document (every route, field, and operationId): https://wav1-api.recrav.com/openapi/json - Agent quickstart: https://wav1.recrav.com/docs/agents.md - MCP server: https://wav1-api.recrav.com/mcp (streamable HTTP, x-api-key header) or `npx -y @sendable-dev/mcp` (stdio). Docs: https://wav1.recrav.com/docs/mcp.md - All docs in one file: https://wav1.recrav.com/llms-full.txt Basics: - Auth: send the API key in the `x-api-key` header. Most routes take a session key, which acts on one WhatsApp session. - Rate limits: responses carry `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`. On `429`, wait `Retry-After` seconds. - Idempotency: send an `Idempotency-Key` header with `POST /v1/message/send`; a retry with the same key and body never sends twice. - Errors: JSON errors look like `{ "error": "", "message": "..." }`; some are plain text. # Agent Quickstart > The short version of the Sendable API for AI agents and LLM tools. Source: https://wav1.recrav.com/docs/agents Everything an agent needs to send and read WhatsApp messages through Sendable. Machine-readable sources: * OpenAPI: `https://api.sendable.dev/openapi/json`. Every operation has a stable `operationId` (for example `sendMessage`, `listChatMessages`). * MCP server: `https://api.sendable.dev/mcp` (hosted, streamable HTTP) or `npx -y @sendable-dev/mcp` (stdio). See [MCP Server](/docs/mcp). * Docs index: [`/llms.txt`](/llms.txt). All docs in one file: [`/llms-full.txt`](/llms-full.txt). Any docs page as Markdown: add `.md` to its URL (this page is `/docs/agents.md`). ## 1. Get a key [#1-get-a-key] Create a **session API key** in the dashboard (Session > API Keys). It acts on one linked WhatsApp number. Send it on every request: ```http x-api-key: ``` `401` means the key is missing, invalid, disabled, or expired. Do not retry a `401`. Give agent keys only the [permissions](/docs/learn/api-keys#permissions) they need, for example the Send only set (`message:write`, `media:write`, `chats:read`, `contacts:read`); a missing permission returns `403` with `"error": "insufficient_scope"` and the `required` permission. ## 2. Send a message [#2-send-a-message] ```bash curl https://api.sendable.dev/v1/message/send \ -H "x-api-key: $SENDABLE_API_KEY" \ -H "content-type: application/json" \ -H "Idempotency-Key: order-123-notify" \ -d '{ "chatId": "6281234567890@s.whatsapp.net", "text": { "content": "Your order has shipped" } }' ``` * `chatId` is a full jid: `@s.whatsapp.net` for people, `@g.us` for groups. * The response has `messageId`. With `"async": true` the send is queued and the `202` response has a `runId` for `GET /v1/message/delivery-status/{runId}`. * Always send an `Idempotency-Key` (1-128 printable characters, unique per logical message). Retrying with the same key and body returns the first response with `Idempotent-Replayed: true` and never sends twice. The same key with a different body returns `422`; a retry while the first request still runs returns `409`. ## 3. Read messages [#3-read-messages] ```bash curl "https://api.sendable.dev/v1/chats?limit=20" -H "x-api-key: $SENDABLE_API_KEY" curl "https://api.sendable.dev/v1/chats/6281234567890%40s.whatsapp.net/messages?limit=20" \ -H "x-api-key: $SENDABLE_API_KEY" ``` Lists return `{ data, nextCursor }`; pass `nextCursor` back as `cursor`. URL-encode jids in paths. ## 4. Get new events [#4-get-new-events] * **Webhooks** (push): register a URL with `POST /webhooks` and verify signatures. See [Webhooks](/docs/webhooks). * **Polling** (pull): `GET /v1/events?type=message.created&limit=50` returns events newest first (incoming and outgoing messages). Poll the first page and stop at the last event `id` you processed. ## 5. Limits and errors [#5-limits-and-errors] * Each key may make 500 requests per hour. Responses carry `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset`. * On `429`, wait `Retry-After` seconds, then retry. Sends are also paced per number (a gap of a few seconds, optional daily cap and quiet hours). See [Rate Limits](/docs/rate-limits). * JSON errors look like `{ "error": "", "message": "..." }`; some errors are plain text. Retry `429`, `502`, `503`, and `5xx` with backoff; fix the request on other `4xx`. See [Errors](/docs/errors). ## SDK [#sdk] ```typescript import { Sendable } from '@sendable-dev/sdk' const sendable = new Sendable({ apiKey: process.env.SENDABLE_API_KEY!, apiKeyScope: 'session' }) await sendable.messages.send( { chatId: '6281234567890@s.whatsapp.net', text: { content: 'Hello' } }, { idempotencyKey: 'hello-1' }, ) ``` # API Keys > Authenticate requests to Sendable with session-scoped API keys. Source: https://wav1.recrav.com/docs/api-keys ## Creating an API Key [#creating-an-api-key] 1. Navigate to your [Dashboard](/dashboard) 2. Select the session you want to use 3. Go to the "API Keys" tab 4. Click "Generate New Key" 5. Copy the key immediately (it's only shown once) ## Using API Keys [#using-api-keys] Include your API key in the `x-api-key` header of every request: ```bash curl -X POST "https://api.sendable.dev/messages/send" \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"to":"6281234567890","text":"Hello"}' ``` ## Best Practices [#best-practices] ### Store Keys Securely [#store-keys-securely] Never commit API keys to version control. Use environment variables: ```bash ## .env SENDABLE_API_KEY=your_api_key_here ``` ```typescript // config.ts export const SENDABLE_API_KEY = process.env.SENDABLE_API_KEY if (!SENDABLE_API_KEY) { throw new Error('SENDABLE_API_KEY is required') } ``` ### Use Separate Keys for Different Environments [#use-separate-keys-for-different-environments] Create different keys for development, staging, and production: | Environment | Session | API Key | | ----------- | --------------- | -------------- | | Development | dev-session | sk_dev_xxx | | Staging | staging-session | sk_staging_xxx | | Production | prod-session | sk_prod_xxx | ### Rotate Keys Regularly [#rotate-keys-regularly] Rotate your API keys every 90 days: 1. Generate a new key 2. Update your application configuration 3. Revoke the old key 4. Monitor for any errors ### Revoke Compromised Keys [#revoke-compromised-keys] If you suspect a key has been compromised: 1. Revoke the key immediately in the dashboard 2. Generate a new key 3. Update your application 4. Review API logs for unauthorized usage ## Key Permissions [#key-permissions] API keys inherit permissions from their associated session: * Send messages * Receive webhooks * Access session status * Manage webhooks ## Error Handling [#error-handling] Invalid or expired keys return a `401 Unauthorized` error: ```json { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Invalid or expired API key" } } ``` See [Error Handling](/docs/errors) for more details. # API Reference > Complete API endpoint reference for Sendable WhatsApp API. Source: https://wav1.recrav.com/docs/api-reference All endpoints live under `https://api.sendable.dev` and authenticate with the `x-api-key` header. Most routes use a **session-scoped** API key and act on that key's WhatsApp session. The OpenAPI document at `/openapi/json` documents every request and response field. ## Conventions [#conventions] * **Ids**: personal chats use a PN jid (`6281234567890@s.whatsapp.net`) or a LID (`123456@lid`). Participant, recipient, and block lists on the group, community, account, status, and newsletter routes also accept a bare phone number (`6281234567890`); `POST /v1/message/send` needs a full jid. Groups and communities use `@g.us` (bare ids are accepted on group and community routes). Newsletters use `@newsletter`. URL-encode ids in paths. * **Pagination**: list routes return `{ data, nextCursor }`. Pass `nextCursor` back as `cursor`. `GET /v1/contacts` returns a plain array and the next cursor in the `x-next-cursor` header. * **Errors**: WhatsApp errors map to HTTP: `400` bad input, `403` not allowed (for example, not an admin), `404` not found, `409` conflict, `410` gone (expired invite), `502` WhatsApp failure, `503` socket not connected. * **Idempotency**: `POST /v1/message/send` (sync and async) accepts an `Idempotency-Key` header (alias `x-idempotency-key`), 1-128 printable ASCII characters. Keys are scoped to the WhatsApp session and kept for 24 hours. Retrying with the same key and the same body returns the first response again with `Idempotent-Replayed: true` instead of sending twice. The same key with a different body returns `422`; a retry while the first request is still running returns `409` with `Retry-After: 1`. `429` and `5xx` responses are not stored, so you can retry them with the same key. If the server crashes mid-send, the key becomes usable again after 2 minutes, which can cause one duplicate. * **Images by URL**: picture, cover photo, product image, and status media URLs must be public https URLs. Private, loopback, and link-local hosts are rejected. * **Received statuses** are stored only after the session opts in with `PUT /v1/status/settings` `{ "storeReceived": true }`. Until then they are dropped before storage, `GET /v1/status` stays empty, and no `status.received` event is produced. Statuses you post are always stored. ## Sessions [#sessions] Session lifecycle and the linked account. Routes without `:id` act on the session of a session-scoped API key. | Method | Path | Description | | -------- | ------------------------- | --------------------------------------- | | `GET` | `/v1/session` | List WhatsApp sessions | | `POST` | `/v1/session` | Create WhatsApp session | | `POST` | `/v1/session/start` | Start scoped WhatsApp session | | `POST` | `/v1/session/restart` | Restart scoped WhatsApp session | | `GET` | `/v1/session/uptime` | Get scoped WhatsApp session uptime | | `GET` | `/v1/session/status` | Get scoped WhatsApp session status | | `GET` | `/v1/session/profile` | Get scoped WhatsApp session own profile | | `POST` | `/v1/session/end` | End scoped WhatsApp session | | `POST` | `/v1/session/logout` | Logout scoped WhatsApp session | | `GET` | `/v1/session/:id/uptime` | Get WhatsApp session uptime | | `POST` | `/v1/session/:id/start` | Start WhatsApp session | | `POST` | `/v1/session/:id/restart` | Restart WhatsApp session | | `GET` | `/v1/session/:id/status` | Get WhatsApp session status | | `GET` | `/v1/session/:id/profile` | Get WhatsApp session own profile | | `POST` | `/v1/session/:id/end` | End WhatsApp session | | `POST` | `/v1/session/:id/logout` | Logout WhatsApp session | | `GET` | `/v1/session/:id` | Get WhatsApp session | | `PATCH` | `/v1/session/:id` | Update WhatsApp session | | `DELETE` | `/v1/session/:id` | Delete WhatsApp session | ## Messages [#messages] Send, edit, delete, star, read, and fetch messages. `POST /v1/message/send` accepts `text`, `image`, `video`, `audio`, `document`, `sticker`, `location`, `contacts`, `poll`, `event`, `album`, and more; see the OpenAPI schema for every field. | Method | Path | Description | | ------ | -------------------------------------- | ---------------------------------------- | | `GET` | `/v1/messages` | List messages | | `GET` | `/v1/message/:messageId` | Get message details | | `GET` | `/v1/message/:messageId/media` | Download message media | | `POST` | `/v1/message/:messageId/media/refresh` | Refresh expired message media | | `GET` | `/v1/message/:messageId/annotations` | List message annotations | | `POST` | `/v1/message/:messageId/annotations` | Create message annotation | | `POST` | `/v1/message/send` | Send message | | `POST` | `/v1/message/send-async` | Send message asynchronously (deprecated) | | `POST` | `/v1/message/edit` | Edit message | | `POST` | `/v1/message/delete` | Delete message for everyone | | `POST` | `/v1/message/read` | Mark messages as read | | `POST` | `/v1/message/star` | Star or unstar messages | | `POST` | `/v1/message/history` | Fetch older message history | | `POST` | `/v1/message/resend` | Request placeholder message resend | | `POST` | `/v1/media` | Upload outbound media | | `GET` | `/v1/message/delivery-status/:runId` | Get message delivery status | | `GET` | `/v1/chats.recent` | List recent chats | ## Chats [#chats] Chat list, details, notes, tags, and app-state actions (archive, pin, mute, clear, delete). Read state is sent with read receipts only. | Method | Path | Description | | -------- | ----------------------------------------------------- | --------------------------------- | | `GET` | `/v1/chats` | List chats | | `GET` | `/v1/chats/:chatId` | Get chat details | | `GET` | `/v1/chats/:chatId/messages` | List chat messages | | `GET` | `/v1/chats/:chatId/notes` | List chat notes | | `POST` | `/v1/chats/:chatId/notes` | Create chat note | | `GET` | `/v1/chats/:chatId/tags` | List chat tags | | `POST` | `/v1/chats/:chatId/tags` | Create chat tag | | `GET` | `/v1/chats/:chatId/state` | Get chat state | | `POST` | `/v1/chats/:chatId/archive` | Archive or unarchive chat | | `POST` | `/v1/chats/:chatId/pin` | Pin or unpin chat | | `POST` | `/v1/chats/:chatId/mute` | Mute or unmute chat | | `POST` | `/v1/chats/:chatId/clear` | Clear chat | | `DELETE` | `/v1/chats/:chatId` | Delete chat | | `POST` | `/v1/chats/:chatId/messages/:messageId/delete-for-me` | Delete message for me | | `POST` | `/v1/chats/:chatId/star` | Star or unstar chat messages | | `PUT` | `/v1/chats/:chatId/disappearing` | Set disappearing-message duration | ## Contacts [#contacts] | Method | Path | Description | | -------- | ------------------------------------ | ------------------------------------------- | | `GET` | `/v1/contacts` | List contacts | | `GET` | `/v1/contacts/:jid` | Get contact | | `DELETE` | `/v1/contacts/:jid` | Remove contact | | `GET` | `/v1/contacts/:jid/profile-picture` | Get profile picture URL | | `POST` | `/v1/contacts/status` | Fetch contact about/status text | | `POST` | `/v1/contacts/disappearing-duration` | Fetch default disappearing-message duration | | `POST` | `/v1/contacts/devices` | List linked devices | | `POST` | `/v1/contacts` | Create or update contact | | `POST` | `/v1/contacts/check` | Check if phone numbers exist on WhatsApp | ## Presence [#presence] | Method | Path | Description | | ------ | ------------------------ | ---------------------------------- | | `POST` | `/v1/presence` | Send presence update | | `POST` | `/v1/presence/subscribe` | Subscribe to chat presence updates | ## Groups [#groups] Stored groups (`GET`) plus write APIs that call the Baileys `group*` methods. | Method | Path | Description | | -------- | ----------------------------------- | ------------------------------------------------------------------ | | `GET` | `/v1/groups` | List WhatsApp groups | | `GET` | `/v1/groups/:id` | Get WhatsApp group details | | `GET` | `/v1/groups/:id/logs` | List WhatsApp group audit logs | | `POST` | `/v1/groups` | Create group | | `PUT` | `/v1/groups/:id/member-label` | Set my member label (max 30 chars) | | `POST` | `/v1/groups/invites/accept` | Join by invite code or link | | `POST` | `/v1/groups/invites/accept-v4` | Accept an invite message (`messageId`, or `inviterJid` + `invite`) | | `GET` | `/v1/groups/invites/:code` | Get invite info | | `POST` | `/v1/groups/:id/leave` | Leave | | `PUT` | `/v1/groups/:id/subject` | Update subject | | `PUT` | `/v1/groups/:id/description` | Update description (omit or empty clears) | | `PUT` | `/v1/groups/:id/settings` | `announce` / `locked` settings | | `PUT` | `/v1/groups/:id/ephemeral` | Disappearing-message timer (0, 24h, 7d, 90d) | | `PUT` | `/v1/groups/:id/member-add-mode` | `admin_add` or `all_member_add` | | `PUT` | `/v1/groups/:id/join-approval-mode` | Turn join approval on or off | | `PUT` | `/v1/groups/:id/picture` | Set picture (`url` or `base64`) | | `DELETE` | `/v1/groups/:id/picture` | Remove picture | | `POST` | `/v1/groups/:id/participants` | Add, remove, promote, or demote participants | | `GET` | `/v1/groups/:id/join-requests` | List pending join requests | | `POST` | `/v1/groups/:id/join-requests` | Approve or reject join requests | | `GET` | `/v1/groups/:id/invite-code` | Get invite code and link | | `POST` | `/v1/groups/:id/invite-code/revoke` | Revoke invite code | | `POST` | `/v1/groups/:id/invites/revoke-v4` | Revoke an invite message sent to `invitedJid` | ## Communities [#communities] Community-specific routes plus the same write routes as groups, calling the `community*` methods. Stored communities are listed with `GET /v1/groups?isCommunity=true`. | Method | Path | Description | | -------- | ---------------------------------------- | ------------------------------------------------------------------ | | `GET` | `/v1/v1/communities` | List communities (live) | | `POST` | `/v1/v1/communities` | Create community | | `GET` | `/v1/v1/communities/:id` | Get community metadata (live) | | `GET` | `/v1/v1/communities/:id/groups` | List linked groups | | `POST` | `/v1/v1/communities/:id/groups` | Create linked group | | `PUT` | `/v1/v1/communities/:id/groups/:groupId` | Link group to community | | `DELETE` | `/v1/v1/communities/:id/groups/:groupId` | Unlink group from community | | `POST` | `/v1/communities/invites/accept` | Join by invite code or link | | `POST` | `/v1/communities/invites/accept-v4` | Accept an invite message (`messageId`, or `inviterJid` + `invite`) | | `GET` | `/v1/communities/invites/:code` | Get invite info | | `POST` | `/v1/communities/:id/leave` | Leave | | `PUT` | `/v1/communities/:id/subject` | Update subject | | `PUT` | `/v1/communities/:id/description` | Update description (omit or empty clears) | | `PUT` | `/v1/communities/:id/settings` | `announce` / `locked` settings | | `PUT` | `/v1/communities/:id/ephemeral` | Disappearing-message timer (0, 24h, 7d, 90d) | | `PUT` | `/v1/communities/:id/member-add-mode` | `admin_add` or `all_member_add` | | `PUT` | `/v1/communities/:id/join-approval-mode` | Turn join approval on or off | | `PUT` | `/v1/communities/:id/picture` | Set picture (`url` or `base64`) | | `DELETE` | `/v1/communities/:id/picture` | Remove picture | | `POST` | `/v1/communities/:id/participants` | Add, remove, promote, or demote participants | | `GET` | `/v1/communities/:id/join-requests` | List pending join requests | | `POST` | `/v1/communities/:id/join-requests` | Approve or reject join requests | | `GET` | `/v1/communities/:id/invite-code` | Get invite code and link | | `POST` | `/v1/communities/:id/invite-code/revoke` | Revoke invite code | | `POST` | `/v1/communities/:id/invites/revoke-v4` | Revoke an invite message sent to `invitedJid` | ## Account [#account] Profile, privacy, blocklist, account caps, and app-state sync for the linked account. | Method | Path | Description | | -------- | ---------------------------------- | --------------------------------- | | `GET` | `/v1/account/profile` | Get my profile | | `PUT` | `/v1/account/profile/name` | Update my profile name | | `PUT` | `/v1/account/profile/status` | Update my about text | | `PUT` | `/v1/account/profile/picture` | Update my profile picture | | `DELETE` | `/v1/account/profile/picture` | Remove my profile picture | | `GET` | `/v1/account/privacy` | Get privacy settings | | `PUT` | `/v1/account/privacy` | Update privacy settings | | `PUT` | `/v1/account/default-disappearing` | Set default disappearing messages | | `GET` | `/v1/account/blocklist` | List blocked accounts | | `POST` | `/v1/account/blocklist` | Block an account | | `DELETE` | `/v1/account/blocklist/:jid` | Unblock an account | | `GET` | `/v1/account/reachout-timelock` | Get reachout timelock | | `GET` | `/v1/account/message-cap` | Get new-chat message cap | | `GET` | `/v1/account/settings` | Get stored account settings | | `GET` | `/v1/account/bots` | List Meta AI bots | | `POST` | `/v1/account/app-state/resync` | Resync app state | | `POST` | `/v1/account/dirty-bits/clean` | Clean dirty bits | ## Labels [#labels] WhatsApp Business labels, synced from `labels.edit` and `labels.association`. | Method | Path | Description | | -------- | ------------------------------------------------------- | ------------------------- | | `GET` | `/v1/labels` | List labels | | `POST` | `/v1/labels` | Create label | | `PUT` | `/v1/labels/:labelId` | Update label | | `DELETE` | `/v1/labels/:labelId` | Delete label | | `GET` | `/v1/labels/:labelId/associations` | List label associations | | `GET` | `/v1/chats/:chatId/labels` | List chat labels | | `PUT` | `/v1/chats/:chatId/labels/:labelId` | Add label to chat | | `DELETE` | `/v1/chats/:chatId/labels/:labelId` | Remove label from chat | | `PUT` | `/v1/chats/:chatId/messages/:messageId/labels/:labelId` | Add label to message | | `DELETE` | `/v1/chats/:chatId/messages/:messageId/labels/:labelId` | Remove label from message | ## Business [#business] WhatsApp Business profile, catalog, orders, and quick replies. Catalog prices are sent unchanged; WhatsApp expects the amount × 1000. | Method | Path | Description | | -------- | --------------------------------------- | -------------------------- | | `GET` | `/v1/business/profile` | Get business profile | | `PUT` | `/v1/business/profile` | Update business profile | | `PUT` | `/v1/business/cover-photo` | Set cover photo | | `DELETE` | `/v1/business/cover-photo/:id` | Remove cover photo | | `GET` | `/v1/business/catalog` | List catalog products | | `GET` | `/v1/business/collections` | List catalog collections | | `POST` | `/v1/business/products` | Create product | | `POST` | `/v1/business/products/delete` | Delete products | | `PUT` | `/v1/business/products/:productId` | Update product | | `DELETE` | `/v1/business/products/:productId` | Delete product | | `GET` | `/v1/business/orders/:orderId` | Get order details | | `PUT` | `/v1/business/quick-replies` | Create or edit quick reply | | `DELETE` | `/v1/business/quick-replies/:timestamp` | Remove quick reply | ## Status [#status] Post statuses (stories) and read statuses posted by contacts. | Method | Path | Description | | ------ | --------------------- | ---------------------- | | `POST` | `/v1/status` | Post a status | | `GET` | `/v1/status` | List received statuses | | `GET` | `/v1/status/settings` | Get status settings | | `PUT` | `/v1/status/settings` | Update status settings | ## Newsletters [#newsletters] WhatsApp Channels. Ids are `@newsletter`; bare ids are accepted. | Method | Path | Description | | -------- | ------------------------------------------------- | ----------------------------- | | `GET` | `/v1/newsletters` | List stored newsletters | | `POST` | `/v1/newsletters` | Create newsletter | | `GET` | `/v1/newsletters/invites/:code` | Get newsletter by invite code | | `GET` | `/v1/newsletters/:id` | Get newsletter metadata | | `PUT` | `/v1/newsletters/:id` | Update newsletter | | `DELETE` | `/v1/newsletters/:id` | Delete newsletter | | `PUT` | `/v1/newsletters/:id/name` | Rename newsletter | | `PUT` | `/v1/newsletters/:id/description` | Update newsletter description | | `PUT` | `/v1/newsletters/:id/picture` | Set newsletter picture | | `DELETE` | `/v1/newsletters/:id/picture` | Remove newsletter picture | | `POST` | `/v1/newsletters/:id/follow` | Follow newsletter | | `DELETE` | `/v1/newsletters/:id/follow` | Unfollow newsletter | | `POST` | `/v1/newsletters/:id/mute` | Mute newsletter | | `DELETE` | `/v1/newsletters/:id/mute` | Unmute newsletter | | `GET` | `/v1/newsletters/:id/subscribers` | Get subscriber count | | `GET` | `/v1/newsletters/:id/admin-count` | Get admin count | | `GET` | `/v1/newsletters/:id/messages` | Fetch newsletter posts | | `PUT` | `/v1/newsletters/:id/messages/:serverId/reaction` | React to a newsletter post | | `POST` | `/v1/newsletters/:id/subscribe-updates` | Subscribe to live updates | | `POST` | `/v1/newsletters/:id/owner` | Transfer ownership | | `POST` | `/v1/newsletters/:id/demote` | Demote admin | ## Calls [#calls] Call log built from the `call` event, call rejection, and call links. | Method | Path | Description | | ------ | -------------------------- | ---------------- | | `GET` | `/v1/calls` | List calls | | `POST` | `/v1/calls/links` | Create call link | | `GET` | `/v1/calls/:callId` | Get call | | `POST` | `/v1/calls/:callId/reject` | Reject call | ## Events [#events] Replayable feed of normalized events. See [Webhook Events](/docs/webhook-events#normalized-events) for every `type` and its `data`. | Method | Path | Description | | ------ | ------------ | ---------------------- | | `GET` | `/v1/events` | List normalized events | ## Webhooks [#webhooks] Webhook endpoints, delivery logs, and retries. These routes have no `/v1` prefix. | Method | Path | Description | | -------- | --------------------------------------------- | -------------------------- | | `GET` | `/webhooks/event-types` | List webhook event types | | `POST` | `/webhooks` | Create webhook | | `GET` | `/webhooks` | List webhooks | | `GET` | `/webhooks/:webhookId` | Get webhook details | | `PATCH` | `/webhooks/:webhookId` | Update webhook | | `DELETE` | `/webhooks/:webhookId` | Delete webhook | | `POST` | `/webhooks/:webhookId/rotate-secret` | Rotate webhook secret | | `GET` | `/webhooks/:webhookId/logs` | List webhook delivery logs | | `POST` | `/webhooks/:webhookId/logs/:deliveryId/retry` | Retry a webhook delivery | ## Examples [#examples] ### Send a Text Message [#send-a-text-message] ```bash curl -X POST "https://api.sendable.dev/v1/message/send" \ -H "x-api-key: YOUR_SESSION_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "chatId": "6281234567890@s.whatsapp.net", "text": { "content": "Hello from Sendable" } }' ``` ```json { "messageId": "3EB0C0A9F1D2...", "runId": null, "status": "PENDING" } ``` ### Add Group Participants [#add-group-participants] ```bash curl -X POST "https://api.sendable.dev/v1/groups/120363025000000000@g.us/participants" \ -H "x-api-key: YOUR_SESSION_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "participants": ["6281234567890"], "action": "add" }' ``` ```json { "groupId": "120363025000000000@g.us", "action": "add", "results": [ { "jid": "6281234567890@s.whatsapp.net", "status": "200" } ] } ``` When WhatsApp refuses a direct add (`status: "403"`), the result includes `addRequest: { code, expiration }` so you can send an invite instead. ### List Group Or Community Audit Logs [#list-group-or-community-audit-logs] Group and community audit logs include participant changes, setting changes, join requests (`group.join-request`), and member tag changes (`group.member-tag.update`). ```bash curl -X GET "https://api.sendable.dev/v1/groups/120363025000000000@g.us/logs?limit=25&eventKey=group-participants.update" \ -H "x-api-key: YOUR_SESSION_API_KEY" ``` ```json { "data": [ { "id": "log_123", "groupId": "120363025000000000@g.us", "eventKey": "group-participants.update", "action": "add", "authorId": "6281234567890@s.whatsapp.net", "authorJid": "6281234567890@s.whatsapp.net", "authorLid": null, "participants": [ { "id": "6289876543210@s.whatsapp.net", "jid": "6289876543210@s.whatsapp.net", "phoneNumber": "6289876543210" } ], "leftAtBefore": null, "leftAtAfter": null, "payload": {}, "createdAt": "2026-03-14T08:10:00.000Z" } ], "nextCursor": null } ``` ### Create a Webhook [#create-a-webhook] ```bash curl -X POST "https://api.sendable.dev/webhooks" \ -H "x-api-key: YOUR_SESSION_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "event_name": "main", "https_url": "https://your-app.com/webhook", "event_types": ["message.received", "message.delivered", "group.join-request"], "max_retries": 3, "retry_interval_second": 60 }' ``` The response includes `webhook_secret` (`whsec_...`). Use it to verify the `webhook-signature` header. Rotate it with `POST /webhooks/:webhookId/rotate-secret`. ### Retry a Failed Delivery [#retry-a-failed-delivery] ```bash curl -X GET "https://api.sendable.dev/webhooks/WEBHOOK_ID/logs?limit=10" \ -H "x-api-key: YOUR_SESSION_API_KEY" curl -X POST "https://api.sendable.dev/webhooks/WEBHOOK_ID/logs/DELIVERY_ID/retry" \ -H "x-api-key: YOUR_SESSION_API_KEY" ``` `DELIVERY_ID` is `delivery_id` from the logs. The retry keeps the same `webhook-id` header so your endpoint can deduplicate it. # Error Handling > HTTP status codes, error bodies, and which Sendable API errors to retry. Source: https://wav1.recrav.com/docs/errors ## HTTP Status Codes [#http-status-codes] | Code | Meaning | Retry? | | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | | `400` | Invalid request: body validation failed, bad cursor, bad phone number or jid | No, fix the request | | `401` | Missing, invalid, disabled, or expired API key | No | | `403` | The key may not call this route: missing permission (`insufficient_scope`), or a session key on an account route. Also when WhatsApp refuses (not a group admin) | No | | `404` | Session, chat, message, group, or webhook not found | No | | `409` | Conflict, for example an `Idempotency-Key` whose first request is still running | Yes, after `Retry-After` | | `410` | Gone, for example an expired invite | No | | `422` | `Idempotency-Key` reused with a different request body | No, use a new key | | `429` | Rate limited (per API key or by the session send policy) | Yes, after `Retry-After` | | `500` | Unexpected server error | Yes, with backoff | | `502` | WhatsApp returned an error | Yes, with backoff | | `503` | WhatsApp session not connected, or the send queue is unavailable | Yes, with backoff | ## Error Bodies [#error-bodies] JSON errors have an `error` field with a stable code and, usually, a `message`: ```json { "error": "rate_limited", "message": "api key rate limit exceeded", "retryAfter": 1260 } ``` | `error` | Status | Meaning | | ----------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------- | | `Validation failed` | `400` | The body or query failed validation. `issues` lists each field: `[{ "path": "/chatId", "message": "Expected string" }]` | | `insufficient_scope` | `403` | The API key's [permissions](/docs/learn/api-keys#permissions) do not include `required` (for example `message:write`) | | `rate_limited` | `429` | The API key used up its request limit. `retryAfter` is in seconds | | `idempotency_key_in_progress` | `409` | The first request with this `Idempotency-Key` is still running | | `idempotency_key_mismatch` | `422` | The `Idempotency-Key` was used before with a different body | | `internal_error` | `500` | Unexpected server error | Other errors are returned as a plain-text message (`Content-Type: text/plain`), for example `401 invalid api key`, `404 chat not found`, or `503 whatsapp socket not connected`. Read the body as text when it is not JSON. The [OpenAPI document](/docs/api-reference) describes these as the shared `ErrorResponse` schema. ## Retry Strategy [#retry-strategy] * Honour `Retry-After` (seconds) on `409` and `429`. * Retry `500`, `502`, and `503` with exponential backoff and jitter. * Send an `Idempotency-Key` with `POST /v1/message/send` so a retry never sends the same message twice. * The [SDK](/docs/quickstart/nodejs/sdk) retries `429`, `503`, and network errors for you when you set `maxRetries`. ```typescript async function sendWithRetry(body: unknown, idempotencyKey: string, maxRetries = 3) { for (let attempt = 0; ; attempt++) { const res = await fetch('https://api.sendable.dev/v1/message/send', { method: 'POST', headers: { 'x-api-key': process.env.SENDABLE_API_KEY!, 'content-type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify(body), }) const retryable = [409, 429, 500, 502, 503].includes(res.status) if (!retryable || attempt >= maxRetries) return res const retryAfter = Number(res.headers.get('retry-after')) const delayMs = retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 1000 await new Promise((r) => setTimeout(r, delayMs + Math.random() * 250)) } } ``` # Introduction > Complete documentation for Sendable WhatsApp API. Source: https://wav1.recrav.com/docs ## Quick Start [#quick-start] Get up and running quickly with your preferred framework: ## Learn [#learn] Master Sendable features and dashboard: ## Explore [#explore] API references and advanced topics: ## Support [#support] Need help? Contact us at [support@sendable.dev](mailto:support@sendable.dev) # Analytics > Track messaging performance and usage statistics. Source: https://wav1.recrav.com/docs/learn/analytics ## Dashboard Overview [#dashboard-overview] The analytics section provides insights into: * Message volume * Delivery rates * Response times * Session health ## Key Metrics [#key-metrics] ### Message Volume [#message-volume] Track messages over time: * Total messages sent * Total messages received * Messages by type (text, media) * Hourly/daily/weekly trends ### Delivery Rates [#delivery-rates] Monitor message delivery success: | Metric | Description | Good Range | | ------------- | ----------------------- | ---------- | | Delivery Rate | % of messages delivered | > 95% | | Read Rate | % of messages read | > 70% | | Failure Rate | % of failed messages | \< 5% | ### Response Time [#response-time] Track API performance: * Average response time * 95th percentile latency * Error rate ## Viewing Analytics [#viewing-analytics] ### Session Analytics [#session-analytics] Per-session statistics: 1. Select a session 2. Go to "Analytics" tab 3. View charts and metrics Time ranges: * Last 24 hours * Last 7 days * Last 30 days * Custom range ### Account Analytics [#account-analytics] Aggregate across all sessions: 1. Go to main dashboard 2. View account-level metrics 3. Compare session performance ## Metrics Explained [#metrics-explained] ### Messages Sent [#messages-sent] Total outgoing messages from your session. **High volume + low delivery rate?** * Check session health * Verify phone numbers * Review error logs ### Messages Received [#messages-received] Total incoming messages to your session. **No incoming messages?** * Verify webhook is configured * Check webhook delivery logs * Ensure session is connected ### Delivery Rate [#delivery-rate] Percentage of messages successfully delivered. ``` Delivery Rate = (Delivered / Sent) × 100 ``` **Low delivery rate causes:** * Invalid phone numbers * Recipient blocked you * Session disconnected * Rate limiting ### Read Rate [#read-rate] Percentage of delivered messages that were read. ``` Read Rate = (Read / Delivered) × 100 ``` **Improving read rates:** * Send at optimal times * Use engaging message content * Personalize messages ### API Usage [#api-usage] Track your API consumption: * Requests per minute * Rate limit status * Error breakdown ## Exporting Data [#exporting-data] Download analytics reports: 1. Select date range 2. Choose metrics 3. Click "Export CSV" 4. Download report ## Use Cases [#use-cases] ### Monitoring Campaign Performance [#monitoring-campaign-performance] Track marketing message effectiveness: ``` Campaign: Summer Sale - Messages Sent: 10,000 - Delivered: 9,800 (98%) - Read: 7,200 (73%) - Clicked: 1,500 (21% of read) ``` ### Identifying Issues [#identifying-issues] Spot problems early: ``` Alert: Delivery rate dropped to 85% Investigation: - Session status: Connected ✓ - Error logs: Many 404 errors - Cause: Invalid phone number format - Fix: Updated number validation ``` ### Capacity Planning [#capacity-planning] Predict when to upgrade: ``` Current: Starter Plan (1,000 msg/hour) Usage: 850 msg/hour average Growth: 20% monthly Recommendation: Upgrade to Pro in 2 months ``` ### Reporting to Stakeholders [#reporting-to-stakeholders] Generate executive reports: ``` Monthly WhatsApp Metrics: ├── Messages Sent: 45,000 (↑ 15%) ├── Delivery Rate: 97.5% (↑ 2%) ├── Avg Response Time: 120ms └── Customer Satisfaction: 4.5/5 ``` ## Alerts [#alerts] Set up notifications for: * Delivery rate drops below threshold * Session disconnects * Rate limit approaching * Unusual traffic patterns Configure in Settings → Alerts ## Best Practices [#best-practices] ### Regular Monitoring [#regular-monitoring] Check analytics weekly: * Spot trends early * Identify issues * Optimize performance ### Benchmarking [#benchmarking] Set baseline metrics: * Record normal performance * Detect anomalies * Measure improvements ### Action on Data [#action-on-data] Don't just collect data - act on it: * Low delivery? Fix phone numbers * Low read rate? Improve content * High errors? Check integration # API Keys > Manage API keys for secure Sendable integration. Source: https://wav1.recrav.com/docs/learn/api-keys ## API Key Basics [#api-key-basics] Each API key: * Is unique to a session * Has full access to that session, unless you give it [permissions](#permissions) * Can be revoked at any time * Is only shown once at creation ## Permissions [#permissions] A key can be limited to the parts of the API it needs. Permissions are a list of `resource:action` pairs. Keys created without permissions keep full access. In the dashboard, pick **Permissions** when you create or edit a key (session keys under Session > API Keys, account keys under Settings > API Keys): Full access, Read only, Send only, Webhook manager, or Custom to choose actions per resource. The key list shows each key's permissions; hover a badge to see the exact scopes. | Action | Covers | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `read` | `GET` routes, and `POST` routes that only look data up (`/v1/contacts/check`, `/v1/contacts/status`, `/v1/contacts/devices`, `/v1/contacts/disappearing-duration`, `/v1/message/history`, `/v1/presence/subscribe`, `/v1/newsletters/:id/subscribe-updates`) | | `write` | Other `POST`, `PUT`, `PATCH`, and `DELETE` routes | | `admin` | Destructive or account-wide changes: session create, restart, end, logout, and delete; chat delete and clear; group and community participant changes; profile, privacy, default disappearing timer, and blocklist changes; newsletter delete, owner transfer, and admin demote; webhook create, update, delete, and secret rotation | Actions do not include each other: a key with `message:write` can send but cannot list messages unless it also has `message:read`. | Resource | Routes | | ------------- | ------------------------------------------------------------ | | `session` | `/v1/session/*` | | `message` | `/v1/message/*`, `/v1/messages` | | `media` | `/v1/media`, `/v1/message/:messageId/media*` | | `chats` | `/v1/chats/*` (except labels), `/v1/chats.recent` | | `contacts` | `/v1/contacts/*` | | `groups` | `/v1/groups/*` | | `communities` | `/v1/communities/*` | | `account` | `/v1/account/*` | | `labels` | `/v1/labels/*`, `/v1/chats/:chatId/labels/*`, message labels | | `business` | `/v1/business/*` | | `status` | `/v1/status/*` | | `newsletters` | `/v1/newsletters/*` | | `calls` | `/v1/calls/*` | | `webhooks` | `/webhooks/*` | | `events` | `/v1/events` | | `presence` | `/v1/presence/*` | Common sets: * **Read only**: `read` on every resource. * **Send only**: `message:write`, `media:write`, `chats:read`, `contacts:read`. Good for bots and AI agents that only send. * **Webhook manager**: `webhooks:read`, `webhooks:write`, `webhooks:admin`, `events:read`. A request the key is not allowed to make gets `403` with the missing permission: ```json { "error": "insufficient_scope", "message": "api key is missing the chats:read permission", "required": "chats:read" } ``` ## Creating an API Key [#creating-an-api-key] ### Step-by-Step [#step-by-step] 1. Select a session from dashboard 2. Go to "API Keys" tab 3. Click "Generate New Key" 4. Choose [permissions](#permissions) (Full access by default) 5. Copy the key immediately 6. Store it securely ⚠️ **Important**: The key is only shown once. If you lose it, you must create a new one. ## API Key Management [#api-key-management] ### View All Keys [#view-all-keys] In the API Keys tab, see: * Key ID (first 8 characters) * Created date * Last used * Status (Active/Revoked) ### Revoke a Key [#revoke-a-key] If a key is compromised: 1. Find the key in the list 2. Click "Revoke" 3. Confirm revocation 4. The key is immediately disabled ### Key Usage Statistics [#key-usage-statistics] Monitor key usage: * Requests per day * Success rate * Error rate * Last used timestamp ## Security Best Practices [#security-best-practices] ### Store Keys Safely [#store-keys-safely] ❌ **Never do this:** ```javascript // BAD: Hardcoded key const apiKey = 'sk_live_abc123' ``` ✅ **Do this instead:** ```javascript // GOOD: Environment variable const apiKey = process.env.SENDABLE_API_KEY ``` ### Use .env Files [#use-env-files] Create `.env`: ```bash SENDABLE_API_KEY=sk_live_abc123 ``` Add to `.gitignore`: ``` .env .env.local .env.production ``` ### Rotate Keys Regularly [#rotate-keys-regularly] Set a rotation schedule: * Development: Monthly * Production: Quarterly Rotation process: 1. Generate new key 2. Update application config 3. Test with new key 4. Revoke old key 5. Monitor for errors ### Separate Environments [#separate-environments] Use different keys for different environments: | Environment | Key Prefix | Session | | ----------- | ------------- | ------------------ | | Development | `sk_dev_` | Dev Session | | Staging | `sk_staging_` | Staging Session | | Production | `sk_live_` | Production Session | ## Use Cases [#use-cases] ### Single Application [#single-application] One app, one session, one key: ``` App → API Key → Sendable Session ``` ### Multi-Tenant Application [#multi-tenant-application] Different keys for different customers: ``` Customer A → API Key A → Session A Customer B → API Key B → Session B ``` ### Microservices [#microservices] Each service gets its own key: ``` Notification Service → Key 1 Chat Service → Key 2 Marketing Service → Key 3 ``` ## Troubleshooting [#troubleshooting] ### "Invalid API Key" Error [#invalid-api-key-error] 1. Check key is copied correctly (no extra spaces) 2. Verify key hasn't been revoked 3. Confirm key belongs to correct session 4. Ensure `x-api-key` header is used ### Rate Limit Errors [#rate-limit-errors] If you see `429 Too Many Requests`: 1. Check your current usage in dashboard 2. Implement retry with backoff 3. Consider upgrading your plan ### Key Not Working [#key-not-working] 1. Verify session is connected 2. Check session health status 3. Try regenerating the key 4. Contact support if persists ## API Key Limits [#api-key-limits] | Plan | Keys per Session | Rate Limit | | ---------- | ---------------- | ---------- | | Free | 3 | 60/min | | Starter | 10 | 300/min | | Pro | Unlimited | 1000/min | | Enterprise | Unlimited | Custom | ## Monitoring [#monitoring] Track API key usage in dashboard: * Total requests * Failed requests * Average response time * Error breakdown Set up alerts for: * Unusual traffic spikes * High error rates * Key nearing rate limits # Messaging > Send and receive WhatsApp messages with Sendable. Source: https://wav1.recrav.com/docs/learn/messaging ## Message Types [#message-types] Sendable supports various message types for different use cases. ### Text Messages [#text-messages] Simple text messages for notifications and conversations: ```json { "to": "6281234567890", "text": "Hello! Your order #12345 has been shipped." } ``` ### Group Mentions [#group-mentions] To send a real WhatsApp mention in a group, include the visible `@number` in `text.content` and the full WhatsApp JID in `mentions`: ```json { "chatId": "120363427458591243@g.us", "text": { "content": "asd @6285176702468" }, "mentions": ["6285176702468@s.whatsapp.net"] } ``` ### Media Messages [#media-messages] Send images, videos, documents: ```json { "to": "6281234567890", "mediaUrl": "https://example.com/invoice.pdf", "mediaType": "document", "caption": "Your invoice for order #12345" } ``` Supported media types: * `image` - JPG, PNG * `video` - MP4 * `audio` - MP3, OGG * `document` - PDF, DOC, etc. ## Sending Messages [#sending-messages] ### Dashboard [#dashboard] Send quick messages directly from the dashboard: 1. Go to your session 2. Click "Send Message" 3. Enter phone number 4. Type message or attach media 5. Send ### API [#api] Send programmatically via API: ```bash curl -X POST "https://api.sendable.dev/messages/send" \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "to": "6281234567890", "text": "Hello from API!" }' ``` ## Message Status [#message-status] Track message delivery status: | Status | Meaning | | ----------- | ------------------------------ | | `pending` | Queued for sending | | `sent` | Sent to WhatsApp servers | | `delivered` | Delivered to recipient's phone | | `read` | Recipient opened the message | | `failed` | Could not be delivered | ### Check Status via API [#check-status-via-api] ```bash curl "https://api.sendable.dev/messages/{messageId}/status" \ -H "x-api-key: YOUR_API_KEY" ``` ### Real-time Updates [#real-time-updates] Use webhooks to get instant status updates: * `message.delivered` - Message arrived * `message.read` - Message seen * `message.failed` - Delivery failed ## Receiving Messages [#receiving-messages] ### Webhook Setup [#webhook-setup] Configure webhook to receive incoming messages: 1. Go to session → Webhooks 2. Subscribe to `message.received` event 3. Your endpoint receives: ```json { "event": "message.received", "data": { "messageId": "msg_incoming_456", "from": "6281234567890", "type": "text", "text": "Hi, I have a question about my order", "timestamp": "2026-03-02T10:30:00Z" } } ``` ### Auto-Reply [#auto-reply] Example: Automatic response to incoming messages: ```javascript app.post('/webhook', (req, res) => { const { event, data } = req.body if (event === 'message.received') { // Send auto-reply sendMessage(data.from, "Thanks for your message! We'll respond shortly.") } res.sendStatus(200) }) ``` ## Use Cases [#use-cases] ### Customer Support [#customer-support] Two-way conversation handling: ```javascript // Store incoming messages if (event === 'message.received') { await createTicket({ customer: data.from, message: data.text, timestamp: data.timestamp }) } // Notify agents await notifySupportTeam(newTicket) ``` ### Order Notifications [#order-notifications] Automated order updates: ```javascript // Order confirmation await sendMessage(customerPhone, `Order #${orderId} confirmed! Total: $${amount}`) // Shipping notification await sendMessage(customerPhone, `Order #${orderId} shipped! Track: ${trackingUrl}`) // Delivery confirmation await sendMessage(customerPhone, `Order #${orderId} delivered! Enjoy your purchase.`) ``` ### Appointment Reminders [#appointment-reminders] Reduce no-shows with reminders: ```javascript // 24 hours before await sendMessage(patientPhone, `Reminder: Appointment with Dr. Smith tomorrow at ${time}`) // 1 hour before await sendMessage(patientPhone, `Your appointment starts in 1 hour. See you soon!`) ``` ### OTP Verification [#otp-verification] Secure authentication codes: ```javascript // Generate and send OTP const otp = generateOTP() await sendMessage(userPhone, `Your verification code is: ${otp}. Valid for 5 minutes.`) ``` ## Message Templates [#message-templates] Create reusable message formats: ```javascript const templates = { welcome: (name) => `Hi ${name}! Welcome to our service.`, orderShipped: (orderId, tracking) => `Order #${orderId} shipped! Track: ${tracking}`, appointmentReminder: (doctor, time) => `Reminder: Appointment with ${doctor} at ${time}` } // Usage await sendMessage(phone, templates.welcome('John')) ``` ## Best Practices [#best-practices] ### Phone Number Format [#phone-number-format] Always use international format: * ✅ `6281234567890` (Indonesia) * ❌ `081234567890` (missing country code) * ❌ `+6281234567890` (remove the +) ### Message Length [#message-length] * Keep messages concise * WhatsApp has no strict limit, but split long messages * Use formatting (bold, italic) for emphasis ### Timing [#timing] * Business hours for promotional messages * Immediate for OTPs and alerts * Consider timezone of recipient ### Personalization [#personalization] Include customer details: ``` Hi {name}, your order #{orderId} is ready! ``` ### Error Handling [#error-handling] Always handle delivery failures: ```javascript try { const result = await sendMessage(phone, text) if (!result.success) { // Log failure await logFailedMessage(phone, text, result.error) // Retry or notify if (isRetryable(result.error)) { await retryLater(phone, text) } } } catch (error) { await notifyAdmin(error) } ``` ## Rate Limits [#rate-limits] Be aware of sending limits: | Plan | Messages/Hour | Notes | | ---------- | ------------- | ---------------- | | Free | 100 | Best for testing | | Starter | 1,000 | Small businesses | | Pro | 10,000 | High volume | | Enterprise | Custom | Unlimited | Monitor your usage in the dashboard. # Cities > Select a city before creating a session to configure the residential proxy location. Source: https://wav1.recrav.com/docs/learn/sessions/cities ## City selection [#city-selection] **City must be selected before creating a session.** This determines the residential proxy configuration and IP location used for the WhatsApp connection. > **Important:** City selection is permanent. Once a session is created, the city cannot be changed. To use a different city, create a new session. ### Available cities [#available-cities] Sendable supports **164 cities worldwide** across 6 continents for proxy configuration. This includes major cities in: * **Asia**: Jakarta, Bangkok, Singapore, Tokyo, Mumbai, Manila * **Europe**: London, Berlin, Amsterdam, Paris, Madrid, Rome * **Americas**: New York, Los Angeles, São Paulo, Mexico City, Toronto * **Africa**: Lagos, Johannesburg, Cairo, Nairobi * **Oceania**: Sydney, Melbourne, Auckland The full list of supported cities is available in your dashboard when creating a session. ### Why city matters [#why-city-matters] The selected city determines: * **Residential IP location** - The session connects through a proxy in the chosen city * **Connection consistency** - Traffic patterns align with the geographic region * **Trust signals** - Using region-appropriate IPs can reduce filtering risk ### How it works [#how-it-works] When you create a session: 1. You select a city from the dropdown (100+ options available) 2. Sendable automatically provisions a residential proxy for that city 3. The WhatsApp connection routes through the city-specific proxy 4. All traffic from that session uses the city's IP location ### Monitoring by city [#monitoring-by-city] Track these metrics for each city session: * Connection stability * Message delivery rate * Session disconnect frequency If a specific city shows persistent issues, consider creating a new session in that city or using an alternative city. # Introduction > Learn the core concepts for managing WhatsApp sessions in Sendable. Source: https://wav1.recrav.com/docs/learn/sessions ## Documentation Index [#documentation-index] > Browse the full docs navigation at `/docs` before diving into session-specific workflows. > Use it to quickly jump between setup, API keys, webhooks, and troubleshooting. ## Managing Sessions [#managing-sessions] > View and control all connected WhatsApp sessions from the Sendable Dashboard. > **Warning:** If a session fails to connect, review troubleshooting guidance at `/docs/troubleshooting`. ### Creating a session [#creating-a-session] A session is a single connected WhatsApp account in Sendable. Each session has: * Its own phone number and connection state * Its own API keys * Independent message history and webhook activity * A designated city for proxy configuration #### Select a city first [#select-a-city-first] **Before creating a session, you must select a city.** This determines the residential proxy configuration used for the connection. Sendable supports **164 cities worldwide** across all continents. When creating a session, you'll choose from cities including: * **Medan, Bandung, Surabaya** (Indonesia) * **Bangkok** (Thailand) * **Singapore** * **Mumbai, New Delhi** (India) * **London** (UK) * **New York, Los Angeles** (USA) * **São Paulo** (Brazil) * **Lagos** (Nigeria) And many more. See the [Cities](/docs/learn/sessions/cities) page for full details. > **Important:** City selection is permanent. Once a session is created, the city cannot be changed. To use a different city, create a new session. #### Create the session [#create-the-session] 1. Open [Dashboard](/dashboard) 2. Click **New Session** 3. **Select a city** from the dropdown (164 cities available) 4. Name the session (for example: `Support-Jakarta-Prod`) 5. Scan the QR code from WhatsApp Linked Devices 6. Wait for status to become **Connected** ### Session states [#session-states] | State | Description | Action | | -------------- | ------------------------- | --------------------------------- | | `connecting` | Setup in progress | Wait for QR scan | | `connected` | Ready for message traffic | No action needed | | `disconnected` | Connection lost | Reconnect and check phone network | | `expired` | QR code timed out | Generate a new QR code | ### Managing session details [#managing-session-details] From each session detail page you can: * Rename the session * Generate or revoke API keys * Configure webhook endpoints * Monitor health and recent activity * Stop or delete the session ### Regional setup [#regional-setup] For location-based operations, create dedicated sessions per city and route traffic accordingly. See the city strategy guide at [Cities](/docs/learn/sessions/cities). ### Best practices [#best-practices] 1. Select city before creating the session (this is required) 2. Use clear names by use case and location 3. Keep the source phone online and stable 4. Separate development and production sessions 5. Monitor connection health daily # Settings > Configure your Sendable account and session settings. Source: https://wav1.recrav.com/docs/learn/settings ## Account Settings [#account-settings] ### Profile [#profile] Manage your account information: * Name and email * Company details * Timezone preferences ### Security [#security] Secure your account: * Change password * Enable two-factor authentication * Review active sessions ## Session Settings [#session-settings] ### General [#general] Configure session behavior: * Auto-reconnect on disconnect * Message retry attempts * Webhook timeout settings ### Notifications [#notifications] Set up alerts for: * Session disconnections * Failed message deliveries * Rate limit warnings * API key usage ## Billing Settings [#billing-settings] ### Subscription [#subscription] Manage your plan: * View current plan * Upgrade or downgrade * Cancel subscription ### Payment Methods [#payment-methods] Update payment information: * Add/remove cards * Update billing address * View invoice history ## Team Settings (Pro/Enterprise) [#team-settings-proenterprise] ### Members [#members] Manage team access: * Invite team members * Assign roles * Remove access ### Roles [#roles] Available roles: * **Owner** - Full access * **Admin** - Manage sessions and keys * **Developer** - Send messages only * **Viewer** - Read-only access # Webhooks Dashboard > Configure and manage webhooks for real-time event notifications. Source: https://wav1.recrav.com/docs/learn/webhooks ## What Are Webhooks? [#what-are-webhooks] Webhooks are HTTP callbacks Sendable pushes to your application when subscribed events happen, such as: * outgoing message status changes * incoming messages * session socket connect or disconnect events * WhatsApp account events: edits, reactions, deletes, group changes and join requests, calls, labels, channels, contacts, account settings, and history sync This is the recommended way to react to delivery state and inbound traffic without polling. ## Setting Up Webhooks [#setting-up-webhooks] ### Step 1: Create an Endpoint [#step-1-create-an-endpoint] Your application needs a public HTTPS endpoint that accepts POST requests and preserves the raw body for signature verification. ```typescript import express from 'express' import { Sendable } from '@sendable-dev/sdk' const sendable = new Sendable({ apiKey: process.env.SENDABLE_API_KEY!, apiKeyScope: 'session', webhookSecret: process.env.SENDABLE_WEBHOOK_SECRET, }) app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => { const payload = req.body.toString() try { const event = await sendable.webhooks.verifyAndParse(payload, req.headers) handleEvent(event).catch(console.error) return res.sendStatus(200) } catch { return res.status(401).send('Invalid signature') } }) ``` ### Step 2: Add the Webhook in Dashboard [#step-2-add-the-webhook-in-dashboard] 1. Go to your session 2. Open the `Webhooks` tab 3. Click `Add Webhook` 4. Enter your URL 5. Choose subscribed event types 6. Save ### Step 3: Save the Secret [#step-3-save-the-secret] Every endpoint has a signing secret in the form `whsec_...`. Store it in `SENDABLE_WEBHOOK_SECRET` and never expose it to the browser. ## Event Types [#event-types] ### Message Events [#message-events] | Event | When It Fires | Use Case | | --------------------------- | ----------------------------- | ---------------------- | | `message.sent` | WhatsApp accepted an API send | Track outbound traffic | | `message.delivered` | Message delivered | Confirm delivery | | `message.read` | Recipient read message | Track engagement | | `message.failed` | API send failed | Retry or alert | | `message.received` | Direct incoming message | Store or respond | | `message-personal.received` | Personal chat message | Personal inbox flows | | `message-group.received` | Group or community message | Group automations | ### Session Events [#session-events] | Event | When It Fires | Use Case | | ----------------------------- | -------------------- | ------------------------- | | `session.socket-connected` | Session goes online | Resume sending | | `session.socket-disconnected` | Session goes offline | Alert team, pause sending | ### Normalized Events [#normalized-events] | Event | When It Fires | Use Case | | ----------------------------------------------------------------- | ------------------------------------------------- | --------------------------- | | `message.deleted` / `message.edited` / `message.reaction` | Message revoked, edited, or reacted to | Keep a mirror in sync | | `status.received` / `status.posted` | Contact posted a status (opt-in) / you posted one | Status feeds | | `chat.upsert` / `chat.updated` / `chat.deleted` / `chat.locked` | Chat app-state changed | Inbox sync | | `group.upserted` / `group.updated` / `group.participants.updated` | Group joined, changed, or membership changed | Group automations | | `group.join-request` / `group.member-tag.updated` | Join request or member tag change | Approve members, moderation | | `contact.upserted` / `contact.updated` | Contacts synced or changed | CRM sync | | `label.edited` / `label.association.updated` | Business labels changed | CRM pipelines | | `call.updated` | Incoming call status | Auto-reject, call logs | | `newsletter.*` | Channel reactions, views, admins, settings | Channel analytics | | `settings.updated` / `message-capping.updated` / `blocklist.*` | Account settings, caps, blocklist | Compliance and limits | | `history.synced` / `history.status` | History sync progress | Know when backfill is done | See [Webhook Events](/docs/webhook-events#normalized-events) for payloads. Each one can also be replayed from `GET /v1/events`. ## Security [#security] ### Signature Verification [#signature-verification] Sendable uses [Standard Webhooks](https://www.standardwebhooks.com) signatures. Requests include: * `webhook-id` * `webhook-timestamp` * `webhook-signature` The SDK also accepts the older `svix-*` header names. You should verify against the raw request body before parsing JSON: ```typescript const payload = req.body.toString() const event = await sendable.webhooks.verifyAndParse(payload, req.headers) ``` ## Best Practices [#best-practices] ### Respond Quickly [#respond-quickly] Return HTTP 200 after verification and push real work into background jobs when possible. ### Handle Duplicates [#handle-duplicates] Webhook delivery is at-least-once, so build idempotency around the envelope: ```typescript async function handleEvent(event) { const key = `${event.type}-${event.data.id ?? event.data.sessionId}-${event.createdAt}` if (await wasProcessed(key)) { return } await processEvent(event) } ``` ### Log Failures [#log-failures] ```typescript async function processEvent(event) { if (event.type === 'message.failed') { console.error('message failed', event.data.id, event.data.status) } } ``` ## Use Cases [#use-cases] ### Delivery Tracking [#delivery-tracking] ```typescript if (event.type === 'message.delivered') { await updateOrderStatus(event.data.id, 'delivered') } ``` ### Incoming Chat Automation [#incoming-chat-automation] ```typescript if (event.type === 'message.received') { await saveMessage(event.data) await maybeAutoReply(event.data.chatId, event.data.text?.content) } ``` ### Session Monitoring [#session-monitoring] ```typescript if (event.type === 'session.socket-disconnected') { await notifyOps(`Session ${event.data.sessionId} disconnected`) } ``` ## Troubleshooting [#troubleshooting] ### Invalid Signature [#invalid-signature] * Use the raw body, not `JSON.stringify(req.body)` * Verify the `whsec_...` secret matches the endpoint in the dashboard * Make sure body parsing middleware is not running before verification ### Missing Events [#missing-events] * Confirm the webhook is active * Confirm the event type is subscribed * Check delivery logs in the dashboard # MCP Server > Use Sendable from Claude, Cursor, Kiro and other MCP clients, hosted or with npx. Source: https://wav1.recrav.com/docs/mcp Sendable ships an [MCP](https://modelcontextprotocol.io) server with about 35 curated tools: read chats, messages, contacts, groups and events, send and react to messages, manage group settings and webhooks. Two ways to run it: | | Hosted | Local (stdio) | | ----------------- | ------------------------------------------------------------ | ----------------------------------------------------------- | | URL / command | `https://api.sendable.dev/mcp` | `npx -y @sendable-dev/mcp` | | Transport | Streamable HTTP (stateless, JSON responses) | stdio | | Auth | `x-api-key` header (or `Authorization: Bearer `) | `SENDABLE_API_KEY` env | | Read-only | `?read_only=1` | `--read-only` or `SENDABLE_MCP_READ_ONLY=1` | | Destructive tools | `?allow_destructive=1` **and** a key with the `admin` action | `--allow-destructive` or `SENDABLE_MCP_ALLOW_DESTRUCTIVE=1` | ## Keys and permissions [#keys-and-permissions] Use a **session API key** with only the [permissions](/docs/learn/api-keys#permissions) the agent needs. The hosted server reads the key's permissions and only lists tools the key can call: a key made from the **Read only** preset never sees `send_message`. Every tool call goes through the normal API, so permissions, [rate limits](/docs/rate-limits) (each tool call counts as one API request), the session send policy and idempotency keys apply exactly as for direct API calls. An account key only sees the session tools (`list_sessions`, `get_session_status`, `get_session_profile`). ## Tools [#tools] All tools carry MCP annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). * **Read:** `list_sessions`, `get_session_status`, `get_session_profile`, `list_chats`, `get_chat`, `list_chat_messages`, `list_messages`, `get_message`, `get_message_media`, `get_delivery_status`, `search_contacts`, `get_contact`, `list_groups`, `get_group`, `list_group_join_requests`, `list_labels`, `list_chat_labels`, `list_events`, `list_webhooks`, `list_webhook_event_types`. * **Write:** `send_message` (text; image, video, document or audio URL; location; poll; with optional `quoted_message_id`, `mentions`, `mention_all` and `typing_ms`), `reply_to_message` (also takes `mentions`, `mention_all`, `typing_ms`), `react_to_message`, `edit_message`, `mark_read`, `fetch_history`, `star_message`, `pin_message`, `update_group_subject`, `update_group_description`, `get_group_invite_link`, `create_webhook`, `update_webhook`. * **Destructive** (hidden unless enabled, and each call needs `"confirm": true`): `delete_message`, `update_group_participants`, `revoke_group_invite`, `leave_group`, `delete_webhook`. Never exposed: logout or ending a session, privacy settings, webhook secret rotation, profile pictures. Webhook secrets and custom header values are redacted in tool output. `send_message` and `reply_to_message` need an explicit `chat_id` and send an `Idempotency-Key`: pass `idempotency_key` to make a retried call safe (a repeat within 24 hours returns the first result instead of sending twice); without it a key is generated per call. Lists return 20 items by default with a `nextCursor`. ## Client config [#client-config] ### Hosted (clients that support remote servers with custom headers, such as Cursor and Kiro) [#hosted-clients-that-support-remote-servers-with-custom-headers-such-as-cursor-and-kiro] ```json { "mcpServers": { "sendable": { "url": "https://api.sendable.dev/mcp", "headers": { "x-api-key": "" } } } } ``` ### Local with npx (any client, including Claude Desktop) [#local-with-npx-any-client-including-claude-desktop] ```json { "mcpServers": { "sendable": { "command": "npx", "args": ["-y", "@sendable-dev/mcp"], "env": { "SENDABLE_API_KEY": "" } } } } ``` Config file locations: Claude Desktop `claude_desktop_config.json`, Cursor `.cursor/mcp.json`, Kiro `.kiro/settings/mcp.json`. ## Errors [#errors] Tool failures come back as MCP tool errors with a short message: invalid key (401), missing permission (403 `insufficient_scope`, naming the permission), rate limited (429, with the wait time), not found, and network errors. A request to `/mcp` without a valid key gets HTTP `401`. ## Safety [#safety] Message contents are written by other people. The server tells the model to treat them as data, not instructions. Keep agents on narrow keys: a read-only key for assistants that only summarise, a send-only key for agents that notify. Destructive tools need both the opt-in and `confirm: true` on every call. # Astro Integration > Build a static site with Astro and Sendable API routes. Source: https://wav1.recrav.com/docs/quickstart/nodejs/astro ## Project Setup [#project-setup] ```bash npm create astro@latest my-sendable-app cd my-sendable-app ``` ## Environment Setup [#environment-setup] Create `.env`: ```bash SENDABLE_API_KEY=your_api_key_here ``` ## API Route [#api-route] Create `src/pages/api/send-message.ts`: ```typescript import type { APIRoute } from 'astro' export const POST: APIRoute = async ({ request }) => { const { to, text } = await request.json() const response = await fetch('https://api.sendable.dev/messages/send', { method: 'POST', headers: { 'x-api-key': import.meta.env.SENDABLE_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ to, text }), }) return new Response(JSON.stringify(await response.json()), { status: response.status, }) } ``` ## Component [#component] Create `src/components/MessageForm.astro`: ```astro

``` See full example on [GitHub](https://github.com/sendablelabs/examples/tree/main/astro). # Express Integration > Build a REST API with Express and Sendable WhatsApp API. Source: https://wav1.recrav.com/docs/quickstart/nodejs/express ## Project Setup [#project-setup] ```bash mkdir sendable-express-api cd sendable-express-api npm init -y npm install express cors dotenv @sendable-dev/sdk npm install -D @types/express @types/cors @types/node typescript ts-node nodemon ``` ### TypeScript Configuration [#typescript-configuration] Create `tsconfig.json`: ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist" }, "include": ["src/**/*"] } ``` ### Project Structure [#project-structure] ``` src/ ├── config/ │ └── sendable.ts ├── routes/ │ ├── messages.ts │ └── webhooks.ts ├── middleware/ │ └── auth.ts └── index.ts ``` ### Configuration [#configuration] Create `src/config/sendable.ts`: ```typescript import { Sendable } from '@sendable-dev/sdk' if (!process.env.SENDABLE_API_KEY) { throw new Error('SENDABLE_API_KEY is required') } export const sendable = new Sendable({ apiKey: process.env.SENDABLE_API_KEY, apiKeyScope: 'session', baseUrl: process.env.SENDABLE_API_URL, webhookSecret: process.env.SENDABLE_WEBHOOK_SECRET, }) ``` ### Authentication Middleware [#authentication-middleware] Create `src/middleware/auth.ts`: ```typescript import { Request, Response, NextFunction } from 'express' // Simple API key auth for your own API export function authMiddleware(req: Request, res: Response, next: NextFunction) { const apiKey = req.headers['authorization']?.replace('Bearer ', '') if (apiKey !== process.env.API_KEY) { return res.status(401).json({ error: 'Unauthorized' }) } next() } ``` ### Messages Route [#messages-route] Create `src/routes/messages.ts`: ```typescript import { Router } from 'express' import { sendable } from '../config/sendable' const router = Router() // Send a message router.post('/send', async (req, res) => { try { const { chatId, text } = req.body if (!chatId || !text) { return res.status(400).json({ error: 'chatId and message text are required' }) } const response = await sendable.messages.send({ chatId, text: { content: text }, }) res.json({ success: true, messageId: response.messageId, status: response.status }) } catch (error) { console.error('Error sending message:', error) res.status(500).json({ error: 'Failed to send message' }) } }) // Get message status router.get('/:messageId/status', async (req, res) => { try { const { messageId } = req.params const message = await sendable.messages.get(messageId) res.json(message) } catch (error) { console.error('Error getting status:', error) res.status(500).json({ error: 'Failed to get message status' }) } }) export default router ``` ### Webhook Route [#webhook-route] Create `src/routes/webhooks.ts`: ```typescript import express from 'express' import { Router } from 'express' import { sendable } from '../config/sendable' const router = Router() // Webhook handler router.post('/', express.raw({ type: 'application/json' }), async (req, res) => { const payload = req.body.toString() let event try { event = await sendable.webhooks.verifyAndParse(payload, req.headers) } catch { return res.status(401).json({ error: 'Invalid signature' }) } // Process event asynchronously handleWebhookEvent(event).catch(console.error) // Respond immediately res.json({ received: true }) }) async function handleWebhookEvent(event: any) { console.log(`[${new Date().toISOString()}] Event: ${event.type}`) switch (event.type) { case 'message.delivered': // Update database, notify user, etc. console.log(`Message ${event.data.id} delivered`) break case 'message.read': console.log(`Message ${event.data.id} read by ${event.data.to}`) break case 'message.failed': console.error(`Message ${event.data.id} failed with status ${event.data.status}`) // Handle failure - retry, notify, etc. break case 'message.received': console.log(`Received from ${event.data.from}: ${event.data.text?.content}`) // Handle incoming message - auto-reply, store, etc. break case 'session.socket-disconnected': console.error(`Session ${event.data.sessionId} disconnected`) // Alert admin, attempt reconnect, etc. break } } export default router ``` ### Main Server [#main-server] Create `src/index.ts`: ```typescript import express from 'express' import cors from 'cors' import dotenv from 'dotenv' dotenv.config() import messagesRouter from './routes/messages' import webhooksRouter from './routes/webhooks' import { authMiddleware } from './middleware/auth' const app = express() const PORT = process.env.PORT || 3000 // Middleware app.use(cors()) // Public webhook route (no auth - uses signature verification) app.use('/webhook', webhooksRouter) // JSON parsing for the rest of your API app.use(express.json()) // Protected API routes app.use('/api/messages', authMiddleware, messagesRouter) // Health check app.get('/health', (req, res) => { res.json({ status: 'ok', timestamp: new Date().toISOString() }) }) // Start server app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`) }) ``` ### Environment Variables [#environment-variables] Create `.env`: ```bash ## Sendable SENDABLE_API_KEY=your_sendable_api_key SENDABLE_WEBHOOK_SECRET=whsec_your_webhook_secret ## Your API API_KEY=your_internal_api_key ## Server PORT=3000 ``` ### Running the Server [#running-the-server] ```bash ## Development npx nodemon src/index.ts ## Production npm run build npm start ``` ### API Usage Examples [#api-usage-examples] #### Send a message [#send-a-message] ```bash curl -X POST http://localhost:3000/api/messages/send \ -H "Authorization: Bearer your_internal_api_key" \ -H "Content-Type: application/json" \ -d '{ "to": "6281234567890", "text": "Hello from Express!" }' ``` #### Get message status [#get-message-status] ```bash curl http://localhost:3000/api/messages/msg_abc123/status \ -H "Authorization: Bearer your_internal_api_key" ``` #### Production Deployment [#production-deployment] 1. Use a process manager like PM2: ```bash npm install -g pm2 pm2 start dist/index.js --name sendable-api ``` 2. Set up a reverse proxy with Nginx 3. Use HTTPS for webhook endpoints 4. Monitor logs and set up alerts # Hono Integration > Build a lightweight API with Hono and Sendable. Source: https://wav1.recrav.com/docs/quickstart/nodejs/hono ## Project Setup [#project-setup] ```bash mkdir my-sendable-api cd my-sendable-api npm init -y npm install hono @hono/node-server npm install -D typescript tsx ``` ## Basic Server [#basic-server] Create `src/index.ts`: ```typescript import { Hono } from 'hono' import { serve } from '@hono/node-server' const app = new Hono() app.post('/send', async (c) => { const { to, text } = await c.req.json() const response = await fetch('https://api.sendable.dev/messages/send', { method: 'POST', headers: { 'x-api-key': process.env.SENDABLE_API_KEY!, 'Content-Type': 'application/json', }, body: JSON.stringify({ to, text }), }) return c.json(await response.json()) }) app.post('/webhook', async (c) => { const body = await c.req.json() console.log('Webhook:', body) return c.json({ received: true }) }) serve({ fetch: app.fetch, port: 3000 }) ``` ## Run [#run] ```bash npx tsx src/index.ts ``` See full example on [GitHub](https://github.com/sendablelabs/examples/tree/main/hono). # Introduction > Get started with Sendable in Node.js applications. Source: https://wav1.recrav.com/docs/quickstart/nodejs ## Prerequisites [#prerequisites] * Node.js 18 or higher * A Sendable account with an active session * An API key from your dashboard ### Installation [#installation] Install the official TypeScript SDK: ```bash npm install @sendable-dev/sdk ``` ### Basic Setup [#basic-setup] Create a `.env` file: ```bash SENDABLE_API_KEY=your_api_key_here SENDABLE_API_URL=https://api.sendable.dev ``` ### Quick Example [#quick-example] ```typescript import { Sendable } from '@sendable-dev/sdk' const sendable = new Sendable({ apiKey: process.env.SENDABLE_API_KEY!, apiKeyScope: 'session', baseUrl: process.env.SENDABLE_API_URL, }) export async function sendMessage(chatId: string, text: string) { return sendable.messages.send({ chatId, text: { content: text }, }) } // Usage await sendMessage('6281234567890@s.whatsapp.net', 'Hello from Node.js!') ``` ### Available Guides [#available-guides] * [TypeScript SDK](/docs/quickstart/nodejs/sdk) - Install and use the official SDK * [Next.js Integration](/docs/quickstart/nodejs/nextjs) - Full-stack Next.js app with Sendable * [Express Integration](/docs/quickstart/nodejs/express) - REST API with Express and Sendable ### Environment Variables [#environment-variables] | Variable | Required | Description | | ------------------------- | -------- | ---------------------------------------------------------------------------- | | `SENDABLE_API_KEY` | Yes | Your session API key | | `SENDABLE_API_URL` | No | API base URL (default: [https://api.sendable.dev](https://api.sendable.dev)) | | `SENDABLE_WEBHOOK_SECRET` | No | For verifying webhooks | # Next.js Integration > Build a full-stack Next.js app with Sendable WhatsApp API. Source: https://wav1.recrav.com/docs/quickstart/nodejs/nextjs ## Project Setup [#project-setup] ```bash npx create-next-app@latest my-sendable-app --typescript --tailwind --app cd my-sendable-app ``` ### Environment Setup [#environment-setup] Create `.env.local`: ```bash SENDABLE_API_KEY=your_api_key_here SENDABLE_WEBHOOK_SECRET=your_webhook_secret ``` ### API Route for Sending Messages [#api-route-for-sending-messages] Create `app/api/send-message/route.ts`: ```typescript import { NextRequest, NextResponse } from 'next/server' export async function POST(req: NextRequest) { try { const { to, text } = await req.json() const response = await fetch('https://api.sendable.dev/messages/send', { method: 'POST', headers: { 'x-api-key': process.env.SENDABLE_API_KEY!, 'Content-Type': 'application/json', }, body: JSON.stringify({ to, text }), }) if (!response.ok) { const error = await response.json() return NextResponse.json(error, { status: response.status }) } const data = await response.json() return NextResponse.json(data) } catch (error) { return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ) } } ``` ### Webhook Handler [#webhook-handler] Create `app/api/webhook/route.ts`: ```typescript import { NextRequest, NextResponse } from 'next/server' import { Sendable } from '@sendable-dev/sdk' const sendable = new Sendable({ apiKey: process.env.SENDABLE_API_KEY!, apiKeyScope: 'session', webhookSecret: process.env.SENDABLE_WEBHOOK_SECRET, }) export async function POST(req: NextRequest) { const payload = await req.text() let event try { event = await sendable.webhooks.verifyAndParse(payload, req.headers) } catch { return NextResponse.json({ error: 'Invalid signature' }, { status: 401 }) } // Handle different event types switch (event.type) { case 'message.delivered': console.log(`Message ${event.data.id} delivered`) break case 'message.failed': console.log(`Message ${event.data.id} failed with status ${event.data.status}`) break case 'message.received': console.log(`Received message from ${event.data.from}:`, event.data.text?.content) break } return NextResponse.json({ received: true }) } ``` ### Frontend Component [#frontend-component] Create `app/components/MessageForm.tsx`: ```typescript 'use client' import { useState } from 'react' export function MessageForm() { const [to, setTo] = useState('') const [text, setText] = useState('') const [status, setStatus] = useState('') async function handleSubmit(e: React.FormEvent) { e.preventDefault() setStatus('Sending...') try { const res = await fetch('/api/send-message', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ to, text }), }) if (res.ok) { setStatus('Message sent!') setTo('') setText('') } else { const error = await res.json() setStatus(`Error: ${error.message}`) } } catch { setStatus('Failed to send message') } } return (
setTo(e.target.value)} placeholder="6281234567890" className="mt-1 block w-full rounded-md border p-2" required />