How a WhatsApp bot works: the path of a message and an API call
How a bot receives a WhatsApp message, fetches data from another API and sends the reply back, step by step. A bank-queue demo is the running example.
The big picture
A WhatsApp bot involves three separate conversations. Each one is a single HTTP call.
A message arrives
Meta sends a POST to an address on your server. This is called a webhook.
The reply goes out
Your server sends a POST to Meta's Cloud API. Meta delivers it to the user's phone.
Data comes in
Menu data, such as a list of banks or branches, comes from another API that the bot calls.
flowchart LR
U["User's WhatsApp"] -->|"1 message"| M["Meta Cloud API"]
M -->|"2 webhook POST"| S["Bot server"]
S -->|"3 GET or POST"| D["Demo API"]
D -->|"4 JSON reply"| S
S -->|"5 POST messages"| M
M -->|"6 reply"| U
How to get started
To build a bot you need a Meta account, an app and a WhatsApp number. It costs nothing to begin, because Meta gives you a test number. Menu names change from time to time, so if you cannot find a button, use the official guides at the end of this section.
- Create a Meta Business portfolio. Sign in to business.facebook.com with your Facebook account and create a Business portfolio. Enter a business name, your name and an email.
- Open a developer account. Go to developers.facebook.com/apps. The first time, you register as a developer and Meta asks you to verify your phone number.
- Create an app. Click Create App, choose the use case Connect with customers through WhatsApp, enter an app name and email, and attach the Business portfolio from step 1. If you cannot find that use case, choose Other, then the type Business, and add the WhatsApp product to the app.
- Get the test number and the Phone number ID. In the app dashboard open WhatsApp → API Setup. Meta provides a test number there and shows its Phone number ID. Note it down (that is the
PHONE_NUMBER_IDused above). In the "To" box add your own phone number and verify it with the OTP, then click Send message. Ahello_worldmessage should arrive in your WhatsApp. If it does, the connection works. - Create a permanent token. The token on the API Setup page expires after a few hours, so it is only good for the first test. For a permanent one, go to Business Settings → Users → System users. Click Add (role Admin), then under Add assets → Apps choose your app, give it Full control and save. Next click Generate token, pick the app, set the expiry to Never, and tick
whatsapp_business_messagingandwhatsapp_business_management. If you see "No permissions available", the app has not been given to the System User yet. The token is shown only once, so store it somewhere safe right away. - Copy the App Secret. On the app's App settings → Basic page click Show next to App secret. You need it to check the webhook signature.
- Get your server online. A webhook needs an HTTPS address reachable from the internet. Deploy the bot code to get one. If the address is not live yet, the check in the next step fails. If you run it on your own computer, a tunnel such as ngrok can give you an address.
- Register the webhook. Under WhatsApp → Configuration → Webhook click Edit. Enter your address as the Callback URL and a secret word of your choice as the Verify token (your server must use the same word). Click Verify and save, then switch on Subscribe next to the messages field.
- Test it. From your phone, write a message to the test number. A
POSTshould reach your server, and if the bot answers, everything works.
Official guides: Get started · Webhooks · Access tokens · Messaging limits · Pricing
How a message arrives
When a user writes, Meta sends a POST to the address you registered. A good webhook does these things.
- Check the signature. Meta adds an
X-Hub-Signature-256header to every request. It is the HMAC-SHA256 of the raw request body, made with your App Secret. Calculate the same value yourself and drop the request if it does not match. Otherwise anyone can send fake messages to your address. - Never handle the same message twice. Meta sometimes delivers a message again. Remember each message
idand skip ones you have seen. - "Read" and "typing…". Optionally mark the message as read and show a typing bubble. Users like it when a reply takes a moment.
- Decide the reply. Your own logic chooses it. It can be an AI model, or a button menu.
- Send the reply. Then always answer Meta with
200. If you do not, Meta assumes you missed the message and sends it again.
sequenceDiagram
participant U as User
participant M as Meta
participant S as Bot server
participant A as Demo API
U->>M: types Queue Pro
M->>S: POST webhook
S->>S: check signature and duplicates
S->>M: read and typing
S->>A: GET banks
A-->>S: bank list JSON
S->>M: POST messages list menu
M->>U: bank list
What Meta sends
{
"entry": [{
"changes": [{
"value": {
"contacts": [{ "wa_id": "8801XXXXXXXXX", "profile": { "name": "Rahim" } }],
"messages": [{
"id": "wamid.HBgL...",
"from": "8801XXXXXXXXX",
"type": "text",
"text": { "body": "Queue Pro" }
}]
}
}]
}]
}
When a user taps a list row or a button, type is interactive, and instead of text you get interactive.list_reply or button_reply with the chosen row's id and title. A handy trick is to write the earlier choices into each row's id (for example q:b:dbbl), so the bot does not have to remember anything between steps.
The first connection check
When you register the webhook, Meta sends a GET to check that the address really is yours.
hub.verify_token = matches the secret word you gave Meta
reply = 200 with only the hub.challenge value (12345) as the body
otherwise = 403
How to send a message on WhatsApp
Every kind of message goes to the same address. Only the type and the part inside it change.
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
PHONE_NUMBER_ID is the ID of your WhatsApp number, shown on Meta's API Setup page. ACCESS_TOKEN is your permission key. Keep it secret: never put it in code or in a public repository.
Plain text
{
"messaging_product": "whatsapp",
"to": "8801XXXXXXXXX",
"type": "text",
"text": { "body": "⏰ Reminder: test vaccination" }
}
Buttons (up to 3)
{
"messaging_product": "whatsapp",
"to": "8801XXXXXXXXX",
"type": "interactive",
"interactive": {
"type": "button",
"body": { "text": "Done or need more time?" },
"action": {
"buttons": [
{ "type": "reply", "reply": { "id": "done", "title": "Done" } },
{ "type": "reply", "reply": { "id": "snooze1h", "title": "Remind in 1 hour" } }
]
}
}
}
List menu (up to 10 rows)
{
"messaging_product": "whatsapp",
"to": "8801XXXXXXXXX",
"type": "interactive",
"interactive": {
"type": "list",
"body": { "text": "Please choose your bank." },
"action": {
"button": "Choose bank",
"sections": [{
"title": "Menu",
"rows": [
{ "id": "q:b:dbbl", "title": "1. DBBL" },
{ "id": "q:b:brac", "title": "2. BRAC BANK" },
{ "id": "q:b:ific", "title": "3. IFIC BANK" }
]
}]
}
}
}
Image
{
"messaging_product": "whatsapp",
"to": "8801XXXXXXXXX",
"type": "image",
"image": {
"link": "https://example.com/ticket.png",
"caption": "Thank you for using QueuePro.\nYour Token Number is A-001"
}
}
You do not upload the image. Meta downloads it from the link itself, so the link must be reachable from the internet. The format must be PNG or JPEG; SVG does not work.
"Read" and typing
{
"messaging_product": "whatsapp",
"status": "read",
"message_id": "wamid.HBgL...",
"typing_indicator": { "type": "text" }
}
template message is allowed, and it costs extra. Plan any timed messages around this rule.
Getting data from another API
The menus of the bank-queue demo come from a demo API. The bot calls it with real HTTP requests. That makes it easy to see, for every message, which call was made, its address, its status and how long it took.
| Call | End of the address | What it does | Protection |
|---|---|---|---|
| GET | /banks | List of banks | Open to everyone |
| GET | /branches?bankId=dbbl | Branches of that bank | Open to everyone |
| GET | /services?bankId=…&branchId=… | List of services | Open to everyone |
| POST | /tokens | Creates a token | Needs a secret key |
| POST | /serve | Calls a token to a counter | Needs a secret key |
| POST | /feedback | Saves a rating or comment | Needs a secret key |
Calls that write data (POST) do not work without a secret key, and only the bot's server knows it. Calls that only show lists (GET) can stay open, because there is nothing secret in them.
A list call and its reply
{
"success": true,
"banks": [
{ "id": "dbbl", "name": "DBBL" },
{ "id": "brac", "name": "BRAC BANK" },
{ "id": "ific", "name": "IFIC BANK" }
]
}
The reply to getting a token (simplified)
{
"success": true,
"token": {
"tokenNo": "A-001",
"bank": "DBBL",
"branch": "Gulshan Branch",
"service": "Account Opening",
"path": "2nd Floor",
"menu": "Main Menu",
"subMenu": "Accounts"
}
}
A token number is the service's letter plus three digits, such as A-001. The number counts up from 1 separately for each day, bank, branch and service. An atomic database increment makes sure two people never get the same number.
Writing down every call for debugging
The bot keeps a small record of every API call next to the message it helped build. That makes it easy to understand the call behind a message, and to find the step where something went wrong.
{
"label": "Get banks",
"method": "GET",
"url": "https://example.com/api/demo/queuepro/banks",
"status": 200,
"ms": 42,
"request": "",
"response": "{\"success\":true,\"banks\":[...]}"
}
Never write a secret key into such a record, and cut long responses short.
Every step of the demo
The demo's story: the user picks a bank, a branch and a service, the bot sends a token ticket image, calls the user to a counter a little later, then asks for a rating.
| Step | User | API call | Bot's message |
|---|---|---|---|
| 1 | Types Queue Pro | GET /banks | List of banks |
| 2 | Taps a bank | GET /branches | List of branches |
| 3 | Taps a branch | GET /services | List of services |
| 4 | Taps a service | POST /tokens | Ticket image, token number in the caption |
| 5 | About 1 minute later (on its own) | POST /serve | "You are serving counter number N" |
| 6 | About 1 more minute later | none | 5-star rating list |
| 7 | Taps a star | POST /feedback (rating) | Thanks, asks for an optional comment (Skip button) |
| 8 | Types a comment or skips | POST /feedback (comment) | Thanks |
The ticket image is drawn on the server: branch, service, token number, a QR code, which floor to go to, the date, the time and the bank's name. The image link is signed, so nobody can make fake tickets.
How timed messages are sent
"Call to a counter after 1 minute" or "remind at 9 am" is not a reply to anything the user just wrote, so a webhook does not help here. You need a timer.
- A timer opens an address on your server every minute. It can be an outside service.
- The server checks the database for whose time has come. For example reminders or tokens.
- For each one it first writes "I took this" in the database, then sends the message. That way two timers firing together never send the same message twice. If sending fails, it removes the mark so the next minute tries again.
Because the timer runs once a minute, a message can arrive anywhere from a few seconds to two minutes late.
Try it yourself
You can run these calls in a terminal with curl. Replace the capitalised words with your own values.
Send a message on WhatsApp directly
curl -X POST "https://graph.facebook.com/v21.0/PHONE_NUMBER_ID/messages" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"messaging_product":"whatsapp","to":"8801XXXXXXXXX","type":"text","text":{"body":"Hello from curl"}}'
The message arrives if the user has written to your number in the last 24 hours. If not, Meta returns an error, because a template is needed.
The webhook handshake
curl "https://YOUR-SERVER/webhook?hub.mode=subscribe&hub.verify_token=YOUR_SECRET_WORD&hub.challenge=12345"
# if it is correct, 12345 comes back
WhatsApp Cloud API webhook verified but messages not received? Here's the fix
A real case from building the second bot for this demo, and the order in which it was narrowed down. It is a good first thing to check when a WhatsApp webhook is verified but not receiving messages.
The problem
The Callback URL was saved and verified in Meta Developers, and the messages field was subscribed. The dashboard's test payload looked right: object was whatsapp_business_account, field was messages, and messages[0].text.body was Hi. Yet a real message produced no POST in the server's runtime logs, and the database held no customer and no message for that bot.
The first bot, on the same server, kept receiving messages normally. So the server code and the database were not the first suspects. The search moved to the Meta side: the app, the WhatsApp Business Account (WABA) and the delivery path.
The cause in this case
The app-level webhook settings and the messages field were already in place, but the second app was not subscribed to the WABA that owns the phone number. The WABA's list of subscribed apps did not contain it. These are two separate settings: the webhook field subscription says what to send, and the WABA subscription says which app receives events for this account.
The fix: subscribe the app to the WABA
Call the Graph API with a token that belongs to the intended app and can manage that WABA. Replace vXX.X with a Graph API version that Meta currently supports, and put the real values in only on your own machine, never in a public post.
curl -X POST \
"https://graph.facebook.com/vXX.X/YOUR_WABA_ID/subscribed_apps" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
A successful call typically answers:
{
"success": true
}
Then read the list back to confirm it:
curl -X GET \
"https://graph.facebook.com/vXX.X/YOUR_WABA_ID/subscribed_apps" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
The response has a data list. Look for your app's ID or name in it. If it is missing, check these before retrying: the token really belongs to the intended app, the token has the whatsapp_business_management permission, and the WABA ID is the one that owns your phone number. success: true alone does not prove messages will be delivered, so finish with a real test message (step 6 below). Please also check Meta's current documentation for the exact request, because Meta can change it.
Verification checklist
- The Callback URL is public and uses HTTPS. Meta cannot reach a private address.
- The GET check succeeds. The verify token matches and the reply is exactly the
hub.challengevalue (see How a message arrives). - The
messagesfield is subscribed in the app's webhook settings. - Your app appears in the WABA's
subscribed_appslist. Field subscription and WABA subscription are separate. - The Phone Number ID belongs to that WABA. Do not mix up the Phone Number ID, the WABA ID and the App ID.
- A fresh WhatsApp message produces a POST in your hosting provider's runtime logs. Use a new message, not an old test payload.
- The signature check uses the right secret and the exact raw body. Compute
X-Hub-Signature-256with the App Secret over the unparsed bytes. A re-serialised JSON body gives a different result. - Incoming messages and delivery updates are told apart. Messages sit in
value.messages. Updates about messages you sent sit invalue.statusesand should not be treated as customer messages. - The bot processes the message and its reply is accepted by Meta. Check the reply's response and, later, its status update.
Troubleshooting table
Each row is a lead to check, not a verdict.
| Symptom | Likely cause | Next action |
|---|---|---|
| The GET check succeeds, but no POST reaches the server | The app may not be subscribed to the WABA, the field may be missing, or you wrote to a different number than the one on this app | List subscribed_apps, recheck the messages field, confirm the Phone Number ID, send a fresh message |
The POST arrives and returns 401 | Signature check failing: wrong App Secret (for example from another app) or a changed request body | Use the secret of the app that sends the webhook and sign the raw body |
| The POST succeeds, but the database stays empty | The message was filtered out (allow-list, duplicate, statuses only) or the save failed | Read the processing logs and look at what the payload contained |
| The message is stored, but no reply is sent | Expired or wrong access token, wrong Phone Number ID, or a send error | Log the response of the send call and read its error code |
A status update contains error code 131000 | Meta lists this as a generic error, so the code alone does not name the cause | Read the error's title and details in the status payload, retry once, and compare with Meta's error code list |
Your app ID is missing from GET /{WABA_ID}/subscribed_apps | The app is not subscribed to that WABA, or you queried a different WABA or used another app's token | Check the token, its permissions and the WABA ID, then subscribe and list again |
Testing a webhook from your own computer
Meta's servers cannot open localhost, 127.0.0.1 or a private LAN address. To test a webhook that runs on your computer, expose it with a tunnel such as ngrok. If your server listens on port 3000:
ngrok http 3000
ngrok prints a public HTTPS address. Use it as the Callback URL, followed by your real webhook path, for example https://YOUR-TUNNEL-URL/webhook. The path must match your route, your development server must keep running, and you may have to update the Callback URL in Meta when the tunnel address changes. If your server is already deployed on a public HTTPS address, you can use that instead of a tunnel.
Related: the handshake test with curl and the common mistakes table below.
What saves time when you start
| Mistake or symptom | Cause | What to do |
|---|---|---|
After a few hours the bot stops replying, and Meta returns 401 (code 190) | The temporary token on Meta's API Setup page expires after a few hours | Create a non-expiring token with a System User in Business Settings and use that |
| The same message is answered again and again | The webhook is not returning 200, so Meta resends it | Always return 200 after the signature check, and remember each message id |
| Sending a message returns an error | More than 24 hours have passed since the user's last message | Use an approved template, or send within 24 hours |
| Someone can send fake messages | The webhook does not check the signature | Verify X-Hub-Signature-256 |
| You changed an environment value but nothing changed | On most hosts a new value only applies after a new deployment | Deploy again after the change |