Building a WhatsApp AI chatbot for your business
How to build an AI chatbot on the WhatsApp Business Platform: Cloud API setup, webhooks, the 24-hour customer service window, message templates, opt-in rules and handoff to humans.
Codestria Engineering
Engineering team
For many businesses, WhatsApp is where customers already are. They would rather send a quick message than fill in a form or wait on hold. That makes it an obvious place for an AI assistant that answers questions, checks order status, books appointments and passes difficult conversations to a person.
It is also a platform with rules that a website chatbot does not have: who you can message, when, with what content and with what consent. Most of the work in a good WhatsApp bot is respecting those rules while keeping the conversation natural. This guide covers the architecture and the platform constraints you need to design around.
The building blocks
Automated WhatsApp messaging runs on the WhatsApp Business Platform. You can use Meta's Cloud API, which Meta hosts, or go through a Business Solution Provider that wraps it with extra tooling. Either way you will need a Meta business account, a phone number registered to the platform and a verified business for higher messaging limits.
A typical bot has five parts:
- A webhook endpoint that receives incoming messages and status updates from Meta.
- A conversation store holding history, customer identity and whether a human currently owns the chat.
- The AI layer: a model with your knowledge base and a small set of tools, such as order lookup or booking.
- A sender that calls the Cloud API to reply with text, media, buttons or templates.
- A handoff path into the tool your team already uses for support.
Receiving messages with webhooks
When you register your webhook, Meta sends a GET request with a verify token and a challenge; you echo the challenge if the token matches. After that, messages arrive as POST requests. Verify the X-Hub-Signature-256 header against your app secret so nobody else can post fake messages to your bot, respond quickly with 200, and do the slow AI work in a background job. Meta retries deliveries, so make processing idempotent using the message ID.
import crypto from "node:crypto";
import { enqueue } from "@/lib/queue";
export async function GET(req: Request) {
const url = new URL(req.url);
const ok =
url.searchParams.get("hub.mode") === "subscribe" &&
url.searchParams.get("hub.verify_token") === process.env.WA_VERIFY_TOKEN;
return ok
? new Response(url.searchParams.get("hub.challenge"))
: new Response("Forbidden", { status: 403 });
}
export async function POST(req: Request) {
const raw = await req.text();
const expected =
"sha256=" +
crypto.createHmac("sha256", process.env.WA_APP_SECRET!).update(raw).digest("hex");
const given = req.headers.get("x-hub-signature-256") ?? "";
if (
given.length !== expected.length ||
!crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected))
) {
return new Response("Invalid signature", { status: 401 });
}
const body = JSON.parse(raw);
for (const entry of body.entry ?? []) {
for (const change of entry.changes ?? []) {
for (const msg of change.value?.messages ?? []) {
// Dedupe on msg.id inside the job; Meta may deliver the same message twice.
await enqueue("whatsapp-inbound", { id: msg.id, from: msg.from, message: msg });
}
}
}
return new Response("OK");
}The 24-hour window and message templates
This is the rule that shapes everything. When a customer messages you, a 24-hour customer service window opens. Inside it, your bot can send free-form replies: any text, media or interactive buttons. Each new message from the customer resets the window. Once it closes, you can only reach that customer with a message template: a pre-written message, submitted to Meta for approval, with placeholders for variables such as a name or order number.
Templates are grouped into categories, such as utility (order updates, appointment reminders), authentication (one-time codes) and marketing, and are reviewed and priced differently. In practice, design your bot so that anything proactive, like a shipping notification or a follow-up the next day, uses an approved utility template, and keep conversational AI replies inside the window. Your sender should check when the last inbound message arrived and refuse to send free-form text after the window closes.
const GRAPH = `https://graph.facebook.com/${process.env.WA_GRAPH_VERSION}`;
async function send(payload: Record<string, unknown>) {
const res = await fetch(`${GRAPH}/${process.env.WA_PHONE_NUMBER_ID}/messages`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.WA_ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ messaging_product: "whatsapp", ...payload }),
});
if (!res.ok) throw new Error(`WhatsApp send failed: ${res.status} ${await res.text()}`);
return res.json();
}
export function sendText(to: string, body: string, lastInboundAt: Date) {
const windowOpen = Date.now() - lastInboundAt.getTime() < 24 * 60 * 60 * 1000;
if (!windowOpen) throw new Error("Service window closed: use an approved template");
return send({ to, type: "text", text: { body } });
}
export function sendTemplate(to: string, name: string, lang: string, params: string[]) {
return send({
to,
type: "template",
template: {
name,
language: { code: lang },
components: [{ type: "body", parameters: params.map((text) => ({ type: "text", text })) }],
},
});
}Opt-in, policy and the AI layer
Before sending a business-initiated message, you need the person's opt-in to receive WhatsApp messages from your business. Collect it clearly, for example a checkbox at checkout or a sign-up form that names WhatsApp, record when and how it was given, and honour opt-out requests promptly. Meta's Business and Commerce policies also restrict certain products and content, and they evolve, so review the current versions before launch.
For the AI itself, keep the scope tight. A WhatsApp assistant works best with a focused knowledge base and a handful of tools that act only on the customer identified by their phone number, never on IDs typed into the chat. Keep replies short; long paragraphs read badly on a phone. Use interactive buttons and lists for common choices. Ground answers in your own content so the bot does not invent policies, and make it say plainly when it does not know.
Handoff to humans
The handoff is what separates a helpful bot from an annoying one. Escalate when the customer asks for a person, when the topic is sensitive (complaints, refunds above a limit, account security), when the model abstains or when the same question has looped twice. On handoff, set a flag on the conversation so the bot stops replying, create a ticket or route the chat into your support inbox with the history and a short AI summary, and tell the customer what happens next and roughly when.
Remember the 24-hour window applies to your agents too. If a human picks up the conversation after it closes, they will need a template to restart it. Shared inbox tools built on the WhatsApp platform handle this for you; if you build your own, design for it.
Testing and going live
Meta provides a test phone number and a sandbox setup so you can develop without touching production. Use it to run through real conversations end to end: greetings, questions the knowledge base covers, questions it does not, requests for a human, media messages your bot does not support and customers who come back after the window has closed. Log every inbound and outbound message with its status updates (sent, delivered, read, failed), because failed sends are how you discover expired tokens, unapproved templates or numbers that are not on WhatsApp.
Start with a limited scope, such as order status and opening hours, and expand once you have reviewed real transcripts. Transcripts are the best source of new knowledge base content and new eval cases, and they show quickly where customers get stuck.
Key takeaways
- Build on the WhatsApp Business Platform via the Cloud API or a provider, not the Business app.
- Verify webhook signatures, acknowledge fast, process in the background and dedupe on message ID.
- Free-form replies only within the 24-hour window; use approved templates for everything proactive.
- Collect and record opt-in, honour opt-outs and check Meta's current policies and pricing.
- Keep the AI focused and grounded, and make handoff to a human quick, clear and complete.
We build WhatsApp and web assistants connected to the systems you already use. See our AI automations service or get in touch to plan yours.
Frequently asked questions
Do I need the WhatsApp Business app or the API for an AI chatbot?
The API. The WhatsApp Business app is designed for manual use on a phone. Automated bots run on the WhatsApp Business Platform, either through Meta's Cloud API directly or through a Business Solution Provider.
Can my chatbot message customers first?
Only with an approved message template, and only to people who have opted in to receive messages from you. Free-form replies are allowed within 24 hours of the customer's last message.
How is WhatsApp Business messaging priced?
Meta charges for certain message types, mainly templates, with rates that vary by category and country and that have changed over time. Check Meta's current pricing page rather than relying on older figures.
Need help with ai automations?
Replace repetitive manual work with AI-powered workflows across the tools you already use.