Webhooks
Receiving events
wapi-cloud provides HMAC-SHA256 signature verification, webhook challenge handshakes, normalized event parsing, and event dispatcher utilities for Express, Next.js, and Fastify.
1. Express One-Liner (handleExpress)
For Express servers, whatsapp.webhooks.handleExpress automatically wires up both the GET verification challenge and the POST signature verification/event dispatcher in a single call:
import express from "express";
import { Whatsapp } from "wapi-cloud";
const app = express();
const whatsapp = new Whatsapp({
accessToken: process.env.WA_TOKEN!,
phoneNumberId: process.env.WA_PHONE_ID!,
appSecret: process.env.WA_APP_SECRET!,
});
// Setup webhook route and verifyToken challenge
whatsapp.webhooks.handleExpress(app, "/webhook", {
verifyToken: process.env.WA_VERIFY_TOKEN!,
});
// Listen for incoming customer messages
whatsapp.webhooks.on("message", async (msg) => {
if (msg.messageType === "text") {
console.log("Received text from " + msg.sender + ": " + msg.text.body);
// msg.sender is the phone number, or the BSUID for username users
await whatsapp.messages.sendText(msg.sender, {
body: "Echo: " + msg.text.body,
});
} else if (msg.messageType === "image") {
console.log("Received photo from " + msg.sender + ", mediaId: " + msg.image.id);
}
});
// Listen for delivery status updates (sent, delivered, read, failed)
whatsapp.webhooks.on("status", (status) => {
console.log("Message " + status.messageId + " to " + (status.recipientId ?? status.recipientUserId) + ": " + status.status);
});
// Listen for template approval or rejection updates
whatsapp.webhooks.on("template_status_update", (t) => {
console.log("Template " + t.messageTemplateName + " updated to " + t.event);
});
app.listen(3000, () => console.log("Server listening on :3000"));2. Next.js App Router (Route Handler)
In modern Next.js applications (App Router app/api/webhook/route.ts), use verifyHandshake and verifySignature:
import { whatsapp } from "@/lib/whatsapp";
// 1. GET: Webhook verification challenge
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
try {
const challenge = whatsapp.webhooks.verifyHandshake({
mode: searchParams.get("hub.mode"),
token: searchParams.get("hub.verify_token"),
challenge: searchParams.get("hub.challenge"),
expectedToken: process.env.WA_VERIFY_TOKEN!,
});
return new Response(challenge, { status: 200 });
} catch {
return new Response("Forbidden", { status: 403 });
}
}
// 2. POST: Inbound messages and status receipts
export async function POST(req: Request) {
const rawBody = await req.text();
const signatureHeader = req.headers.get("x-hub-signature-256") ?? undefined;
// Verify HMAC-SHA256 signature
const isValid = whatsapp.webhooks.verifySignature({
payload: rawBody,
signatureHeader,
});
if (!isValid) {
return new Response("Invalid signature", { status: 401 });
}
// Parse events into strongly-typed array
const events = whatsapp.webhooks.parse(JSON.parse(rawBody));
for (const event of events) {
if (event.type === "message" && event.messageType === "text") {
await whatsapp.messages.sendText(event.sender, {
body: "Hello! Received: " + event.text.body,
});
}
}
return new Response("OK", { status: 200 });
}3. Manual Express Handler
// Mount express.raw on the webhook path to preserve unmodified byte payload for HMAC
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
const isValid = whatsapp.webhooks.verifySignature({
payload: req.body,
signatureHeader: req.headers["x-hub-signature-256"],
});
if (!isValid) return res.sendStatus(401);
const json = JSON.parse(req.body.toString("utf-8"));
const events = whatsapp.webhooks.parse(json);
for (const event of events) {
if (event.type === "message") {
console.log("Inbound message from:", event.sender);
}
}
res.sendStatus(200);
});Event Types
| Parameter | Type | Description |
|---|---|---|
| message | InboundMessageEvent | Inbound message from a user. Discriminated by messageType: 'text' | 'image' | 'video' | 'audio' | 'document' | 'sticker' | 'location' | 'contacts' | 'interactive' | 'button' | 'reaction' | 'order' | 'system' | 'request_welcome' | 'unsupported' | 'unknown'. |
| status | MessageStatusEvent | Delivery receipt for an outbound message: 'sent' | 'delivered' | 'read' | 'failed' | 'deleted' | 'warning'. Includes pricing, conversation, your bizOpaqueCallbackData, and errors if failed. |
| template_status_update | TemplateStatusUpdateEvent | Notification that a message template was APPROVED, REJECTED, PAUSED, or DISABLED by Meta. |
| call (1.1.0) | CallEvent | Calling API webhook: inbound call connect (with the SDP offer in session), terminate, and status updates. Pass the offer to your WebRTC stack, then call whatsapp.calls.accept. |
| group_update (1.1.0) | GroupUpdateEvent | Groups API webhooks: group_lifecycle_update, group_settings_update, group_participants_update and group_status_update. This is where the ID and invite link of a newly created group arrive. |
| account_alert | AccountAlertEvent | System alerts regarding WABA health, such as phone_number_quality_update and account_update. |
| unknown_field (1.1.0) | UnknownFieldEvent | A webhook field the SDK has no typed event for yet. Previously these were emitted as account_alert. |
Identifying the sender: sender, userId and username
Users who adopt a WhatsApp username may not expose a phone number, so from on inbound messages and recipientId on statuses are now optional. Every inbound message carries sender, the best identifier to reply to (the phone number if present, otherwise the BSUID). The other identity fields are userId, parentUserId, username and profileName.
Richer parsed messages
contextfor replies, forwards and product inquiries, andreferralfor Click-to-WhatsApp ads.- Interactive replies normalised into
msg.reply:button_reply,list_replyandnfm_reply(with the Flow's parsedresponseJson). order,systemandunsupportedmessages, and on statusespricing,conversationandbizOpaqueCallbackData.
whatsapp.webhooks.on("message", async (msg) => {
if (msg.messageType === "interactive" && msg.reply.kind === "button_reply") {
console.log("Clicked:", msg.reply.id, msg.reply.title);
}
if (msg.messageType === "order") {
console.log("Order from catalog", msg.order.catalogId, msg.order.productItems);
}
});
whatsapp.webhooks.on("call", async (call) => {
if (call.event === "connect" && call.session) {
// create your WebRTC answer, then:
// await whatsapp.calls.accept(call.callId, { sdpType: "answer", sdp: answer });
}
});
whatsapp.webhooks.on("group_update", (e) => console.log(e.field, e.value));Listener errors and handleExpress behaviour
handleExpressnow sends the200response before running listeners and isolates listener errors, so a throwing handler can no longer trigger Meta retries.- If the body is not raw (
express.json()ran first),handleExpressreturns400and logs a message. Mountexpress.rawon the webhook path. verifySignaturereturnsfalsefor non-raw payloads instead of throwing, and the verify-token check is timing-safe.
// Called whenever a listener throws or rejects
whatsapp.webhooks.onListenerError = (err, event) => {
console.error("Listener failed for", event.type, err);
};