← Back to Blog
AI Chatbot

WhatsApp Business API Chatbot with OpenAI and LangChain: A 2026 Build Guide

Share

WhatsApp says more than 3 billion people use it, so for many businesses it is where customers already write. A WhatsApp AI chatbot on the WhatsApp Business API (since October 2025 that means Meta's Cloud API; the On-Premises API has expired) can answer from your own documents, remember a conversation across days and hand over to a person when it should. This guide covers the build as it stands in December 2026, from setup to CRM logging.

Updated 4 December 2026. The 2024 version used GPT-4, which OpenAI shut down on 23 October 2026, and LangChain classes that are now deprecated, and its memory code never saved the conversation. Everything here was re-checked against Meta's, OpenAI's and LangChain's documentation on 4 December 2026.

Step 1: Set Up the WhatsApp Business Platform

  • For your own business: in the Meta App Dashboard, create an app with the WhatsApp use case and attach it to your business portfolio (the current name for a Business Manager account). For production, create a system user in Business Settings and generate a token with the business_management, whatsapp_business_messaging and whatsapp_business_management permissions; the quick-start token expires quickly.
  • For your customers' businesses: a platform that connects other companies' numbers works as a Tech Provider or Solution Partner and uses Embedded Signup. The business signs in with its own Meta credentials, chooses its business portfolio and WhatsApp account, verifies its number and owns every asset created. Embedded Signup v2 and v3 were deprecated on 15 October 2026, so start on v4 or later.

The number must be yours and able to receive an SMS or voice call. The old rule that it can never touch the WhatsApp app again no longer holds:

  • A number already on WhatsApp can be registered on the Cloud API alone only after that account is deleted. Meta warns that deleting a WhatsApp Business app account this way loses its message history, and the number cannot go back to the Business app unless it is first deregistered from the Cloud API.
  • Coexistence avoids that. Through Embedded Signup, a number in the WhatsApp Business app (version 2.24.17 or later) joins the Cloud API and keeps working in the app; new messages show in both, and past chats can be imported if the business agrees and the integration requests them within 24 hours of connecting. API sending on it is fixed at 20 messages a second. See our WhatsApp coexistence guide.
  • A number used only on the Cloud API can be deregistered through Meta's deregister endpoint, which takes it off the Cloud API without deleting the number or its message history. The endpoint does not work on a coexistence number; that business disconnects from inside the WhatsApp Business app instead.

Meta checks the display name against its guidelines automatically once the business reaches a higher messaging limit, and publishes no turnaround time for that check. Until it is approved, the name appears in the business profile but not at the top of chats.

Step 2: Receive Messages Safely

Meta sends every incoming message and status update (sent, delivered, read) to one webhook URL with a valid TLS certificate. Three rules shape the handler:

  • Verify the signature. The X-Hub-Signature-256 header is an HMAC-SHA256 of the payload, keyed with your app secret. Compute it over the bytes received, before JSON parsing, and reject mismatches.
  • Return 200 at once. Meta retries any delivery that gets a status other than 200, with decreasing frequency, for up to 7 days. Retrieval and a model call are slow, so acknowledge first and work afterwards.
  • De-duplicate by message ID. Meta says retries can produce duplicate notifications. Record each message's wamid and skip any you have seen, or the customer gets two answers.

Key conversations on the business-scoped user ID (BSUID, from_user_id), not the phone number. BSUIDs have appeared in webhooks since April 2026, and when a customer turns on a WhatsApp username, the phone number can be missing from the webhook. If the customer changes number, Meta issues a new BSUID and a system message carrying previous_user_id. Handle that message: move any handover row to the new ID, or the bot may answer a chat a person owns (the code below skips system messages). The conversation memory stays under the old ID, so the bot starts the new thread without it unless you copy it across. Meta omits previous_user_id when the old ID is not available.

-- Postgres holds everything: bookkeeping, conversation memory and the knowledge base. CREATE EXTENSION IF NOT EXISTS vector; -- pgvector, for the knowledge base CREATE TABLE processed_messages ( wamid text PRIMARY KEY, -- WhatsApp message ID, unique per message received_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE handovers ( -- a row here means a person owns the chat user_id text PRIMARY KEY, -- the customer's BSUID reason text, created_at timestamptz NOT NULL DEFAULT now() );
// server.js: Node.js 22+, Express 5, pg 8. WhatsApp Cloud API, Graph API v27.0. import express from "express"; import crypto from "node:crypto"; import { db, handleMessage } from "./bot.js"; const app = express(); // Meta signs the bytes it sent, so keep them before the JSON is parsed. // Meta's payloads can reach 3 MB; express.json() refuses anything over 100 kB by default. app.use(express.json({ limit: "3mb", verify: (req, res, buf) => { req.rawBody = buf; } })); // Meta calls this each time you set or edit the callback URL or verify token. // Once it saves, subscribe to the "messages" field in the same panel. app.get("/webhook", (req, res) => { const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === process.env.VERIFY_TOKEN; if (!ok) return res.sendStatus(403); res.status(200).send(req.query["hub.challenge"]); }); function hasValidSignature(req) { const received = Buffer.from(req.get("X-Hub-Signature-256") ?? ""); const expected = Buffer.from("sha256=" + crypto .createHmac("sha256", process.env.APP_SECRET) .update(req.rawBody) .digest("hex")); // timingSafeEqual throws on unequal lengths, so compare the lengths first. return received.length === expected.length && crypto.timingSafeEqual(received, expected); } app.post("/webhook", async (req, res) => { if (!req.rawBody || !hasValidSignature(req)) return res.sendStatus(401); res.sendStatus(200); // acknowledge first; the slow work happens below try { for (const entry of req.body.entry ?? []) { for (const change of entry.changes ?? []) { const value = change.value ?? {}; // Status updates arrive on this webhook too, as value.statuses; skipped here. for (const msg of value.messages ?? []) { // A retried delivery repeats the same wamid: only the first insert counts. const { rowCount } = await db.query( "INSERT INTO processed_messages (wamid) VALUES ($1) ON CONFLICT DO NOTHING", [msg.id], ); if (rowCount === 0) continue; handleMessage(value.metadata.phone_number_id, msg) .catch((err) => console.error("reply failed", msg.id, err)); } } } } catch (err) { console.error("webhook processing failed", err); } }); app.listen(process.env.PORT ?? 3000);

Meta will not resend a message it has had a 200 for, so in production hand each new message to a queue or jobs table here and let a worker retry failures. Process one customer's messages one at a time: LangGraph's open-source checkpointer does not stop two runs on the same thread_id from overlapping, and when they overlap, both start from the same saved state and one exchange can drop out of the memory.

Step 3: Work Within Meta's Messaging Rules

  • The customer service window. A customer's message or call opens a 24-hour window, and each new message resets it. Inside it the bot can reply freely.
  • Templates. Outside the window, only pre-approved templates can be sent, and they are the only way to message a customer first. Each is categorised as marketing, utility or authentication, and Meta's review can take up to 24 hours.
  • Messaging limits. These cap the unique customers you can message outside a service window in a rolling 24 hours. They are set per business portfolio and start at 250. Business verification, verification by your onboarding partner, or 2,000 delivered messages outside service windows to unique customers within 30 days using high-quality templates qualifies you for 2,000. After any of these, Meta reviews your message quality before raising the limit. From there it rises to 10,000, 100,000 and unlimited automatically, one level at a time, while your messages stay high quality and you have used at least half your current limit in the last 7 days.

Step 4: Retrieval, Memory and the Model

OpenAI's current flagship line is GPT-6: it describes gpt-6.2-sol as its go-to model for everyday work and agents at scale, and gpt-6-luna as its most efficient for focused, high-volume tasks. Our team has built with GPT-6. On the LangChain side, ConversationBufferWindowMemory and ConversationalRetrievalChain are deprecated and live in the classic package; the current pattern is createAgent with a checkpointer for memory and tools for actions.

You may not need a framework. LangChain's documentation notes that two-step RAG (always retrieve, then one model call) has more predictable latency, because the number of model calls is capped. If the bot only answers from documents, a direct call is simpler: embed the question, search pgvector, and send the top passages with the question to OpenAI's Responses API. The agent below earns its place when the bot must choose between actions, such as searching or handing over.

// bot.js: langchain 1.6, @langchain/openai 1.8, @langchain/pgvector 0.1, // @langchain/langgraph-checkpoint-postgres 1.2, zod 4. import pg from "pg"; import * as z from "zod"; import { createAgent, tool } from "langchain"; import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai"; import { PGVectorStore } from "@langchain/pgvector"; import { PostgresSaver } from "@langchain/langgraph-checkpoint-postgres"; export const db = new pg.Pool({ connectionString: process.env.DATABASE_URL }); // Your FAQs, price lists and policies, loaded beforehand with addDocuments. const vectorStore = await PGVectorStore.initialize( new OpenAIEmbeddings({ model: "text-embedding-3-small" }), { pool: db, tableName: "kb_chunks" }, ); const searchKnowledgeBase = tool( async ({ query }) => { const docs = await vectorStore.similaritySearch(query, 4); return docs.map((d) => d.pageContent).join("\n\n---\n\n"); }, { name: "search_knowledge_base", description: "Search our product, price and policy documents.", schema: z.object({ query: z.string().describe("What the customer wants to know") }), }, ); const handToPerson = tool( async ({ reason }, config) => { await db.query( "INSERT INTO handovers (user_id, reason) VALUES ($1, $2) ON CONFLICT DO NOTHING", [config.context.userId, reason], ); // Notify your agent desk and log the handover to the CRM here. return "Handed to a colleague."; }, { name: "hand_to_person", description: "Pass this chat to a human colleague.", schema: z.object({ reason: z.string() }), }, ); // Conversation memory in Postgres: survives restarts and works across servers. const checkpointer = PostgresSaver.fromConnString(process.env.DATABASE_URL); await checkpointer.setup(); // creates the checkpoint tables on first run const agent = createAgent({ // gpt-6.2-sol needs the Responses API for tool calling; @langchain/openai does not switch to it by itself. model: new ChatOpenAI({ model: "gpt-6.2-sol", useResponsesApi: true }), tools: [searchKnowledgeBase, handToPerson], systemPrompt: "You answer customers of Example Ltd on WhatsApp in short, plain messages. " + "Answer product, price and policy questions only from search_knowledge_base. " + "If it has no answer, or the customer asks for a person, call hand_to_person " + "and tell them a colleague will reply.", checkpointer, contextSchema: z.object({ userId: z.string() }), }); export async function handleMessage(phoneNumberId, msg) { // BSUID: present even when a username hides the customer's phone number. const userId = msg.from_user_id ?? msg.from; const { rows } = await db.query("SELECT 1 FROM handovers WHERE user_id = $1", [userId]); if (rows.length > 0) return; // a person owns this chat if (msg.type !== "text") return; // send media, locations and the rest to a person // Read receipt plus a typing indicator while the model works. await sendToWhatsApp(phoneNumberId, { status: "read", message_id: msg.id, typing_indicator: { type: "text" }, }); const result = await agent.invoke( { messages: [{ role: "user", content: msg.text.body }] }, { configurable: { thread_id: userId }, context: { userId } }, ); const address = msg.from_user_id ? { recipient: msg.from_user_id } : { to: `+${msg.from}` }; await sendToWhatsApp(phoneNumberId, { recipient_type: "individual", ...address, type: "text", text: { body: result.messages.at(-1).text.slice(0, 4096) }, }); } async function sendToWhatsApp(phoneNumberId, payload) { const res = await fetch(`https://graph.facebook.com/v27.0/${phoneNumberId}/messages`, { method: "POST", headers: { Authorization: `Bearer ${process.env.WHATSAPP_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify({ messaging_product: "whatsapp", ...payload }), }); if (!res.ok) throw new Error(`WhatsApp API ${res.status}: ${await res.text()}`); }

The thread_id is the customer's BSUID, so the Postgres checkpointer reloads the right conversation on every message, after restarts and across servers, as long as each customer's messages are processed one at a time. useResponsesApi is set because OpenAI's documentation says gpt-6.2-sol needs the Responses API for tool calling, and @langchain/openai does not switch to it automatically for this model. The reply is cut at 4,096 characters, WhatsApp's limit for a text body.

Index documents with the same embedding model you search with. Long-running conversations grow without limit, so add LangChain's summarizationMiddleware or trimMessages from the first release.

Step 5: Hand Over to a Person and Log to the CRM

The hand_to_person tool writes a row, and while it exists the bot stays silent on that chat. A person replies from your agent desk through the same Cloud API; deleting the row hands the chat back.

  • Hand over when asked, when the knowledge base has no answer, and for refunds, complaints and anything else the bot must not decide. Test each case.
  • Show the person the conversation so far; the checkpointer already holds it.
  • On a coexistence number, a reply typed on the owner's phone arrives as an smb_message_echoes event. Treat it as a handover too.

Log each inbound message, bot reply and handover to the CRM from a background job, never in the webhook path. Store the BSUID on the contact as well as the phone number, because the number can be missing. We have built CRM integrations with Salesforce, HubSpot, Zoho CRM and Odoo.

What It Costs

Meta charges per delivered message, by category and recipient country; customer messages are free. Since 1 October 2026 each number gets 1,000 free service messages a month, and utility templates sent inside the service window are charged. For current rates and worked examples, see WhatsApp Business API pricing in India. OpenAI bills the model and embeddings separately, per token.

Before You Launch

  1. A payload signed with the wrong secret is rejected.
  2. The same webhook delivered twice produces one reply.
  3. After a server restart, the bot still remembers the conversation.
  4. A question the knowledge base cannot answer gets a handover, not an invented answer.

Frequently Asked Questions

Can I use the number already on my WhatsApp Business app?

Yes, through coexistence: it joins the Cloud API through a partner's Embedded Signup and keeps working in the Business app. Deleting the app account and registering the number on the API alone loses the message history, and the number cannot return to the app unless it is deregistered from the Cloud API.

Which OpenAI model should a WhatsApp chatbot use?

In December 2026, gpt-6.2-sol for a bot that uses tools and follows multi-step instructions, or gpt-6-luna for narrow, high-volume work. Test both on real customer questions, and check OpenAI's deprecations page before launch.

Why does my WhatsApp bot reply twice?

Usually because Meta retried the webhook. It retries anything that did not get a 200, for up to 7 days, and retries can arrive as duplicates. Record each message ID and skip repeats.

Can the chatbot message customers first?

Only with an approved template. Free-form messages are allowed only inside the 24-hour window that opens when the customer messages or calls you, and template review can take up to 24 hours.

A WhatsApp Business API chatbot depends less on the model than on what surrounds it: a signed, de-duplicated webhook, memory written to a database, retrieval that keeps answers to your own documents, and a clean path to a person. Get those right and the model can change as OpenAI's list does. Samcom Technologies builds WhatsApp chatbots and Business API integrations on the Cloud API. Tell us what your customers ask on WhatsApp and we will scope the build with you.

Share
Let's Talk

Need Help With Your Project?

The same engineers who wrote this article will work on your project. Free consultation.