@kapso/whatsapp-cloud-api
v0.4.0
Published
TypeScript client for WhatsApp Business Cloud API with typed responses and Zod-validated builders.
Readme
whatsapp-cloud-api-js
TypeScript client for the WhatsApp Cloud API.
Install
npm install @kapso/whatsapp-cloud-apiQuick start
import { WhatsAppClient } from "@kapso/whatsapp-cloud-api";
const client = new WhatsAppClient({
accessToken: process.env.WHATSAPP_TOKEN!,
// or route via Kapso proxy:
// baseUrl: "https://api.kapso.ai/meta/whatsapp",
// kapsoApiKey: process.env.KAPSO_API_KEY,
});
await client.messages.sendText({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
body: "Hello from Kapso",
});Choose your setup
- Meta setup (~ 1 hour)
Create a Meta WhatsApp app, generate a system token, and link a WhatsApp Business phone number in Meta Business Manager.
- Kapso proxy (~ 2 minutes)
Have Kapso provision and connect a WhatsApp number for you, then use your Kapso API key and base URL to begin sending immediately.
Query conversations, messages, contacts, and more.
API surface
Core
client.messages— send text/media/interactive/templates, send raw payloads, and mark messages as readclient.templates— list/get/create/delete templates on your WABAclient.media— upload media, fetch metadata, delete mediaclient.phoneNumbers— request/verify code, register/deregister, settings, business profileclient.flows— author, validate, deploy, and preview WhatsApp FlowsverifySignature— verify webhook signatures (app secret)receiveFlowEvent,respondToFlow,downloadFlowMedia— decrypt and respond to Flow callbacksTemplateDefinition— strict template creation buildersbuildTemplateSendPayload— build send-time template payloadsbuildTemplatePayload— accept Meta-style rawcomponentsand normalize/camelize inputs
Kapso proxy extras
Requires baseUrl and kapsoApiKey.
client.conversations— list/get/update conversations across your projectclient.messages.query/listByConversation/get— pull stored message historyclient.contacts— list/get/update contacts, withcustomerIdfilterclient.calls— initiate calls plus historic call logs (list/get) and permission helpersKapso Extensions— opt-in to extra fields viafields=kapso(...)
Using the Kapso Proxy
To use Kapso’s proxy, set the client base URL and API key:
const client = new WhatsAppClient({
baseUrl: "https://api.kapso.ai/meta/whatsapp",
kapsoApiKey: process.env.KAPSO_API_KEY!,
});Why Kapso?
- Get a WhatsApp API for your number in ~2 minutes.
- Built‑in inbox for your team.
- Query conversations, messages and contacts.
- Automatic backup to Supabase.
- Webhooks for critical events: message received, message sent, conversation inactive, and more.
- Get a US phone number for WhatsApp (works globally).
- Multi‑tenant by design — onboard thousands of customers safely.
- And more.
Notes:
- Media GET/DELETE requires
phoneNumberIdquery on the proxy. - Responses mirror Meta’s Cloud API message schema.
- Kapso-only enrichments live under the
kapsokey; use thefieldsparameter (for examplefields: "kapso(flow_response,flow_token)") to opt into specific fields orfields: "kapso()"to omit them entirely. - You can also pass a bearer
accessTokeninstead ofkapsoApiKeyif you’ve stored a token with Kapso.
Sending messages
Below are concise examples for common message types. Assume client is created as shown above.
Every send accepts to (a phone number), recipient (a business-scoped user ID), or both. See Business-scoped user IDs.
Text
await client.messages.sendText({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
body: "Hello!",
});Raw payload
await client.messages.sendRaw({
phoneNumberId: "<PHONE_NUMBER_ID>",
payload: {
messaging_product: "whatsapp",
recipient_type: "individual",
to: "+15551234567",
type: "text",
text: { body: "Hello from a raw payload" },
},
});Image
By media ID:
await client.messages.sendImage({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
image: { id: "<MEDIA_ID>", caption: "Check this out" },
});By link:
await client.messages.sendImage({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
image: { link: "https://example.com/photo.jpg", caption: "Photo" },
});Document
await client.messages.sendDocument({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
document: { link: "https://example.com/invoice.pdf", filename: "invoice.pdf", caption: "Invoice" },
});Video
await client.messages.sendVideo({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
video: { link: "https://example.com/clip.mp4", caption: "Clip" },
});Sticker
await client.messages.sendSticker({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
sticker: { id: "<MEDIA_ID>" },
});Location
await client.messages.sendLocation({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
location: { latitude: -33.45, longitude: -70.66, name: "Santiago", address: "CL" },
});Contacts
await client.messages.sendContacts({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
contacts: [
{ name: { formattedName: "John Doe" }, phones: [{ phone: "+15551234567", type: "WORK" }] },
],
});Reaction
await client.messages.sendReaction({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
reaction: { messageId: "wamid......", emoji: "😀" },
});Mark read & typing indicator
await client.messages.markRead({
phoneNumberId: "<PHONE_NUMBER_ID>",
messageId: "wamid......",
typingIndicator: { type: "text" },
});Interactive buttons
await client.messages.sendInteractiveButtons({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
header: { type: "image", image: { id: "<MEDIA_ID>" } },
bodyText: "Pick an option",
footerText: "Footer",
buttons: [ { id: "accept", title: "Accept" }, { id: "decline", title: "Decline" } ],
});Interactive CTA URL
await client.messages.sendInteractiveCtaUrl({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
header: { type: "image", image: { link: "https://example.com/banner.png" } },
bodyText: "Tap the button to see dates.",
parameters: { displayText: "See Dates", url: "https://example.com?utm=wa" }
});Interactive Carousel
await client.messages.sendInteractiveCarousel({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
bodyText: "Choose an option",
cards: [
{
cardIndex: 0,
header: { type: "image", image: { link: "https://example.com/one.jpg" } },
bodyText: "First card",
action: { type: "cta_url", displayText: "View", url: "https://example.com/one" }
},
{
cardIndex: 1,
header: { type: "image", image: { link: "https://example.com/two.jpg" } },
bodyText: "Second card",
action: { displayText: "View", url: "https://example.com/two" }
}
]
});Catalog Message
await client.messages.sendInteractiveCatalogMessage({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
bodyText: "Browse our catalog on WhatsApp",
parameters: { thumbnailProductRetailerId: "SKU-123" }
});Call buttons and calling deep links
These helpers invite a user to call your business number on WhatsApp. They only build or send messages; building a payload or a link never calls an API. The business number must have Cloud API calling enabled. Meta's call button and deep link guide is the reference for this behavior.
Free-form call button
Meta accepts this message only inside a customer service window or an open conversation window. To reach a user outside these windows, use a template with a voice_call button. to, recipient (BSUID), or both are accepted.
await client.messages.sendInteractiveVoiceCall({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
bodyText: "You can call us on WhatsApp now for faster service!",
parameters: {
displayText: "Call on WhatsApp", // optional, ≤ 20 characters (Meta default "Call Now")
ttlMinutes: 1440, // optional, 1–43200 (Meta default 10080 = 7 days)
payload: "campaign=fall-2026", // optional, ≤ 512 characters, returned as ctaPayload
},
});Users on WhatsApp versions without call button support cause Meta to send an error webhook with code 131026.
Call button templates
Creation uses a voice_call button. Creation ttlMinutes must be 1440–43200 (1–30 days). The button can share the template with URL buttons.
import { TemplateDefinition } from "@kapso/whatsapp-cloud-api";
const definition = TemplateDefinition.buildTemplateDefinition({
name: "wa_voice_call",
language: "en",
category: "MARKETING",
components: [
{ type: "BODY", text: "You can call us on WhatsApp now for faster service!" },
{
type: "BUTTONS",
buttons: [
{ type: "voice_call", text: "Call Now", ttlMinutes: 1440 },
{ type: "URL", text: "Contact Support", url: "https://example.com/support" },
],
},
],
});
await client.templates.create({ businessAccountId: "<WABA_ID>", ...definition });At send time you can override the lifetime (1–43200 minutes) and attach a tracking payload (≤ 512 characters):
import { buildTemplateSendPayload, buildVoiceCallTemplateButton } from "@kapso/whatsapp-cloud-api";
await client.messages.sendTemplate({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
template: buildTemplateSendPayload({
name: "wa_voice_call",
language: "en",
buttons: [buildVoiceCallTemplateButton({ index: 0, ttlMinutes: 100, payload: "campaign=fall-2026" })],
}),
});The SDK builders require the button index, as for every other template button. Meta's own sample omits it; to send that exact shape, pass the raw template object to messages.sendTemplate.
Calling deep links
buildCallDeepLink returns a https://wa.me/call/<number> link. Use it on a website, in an app, in a QR code, or in a message. It removes +, spaces, dashes and parentheses from the number and percent-encodes payload into biz_payload. It never shortens the link or makes a network call.
import { buildCallDeepLink } from "@kapso/whatsapp-cloud-api";
buildCallDeepLink({ phoneNumber: "+1 (408) 555-1234", payload: "qr=lobby&floor=2" });
// https://wa.me/call/14085551234?biz_payload=qr%3Dlobby%26floor%3D2Use the business display phone number, not the phone number ID. Meta does not support calling deep links on WhatsApp desktop clients.
Tracking which button or link started a call
On connect and terminate call webhooks, Meta returns the button payload as cta_payload and the deep link biz_payload as deeplink_payload. Your app must be subscribed to the calls webhook field. normalizeWebhook exposes them as call.ctaPayload and call.deeplinkPayload. Each field is absent when Meta does not send it.
events.calls.forEach((call) => {
if (call.event === "connect" || call.event === "terminate") {
console.log(call.callId, call.ctaPayload, call.deeplinkPayload);
}
});Meta propagates both payloads only from WhatsApp clients on version 2.25.27 or later, so treat them as optional attribution. These payloads are separate from bizOpaqueCallbackData, which correlates message status and call termination webhooks. The SDK tests check request shapes against Meta's documented samples. They do not send live calls or messages.
Business-scoped user IDs (BSUIDs)
Meta is replacing phone numbers as the way to identify WhatsApp users. Every user already has a business-scoped user ID (US.13491208655302741918), it arrives on every webhook, and for users who adopt a username the phone number eventually stops arriving.
All message builders and calls.connect take recipient alongside to. Provide either or both; when both are present, Meta delivers to the phone number.
// By BSUID only (the phone number never arrived):
await client.messages.sendText({
phoneNumberId: "<PHONE_NUMBER_ID>",
recipient: "US.13491208655302741918",
body: "On its way.",
});
// Recommended default when you have both identifiers:
await client.messages.sendText({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
recipient: "US.13491208655302741918",
body: "On its way.",
});On webhooks, normalizeWebhook surfaces the identifiers as message.fromUserId, message.fromParentUserId, contact.userId, and status.recipientUserId, and infers message direction even when no phone number arrives. Statuses for your own sends carry both identifiers, which is the cheapest way to build your phone-to-BSUID mapping.
isBusinessScopedUserId(value) (and BSUID_PATTERN) check the shape, including the parent ENT variant. The builders deliberately do not enforce it, so future format changes on Meta's side don't turn valid sends into client-side errors.
One limit from Meta: one-tap, zero-tap and copy-code authentication templates require a phone number and cannot be delivered to a BSUID (error 131062).
For the full migration story, read the Business-scoped user IDs guide.
Flows
Use client.flows.deploy() for idempotent deployments, or create/updateAsset/publish/preview for granular control. Server utilities (receiveFlowEvent, respondToFlow, downloadFlowMedia) handle Data Endpoint callbacks.
Deploy a Flow
import { WhatsAppClient } from "@kapso/whatsapp-cloud-api";
const flowJson = {
version: "7.2",
screens: [
{
id: "CSAT",
terminal: true,
layout: {
type: "SingleColumnLayout",
children: [
{ type: "RadioButtonsGroup", name: "rating", label: "Rate us", dataSource: [
{ id: "up", title: "👍" },
{ id: "down", title: "👎" }
] },
{ type: "Footer", label: "Submit", onClickAction: { name: "complete", payload: { rating: "${form.rating}" } } }
]
}
}
]
};
const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_TOKEN! });
await client.flows.deploy(flowJson, {
wabaId: process.env.WABA_ID!,
name: "csat-flow",
publish: true,
preview: true
});Send a Flow message
import { WhatsAppClient, type FlowInteractiveInput } from "@kapso/whatsapp-cloud-api";
const client = new WhatsAppClient({ accessToken: process.env.WHATSAPP_TOKEN! });
await client.messages.sendInteractiveFlow({
phoneNumberId: "1234567890",
to: "+15551234567",
bodyText: "Check out our new experience",
parameters: {
flowId: "1234567890",
flowCta: "Open",
mode: "draft", // required when sending an unpublished Flow
flowToken: "token123",
flowAction: "navigate",
flowActionPayload: { screen: "WELCOME" }
}
});
flowCtais required by Meta.flowMessageVersiondefaults to"3"when omitted. Meta treats an omittedmodeas"published"; usemode: "draft"for an unpublished Flow.
For a full walkthrough (authoring guidance, deployment scripts, Express/Edge examples, and manual testing tips) see docs/flows.md.
Templates
Build with components
Use buildTemplatePayload as the primary way to build templates. It accepts Meta‑style components, normalizes casing, and enforces shape (e.g., language.policy = 'deterministic' when using an object).
import { buildTemplatePayload } from '@kapso/whatsapp-cloud-api';
const template = buildTemplatePayload({
name: 'order_confirmation',
language: 'en_US', // or { code: 'en_US', policy: 'deterministic' }
components: [
{ type: 'body', parameters: [{ type: 'text', text: 'Jessica', parameter_name: 'customer_name' }] },
],
});When you pass raw Meta-style components, keep the snake_case field (parameter_name) Meta expects.
Typed builder
Prefer typed guardrails? Use buildTemplateSendPayload. It outputs the same Meta structure but gives compile‑time guidance. Example with body parameters and a Flow button:
import { buildTemplateSendPayload } from '@kapso/whatsapp-cloud-api';
const template = buildTemplateSendPayload({
name: 'order_confirmation',
language: 'en_US',
body: [
{ type: 'text', text: 'Jessica', parameterName: 'customerName' },
{ type: 'text', text: 'SKBUP2-4CPIG9', parameterName: 'orderId' },
],
buttons: [
{
type: 'button',
subType: 'flow',
index: 0,
parameters: [{ type: 'action', action: { flow_token: 'FT_123', flow_action_data: { step: 'one' } } }],
},
],
});The typed builder accepts camelCase parameterName and the client automatically snake-cases it when sending.
Template creation
The creation builder validates components and examples like Meta’s review.
Minimal examples:
import { buildTemplateDefinition } from '@kapso/whatsapp-cloud-api';
// Authentication (copy code)
const authenticationTemplate = buildTemplateDefinition({
name: 'authentication_code',
language: 'en_US',
category: 'AUTHENTICATION',
messageSendTtlSeconds: 60,
components: [
{ type: 'BODY', addSecurityRecommendation: true },
{ type: 'FOOTER', codeExpirationMinutes: 10 },
{ type: 'BUTTONS', buttons: [{ type: 'OTP', otpType: 'COPY_CODE' }] },
],
});
// Named parameters (parameter_format = NAMED)
const namedOrderTemplate = buildTemplateDefinition({
name: 'order_confirmation_named',
language: 'en_US',
category: 'UTILITY',
parameterFormat: 'NAMED',
components: [
{
type: 'BODY',
text: 'Thank you, {{customer_name}}! Your order {{order_number}} ships {{ship_date}}.',
example: {
bodyTextNamedParams: [
{ paramName: 'customer_name', example: 'Pablo' },
{ paramName: 'order_number', example: '860198-230332' },
{ paramName: 'ship_date', example: '2025-11-15' },
],
},
},
],
});
// Limited-time offer
const limitedTimeOfferTemplate = buildTemplateDefinition({
name: 'limited_offer', language: 'en_US', category: 'MARKETING',
components: [
{ type: 'BODY', text: 'Hello {{1}}', example: { bodyText: [['Pablo']] } },
{ type: 'LIMITED_TIME_OFFER', limitedTimeOffer: { text: 'Expiring!', hasExpiration: true } },
],
});
// Catalog / MPM / SPM
const catalogTemplate = buildTemplateDefinition({
name: 'catalog_push', language: 'en_US', category: 'MARKETING',
components: [ { type: 'BODY', text: 'Browse our catalog' }, { type: 'BUTTONS', buttons: [{ type: 'CATALOG', text: 'View catalog' }] } ],
});parameterFormat matches the API’s parameter_format field. When set to "NAMED", use named placeholders (for example {{customer_name}}) and provide examples via bodyTextNamedParams / headerTextNamedParams so WhatsApp can validate your template.
Query history & contacts
When you point the client to Kapso’s proxy (baseUrl: "https://api.kapso.ai/meta/whatsapp" plus kapsoApiKey), you can query stored data in addition to sending messages.
const client = new WhatsAppClient({
baseUrl: "https://api.kapso.ai/meta/whatsapp",
kapsoApiKey: process.env.KAPSO_API_KEY!,
});
// Conversations
const conversations = await client.conversations.list({
phoneNumberId: "647015955153740",
status: "active",
limit: 50,
});
const conversation = await client.conversations.get({ conversationId: conversations.data[0].id, });
await client.conversations.updateStatus({ conversationId: conversation.id, status: "ended", });
// Message history
const history = await client.messages.query({
phoneNumberId: "647015955153740",
direction: "inbound",
since: "2025-01-01T00:00:00Z",
limit: 50,
after: conversations.paging.cursors.after,
});
const message = await client.messages.get({
phoneNumberId: "647015955153740",
messageId: history.data[0].id,
fields: "kapso(default)",
});
// Contacts
const contacts = await client.contacts.list({ phoneNumberId: "647015955153740", customerId: "123", });
// waId can be absent: contacts identified only by their BSUID exist.
const waId = contacts.data[0].waId;
if (waId) {
await client.contacts.update({
phoneNumberId: "647015955153740",
waId,
metadata: { tags: ["vip"], source: "import" },
});
}
// Call logs
const calls = await client.calls.list({ phoneNumberId: "647015955153740", direction: "INBOUND", limit: 20, });
const metaCallId = calls.data[0]?.callId; // Meta wacid, not the local id UUID
if (metaCallId) {
const call = await client.calls.get({ phoneNumberId: "647015955153740", callId: metaCallId });
}All history endpoints return Meta-compatible records with Graph paging:
page.data(camelCased) mirrors Meta’s message/contact/conversation/call schema.page.pagingexposescursors.before/cursors.afterplusnext/previousURLs when present.- Supply
fields: buildKapsoFields()(or the string"kapso(default)") to include all Kapso extensions, or pass your own subset such asfields: "kapso(flow_response,flow_token)". Usefields: "kapso()"to omit Kapso extras entirely. - When you store messages via Kapso, request
kapso(content)to hydrate the normalized message with the original payload fragment (for example, catalog interactive content). - Tip:
buildKapsoFieldsis exported from the SDK, so you canimport { buildKapsoFields } from "@kapso/whatsapp-cloud-api";and drop it straight into your queries.
Templates
Create
import { TemplateDefinition } from "@kapso/whatsapp-cloud-api";
const templateDefinition = TemplateDefinition.buildTemplateDefinition({
name: "seasonal_promo",
language: "en_US",
category: "MARKETING",
parameterFormat: "NAMED",
components: [
{
type: "HEADER",
format: "TEXT",
text: "Our {{sale_name}} is on!",
example: { headerTextNamedParams: [{ paramName: "sale_name", example: "Summer Sale" }] }
},
{
type: "BODY",
text: "Shop now through {{end_date}} using code {{discount_code}}",
example: {
bodyTextNamedParams: [
{ paramName: "end_date", example: "Aug 31" },
{ paramName: "discount_code", example: "SALE25" }
]
}
},
{ type: "FOOTER", text: "Tap a button below" },
{
type: "BUTTONS",
buttons: [
{ type: "QUICK_REPLY", text: "Unsubscribe" },
{
type: "URL",
text: "Shop",
url: "https://store.example/promo?code={{discount_code}}",
example: ["SALE25"]
}
]
}
],
});
await client.templates.create({
businessAccountId: "<WABA_ID>",
name: templateDefinition.name,
language: templateDefinition.language,
category: templateDefinition.category,
parameterFormat: templateDefinition.parameterFormat,
components: templateDefinition.components,
});Get a template
const template = await client.templates.get({
businessAccountId: "<WABA_ID>",
templateId: "<TEMPLATE_ID>",
});Send a template
import { buildTemplateSendPayload } from "@kapso/whatsapp-cloud-api";
const templatePayload = buildTemplateSendPayload({
name: "seasonal_promo",
language: "en_US",
header: { type: "image", image: { link: "https://cdn.example/banner.jpg" } },
body: [ { type: "text", text: "Aug 31" }, { type: "text", text: "SALE25" } ],
buttons: [ { type: "button", subType: "quick_reply", index: 0, parameters: [{ type: "payload", payload: "STOP" }] } ],
});
await client.messages.sendTemplate({
phoneNumberId: "<PHONE_NUMBER_ID>",
to: "+15551234567",
template: templatePayload,
});Media
const imageBlob = new Blob([/* binary data */], { type: "image/png" });
await client.media.upload({ phoneNumberId: "<PHONE_NUMBER_ID>", type: "image", file: imageBlob, fileName: "photo.png", });
const metadata = await client.media.get({ mediaId: "<MEDIA_ID>", phoneNumberId: "<PHONE_NUMBER_ID>", }); // Kapso requires phoneNumberId
await client.media.delete({ mediaId: "<MEDIA_ID>", phoneNumberId: "<PHONE_NUMBER_ID>", });Receiving media
Common cases:
- URL‑first with Kapso
Kapso stores inbound media and now also mirrors outbound media shortly after send. Ask for kapso(media_url) when listing messages and render the URL directly (SSR‑friendly).
import { buildKapsoMessageFields } from "@kapso/whatsapp-cloud-api";
const fields = buildKapsoMessageFields("media_url");
const page = await client.messages.listByConversation({
phoneNumberId: "<PHONE_NUMBER_ID>",
conversationId: "<CONVERSATION_ID>",
fields,
});
const msg = page.data.find(m => m.type === "image");
const src = msg?.kapso?.mediaUrl ?? msg?.image?.link; // use direct URL when present- Bytes fallback (universal)
If you need the raw bytes or the URL has not been mirrored yet, use download(). The SDK automatically skips auth headers for public WhatsApp CDNs and uses them for kapso.ai and its DNS subdomains. Media IDs must be IDs, not URLs or paths. Downloads require HTTPS URLs without embedded credentials; all media downloads reject redirects (including downloads with caller-supplied headers). Byte and Blob modes throw GraphApiError for HTTP failures; as: "response" returns the raw response, including non-2xx statuses, for caller inspection.
Key points:
client.media.download({ mediaId, ... })resolves the short‑lived URL viamedia.get()then fetches the bytes.- Return types: default
ArrayBuffer,as: "blob"→Blob,as: "response"→Response. - Direct Meta:
phoneNumberIdis not required. - Kapso proxy: pass
phoneNumberId.
Examples:
// 1) From a message record you loaded (e.g., via client.messages.query):
const { data } = await client.messages.query({ phoneNumberId: "<PHONE_NUMBER_ID>", limit: 1, });
const msg = data[0];
if (msg.type === "image" && msg.image?.id) {
const mediaId = msg.image.id;
const bytes = await client.media.download({ mediaId, phoneNumberId: "<PHONE_NUMBER_ID>", });
// bytes is an ArrayBuffer; do what you need with it
}Phone numbers
await client.phoneNumbers.requestCode({ phoneNumberId: "<PHONE_NUMBER_ID>", codeMethod: "SMS", language: "en_US", });
await client.phoneNumbers.verifyCode({ phoneNumberId: "<PHONE_NUMBER_ID>", code: "123456", });
await client.phoneNumbers.register({ phoneNumberId: "<PHONE_NUMBER_ID>", pin: "000111", });
await client.phoneNumbers.settings.update({ phoneNumberId: "<PHONE_NUMBER_ID>", fallbackLanguage: "en_US", });
await client.phoneNumbers.businessProfile.update({ phoneNumberId: "<PHONE_NUMBER_ID>", about: "My Shop", websites: ["https://example.com"], });Webhooks
import express from "express";
import { normalizeWebhook, verifySignature } from "@kapso/whatsapp-cloud-api/server";
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
const ok = verifySignature({
appSecret: process.env.META_APP_SECRET!,
rawBody: req.body,
signatureHeader: req.headers["x-hub-signature-256"] as string,
});
if (!ok) return res.status(401).end();
const payload = JSON.parse(req.body.toString("utf8"));
const events = normalizeWebhook(payload);
events.messages.forEach((message) => {
// message matches the same shape returned by client.messages.query()
});
events.statuses.forEach((status) => {
// handle delivery receipts
});
events.calls.forEach((call) => {
// handle calling events
});
res.sendStatus(200);
});
// events.contacts contains the contact array from the webhook, already camelCasednormalizeWebhook() unwraps the raw Graph payload, returning { messages, statuses, calls, contacts } with camelCased fields so webhook events and history queries share the same Meta-compatible structure. Each normalized message also gets kapso.direction ("inbound"/"outbound") and SMB echoes are tagged with kapso.source = "smb_message_echo" so you can tell when the business initiated a message. All other webhook field payloads are exposed under events.raw.<fieldName> (camelCased), so you can react to updates like accountAlerts, templateCategoryUpdate, etc., without additional parsing.
Raw fetch helper
Use client.fetch(url, init?) to make a request to any absolute URL with the client’s auth headers applied. Only pass trusted URLs: this low-level method intentionally allows absolute destinations and caller-selected redirect behavior. Use redirect: "error" to prevent forwarding custom auth headers through redirects. Resource request() calls are confined to the configured API and reject redirects. Most users do not need this for media anymore because media.download() handles header policy automatically.
// Sends Authorization (Meta) or X-API-Key (Kapso) automatically
const response = await client.fetch("https://files.example/resource", { headers: { Accept: "image/*" }, });Typed responses
- All helpers return typed payloads (e.g.,
SendMessageResponse,MediaUploadResponse, etc.). - You can also call the low-level client with typing:
const response = await client.request<MyType>("GET", "<path>", { responseType: "json", });Error handling
When a response is not OK, the client throws an Error whose message includes the HTTP status and response text, e.g.:
Meta API request failed with status 400: {"error":{...}}Native call capture and BSUID permissions
Capture is optional on calls.connect and calls.accept. Meta plays a consent
announcement before capture starts. Supply a purpose of 1–250 characters in the
announcement language. Recording and transcription can be enabled independently;
omitting them keeps capture off, and DISABLED needs no purpose or language.
preAccept rejects capture keys, including for JavaScript callers.
import type { CallCaptureOptions } from "@kapso/whatsapp-cloud-api";
const capture: CallCaptureOptions = {
status: "ENABLED", purpose: "quality assurance", announcementLanguage: "en_US",
};
await client.calls.accept({
phoneNumberId, callId: "wacid.…", session: { sdpType: "answer", sdp },
recording: capture, transcription: capture,
});
await client.calls.permissions.get({ phoneNumberId, recipient: "US.13491208655302741918" });
// Alternatively pass userWaId (phone); exactly one identity is required.normalizeWebhook (from /server) collects all entries and changes, aliases Meta
id to callId, and preserves the original id and legacy wacid when present.
isCallArtifactEvent identifies call_recording_available,
call_transcription_available, and call_transcript_available; these late events
must not start another call. getCallArtifactKind maps both transcript spellings
to transcription (and recording to recording) without rewriting event.
Other events return undefined.
Their typed callRecording.audio and callTranscript.document include media
metadata. A BSUID-only event can omit from.
Kapso signatures and native call artifacts
Use verifyKapsoWebhookSignature for Kapso's bare-hex X-Webhook-Signature, using
the webhook secret and the original raw bytes. Use the existing verifySignature
for direct Meta X-Hub-Signature-256 headers (sha256=…).
Call history uses Meta callId (wacid.…); the app detail/artifact API uses
Kapso's local callUuid (calls.get(...).id). details returns camelized
{ data: { ...call, artifacts: { recording, transcription } } }. Each summary
has a state (absent, available, expired) and optional media metadata.
fetchArtifact returns the raw, unconsumed Response: recording is inline audio,
transcription is { data: preview } JSON, and download: true returns original
attachment bytes for either kind. Stream or parse that response as appropriate.
import { WhatsAppClient, GraphApiError } from "@kapso/whatsapp-cloud-api";
import { verifyKapsoWebhookSignature, normalizeWebhook, getCallArtifactKind } from "@kapso/whatsapp-cloud-api/server";
const client = new WhatsAppClient({ kapsoApiKey, baseUrl: "https://api.kapso.ai/meta/whatsapp" });
if (!verifyKapsoWebhookSignature({ secret: webhookSecret, rawBody, signatureHeader })) {
throw new Error("Invalid Kapso webhook signature");
}
const webhook = normalizeWebhook(JSON.parse(rawBody.toString("utf8")));
for (const event of webhook.calls) {
const kind = getCallArtifactKind(event);
if (!kind || !event.callId || !webhook.phoneNumberId) continue;
const call = await client.calls.get({ phoneNumberId: webhook.phoneNumberId, callId: event.callId });
if (!call) continue;
const { data: detail } = await client.calls.details({ callUuid: call.id });
if (detail.artifacts[kind].state !== "available") continue;
try {
const response = await client.calls.fetchArtifact({ callUuid: call.id, kind });
// Consume response.body for audio; await response.json() for transcript preview.
} catch (error) {
if (error instanceof GraphApiError && error.apiCode === "artifact_expired") continue;
throw error;
}
}These helpers send only X-API-Key to https://app.kapso.ai/api/v1; a Meta-token-only
client fails before fetch. Custom proxy deployments must set kapsoAppBaseUrl to
their trusted HTTPS app origin (no path). Meta bearer tokens are never attached to
app requests and redirects are rejected to keep the key on that origin. Helpers
construct fixed paths rather than using webhook URLs or summary fetchPath.
They neither archive artifacts nor send Range headers. Backend errors preserve
the numeric GraphApiError.code/httpStatus and expose structured codes (such as
artifact_expired, artifact_unavailable, artifact_too_large,
artifact_invalid_transcript, artifact_download_failed) as apiCode.
Tests use offline fixtures and packed builds. They verify protocol and package behavior; they do not prove production availability or native handset capture.
License
MIT
Upgrading to 0.4.0
This release combines the call-artifact and voice-call features in CHANGELOG.md with resource/media and native Flow changes. Resource paths are confined to the configured API/version; media IDs cannot be URLs or paths, and resource requests/media downloads reject redirects. Byte/Blob download HTTP errors now throw; as: "response" remains raw. Deliberate low-level client.fetch / client.rawFetch absolute-URL behavior remains available only for trusted destinations.
Native Flow handlers must forward the original raw body and headers, configure appSecret and the matching RSA private key, and provide verifyToken for business actions. Pass the original returned context to respondToFlow once. Authorize ctx.action before business effects and enforce replay/idempotency in your own session store. Trusted pre-decrypted adapters explicitly use inputFormat: "decrypted". See the packaged Flow guide for examples and error statuses.
