← imshahin.dev
WhatsApp bot · 14 October 2026

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.

user → bot

A message arrives

Meta sends a POST to an address on your server. This is called a webhook.

bot → user

The reply goes out

Your server sends a POST to Meta's Cloud API. Meta delivers it to the user's phone.

bot → another API

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
        
The whole trip of one message. Steps 3 and 4 only happen when the reply needs outside data.

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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_ID used above). In the "To" box add your own phone number and verify it with the OTP, then click Send message. A hello_world message should arrive in your WhatsApp. If it does, the connection works.
  5. 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_messaging and whatsapp_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.
  6. 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.
  7. 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.
  8. 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.
  9. Test it. From your phone, write a message to the test number. A POST should reach your server, and if the bot answers, everything works.
About development mode Until you publish the app, Meta's dashboard shows a warning that real messages may not be delivered. In my tests, messages from my own verified number did arrive, but Meta can change its rules. A test number can only talk to the numbers you have verified. To open the bot to other people you need to add your own real number and complete Business verification, which Meta's guides cover.

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.

  1. Check the signature. Meta adds an X-Hub-Signature-256 header 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.
  2. Never handle the same message twice. Meta sometimes delivers a message again. Remember each message id and skip ones you have seen.
  3. "Read" and "typing…". Optionally mark the message as read and show a typing bubble. Users like it when a reply takes a moment.
  4. Decide the reply. Your own logic chooses it. It can be an AI model, or a button menu.
  5. 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 happens when someone types "Queue Pro".

What Meta sends

POSTto your webhook address, from Meta
{
  "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.

GETyour webhook address ?hub.mode=subscribe & hub.verify_token=… & hub.challenge=12345
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.

POSThttps://graph.facebook.com/v21.0/PHONE_NUMBER_ID/messages
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

type: text
{
  "messaging_product": "whatsapp",
  "to": "8801XXXXXXXXX",
  "type": "text",
  "text": { "body": "⏰ Reminder: test vaccination" }
}

Buttons (up to 3)

type: interactive, button
{
  "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)

type: interactive, list
{
  "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

type: 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

status: read
{
  "messaging_product": "whatsapp",
  "status": "read",
  "message_id": "wamid.HBgL...",
  "typing_indicator": { "type": "text" }
}
The 24-hour rule For 24 hours after a user's last message you can send any of the message types above. After that, only a pre-approved 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.

CallEnd of the addressWhat it doesProtection
GET/banksList of banksOpen to everyone
GET/branches?bankId=dbblBranches of that bankOpen to everyone
GET/services?bankId=…&branchId=…List of servicesOpen to everyone
POST/tokensCreates a tokenNeeds a secret key
POST/serveCalls a token to a counterNeeds a secret key
POST/feedbackSaves a rating or commentNeeds 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

GET/banks
{
  "success": true,
  "banks": [
    { "id": "dbbl", "name": "DBBL" },
    { "id": "brac", "name": "BRAC BANK" },
    { "id": "ific", "name": "IFIC BANK" }
  ]
}

The reply to getting a token (simplified)

POST/tokens
{
  "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.

one record
{
  "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.

StepUserAPI callBot's message
1Types Queue ProGET /banksList of banks
2Taps a bankGET /branchesList of branches
3Taps a branchGET /servicesList of services
4Taps a servicePOST /tokensTicket image, token number in the caption
5About 1 minute later (on its own)POST /serve"You are serving counter number N"
6About 1 more minute laternone5-star rating list
7Taps a starPOST /feedback (rating)Thanks, asks for an optional comment (Skip button)
8Types a comment or skipsPOST /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.

  1. A timer opens an address on your server every minute. It can be an outside service.
  2. The server checks the database for whose time has come. For example reminders or tokens.
  3. 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

terminal
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

terminal
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.

A successful handshake proves less than it seems The GET check only shows that Meta can reach your address and that the verify token matches. It does not prove that later POST events will arrive.

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.

POSTsubscribe the app to the WABA
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:

response
{
  "success": true
}

Then read the list back to confirm it:

GETlist the apps subscribed to the WABA
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

  1. The Callback URL is public and uses HTTPS. Meta cannot reach a private address.
  2. The GET check succeeds. The verify token matches and the reply is exactly the hub.challenge value (see How a message arrives).
  3. The messages field is subscribed in the app's webhook settings.
  4. Your app appears in the WABA's subscribed_apps list. Field subscription and WABA subscription are separate.
  5. The Phone Number ID belongs to that WABA. Do not mix up the Phone Number ID, the WABA ID and the App ID.
  6. A fresh WhatsApp message produces a POST in your hosting provider's runtime logs. Use a new message, not an old test payload.
  7. The signature check uses the right secret and the exact raw body. Compute X-Hub-Signature-256 with the App Secret over the unparsed bytes. A re-serialised JSON body gives a different result.
  8. Incoming messages and delivery updates are told apart. Messages sit in value.messages. Updates about messages you sent sit in value.statuses and should not be treated as customer messages.
  9. The bot processes the message and its reply is accepted by Meta. Check the reply's response and, later, its status update.
An empty database is not proof An empty collection does not show that Meta sent nothing. A request that failed the signature check, or crashed before saving, also leaves the database empty. Tell the cases apart with the logs: was there a POST, what status code did it get, and what did the processing log say?

Troubleshooting table

Each row is a lead to check, not a verdict.

SymptomLikely causeNext action
The GET check succeeds, but no POST reaches the serverThe 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 appList subscribed_apps, recheck the messages field, confirm the Phone Number ID, send a fresh message
The POST arrives and returns 401Signature check failing: wrong App Secret (for example from another app) or a changed request bodyUse the secret of the app that sends the webhook and sign the raw body
The POST succeeds, but the database stays emptyThe message was filtered out (allow-list, duplicate, statuses only) or the save failedRead the processing logs and look at what the payload contained
The message is stored, but no reply is sentExpired or wrong access token, wrong Phone Number ID, or a send errorLog the response of the send call and read its error code
A status update contains error code 131000Meta lists this as a generic error, so the code alone does not name the causeRead 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_appsThe app is not subscribed to that WABA, or you queried a different WABA or used another app's tokenCheck 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:

terminal
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 symptomCauseWhat 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 hoursCreate a non-expiring token with a System User in Business Settings and use that
The same message is answered again and againThe webhook is not returning 200, so Meta resends itAlways return 200 after the signature check, and remember each message id
Sending a message returns an errorMore than 24 hours have passed since the user's last messageUse an approved template, or send within 24 hours
Someone can send fake messagesThe webhook does not check the signatureVerify X-Hub-Signature-256
You changed an environment value but nothing changedOn most hosts a new value only applies after a new deploymentDeploy again after the change
Keep secrets out of code Tokens, the App Secret and any API secret key should never sit in a code file or in a screenshot. Keep them in your host's "environment variables".