WhatsApp AI chatbot: build and test the webhook
AI Techbom · Automation · · 8 min read
The WhatsApp Cloud API sends every message your business number receives to a webhook: a URL on your server. A WhatsApp AI chatbot is that webhook plus a model: it checks the request really came from Meta, reads the message, writes a reply from your own information and sends it back through the API. This tutorial builds the whole webhook and tests it locally with requests in the same format Meta sends.
Tested on 21 November 2026 with Node.js 26, tsx 4 and a local model (qwen2.5:3b through Ollama 0.40.16). The code type-checks with TypeScript 5 in strict mode. Sending was run in dry-run mode, which prints the message instead of posting it: sending for real needs a WhatsApp Business account, and we did not test against Meta's servers. The request formats and Graph API version (v27.0) follow Meta's developer documentation on that date.
What you need to go live
- A Meta developer app with the WhatsApp product, a WhatsApp Business Account and a business phone number.
- The phone number ID and an access token, for sending messages.
- The app secret, for checking webhook signatures.
- A verify token: any string you choose, entered in the App Dashboard and on your server.
- A public HTTPS URL for the webhook.
Free-form replies like these can be sent inside the 24-hour customer service window that opens when a customer messages you. Outside it, WhatsApp requires an approved message template.
1. The webhook
It uses only Node's built-in modules. FACTS is the information the bot may answer from; in production it would come from your own records.
// A WhatsApp AI chatbot webhook for the WhatsApp Cloud API.
// GET verifies the webhook; POST checks Meta's signature, reads the message,
// asks a model for a reply grounded in your facts, and sends it back.
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";
const VERIFY_TOKEN = process.env.VERIFY_TOKEN ?? "";
const APP_SECRET = process.env.APP_SECRET ?? "";
const ACCESS_TOKEN = process.env.ACCESS_TOKEN ?? "";
const DRY_RUN = process.env.DRY_RUN === "1"; // log the reply instead of sending it
const GRAPH_VERSION = "v27.0";
const FACTS = `Opening hours: 9 am to 11 pm every day.
Delivery: within 10 km of the shop; orders before 2 pm arrive the same day.
Returns: unopened items within 7 days with the receipt.`;
function signatureIsValid(rawBody: Buffer, header: string | undefined): boolean {
if (!header?.startsWith("sha256=")) return false;
const expected = createHmac("sha256", APP_SECRET).update(rawBody).digest();
const received = Buffer.from(header.slice("sha256=".length), "hex");
return received.length === expected.length && timingSafeEqual(received, expected);
}
async function writeReply(question: string): Promise<string> {
const response = await fetch("http://localhost:11434/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "qwen2.5:3b",
stream: false,
options: { temperature: 0 },
messages: [
{
role: "system",
content: `You answer WhatsApp messages for a shop. Reply in one or two short sentences, using only these facts:\n${FACTS}\nIf the facts do not answer the question, say a team member will reply soon.`,
},
{ role: "user", content: question },
],
}),
});
const data = (await response.json()) as { message: { content: string } };
return data.message.content.trim();
}
async function sendText(phoneNumberId: string, to: string, body: string, replyTo: string) {
const payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to,
type: "text",
context: { message_id: replyTo },
text: { body },
};
if (DRY_RUN) {
console.log("would send:", JSON.stringify(payload));
return;
}
const response = await fetch(`https://graph.facebook.com/${GRAPH_VERSION}/${phoneNumberId}/messages`, {
method: "POST",
headers: { Authorization: `Bearer ${ACCESS_TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) console.error("send failed:", response.status, await response.text());
}
type WebhookBody = {
entry?: {
changes?: {
value?: {
metadata?: { phone_number_id: string };
messages?: { from: string; id: string; type: string; text?: { body: string } }[];
};
}[];
}[];
};
async function handleMessages(body: WebhookBody) {
for (const entry of body.entry ?? []) {
for (const change of entry.changes ?? []) {
const phoneNumberId = change.value?.metadata?.phone_number_id;
for (const message of change.value?.messages ?? []) {
if (!phoneNumberId || message.type !== "text" || !message.text) continue;
console.log(`message from ${message.from}: ${message.text.body}`);
const reply = await writeReply(message.text.body);
await sendText(phoneNumberId, message.from, reply, message.id);
}
}
}
}
const server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
if (url.pathname !== "/webhook") return res.writeHead(404).end();
if (req.method === "GET") {
const ok =
url.searchParams.get("hub.mode") === "subscribe" && url.searchParams.get("hub.verify_token") === VERIFY_TOKEN;
return ok ? res.writeHead(200).end(url.searchParams.get("hub.challenge")) : res.writeHead(403).end();
}
if (req.method === "POST") {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => {
const rawBody = Buffer.concat(chunks);
if (!signatureIsValid(rawBody, req.headers["x-hub-signature-256"] as string | undefined)) {
console.log("rejected: bad signature");
return res.writeHead(401).end();
}
res.writeHead(200).end(); // acknowledge first; Meta retries slow or failed deliveries
handleMessages(JSON.parse(rawBody.toString("utf8"))).catch((error) => console.error(error));
});
return;
}
res.writeHead(405).end();
});
server.listen(3000, () => console.log("webhook listening on http://localhost:3000/webhook"));2. How it works
- GET is Meta's one-time verification: if the verify token matches, the server echoes the challenge back.
- POST requests carry an X-Hub-Signature-256 header: an HMAC-SHA256 of the raw body using your app secret. The server recomputes it and compares in constant time, so a forged request is rejected before anything else happens.
- The server answers 200 straight away and handles the message afterwards, so a slow model does not make the delivery look failed.
- The model may answer only from FACTS, and is told to promise a human reply when the facts do not cover the question.
- The reply is sent with context.message_id, so it appears in WhatsApp as a reply to the customer's message.
3. Test it locally
This script sends what Meta would send: two verification requests, a signed message and the same message with a forged signature.
// Sends the requests Meta would send, so the webhook can be tested locally.
import { createHmac } from "node:crypto";
const BASE = "http://localhost:3000/webhook";
const APP_SECRET = process.env.APP_SECRET ?? "";
const verify = await fetch(`${BASE}?hub.mode=subscribe&hub.verify_token=${process.env.VERIFY_TOKEN}&hub.challenge=1158201444`);
console.log("verify, right token:", verify.status, await verify.text());
const wrong = await fetch(`${BASE}?hub.mode=subscribe&hub.verify_token=wrong&hub.challenge=1`);
console.log("verify, wrong token:", wrong.status);
// The shape of a real "messages" webhook, with sample IDs.
const body = JSON.stringify({
object: "whatsapp_business_account",
entry: [{
id: "102290129340398",
changes: [{
field: "messages",
value: {
messaging_product: "whatsapp",
metadata: { display_phone_number: "15550783881", phone_number_id: "106540352242922" },
messages: [{ from: "16505551234", id: "wamid.TEST1", timestamp: "1763700000", type: "text", text: { body: "Do you deliver today if I order now at 1 pm?" } }],
},
}],
}],
});
const signature = "sha256=" + createHmac("sha256", APP_SECRET).update(body).digest("hex");
const signed = await fetch(BASE, { method: "POST", headers: { "Content-Type": "application/json", "X-Hub-Signature-256": signature }, body });
console.log("message, valid signature:", signed.status);
const forged = await fetch(BASE, { method: "POST", headers: { "Content-Type": "application/json", "X-Hub-Signature-256": "sha256=" + "0".repeat(64) }, body });
console.log("message, forged signature:", forged.status);Start the webhook in one terminal and run the test in another (in PowerShell, set each variable with $env:NAME = "value" first):
VERIFY_TOKEN=my-verify-token APP_SECRET=test-app-secret DRY_RUN=1 npx tsx bot.ts
VERIFY_TOKEN=my-verify-token APP_SECRET=test-app-secret npx tsx test.tsThe test printed:
verify, right token: 200 1158201444
verify, wrong token: 403
message, valid signature: 200
message, forged signature: 401And the webhook logged:
webhook listening on http://localhost:3000/webhook
message from 16505551234: Do you deliver today if I order now at 1 pm?
rejected: bad signature
would send: {"messaging_product":"whatsapp","recipient_type":"individual","to":"16505551234","type":"text","context":{"message_id":"wamid.TEST1"},"text":{"body":"Yes, orders placed before 2 pm will arrive the same day. You can place your order now."}}The forged request was rejected with 401 and never reached the model. The signed one was answered from the facts: the customer ordering at 1 pm was told it would arrive the same day, because orders before 2 pm do. The last line is the exact request body the bot would post to the Cloud API.
4. Going live
- Deploy the webhook behind HTTPS, set VERIFY_TOKEN, APP_SECRET and ACCESS_TOKEN, and leave DRY_RUN unset.
- In the App Dashboard, open WhatsApp, then Configuration, enter the callback URL and verify token, and subscribe to the messages field.
- Store each message ID you have handled and skip repeats, so a re-delivered webhook does not get a second reply.
- Hand a conversation to a person when the bot cannot answer, and keep a record of every reply sent.
- Send media, voice notes and anything unexpected to a person until the bot is built to handle them.
Want a WhatsApp chatbot built for your business number? AI chatbot development