Updated on October 29, 2026
To connect a chatbot or AI agent to WhatsApp through the official API, you receive each message by webhook, return 200 right away, put the event in a queue and let a worker build the context, call the language model and send the reply through the API. The bot’s free-form replies can only go out inside the 24-hour window the customer opened, and Meta’s policy requires a clear path to a human agent. Meta’s terms also prohibit using the platform to offer general-purpose AI assistants as the main product, with exceptions in a few countries, Brazil among them.
This guide shows the architecture, the rules that affect the bot and a working Node.js example using Vectalk, which passes through the same payloads and webhooks as Meta.
Architecture: webhook, queue, LLM and reply
Customer on WhatsApp
│
▼
Meta ──POST──▶ Vectalk ──POST──▶ /webhook (returns 200 and enqueues)
│
▼
Queue
│
▼
Worker: dedupe ▶ load history ▶ decide (bot or human)
│
┌───────────┴───────────┐
▼ ▼
LLM writes reply Human agent
│
▼
POST /api/messages (Vectalk) ──▶ Meta ──▶ Customer
Each piece has a clear job:
| Component | Responsibility | Main concern |
|---|---|---|
| Webhook | Receive the event, validate it and return 200 | Don’t call the LLM inside the request |
| Queue | Decouple receiving from processing | Guarantee a retry if the worker crashes |
| Deduplication | Ignore repeated events by their wamid ID | Keep processed IDs for a few days |
| History | Build the conversation context by wa_id | Cap the size to control cost and latency |
| Router | Decide whether the bot replies or the conversation is with a human | Respect the handoff state |
| LLM | Generate the reply within the business scope | A prompt with clear limits and a maximum response time |
| Sending | Call the API and store the sent message ID | Handle errors and check the 24-hour window |
Why the queue is mandatory
A language model can take several seconds to answer. Vectalk expects HTTP 200 in under 20 seconds and resends the event if it doesn’t get it, according to its webhooks documentation. If the endpoint waits for the LLM, a spike in messages causes resends, duplicate replies and double cost. With the queue, the webhook only stores the event and responds.
The article on WhatsApp API webhooks covers the event format, deduplication and status handling, and webhook signature validation shows how to check X-Hub-Signature-256 before enqueueing.
Mark as read and show “typing”
The Cloud API lets you mark the incoming message as read and show the typing indicator in the same call. According to the typing indicators documentation, the indicator disappears when you reply or after 25 seconds, whichever comes first. Meta recommends showing it only if you are actually going to reply.
{
"messaging_product": "whatsapp",
"status": "read",
"message_id": "wamid.HBgLNTUx...",
"typing_indicator": { "type": "text" }
}
On Vectalk, this call goes to POST /api/messages, the same endpoint documented for marking messages as read.
The 24-hour window defines what the bot can send
When the customer sends a message, a 24-hour customer service window opens, and it renews with each new message from them. Inside it, the bot can reply with free-form text, media and interactive messages. Outside it, only approved templates (see Meta’s page on service messages and the customer service window).
In practice, this changes how you design the agent:
- The bot is reactive. It answers what the customer asked. To reach out again after 24 hours, the system needs a template, not text generated by the LLM.
- Slow replies can miss the window. If the bot depends on a slow process (document analysis, a call to another system), record the time of the customer’s last message and check it before sending.
- Buttons and lists help the LLM. Instead of asking the customer to type “1” or “2”, the bot can send clickable options. See WhatsApp interactive messages.
The article on the WhatsApp 24-hour customer service window details the rules for opening and renewing it.
How much each bot reply costs
Free-form replies inside the window are service messages. Since October 1, 2026, each business phone number gets 1,000 free service messages per month, and Meta charges from the 1,001st onward, according to the pricing page. For recipients in Brazil, the service rate is R$ 0.0350 (Brazilian reais) per delivered message; rates for other markets are in WhatsApp API pricing by country. A bot that replies in three short messages costs three times as much as one that replies in a single message, so it pays to combine the answer.
On top of that comes the cost of the language model itself, which depends on the provider and the size of the context.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
Handoff to a human
The WhatsApp Business Messaging Policy allows automation inside the 24-hour window but requires prompt, clear and direct escalation paths. The options it lists include transferring to a human agent in the conversation, a phone number, email, website support, a store visit or a support form.
A customer service bot needs at least three handoff triggers:
- Explicit request. The customer types “agent”, “talk to a person” or taps a human help button.
- Low confidence. The LLM signals it doesn’t know the answer or the topic is outside the defined scope.
- Sensitive topic. A complaint, cancellation, disputed charge or any topic the business decides to handle only with people.
| Conversation state | Who replies | How it leaves the state |
|---|---|---|
bot | AI agent | Handoff trigger |
waiting_human | No one replies automatically; the bot announces the wait time only once | An agent takes over |
human | Agent, through the customer service tool | The agent closes it or the conversation goes idle |
If the number uses coexistence, the agent can reply from the WhatsApp Business app on their phone. Messages sent from the app reach your system as echo events, and the router can use them to switch the conversation to human automatically, so the bot doesn’t talk over the agent. For several agents on the same number, see multi-agent WhatsApp with the API.
What Meta allows for AI chatbots
The Meta Terms for WhatsApp Business Platform, in clause 4.7, deal with “AI Providers”: providers and developers of artificial intelligence or machine learning technologies, such as large language models, generative AI platforms and general-purpose AI assistants, as Meta determines. They are prohibited from using the platform to offer those technologies when they are the primary functionality rather than incidental or ancillary.
What this means for bot builders:
- The business’s own customer service bot. An agent that answers questions about orders, books appointments or explains the company’s products uses AI as a tool for customer service. Meta decides each case, but this is not the use the terms target.
- General-purpose assistant as a product. Offering a “ChatGPT on WhatsApp” to the public, where talking to the AI is the service itself, is the prohibited case, except in the countries where Meta is legally required to allow it.
- Brazil. The AI Providers pricing page lists Brazil (+55) among the markets where AI Providers can send service messages since March 11, 2026, and Meta charges them at the published rates. Other listed markets include Italy and 29 European markets, plus Türkiye since October 15, 2026. In these sends, the status webhook shows the pricing category
general_purpose_ai. This rule applies only to AI Providers; pricing for other businesses doesn’t change. - Training data. The terms prohibit using platform data to create, develop, train or improve AI models. They allow using that data to fine-tune a model for the business’s exclusive use, as long as it isn’t used for other models. Review your LLM provider’s terms on retention and training.
The terms were last updated on September 23, 2026. Reread the clause before launching a product in which AI is the core of the offer.
Node.js example
The example below uses Express, an in-memory queue and the Vectalk API. In production, replace the queue with a persistent service (Redis, SQS, RabbitMQ) and the Map with a database. The generateReply function is where your LLM provider’s SDK goes. For a step-by-step version with an actual model call, see connecting ChatGPT to the WhatsApp Business API.
import express from 'express';
const VECTALK = 'https://apis.vectalk.com.br/api/messages';
const TOKEN = process.env.VECTALK_TOKEN; // instance token
const WINDOW_MS = 24 * 60 * 60 * 1000;
const HUMAN_TRIGGERS = /\b(agent|human|person|complain|cancel)\b/i;
const app = express();
app.use(express.json());
const queue = [];
const processed = new Set(); // wamid IDs already handled
const conversations = new Map(); // wa_id -> { state, history, lastInbound }
// 1. Webhook: validate, enqueue and return 200
app.post('/webhook', (req, res) => {
for (const entry of req.body.entry ?? []) {
for (const change of entry.changes ?? []) {
for (const msg of change.value?.messages ?? []) queue.push(msg);
}
}
res.sendStatus(200);
});
// 2. Send through Vectalk (same payload as Meta)
async function send(payload) {
const r = await fetch(VECTALK, {
method: 'POST',
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ messaging_product: 'whatsapp', ...payload }),
});
if (!r.ok) throw new Error(`Send failed: ${r.status} ${await r.text()}`);
return r.json();
}
// 3. LLM integration point
async function generateReply(history) {
// Call your provider's SDK here, with a system prompt that limits
// the scope to your business and asks it to answer "HANDOFF" when unsure.
throw new Error('Implement the LLM call');
}
// 4. Worker
async function processMessage(msg) {
if (processed.has(msg.id)) return;
processed.add(msg.id);
const c = conversations.get(msg.from) ?? { state: 'bot', history: [], lastInbound: 0 };
c.lastInbound = Number(msg.timestamp) * 1000;
conversations.set(msg.from, c);
if (c.state !== 'bot') return; // a human has the conversation: the bot stays silent
if (msg.type !== 'text') {
await send({ to: msg.from, type: 'text', text: { body: 'For now I only understand text. Could you type your question?' } });
return;
}
const text = msg.text.body;
c.history.push({ role: 'user', content: text });
c.history = c.history.slice(-20); // cap the context
if (HUMAN_TRIGGERS.test(text)) return handOff(msg.from, c);
await send({ status: 'read', message_id: msg.id, typing_indicator: { type: 'text' } });
const reply = await generateReply(c.history);
if (reply.trim() === 'HANDOFF') return handOff(msg.from, c);
if (Date.now() - c.lastInbound > WINDOW_MS) return; // window closed: a template is needed
await send({ to: msg.from, type: 'text', text: { body: reply } });
c.history.push({ role: 'assistant', content: reply });
}
async function handOff(waId, c) {
c.state = 'waiting_human';
await send({ to: waId, type: 'text', text: { body: "I'm bringing in someone from our team. They'll pick up right here shortly." } });
// Notify your customer service tool (ticket queue, Slack, CRM).
}
setInterval(async () => {
const msg = queue.shift();
if (!msg) return;
try { await processMessage(msg); } catch (e) { console.error(e); }
}, 50);
app.listen(3000);
What the example already handles and what’s missing for production:
- Handles: an immediate webhook response, deduplication by
wamid, handoff state, a context cap, the window check and the typing indicator. - Missing: a persistent queue with retries, a database for history and state, a timeout on the LLM call, cost tracking from the status webhook, and a dashboard for agents to take over the conversation and hand it back to the bot. Vectalk doesn’t provide a customer service inbox, so that dashboard is your own tool or a CRM integrated with the webhooks.
Best practices for the agent
- Closed scope. The system prompt should state what the bot does and doesn’t do. Prices, deadlines and policies should come from your system’s data, not from the model’s memory.
- Short replies. On WhatsApp, a three-line message works better than a long text. It also reduces the number of billed messages.
- Identify the bot. Make it clear the customer is talking to a virtual assistant and how to reach a person.
- Log everything. Store the question, the answer, the model used and the response time. Without that, you can’t audit a wrong answer.
- Test with real messages. Voice notes, photos of receipts and stickers arrive every day. Decide what the bot does with each type before going to production.
Frequently asked questions
Can I use any LLM with the official API?
The WhatsApp API doesn’t restrict the model you run on your server. What Meta’s terms regulate is the use: AI supporting the business’s customer service is different from offering a general-purpose assistant as the main product.
Can the bot send the first message to the customer?
Not with free-form text. To start a conversation or reach out again after 24 hours, you need an approved template. See WhatsApp API message templates.
How do I stop the bot from replying twice to the same message?
Store the wamid ID of every processed message and ignore repeats. Webhook resends happen whenever the endpoint is slow or fails.
Can the bot reply to voice notes?
The webhook delivers the media ID, which you download through the media API and transcribe with the service of your choice. Transcription and its cost are on you. Downloading media from the webhook shows the download step.
Do I need any special registration with Meta to use AI?
For the business’s own customer service bot, the documentation we checked doesn’t describe any extra registration. If your product is a general-purpose AI assistant, read clause 4.7 of the terms and the AI Providers page before you start.
Get started with Vectalk
With Vectalk, your bot receives the same webhooks as Meta and sends with the same payloads, using one token for all accounts. You don’t add a card at Meta: you pay a monthly fee and keep a prepaid balance, and each delivered message is deducted from it. Coexistence lets your human team keep using the app. Create your account at apps.vectalk.com.br/register and read the documentation.
Sources checked on October 29, 2026: Meta Terms for WhatsApp Business Platform (updated on September 23, 2026), WhatsApp Business Messaging Policy, Pricing for AI Providers (updated on October 15, 2026), Pricing on the WhatsApp Business Platform, Service messages and customer service window, Typing indicators, Webhooks in the Vectalk documentation.
Put your business on the official WhatsApp
Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.
