How to Build a WhatsApp AI Agent with the Meta Cloud API
By Prashant Sharda ·
A WhatsApp AI agent is software that receives a customer's WhatsApp message, works out what they need, looks things up or takes an action in your systems, and replies. The Meta Cloud API is the official way to connect it to WhatsApp. This guide covers the build end to end: the account setup, the webhook, the reply loop and the rules that keep it safe. The technical steps below were checked against Meta's WhatsApp Business Platform documentation, which changes often, so confirm field names and the API version there before you ship.
If you would rather have it built than build it, see how I build WhatsApp AI agents for businesses. If you want to see one working first, try the WhatsApp AI agent demo.
What you are building
Six parts, in the order a message travels:
- The customer sends a WhatsApp message to your business number.
- Meta's Cloud API receives it and sends a webhook (an HTTP request with JSON) to your server.
- Your webhook checks the request is genuinely from Meta, ignores duplicates and answers quickly.
- A queue holds one job per customer message, so a slow AI call never blocks the webhook.
- The agent worker reads the conversation, calls the AI model, uses tools such as your CRM or order system, and decides the reply.
- The Messages API delivers the reply, and anything the agent should not handle goes to a person.
The reason for the queue is simple. Meta expects your webhook to return a 200 status. If it does not, Meta retries delivery with decreasing frequency for up to seven days, which can produce duplicate notifications. Answer fast, do the AI work afterwards.
WhatsApp AI agent vs WhatsApp chatbot
A traditional WhatsApp chatbot follows a fixed menu or script: reply 1 for pricing, 2 for support. A WhatsApp AI chatbot uses a language model to understand free-text messages and answer from your business information. A WhatsApp AI agent goes one step further: it can use tools, such as looking up an order, checking a calendar or writing to a CRM, and it decides when to hand the conversation to a person.
WhatsApp automation is the wider term for anything sent or answered without someone typing it, including template messages and campaigns. This guide builds the agent version directly on the Meta Cloud API.
Step 1: Set up the Meta side
- In the Meta App Dashboard, click Create App and choose the use case for connecting with customers through WhatsApp. Pick an existing business portfolio or create one.
- Open API Setup. Meta creates a test WhatsApp number for you to begin with.
- Add your own WhatsApp number as a recipient, and send the first test message from the dashboard.
- Note two IDs for later: your phone number ID (used in every send request) and your messaging account ID.
- For anything beyond a quick test, do not use the temporary access token, which expires fast. In Business Settings, create a system user, assign your app and your WhatsApp account to it, and generate a permanent token.
- Production needs the
whatsapp_business_messagingpermission, which goes through App Review, andwhatsapp_business_managementfor the other webhook types.
Keep the token, the app secret and the verify token in environment variables on your server. Never put them in front-end code or a public repository.
Step 2: Build the webhook endpoint
Your endpoint has two jobs.
Verification (GET, once). When you save the callback URL in the dashboard, Meta sends a GET request with three query parameters: hub.mode (always subscribe), hub.verify_token and hub.challenge. If the token matches the one you chose, reply with 200 and the hub.challenge value as the body.
Events (POST, every time). Meta sends a JSON payload and signs it. The signature is in the X-Hub-Signature-256 header as sha256= followed by an HMAC-SHA256 of the raw request body, using your app secret as the key. Compute it yourself and compare. Use the raw bytes, not re-serialised JSON, or the check will fail.
Here is a minimal Node.js (Express) version. It is a starting point, not production code.
import express from "express";
import crypto from "node:crypto";
const app = express();
const { VERIFY_TOKEN, APP_SECRET } = process.env;
// Keep the raw body: the signature is computed over the exact bytes.
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));
// 1) One-time verification handshake
app.get("/webhook", (req, res) => {
if (req.query["hub.mode"] === "subscribe" &&
req.query["hub.verify_token"] === VERIFY_TOKEN) {
return res.status(200).send(req.query["hub.challenge"]);
}
res.sendStatus(403);
});
// 2) Incoming events
app.post("/webhook", (req, res) => {
const sent = (req.get("x-hub-signature-256") || "").replace("sha256=", "");
const expected = crypto.createHmac("sha256", APP_SECRET)
.update(req.rawBody).digest("hex");
const ok = sent.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(expected));
if (!ok) return res.sendStatus(403);
res.sendStatus(200); // answer first, work afterwards
const value = req.body?.entry?.[0]?.changes?.[0]?.value;
for (const msg of value?.messages ?? []) {
enqueue({ id: msg.id, from: msg.from, type: msg.type,
text: msg.text?.body, phoneNumberId: value.metadata.phone_number_id });
}
});
Three details that trip people up:
- The payload is nested. Messages live at
entry[].changes[].value.messages[]. Each message hasfrom,id,timestamp,typeand a type-specific object such astext.body. Thevalue.metadata.phone_number_idtells you which of your numbers received it. - Status updates arrive on the same webhook. Delivery and read updates come as
statuses, notmessages. Handle both or ignore statuses explicitly. - Your app may need to be in Live mode before some webhooks are delivered. If nothing arrives, check this and use the dashboard's test payload button.
Then, in the dashboard under the WhatsApp configuration, paste your public HTTPS callback URL and verify token, and subscribe to the messages field.
Step 3: Make the webhook safe to repeat
Because Meta can deliver the same event more than once, store each message id the first time you see it and skip it afterwards. A small table or a Redis set with an expiry is enough. Without this, a retry can make your agent answer the same customer twice.
Step 4: The agent loop
The worker takes one queued message and runs the loop below. The details of the AI model are up to you; the structure is what matters.
- Load context. Pull the last several turns for this phone number, plus anything you already know about the customer.
- Call the model with a system prompt that states the job, the tone, what it may do and what it may not.
- Let it use tools. Give the model a short list of functions it can request, for example
lookup_order,check_slot,create_lead,book_visit. Your code runs them and returns the result. Keep each tool narrow and validate every input. - Check the answer before it goes out: length, language, no promises you do not allow, no data that belongs to a different customer.
- Send the reply, or hand off to a person.
async function handle(job) {
const history = await loadHistory(job.from);
const result = await runAgent({
system: SYSTEM_PROMPT, // role, tone, limits, when to hand off
history,
message: job.text,
tools: { lookup_order, check_slot, create_lead },
});
if (result.handoff) return routeToPerson(job, result.reason);
await sendText(job.phoneNumberId, job.from, result.reply);
await saveTurn(job.from, job.text, result.reply);
}
Sending the reply
Every send is a POST to the Messages API on your phone number ID, with your access token as a bearer token. Use the current API version shown in Meta's documentation.
async function sendText(phoneNumberId, to, body) {
const url = `https://graph.facebook.com/${process.env.API_VERSION}/${phoneNumberId}/messages`;
const r = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.WA_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
messaging_product: "whatsapp",
to,
type: "text",
text: { body },
}),
});
if (!r.ok) throw new Error(`WhatsApp send failed: ${r.status}`);
}
A text message can be up to 4,096 characters, but short replies read better on a phone. Ask the model for two or three sentences.
Step 5: Respect the 24-hour rule
This rule decides what your agent is allowed to send, and it is where many first builds break.
- When a customer messages you, a 24-hour customer service window opens. Each new message from them resets the timer.
- While it is open you can send free-form messages: text, media and interactive messages.
- When it closes, you can only send pre-approved template messages.
- You can only message people who have opted in to hear from you.
For an agent this means: replies to inbound questions are simple. Anything you start yourself, such as a follow-up after a quiet day, needs an approved template once the window is shut. Build the check into sendText: if the last customer message is older than 24 hours, switch to a template or do not send.
Step 6: Decide what the agent must not do
An agent that answers every message is not the goal. An agent that answers the right ones, and passes the rest to a person, is. Put these in the system prompt and again in code:
- It does not invent prices, availability or policies. If a tool does not return the fact, it says it will check and hands off.
- It does not change or cancel anything above a limit you set without a person approving it.
- It hands off on anger, complaints, refunds, legal or medical questions, or after two failed attempts to understand.
- It tells the customer when a person is taking over, and the person sees the full conversation.
This is the same approach as human-in-the-loop AI agent approvals.
Step 7: Test before you point customers at it
- Run the webhook locally behind a tunnel and send messages from your own number.
- Replay a saved payload twice to confirm deduplication works.
- Send a message with a wrong signature and confirm you get a 403.
- Write twenty real questions from your own inbox, including awkward ones, and read every answer.
- Test the handoff path: does a person actually get the conversation?
- Test the 24-hour edge: what does the agent do on day two?
Example flow (illustrative)
This is an illustrative conversation for a clinic, not a client result. The agent has one tool, check_slot.
| Who | Message | What happens behind it |
|---|---|---|
| Customer | "Can I see Dr. Mehta on Saturday?" | Webhook, signature check, queued |
| Agent | Calls check_slot for Saturday |
Returns two open times |
| Agent | "Saturday has 11:00 or 12:30. Which suits you?" | Sent through the Messages API |
| Customer | "12:30. Is it painful?" | Medical question detected |
| Agent | Books 12:30, then hands the medical question to staff | Staff see the full chat |
The agent handled the booking and recognised what it should not answer. You can try the same pattern in the WhatsApp AI agent demo.

The agent console from the clinic example in the demo (all names and details in it are fictional). Each line is a tool call the agent made; the handoff line is the rule from Step 6 at work.
Common mistakes
- Doing the AI call inside the webhook. The request times out and Meta retries. Queue it.
- Skipping signature verification. Anyone who finds your URL can then make your agent talk.
- Parsing re-serialised JSON for the signature. Use the raw body.
- Ignoring status webhooks. They are how you learn a message failed.
- Using the temporary token in production. It expires. Use a system user token.
- No deduplication. Retries become double replies.
- Starting conversations without a template. Outside the 24-hour window the message will not send.
If you sell real estate
Real estate is one of the businesses where WhatsApp matters most, because buyers ask about projects, prices and site visits there. Rather than building this from scratch, real estate teams can use propai Agents, which I built for brokers and developers. It creates branded AI avatars for real estate sales that engage buyers on WhatsApp, qualify leads, recommend properties and automate site visits. You can get started here. Everything in this guide still applies if you want to build your own.
Build it or have it built
The plumbing above is the easy part. The harder work comes after: the prompts, the tools that connect to your CRM or order system, the handoff rules and the review of real conversations. If you want that done for your business, I cover it on the WhatsApp AI agent page. For the wider picture of what to automate and what to keep with a person, read WhatsApp automation for business, and for the account side, the WhatsApp Business API explained for Indian businesses.
FAQ
Do I need a WhatsApp Business API provider, or can I use the Cloud API directly?
You can use the Cloud API directly through a Meta developer app, as in this guide. A provider adds a dashboard and support on top. The choice depends on whether you want to run the integration yourself.
Can an AI chatbot run on the WhatsApp Cloud API?
Yes. You send and receive messages through the API, and what generates the replies is your own software. Check Meta's current policy on automated and AI messaging for your use case before launch.
What is the 24-hour window?
It is the period after a customer's last message during which you can send free-form replies. After it closes, you can only send approved template messages.
Do I need a server?
Yes. Meta needs a public HTTPS URL it can send webhooks to, so you need a server or a serverless function that stays reachable.
How do I stop the agent giving wrong answers?
Give it tools to look facts up instead of letting it guess, state its limits in the prompt, check answers in code before sending, and hand off whenever it is unsure.
Can the same agent also sync with my CRM?
Yes. Treat the CRM as a tool the agent can call. Keep each call narrow, such as create lead or update status, and log every action.
Want a WhatsApp AI agent for your business?
I build WhatsApp AI agents that answer, book and hand off to your team. See how we work together, or book a free 30-minute call.