# Build a WhatsApp chatbot with the API

> Receive WhatsApp messages on a signed webhook, answer common questions from your own code, and hand the chat to a person when the customer asks for one.

In this guide you build a small WhatsApp bot that answers questions about your opening hours and prices, and passes the chat to a person when the customer asks for one.

**What the customer sees:** they write to your WhatsApp number, their message gets blue ticks, "typing..." appears, and the answer arrives a second later. When they write "can I talk to a person?", the bot says a person will answer, and from then on only your team replies.

**What you see:** every message and answer in the app2email Inbox and Activity Log, the delivery and read ticks of every answer as webhook events, and a summary of the chat when the bot hands it over.

The bot is under 100 lines of Node.js (Express) or Python (Flask). It checks the webhook signature, ignores events it has already handled, retries safely and respects the 24 hour reply window.

## How it works

1. A customer sends a message to your WhatsApp number.
2. app2email sends a signed `POST` with the event `message.received` to your URL.
3. Your code checks the signature, looks up the conversation (is a person handling it? is the reply window open?), marks the message as read with the typing indicator, and sends the answer with `POST /messages`.
4. app2email sends `message.status` events as the answer is sent, delivered and read.

Your URL must answer with a 2xx status within 10 seconds. If it does not, app2email sends the same event again later, so a short outage loses nothing.

## What you need

- **A WhatsApp number connected to app2email**, on a paid plan and live. Without a plan every call answers 403 `plan_not_allowed`; a paused service answers 403 `service_not_live`. See [Getting started](https://www.app2email.com/docs/onboarding).
- **An API key** from [the API key page](https://www.app2email.com/dashboard/apikey) with these scopes:

| Scope | Why the bot needs it |
| --- | --- |
| `messages:send` | Send the answers (`POST /messages`), mark messages as read (`POST /messages/read`), hand a chat to a person (`PUT /conversations/{contact}/owner`) |
| `messages:read` | Look up the conversation: owner and reply window (`GET /conversations/{contact}`) |
| `webhooks:manage` | Register the webhook once (`POST /webhooks`). You can also add it on the API key page under Webhooks, without code |

- **A public https address** for the webhook. On your own computer a tunnel gives you one (step 2 below).
- **An approved template** without placeholders, for the rare answer that goes out after the reply window has closed (see [the 24 hour window](#the-24-hour-window)).

<Tip>
**Try it before you go live.** A **sandbox key** (a key with the sandbox flag, made on the API key page) runs every check against your own number and sends nothing to WhatsApp: answers have `"sandbox": true` and message ids that start with `wamid.SANDBOX.`, and `message.status` events still arrive. With no account at all, the **instant sandbox** gives you a key for the demo number `12025550100` with pretend customers: `POST https://api.app2email.com/v1/account/sandbox` (no key, no body) or the `create_sandbox` tool of the Management MCP server. It has no webhooks: read the events with `GET /events?wait=25` instead (see the FAQ). Details: [Sandbox](/api/sandbox).
</Tip>

## Set up in four steps

<Steps>
  <Step title="Check your key">
    `GET /me` works with any valid key and shows its scopes and limits. In every request, `YOUR_NUMBER` is the WhatsApp number you send from: country code first, digits only.

    <CodeGroup>

    ```bash cURL
    curl https://api.app2email.com/v1/YOUR_NUMBER/me \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/me", {
      headers: { Authorization: `Bearer ${process.env.API_KEY}` },
    });
    console.log(await res.json());
    ```

    ```python Python
    import os, requests

    res = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/me",
                       headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=10)
    print(res.json())
    ```

    </CodeGroup>

    **What you get back:**

    ```json
    {
      "success": true,
      "request_id": "a7k3p",
      "key_valid": true,
      "api_version": "v1",
      "number": "4976659348270",
      "plan": "standard_5000",
      "service_status": "LIVE",
      "key": { "name": "WhatsApp bot", "scopes": ["messages:read", "messages:send"], "ip_allow": "" },
      "limits": { "max_numbers_per_request": 1000, "requests_per_second": 20, "burst": 50, "rate_limit_mode": "enforce", "webhooks_max": 5 }
    }
    ```

    `service_status` must be `LIVE`, and `key.scopes` must list the scopes from the table above (or `*` for full access).
  </Step>
  <Step title="Give your computer a public address">
    app2email can only send events to a public https address. While you develop, a tunnel forwards one to your computer. Start the bot on port 3000 (the code is further down), then in a second terminal:

    ```bash
    # ngrok (https://ngrok.com)
    ngrok http 3000

    # or Cloudflare's cloudflared, no account needed for a quick tunnel
    cloudflared tunnel --url http://localhost:3000
    ```

    Both print an https address such as `https://a1b2-203-0-113-7.ngrok-free.app`. Your webhook URL is that address plus `/webhook`. A quick tunnel may get a new address each time it starts: update the webhook with `PATCH /webhooks/{id}` and a new `url` when that happens.

    No tunnel possible? `GET /events?wait=25` fetches the same events without a public address (see the FAQ).
  </Step>
  <Step title="Register the webhook">
    One call. The answer holds the **signing secret** (`whsec_...`) that signs every event: keep it with your key, for example in an environment variable `WEBHOOK_SECRET`.

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/webhooks", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ url: "https://a1b2-203-0-113-7.ngrok-free.app/webhook" }),
    });
    const { webhook } = await res.json();
    console.log(webhook.id, webhook.secret);
    ```

    ```python Python
    import os, requests

    res = requests.post("https://api.app2email.com/v1/YOUR_NUMBER/webhooks",
                        headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
                        json={"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}, timeout=10)
    webhook = res.json()["webhook"]
    print(webhook["id"], webhook["secret"])
    ```

    </CodeGroup>

    **What you get back** (201 Created; shortened: the answer also lists every event type in `events`):

    ```json
    {
      "success": true,
      "request_id": "w8hk2",
      "webhook": {
        "id": "wh_a1b2c3d4e5f6g7h8",
        "url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook",
        "secret": "whsec_...",
        "created": "2026-11-21T09:00:00.000Z",
        "active": true,
        "format": "app2email"
      }
    }
    ```

    Registering the same URL again answers 200 with the same id and secret, so the call is safe to repeat. A number has at most 5 webhooks, and every webhook gets every event: your code picks the types it handles by `type` and answers 2xx to the rest. Keep `format` at `app2email` (the default) for this guide.
  </Step>
  <Step title="Send a test event">
    `POST /webhooks/{id}/test` sends a signed sample straight away and tells you how your URL answered. With `{"type": "message.received"}` you get that event's sample.

    ```bash
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks/wh_a1b2c3d4e5f6g7h8/test \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"type": "message.received"}'
    ```

    **What you get back** (shortened):

    ```json
    {
      "success": true,
      "request_id": "t3ws9",
      "delivered": true,
      "http_status": 200,
      "response_ms": 38
    }
    ```

    `delivered: true` means your URL answered 2xx within 10 seconds. A test event carries `"test": true` and the header `X-App2email-Test: true`, and its sample contact is made up, so the bot below checks the signature, logs the event and does not reply to it. Up to 30 tests an hour per number. Then send a real message to your number from your own phone: the bot answers.
  </Step>
</Steps>

## The four calls the bot makes

Every call goes to `https://api.app2email.com/v1/YOUR_NUMBER` with `Authorization: Bearer YOUR_API_KEY`.

### 1. Read what the customer sent

This is the body of the `message.received` event your URL gets (a text message):

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "message.received",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "from": "61412345678",
    "name": "Sample Contact",
    "type": "text",
    "text": "What are your opening hours?",
    "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
    "timestamp": "2026-11-06T01:00:00.000Z",
    "from_user_id": "AU.1234567890123456"
  }
}
```

- `id` (also in the header `X-App2email-Delivery`) is the same on every retry: it is what you dedupe by.
- `data.from` is the customer's number. A contact who uses a WhatsApp username may come with `from_user_id` and no number; that id works wherever a number does.
- `data.type` is `text`, `image`, `audio`, `interactive` (a tap on a reply button or a list row, with `interactive.id`), `button` (a template's quick reply button, with `button.payload`), and more. The bot answers text and taps and leaves everything else to your team.

### 2. Look up the conversation

`GET /conversations/{contact}` (scope `messages:read`) says who handles the chat and whether a free-form reply can be sent now.

```bash
curl https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**What you get back:**

```json
{
  "success": true,
  "request_id": "c9slm",
  "contact": "61412345678",
  "identity_type": "phone",
  "phone": "61412345678",
  "name": "John",
  "window_state": "open",
  "window_open": true,
  "window_closes_at": "2026-11-07T00:45:00Z",
  "last_inbound_at": "2026-11-06T01:00:00Z",
  "messages": 12,
  "owner": "",
  "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}
```

`owner` is empty for normal handling. When it is `human` or `paused` a person has the chat and the bot stays quiet; `whatsapp_ai` means WhatsApp's own AI agent holds it.

### 3. Show the blue ticks and "typing..."

`POST /messages/read` (scope `messages:send`) marks the message as read and, with `"typing": true`, shows the typing indicator for up to 25 seconds or until your answer arrives. It is free: not counted against your plan, and not bound to the 24 hour window.

```bash
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages/read \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=", "typing": true}'
```

**What you get back:**

```json
{
  "success": true,
  "request_id": "k2rdq",
  "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
  "status": "read",
  "typing_indicator": true
}
```

### 4. Send the answer

`POST /messages` (scope `messages:send`) with `"type": "text"` sends a free-form message to one contact while the reply window is open.

| Part | What to fill in |
| --- | --- |
| Who | `to`: the customer's number (`data.from`), or their `from_user_id` |
| Which message | `type`: `text` for a normal reply. Outside the window: `template` |
| What it says | `text.body`: your answer. `text.preview_url`: true to show a link preview |
| Your key | the header `Authorization: Bearer YOUR_API_KEY` |
| No doubles | the header `Idempotency-Key`: a value unique to this answer, eg `text-` plus the customer's `message_id`. The same request with the same key within 24 hours is not sent again |

<CodeGroup>

```bash cURL
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: text-wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=" \
  -d '{"to": "61412345678", "type": "text", "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": false}}'
```

```javascript Node.js
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": `text-${messageId}`,
  },
  body: JSON.stringify({
    to: "61412345678",
    type: "text",
    text: { body: "We are open Monday to Friday, 9 am to 5 pm.", preview_url: false },
  }),
});
console.log(res.status, await res.json());
```

```python Python
res = requests.post(
    "https://api.app2email.com/v1/YOUR_NUMBER/messages",
    headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"text-{message_id}"},
    json={"to": "61412345678", "type": "text",
          "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": False}},
    timeout=10,
)
print(res.status_code, res.json())
```

</CodeGroup>

**What you get back** (200):

```json
{
  "success": true,
  "request_id": "kxrkf",
  "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
  "status": "accepted",
  "type": "text",
  "from": "4976659348270",
  "to": "61412345678",
  "window_closes_at": "2026-11-07T00:45:00Z",
  "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
  "contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
}
```

`accepted` means WhatsApp took the message. Whether it was delivered and read comes later as `message.status` events. A repeated request with the same `Idempotency-Key` gets this same answer again with the header `Idempotent-Replayed: true`, and nothing is sent twice.

**When it fails**, the answer has `success: false` and an `error` object. Decide by `error.code`, never by the message text:

```json
{
  "success": false,
  "request_id": "q2v8n",
  "error": {
    "code": "outside_24h_window",
    "message": "The contact has not written to this number in the last 24 hours (or never), so only a template message can be sent.",
    "how_to_fix": "Send an approved template message instead (\"type\": \"template\"). When the contact answers, normal messages work again for 24 hours.",
    "documentation_url": "https://www.app2email.com/docs/api/errors#outside_24h_window",
    "is_retriable": false
  }
}
```

Too many calls answer 429 `rate_limited` with a `Retry-After` header:

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 2

{"success": false, "request_id": "r5lmt", "error": {"code": "rate_limited", "message": "Too many requests for this key.", "how_to_fix": "Wait, then send again.", "documentation_url": "https://www.app2email.com/docs/api/errors#rate_limited", "is_retriable": true, "retry_after_seconds": 2}}
```

### Hand the chat to a person

When the customer asks for a person, `PUT /conversations/{contact}/owner` (scope `messages:send`) with `"owner": "human"`, a short `reason` and a `summary`. app2email's auto reply and other agents then leave the contact alone, the people who get the messages by email see the summary, and every webhook gets `conversation.owner_changed`. `until_minutes` makes it temporary: after that the chat goes back to normal handling by itself.

```bash
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"owner": "human", "reason": "customer asked for a person", "summary": "Wants to move the delivery to Monday.", "until_minutes": 240}'
```

The answer holds the updated `conversation` (the same fields as `GET /conversations/{contact}`).

## The complete bot

Both versions do the same: verify the signature, skip test events and events already handled, skip chats a person owns, mark as read with typing, hand over on "person", answer keywords, and fall back to a template when the window has closed. Set three environment variables first: `NUMBER` (your WhatsApp number, digits), `API_KEY` and `WEBHOOK_SECRET` (the `whsec_...` value from step 3).

<Tabs>
  <Tab title="Node.js (Express)">

```javascript bot.mjs
// Node.js 18 or newer.  npm install express   then   node bot.mjs
import crypto from "node:crypto";
import express from "express";

const { NUMBER, API_KEY, WEBHOOK_SECRET, PORT = 3000 } = process.env;
const API = `https://api.app2email.com/v1/${NUMBER}`;
const FALLBACK = { name: "hello_world", language: { code: "en_US" } }; // an approved template without placeholders
const RETRY_LATER = new Set(["rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"]);
const done = new Set(); // handled event ids: use a database table or Redis in production

const ANSWERS = [
  [/\b(hours?|open|opening|closed)\b/i, "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."],
  [/\b(prices?|cost|how much)\b/i, "A standard service is $49, an express service $79. Full list: https://example.com/prices"],
];
const HUMAN = /\b(human|person|someone|staff)\b/i;
const MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team.";

function verify(raw, header, secret) {
  const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
  const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]); // two during a secret change
  if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const expected = crypto.createHmac("sha256", secret).update(t + ".").update(raw).digest("hex");
  return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}

async function api(method, path, body, idempotencyKey) {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(API + path, {
      method,
      signal: AbortSignal.timeout(4000),
      headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json",
                 ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}) },
      body: body ? JSON.stringify(body) : undefined,
    });
    const json = await res.json();
    if (res.ok) return json;
    const code = json.error?.code;
    const wait = Number(res.headers.get("Retry-After") ?? 1);
    if (code === "rate_limited" && attempt < 3 && wait <= 3) { await new Promise((r) => setTimeout(r, wait * 1000)); continue; }
    if (res.status >= 500 || RETRY_LATER.has(code)) throw new Error(`${code} ${json.request_id}`);
    console.warn(method, path, code, json.error?.how_to_fix, json.request_id);
    return json;
  }
}

async function reply(to, windowOpen, body, inReplyTo) {
  if (windowOpen) {
    const sent = await api("POST", "/messages", { to, type: "text", text: { body } }, `text-${inReplyTo}`);
    if (sent.error?.code !== "outside_24h_window") return sent;
  }
  return api("POST", "/messages", { to, type: "template", template: FALLBACK }, `tpl-${inReplyTo}`);
}

async function handle(m) {
  if (!["text", "interactive", "button"].includes(m.type)) return; // photos, voice notes ...: for the team
  const contact = encodeURIComponent(m.from || m.from_user_id);
  const text = m.interactive?.id || m.button?.payload || m.text || "";
  const conv = await api("GET", `/conversations/${contact}`);
  if (["human", "paused", "whatsapp_ai"].includes(conv.owner)) return; // someone else has this chat
  await api("POST", "/messages/read", { message_id: m.message_id, typing: true });
  const open = conv.window_open !== false;
  if (HUMAN.test(text)) {
    await api("PUT", `/conversations/${contact}/owner`, {
      owner: "human", reason: "customer asked for a person", summary: text.slice(0, 300), until_minutes: 240 });
    return reply(m.from || m.from_user_id, open, "Thanks! A person from our team will answer you here soon.", m.message_id);
  }
  const hit = ANSWERS.find(([pattern]) => pattern.test(text));
  return reply(m.from || m.from_user_id, open, hit ? hit[1] : MENU, m.message_id);
}

const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
  const event = JSON.parse(req.body);
  if (event.test) { console.log("test event ok:", event.type); return res.sendStatus(200); }
  if (event.type !== "message.received" || done.has(event.id)) return res.sendStatus(200);
  try {
    await handle(event.data);
    done.add(event.id); // only after it worked: a failed event comes again
    res.sendStatus(200);
  } catch (err) {
    console.error("not handled, app2email will send it again:", event.id, err.message);
    res.sendStatus(503);
  }
});
app.listen(PORT, () => console.log(`bot on http://localhost:${PORT}/webhook`));
```

  </Tab>
  <Tab title="Python (Flask)">

```python bot.py
# Python 3.9 or newer.  pip install flask requests   then   flask --app bot run --port 3000
import hashlib, hmac, json, os, re, time
import requests
from flask import Flask, request

NUMBER, API_KEY, SECRET = os.environ["NUMBER"], os.environ["API_KEY"], os.environ["WEBHOOK_SECRET"]
API = f"https://api.app2email.com/v1/{NUMBER}"
FALLBACK = {"name": "hello_world", "language": {"code": "en_US"}}  # an approved template without placeholders
RETRY_LATER = {"rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"}
done = set()  # handled event ids: use a database table or Redis in production

ANSWERS = [
    (re.compile(r"\b(hours?|open|opening|closed)\b", re.I), "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."),
    (re.compile(r"\b(prices?|cost|how much)\b", re.I), "A standard service is $49, an express service $79. Full list: https://example.com/prices"),
]
HUMAN = re.compile(r"\b(human|person|someone|staff)\b", re.I)
MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team."

def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
    v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "")  # two during a secret change
    if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
        return False
    expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(v, expected) for v in v1)

def api(method, path, body=None, idempotency_key=None):
    headers = {"Authorization": f"Bearer {API_KEY}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for attempt in (1, 2, 3):
        res = requests.request(method, API + path, json=body, headers=headers, timeout=4)
        data = res.json()
        if res.ok:
            return data
        code = data.get("error", {}).get("code")
        wait = int(res.headers.get("Retry-After", "1"))
        if code == "rate_limited" and attempt < 3 and wait <= 3:
            time.sleep(wait)
            continue
        if res.status_code >= 500 or code in RETRY_LATER:
            raise RuntimeError(f"{code} {data.get('request_id')}")
        print("not done:", method, path, code, data.get("error", {}).get("how_to_fix"), data.get("request_id"))
        return data

def reply(to, window_open, body, in_reply_to):
    if window_open:
        sent = api("POST", "/messages", {"to": to, "type": "text", "text": {"body": body}}, f"text-{in_reply_to}")
        if sent.get("error", {}).get("code") != "outside_24h_window":
            return sent
    return api("POST", "/messages", {"to": to, "type": "template", "template": FALLBACK}, f"tpl-{in_reply_to}")

def handle(m):
    if m.get("type") not in ("text", "interactive", "button"):
        return  # photos, voice notes ...: for the team
    contact = m.get("from") or m.get("from_user_id")
    text = (m.get("interactive") or {}).get("id") or (m.get("button") or {}).get("payload") or m.get("text") or ""
    conv = api("GET", f"/conversations/{contact}")
    if conv.get("owner") in ("human", "paused", "whatsapp_ai"):
        return  # someone else has this chat
    api("POST", "/messages/read", {"message_id": m["message_id"], "typing": True})
    window_open = conv.get("window_open") is not False
    if HUMAN.search(text):
        api("PUT", f"/conversations/{contact}/owner", {"owner": "human", "reason": "customer asked for a person",
                                                       "summary": text[:300], "until_minutes": 240})
        return reply(contact, window_open, "Thanks! A person from our team will answer you here soon.", m["message_id"])
    answer = next((a for pattern, a in ANSWERS if pattern.search(text)), MENU)
    return reply(contact, window_open, answer, m["message_id"])

app = Flask(__name__)

@app.post("/webhook")
def webhook():
    raw = request.get_data()
    if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
        return "bad signature", 401
    event = json.loads(raw)
    if event.get("test"):
        print("test event ok:", event["type"])
        return "", 200
    if event["type"] != "message.received" or event["id"] in done:
        return "", 200
    try:
        handle(event["data"])
    except Exception as err:
        print("not handled, app2email will send it again:", event["id"], err)
        return "", 503
    done.add(event["id"])  # only after it worked: a failed event comes again
    return "", 200
```

  </Tab>
</Tabs>

**Why it is built this way:**

- The signature is checked over the **raw body** before anything is parsed (`express.raw`, `request.get_data()`).
- An event is marked as handled only after the answer went out. If a call fails with a 5xx or a rate limit, the bot answers 503 and app2email sends the event again later (after 10 s, 1 min, 5 min ...). The `Idempotency-Key` makes sure a retry never sends the same answer twice, even when the first try got as far as sending.
- A short 429 `rate_limited` is waited out inside the request (at most 3 seconds, so the 10 second limit holds). Anything longer goes back to app2email's retries.
- Errors that will not change by trying again (a wrong template name, a missing scope) are logged with `how_to_fix` and `request_id`, and the event is answered 200 so it does not keep coming back.
- `FALLBACK` is `hello_world` because the instant sandbox has it. On your own number, put the name and language of one of your approved templates (`GET /templates` lists them, each with a complete `example_request`).

## What happens on WhatsApp

1. The customer writes "What are your opening hours?".
2. Their message gets blue ticks and "typing..." shows.
3. The answer arrives. In the Inbox and the Activity Log you see both messages.
4. Your webhook gets `message.status` for the answer: `sent`, then `delivered`, then `read`.

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs02",
  "type": "message.status",
  "created": "2026-11-06T01:00:03.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "to": "61412345678",
    "status": "delivered",
    "timestamp": "2026-11-06T01:00:03.000Z",
    "sent_by": "api",
    "whatsapp_status": "delivered"
  }
}
```

A failed answer comes as `message.status` with `status: "failed"` and an `error` object (`code` is Meta's code, `error_code` app2email's), and also as `message.failed`.

When the customer writes "can I talk to a person?", they get "A person from our team will answer you here soon", and your webhook gets:

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs03",
  "type": "conversation.owner_changed",
  "created": "2026-11-06T01:02:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "owner": "human",
    "previous_owner": "",
    "reason": "customer asked for a person",
    "summary": "can I talk to a person?",
    "until": "2026-11-06T05:02:00.000Z",
    "set_by": "api",
    "timestamp": "2026-11-06T01:02:00.000Z"
  }
}
```

A person answers from the Inbox, from email, or through the API. The bot sees the owner `human` on the next message and stays quiet.

**Back to the bot:** after `until_minutes` the owner is empty again by itself. A person can also give the chat back earlier with `PUT /conversations/{contact}/owner` and `{"owner": ""}`, which sends `conversation.owner_changed` again. Do not take a chat back in code while a person has it.

<a id="the-24-hour-window"></a>

## The 24 hour window

WhatsApp lets you send free-form messages (text, images, buttons) for 24 hours after the customer's last message. app2email stops 15 minutes early; `window_closes_at` is the exact time. After that only an approved template can start the conversation again.

A bot that answers within seconds is almost always inside the window. It matters when an event is delivered late: retries go on for about 32 hours, so an answer to a message from yesterday may need a template. The bot checks `window_open` before it writes, and still falls back to the template if the send answers 422 `outside_24h_window`.

The Do Not Call list does not apply to free-form replies, because the customer wrote to you. The exception: when their last message was the opt-out itself, a reply answers 403 `recipient_opted_out` until they write again.

## Production checklist

<Check>
**Verify every event.** The header `X-App2email-Signature` is `t=<unix seconds>,v1=<hex>`: the HMAC-SHA256 of the text `t`, a dot and the raw body, with the webhook's secret (`whsec_...`, prefix included) as the key. Check every `v1=` (there are two for a while after `POST /webhooks/{id}/rotate-secret` with `keep_old_for_hours`), compare in constant time, and refuse a `t` older than 5 minutes. `X-Hub-Signature-256` (`sha256=` and the HMAC-SHA256 of the raw body, as Meta signs) is there too if your code already checks Meta's webhooks; it has no time in it and only the current secret.
</Check>

<Check>
**Answer fast.** Return 2xx within 10 seconds. Redirects are not followed. For slow work (a database, an AI model), store the event, answer 200, and process it from a queue that retries by itself.
</Check>

<Check>
**Dedupe.** Keep the event `id` (`X-App2email-Delivery`) of every handled event for at least two days: retries run for about 32 hours. Keep it in a database or Redis, not in memory, when you run more than one process. Events can also arrive out of order: use `data.timestamp`, not the order they came in.
</Check>

<Check>
**Send each answer once.** Give every `POST /messages` an `Idempotency-Key` built from the customer's `message_id`. Same key and same body within 24 hours: the first answer comes back with `Idempotent-Replayed: true`. Same key, other body: 422 `idempotency_key_reused`. 409 `idempotency_request_in_progress`: wait and retry with the same key.
</Check>

<Check>
**Respect the limits.** Every answer has `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (seconds until full again) and `X-RateLimit-Policy`; `GET /me` shows your key's `limits`. Over the limit: 429 `rate_limited` with `Retry-After` and `error.retry_after_seconds`. WhatsApp's own limits (429 `whatsapp_rate_limit`, `too_many_messages_to_recipient`) need minutes, not seconds. 429 `monthly_limit_reached` and `daily_cap_reached` are not worth retrying now (`retry_after_seconds` says until when): tell a person.
</Check>

<Check>
**Keep the webhook on.** After 20 events in a row that were not delivered within their first 4 tries (over at least 24 hours), app2email switches the webhook off. `GET /webhooks/{id}/deliveries?status=failed` shows what failed and why; `PATCH /webhooks/{id}` with `{"active": true}` turns it on again, and `POST /webhooks/{id}/deliveries/{event_id}/redeliver` sends one event again.
</Check>

<Check>
**Leave people alone when a person has the chat.** Check `owner` before every answer (`human`, `paused` and `whatsapp_ai` mean: do not answer), and hand over when the customer asks.
</Check>

<Check>
**One answerer per number.** The number's auto reply (the first reply a new contact gets), chat automations and AI answers also see every message. Check the dashboard so a new contact does not get two first answers.
</Check>

<Check>
**Treat the customer's text as data.** It is written by the customer. Never run it as a command, and if you pass it to an AI model, keep it apart from your instructions.
</Check>

<Check>
**Least access.** A bot key needs `messages:send` and `messages:read` only. Keep it on the server, never in a web page or a log. A key can be limited to your server's IP addresses, have a daily cap, or expire.
</Check>

## If it does not work

| What you see | Why | Fix |
| --- | --- | --- |
| Your bot answers 401 to every event | The signature does not match | Use the `whsec_...` secret of this webhook with its prefix; check the raw body, before any JSON parser touches it; check the server clock (`t` must be within 5 minutes) |
| 401 `missing_api_key`, `invalid_api_key`, `api_key_revoked` | No key, a wrong key, or an old one | Send `Authorization: Bearer YOUR_API_KEY` with a key listed on the API key page, and the number of that key in the URL |
| 403 `insufficient_scope` | The key lacks a permission (`details.required_scope`) | Make a key with `messages:send` and `messages:read` (and `webhooks:manage` to register the webhook) |
| 403 `plan_not_allowed`, `service_not_live` | No paid plan, or the service is paused | Choose a plan; a paused service goes live with "Go Live" on the Settings page |
| 422 `invalid_webhook_url` | The URL is not a public https address | Use the https address of your tunnel or server, with the path (`/webhook`) |
| 409 `webhook_url_in_use` | Another webhook of the number has this URL | Change that webhook with `PATCH`, or delete one |
| 400 `too_many_webhooks` | The number has 5 webhooks | Delete one you no longer use |
| 422 `outside_24h_window` | The customer last wrote more than 24 hours ago | Send an approved template |
| 404 `template_not_found`, 422 `template_not_approved` | The fallback template's name or language is wrong, or it is not approved yet | Pick one from `GET /templates` with status APPROVED |
| 422 `template_parameters_invalid` | The fallback template has placeholders | Use one without placeholders, or fill them as its `example_request` shows |
| 403 `recipient_opted_out` | The customer's last message was the opt-out | Do not reply until they write again |
| 429 `rate_limited` | Too many calls for this key | Wait `Retry-After` seconds, then retry |
| 429 `whatsapp_rate_limit`, `too_many_messages_to_recipient` | WhatsApp's limit | Back off for minutes |
| 429 `too_many_tests` | More than 30 test events in an hour | Wait, or test with a message from your phone |
| 403 `not_in_instant_sandbox` | The demo number does not have this call (webhooks, for one) | Use `GET /events` there, or a sandbox key on your own number |
| No events arrive at all | The webhook is switched off, or the tunnel's address changed | `GET /webhooks` shows `active` and the last delivery; `PATCH` the new `url` or `{"active": true}` |

Every answer has a `request_id`. `GET /requests/{id}` shows what was logged for it, and support@app2email.com can find it too. All codes: [Errors](/api/errors).

## Other ways to answer customers

- **AI answers**: app2email's assistant answers from your website, PDFs and notes and hands the chat to a person when it cannot help (Professional plan and the trial). It reports `ai.answered` and `ai.handover`. It answers a customer only while the conversation has no owner and no app or automation answered, so pick one answerer per number. See the [AI answers settings](https://www.app2email.com/docs/api/ai-answers/get-ai-answers-settings).
- **An AI agent over MCP**: the MCP server `https://api.app2email.com/mcp` has the same calls as tools (`send_text`, `mark_read`, `get_conversation`, `set_conversation_owner`, `list_events`, `wait_for_message` ...). See [Let an AI agent run your WhatsApp with MCP](/guides/how-to-ai-agent-mcp) and [MCP](/api/mcp).
- **Hand-offs in more depth**: [Hand a chat from your bot to a person and back](/guides/how-to-human-handoff).

## FAQ

<AccordionGroup>
  <Accordion title="Can I build and test this without a WhatsApp number?">
    Yes. `POST https://api.app2email.com/v1/account/sandbox` (no key, no body) answers an instant sandbox key (`a2es_...`, valid 7 days) for the demo number `12025550100`. Its pretend customers include Ava (`12025550101`, answers every message) and Eve (`12025550105`, asks for a person). It has `GET /conversations/{contact}`, `PUT /conversations/{contact}/owner`, `POST /messages` and `GET /events`, so the bot's logic runs there, and it has the `hello_world` template used as the fallback. It has no webhooks: read events with `GET /events` (next question). `POST /messages/read` is not there either; it answers 403 `not_in_instant_sandbox`, which the bot logs and carries on. Nothing reaches WhatsApp.
  </Accordion>
  <Accordion title="Can I receive messages without a public URL?">
    Yes: `GET /events?wait=25` (scope `messages:read`) holds the answer until an event arrives, up to 25 seconds. Each event is the same JSON a webhook gets, with the same `id`. Keep the answer's `cursor` and pass it as `after` on the next call; skip ids you have handled, because after a lost answer an event can come again. `types=message.received` gives only incoming messages. The first call switches the number's feed on; events are kept 72 hours.

    ```javascript
    let after = "now";
    for (;;) {
      const page = await api("GET", `/events?wait=25&types=message.received&after=${after}`);
      for (const event of page.events ?? []) if (!done.has(event.id)) { await handle(event.data); done.add(event.id); }
      after = page.cursor ?? after;
    }
    ```
  </Accordion>
  <Accordion title="Can the customer tap buttons instead of typing?">
    Yes, inside the 24 hour window. Send `"type": "interactive"` with up to 3 reply buttons, or a list of up to 10 rows. Give the buttons the ids the bot already understands, and a tap arrives as `message.received` with `type` `interactive` and `interactive.id`:

    ```json
    {
      "to": "61412345678",
      "type": "interactive",
      "interactive": {
        "type": "button",
        "body": { "text": "What would you like to know?" },
        "action": {
          "buttons": [
            { "type": "reply", "reply": { "id": "hours", "title": "Opening hours" } },
            { "type": "reply", "reply": { "id": "prices", "title": "Prices" } },
            { "type": "reply", "reply": { "id": "person", "title": "Talk to a person" } }
          ]
        }
      }
    }
    ```
  </Accordion>
  <Accordion title="What does each answer cost?">
    Each answer the bot sends counts as one message of your app2email plan. Marking as read and the typing indicator are free. Meta bills you directly: answers inside the window are service messages (the first 1,000 a month per number are free), templates are charged per message. `GET /usage` shows what is used and left this month, with Meta's categories in `meta_pricing`.
  </Accordion>
  <Accordion title="What happens with photos, voice notes and documents?">
    They arrive as `message.received` with `type` `image`, `audio`, `document` and so on, and a `media_url`: app2email keeps a copy, served by `GET /media/{message_id}`. The bot above leaves them to your team; you could also hand the chat over as soon as one arrives.
  </Accordion>
  <Accordion title="How does a person reply, and how do I give the chat back to the bot?">
    From the Inbox on the dashboard, from email (when email forwarding is on), or through the API. The chat goes back to the bot when `until_minutes` runs out, or earlier with `PUT /conversations/{contact}/owner` and `{"owner": ""}`.
  </Accordion>
  <Accordion title="Can I get Meta's own webhook format instead?">
    Yes: a webhook with `"format": "meta"` gets what comes from WhatsApp as Meta's own body (`entry[].changes[]`), signed the same way. app2email's own events, such as `conversation.owner_changed`, keep the app2email envelope. This guide uses the default `app2email` format.
  </Accordion>
  <Accordion title="Some customers have no phone number in the event. Why?">
    WhatsApp is moving to usernames with business-scoped user ids (like `AU.1234567890123456`). Such an event may have `from_user_id` and no `from`. Put the id in `to`: it works wherever a number does, including `/conversations/{contact}`. The bots above already do this.
  </Accordion>
</AccordionGroup>

## More how-to guides

<CardGroup cols={2}>
  <Card title="Send order and appointment notifications" href="/guides/how-to-order-notifications">
    Approved utility templates for confirmations and reminders, with delivery status.
  </Card>
  <Card title="Send a marketing broadcast that respects opt-ins" href="/guides/how-to-marketing-broadcast">
    One template to a list or a segment, with consent records and the Do Not Call list.
  </Card>
  <Card title="Let an AI agent run your WhatsApp with MCP" href="/guides/how-to-ai-agent-mcp">
    Connect Claude or another agent to your number with scoped keys and approvals.
  </Card>
  <Card title="Hand a chat from your bot to a person and back" href="/guides/how-to-human-handoff">
    Conversation owners, assignment, notes and summaries for your team.
  </Card>
  <Card title="Ask for a payment inside a WhatsApp chat" href="/guides/how-to-payment-links">
    Send a payment link in the chat and hear when it is paid.
  </Card>
</CardGroup>

[All how-to guides](https://www.app2email.com/docs#how-to)
