Articles

How to host a WhatsApp bot for free with the Cloud API webhook

A WhatsApp Cloud API bot is a webhook, so it runs only while it answers. The code, the signature check, and what Meta charges per message since October 2026.

Updated

Build it on Meta’s WhatsApp Cloud API. Meta sends each incoming message to your webhook over HTTPS, and the bot replies by calling the Graph API, so nothing has to run between messages and the bot fits a free plan that scales to zero. Hosting is the cheap part. Since October 1, 2026, Meta charges for replies past the first 1,000 a month per business phone number, and without a payment method on file it stops delivering them. Messages users send you are free.

Gregale publishes this page. Meta’s rules and prices come from its own docs, checked on December 3, 2026: webhooks, creating a webhook endpoint, get started, pricing and business-scoped user IDs. The library details come from the whatsapp-web.js and Baileys READMEs on the same day. Gregale’s come from its plans page.

The Cloud API or a WhatsApp Web library

Most “WhatsApp bot hosting panel” scripts run on an unofficial library that logs in as WhatsApp Web. That choice decides how the bot has to be hosted:

WhatsApp Cloud API (Meta)WhatsApp Web library (whatsapp-web.js, Baileys)
How messages arriveMeta sends each one to your webhookOver a connection the bot keeps open
When the bot runsOnly while it handles a messageAll the time
How it signs inAn access token from MetaA QR code scanned with the phone, and session files the bot must keep
MemoryWhat your web app needswhatsapp-web.js runs a headless browser; Baileys says skipping it saves about half a GB
Allowed by WhatsAppYes, it’s Meta’s own APINo: neither library is affiliated with WhatsApp, and the number can be blocked

The whatsapp-web.js README puts it plainly: “WhatsApp does not allow bots or unofficial clients on their platform.” Baileys’ maintainers discourage bulk or automated messaging with it. A bot for a business, or one you don’t want banned, belongs on the Cloud API.

How the Cloud API webhook works

  • Verification. When you save the callback URL in the App Dashboard, Meta sends a GET with hub.mode=subscribe, hub.verify_token and hub.challenge. If the token matches the one you chose, answer 200 with the challenge.
  • Messages. Each notification is a POST with a JSON body of up to 3 MB and an X-Hub-Signature-256 header: an HMAC-SHA256 of the body, keyed with your app secret. Check it, then answer 200.
  • Retries. If your endpoint doesn’t answer 200, Meta retries with decreasing frequency for up to 7 days. Retries can deliver a message twice, so skip message IDs you’ve already handled.
  • A real certificate. The endpoint needs a valid TLS certificate; self-signed ones are not supported.
  • Usernames. WhatsApp is rolling out usernames through 2026, and a user who adopts one can hide their phone number. Every message carries the user’s business-scoped user ID in from_user_id, while from, the phone number, can be missing. Since July 2026 you can reply to that ID with recipient instead of to.

The bot

A FastAPI app that answers every text message with an echo. The complete project is on GitHub as gregale-dev/whatsapp-cloud-api-webhook, with tests that sign requests the way Meta does. It adds a health check and logs Meta’s reason when it refuses a reply. requirements.txt:

text
fastapi==0.165.0
uvicorn==0.54.0

main.py:

python
import hashlib
import hmac
import json
import os
import urllib.request

from fastapi import BackgroundTasks, FastAPI, Request, Response

app = FastAPI()
VERIFY_TOKEN = os.environ["WHATSAPP_VERIFY_TOKEN"]
APP_SECRET = os.environ["WHATSAPP_APP_SECRET"].encode()
ACCESS_TOKEN = os.environ["WHATSAPP_ACCESS_TOKEN"]
GRAPH_URL = "https://graph.facebook.com/v23.0"


@app.get("/whatsapp/webhook")
def verify(request: Request):
    # Meta calls this once, when you save the callback URL.
    q = request.query_params
    if q.get("hub.mode") == "subscribe" and hmac.compare_digest(
        q.get("hub.verify_token", ""), VERIFY_TOKEN
    ):
        return Response(q.get("hub.challenge", ""), media_type="text/plain")
    return Response(status_code=403)


@app.post("/whatsapp/webhook")
async def receive(request: Request, background: BackgroundTasks):
    body = await request.body()
    expected = "sha256=" + hmac.new(APP_SECRET, body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(request.headers.get("x-hub-signature-256", ""), expected):
        return Response(status_code=401)

    for entry in json.loads(body).get("entry", []):
        for change in entry.get("changes", []):
            value = change.get("value", {})
            for message in value.get("messages", []):
                if message.get("type") == "text":
                    phone_number_id = value["metadata"]["phone_number_id"]
                    background.add_task(reply, phone_number_id, message)
    # Answer Meta first; the reply goes out after the response.
    return Response(status_code=200)


def reply(phone_number_id: str, message: dict) -> None:
    payload = {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "type": "text",
        "text": {"body": f"You said: {message['text']['body']}"},
    }
    # A user with a username may arrive without a phone number.
    if "from" in message:
        payload["to"] = message["from"]
    else:
        payload["recipient"] = message["from_user_id"]
    request = urllib.request.Request(
        f"{GRAPH_URL}/{phone_number_id}/messages",
        data=json.dumps(payload).encode(),
        headers={
            "Authorization": f"Bearer {ACCESS_TOKEN}",
            "Content-Type": "application/json",
        },
    )
    urllib.request.urlopen(request, timeout=10).read()

What the code does:

  • It checks the signature over the raw body. Parsing the JSON first and hashing it again would not match Meta’s bytes.
  • It answers Meta before it replies. The reply runs as a background task after the 200, so a slow Graph API call never makes Meta retry. On Gregale the instance keeps running while that call is in flight; in our Telegram test, a 4-second call made after the response finished without waiting for the next request.
  • It ignores everything but text. Status updates (sent, delivered, read) arrive on the same webhook without a messages array.
  • v23.0 is the Graph API version in Meta’s get-started sample. Use the version your app is on.

Deploy it and connect Meta

Make the app public in gregale.yaml, because Meta can’t send a Gregale API key:

yaml
access: public

Choose a verify token, and copy the app secret from App settings → Basic and a system user’s access token from Business Settings → System users (the temporary token from the API Setup page expires quickly). Then deploy:

bash
cat > ../whatsapp.secrets <<EOF
WHATSAPP_VERIFY_TOKEN=$(openssl rand -hex 32)
WHATSAPP_APP_SECRET=<app secret>
WHATSAPP_ACCESS_TOKEN=<system user token>
EOF
gregale deploy --name my-whatsapp-bot --secrets-file ../whatsapp.secrets

In the App Dashboard, open WhatsApp → Configuration (Use cases → Customize → Configuration for an app made with the WhatsApp use case), set the callback URL to https://my-whatsapp-bot.gregale.app/whatsapp/webhook and the verify token to the value in your secrets file, then subscribe to the messages field. Keep the secrets file out of the repository.

What it costs

Hosting on Gregale. The Free plan runs 1 app with 256 MB and 20 GB-RAM-hours a month, and requests can take up to 30 seconds. An app parks after 1 minute idle, holds no memory while parked, and the next message restores it from a snapshot in 50 to 83 ms in our measurements. A webhook is plain HTTP, which is all Free serves.

Messages on Meta, since October 1, 2026:

  • Messages users send to the business are free.
  • Replies inside the 24-hour customer service window, which each user message opens, are service messages. Each business phone number gets 1,000 free a month; after that Meta charges per message at the rate for the user’s country. Without a payment method, Meta stops delivering them once the 1,000 are used.
  • Anything you send outside that window must be a template message (marketing, utility or authentication), charged at the published rates.

Elsewhere. Meta’s own guide to a test webhook deploys it on Render. On Render’s Free plan the service spins down after 15 minutes without traffic, and the next message waits about a minute while it starts. Meta retries a webhook it can’t deliver, so that message arrives late rather than never.

What we verified

Meta’s webhook rules, pricing and username changes come from its docs on December 3, 2026. That day we ran the bot’s code locally against sample payloads signed the way Meta signs them: the verification request, a request with a bad signature (answered 401), a text message from a phone number and one from a username, with the Graph API call captured instead of sent. We then deployed the example repository on Gregale at 256 MB and sent it the same requests. Each got the expected answer, and the Graph API call went out after the 200; Meta refused our placeholder token, as it should. After 13 minutes idle, the first byte of the 200 left 28 ms after the wake began. We didn’t connect a live WhatsApp number. Gregale’s plans come from its plans page on the same date, and its restore times from cold start times by language.

Questions

Can I host a WhatsApp bot for free?

Yes. A bot on Meta’s WhatsApp Cloud API is a webhook: Meta sends each message to its HTTPS URL, so it fits a free plan that scales to zero. Meta charges for the messages, though: each business phone number gets 1,000 free service messages a month, then pays per message.

Is whatsapp-web.js or Baileys allowed?

No. Neither is affiliated with WhatsApp, the whatsapp-web.js README says WhatsApp does not allow bots or unofficial clients, and the number can be blocked. They also keep a connection open, so the bot has to run all the time.

How do I verify the WhatsApp webhook?

When you save the callback URL, Meta sends a GET with hub.mode, hub.verify_token and hub.challenge. If the token matches yours, answer 200 with the challenge. Then check the X-Hub-Signature-256 header, an HMAC-SHA256 of the body keyed with your app secret, on every POST.

Why does the webhook have no phone number for some users?

WhatsApp is rolling out usernames, and a user who adopts one can hide their phone number. Every message carries a business-scoped user ID in from_user_id; reply to it with recipient instead of to.