# Send order and appointment notifications with templates

> Create a utility template, get it approved by Meta, send it to one customer when an order ships or an appointment is tomorrow, and follow the delivery and read status.

When an order ships or an appointment is tomorrow, your system makes one API call and the customer gets a WhatsApp message from your business: "Hi John, your order #1234 has shipped."

You get the message's status back as it moves on (sent, delivered, read, or failed with a reason), by webhook or by asking the API. The message also shows in the app2email Activity Log and in the conversation.

## Why a notification needs a template

WhatsApp lets a business send its own free text only within 24 hours of the customer's last message to your number. app2email stops 15 minutes early, to be safe. A shipping update or an appointment reminder usually comes days after the customer last wrote, so a normal text message would be refused with `422 outside_24h_window`.

A **template** is a message text that Meta has reviewed and approved. It can be sent at any time, with your own values in its placeholders (`{{1}}`, `{{2}}`, ...).

Templates have a category. Order, delivery, account and appointment updates are **UTILITY**. Promotions are **MARKETING**. Meta decides the final category itself, so keep a utility template free of offers and sales wording.

## What you need

- A WhatsApp number connected to app2email, on a paid plan, with the service LIVE.
- A payment method on your WhatsApp Business Account at Meta. Without one, template sends fail with Meta error 131042 (`whatsapp_payment_issue`).
- An API key from https://www.app2email.com/dashboard/apikey with these scopes:

| Scope | What it is for in this guide |
| --- | --- |
| `templates:manage` | Create and edit templates (`POST /templates`, `PATCH /templates/{name}`) |
| `messages:read` | Read a template's status (`GET /templates/{name}`) and a message's status (`GET /messages/{message_id}`) |
| `messages:send` | Send the notification (`POST /messages`) |
| `webhooks:manage` | Add the webhook that receives the status events (`POST /webhooks`) |

The Default key (made before keys had permissions) does not have `templates:manage`. Create a key with that scope, or with Full access (`*`). `GET /v1/YOUR_NUMBER/me` shows the scopes of the key you have.

<Info>
**Trying it first.** A **sandbox key** on your own number (a key with the sandbox flag, on the API key page) runs every check for real and sends nothing to WhatsApp. The answer has `"sandbox": true`, message ids start with `wamid.SANDBOX.`, and `message.status` events sent, delivered and read still arrive. A sandbox key cannot create templates (`403 sandbox_key`), so create the template with a normal key.

With no account at all, `POST https://api.app2email.com/v1/account/sandbox` (no key, no body), or the `create_sandbox` tool of the Management MCP server, gives an **instant sandbox key** for the demo number `12025550100`. It has `GET /templates` and `POST /messages`, so you can send one of the demo number's templates to its pretend customers: `12025550101` answers, `12025550103` fails. See [Sandbox](/api/sandbox).
</Info>

## Send a notification, step by step

<Steps>
  <Step title="Create a utility template">
    Send the text with numbered placeholders, and a sample value for each one in `example`. Meta's reviewers read the samples. The name may use lower case letters, digits and underscores.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "order_update",
        "language": "en",
        "category": "UTILITY",
        "components": [
          {
            "type": "BODY",
            "text": "Hi {{1}}, your order {{2}} has shipped.",
            "example": { "body_text": [["John", "#1234"]] }
          }
        ]
      }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/templates", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: "order_update",
        language: "en",
        category: "UTILITY",
        components: [
          {
            type: "BODY",
            text: "Hi {{1}}, your order {{2}} has shipped.",
            example: { body_text: [["John", "#1234"]] },
          },
        ],
      }),
    });
    console.log(res.status, await res.json());
    ```

    ```python Python
    import os, requests

    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/templates",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
        json={
            "name": "order_update",
            "language": "en",
            "category": "UTILITY",
            "components": [
                {
                    "type": "BODY",
                    "text": "Hi {{1}}, your order {{2}} has shipped.",
                    "example": {"body_text": [["John", "#1234"]]},
                }
            ],
        },
    )
    print(res.status_code, res.json())
    ```

    </CodeGroup>

    **What you get back** (HTTP 201): the template is with Meta for review.

    ```json
    {
      "success": true,
      "request_id": "c3ppl",
      "template": {
        "id": "2234567890",
        "name": "order_update",
        "language": "en",
        "category": "UTILITY",
        "status": "PENDING"
      },
      "note": "Submitted to WhatsApp for review (minutes to a day). You get a template.status_changed webhook event with the result, or GET https://api.app2email.com/v1/4976659348270/templates/order_update."
    }
    ```

    For appointments, make a second template the same way, for example `appointment_reminder` with the text `Hi {{1}}, this is a reminder of your {{2}} tomorrow at {{3}}. Reply to this message if you need to change it.` and the samples `[["Ava", "haircut", "10:30"]]`.

    Templates belong to the WhatsApp Business Account: every number on that account can use them.

    <Tip>
    **A tracking button, written by Meta.** Meta's Template Library has ready-made utility texts: `GET /template-library?topic=ORDER_MANAGEMENT&usecase=SHIPMENT_CONFIRMATION` lists them. Create one with `library_template_name` instead of `components`, and give the website of its button:

    ```json
    {
      "name": "my_delivery_update",
      "language": "en_US",
      "category": "UTILITY",
      "library_template_name": "delivery_update_1",
      "library_template_button_inputs": [
        {
          "type": "URL",
          "url": {
            "base_url": "https://www.example.com/{{1}}",
            "url_suffix_example": "https://www.example.com/order/1234"
          }
        }
      ]
    }
    ```
    </Tip>
  </Step>

  <Step title="Wait for Meta's review">
    Review takes minutes to a day. You find out in one of two ways.

    **The `template.status_changed` webhook event** (sent to every number of the WhatsApp Business Account):

    ```json
    {
      "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
      "type": "template.status_changed",
      "created": "2026-11-06T01:00:00.000Z",
      "number": "4976659348270",
      "data": {
        "template": { "name": "order_update", "language": "en", "id": "1234567890123456" },
        "status": "APPROVED",
        "can_send": true,
        "timestamp": "2026-11-06T01:00:00.000Z"
      }
    }
    ```

    **Or ask:** `GET /v1/YOUR_NUMBER/templates/order_update` (scope `messages:read`). It is read from WhatsApp, not from a cache, so a status that just changed shows.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates/order_update \
      -H "Authorization: Bearer $A2E_KEY"
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/templates/order_update", {
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
    });
    const { versions } = await res.json();
    console.log(versions.map((v) => [v.language, v.status, v.rejected_reason]));
    ```

    ```python Python
    res = requests.get(
        "https://api.app2email.com/v1/YOUR_NUMBER/templates/order_update",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
    )
    for v in res.json()["versions"]:
        print(v["language"], v["status"], v.get("rejected_reason"))
    ```

    </CodeGroup>

    **What you get back:** one entry in `versions` per language, with `status`, `can_send`, what values it `needs`, and a complete `example_request` you can send after changing the values.

    ```json
    {
      "success": true,
      "request_id": "k7qtm",
      "name": "order_update",
      "versions": [
        {
          "id": "1234567890",
          "name": "order_update",
          "language": "en",
          "category": "UTILITY",
          "status": "APPROVED",
          "can_send": true,
          "needs": { "body": "2 text values" },
          "example_request": {
            "to": "61412345678",
            "type": "template",
            "template": {
              "name": "order_update",
              "language": { "code": "en" },
              "components": [
                {
                  "type": "body",
                  "parameters": [
                    { "type": "text", "text": "John" },
                    { "type": "text", "text": "#1234" }
                  ]
                }
              ]
            }
          }
        }
      ]
    }
    ```

    **A rejection** looks like this: `status` is `REJECTED`, `can_send` is `false`, and `rejected_reason` (in `GET /templates/{name}`) or `reason` (in the `template.status_changed` event) says why. Fix the text and send it again with `PATCH /v1/YOUR_NUMBER/templates/order_update` and new `components`. Only APPROVED, REJECTED or PAUSED templates can be edited, and an approved one at most once a day and 10 times in 30 days.

    If Meta put the template in another category, `previous_category` and `correct_category` in `GET /templates/{name}` show it.
  </Step>

  <Step title="Add a webhook for the status events">
    One webhook per system is enough: every webhook of the number gets every event, and you pick the types you handle. Up to 5 per number. Scope `webhooks:manage`.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "url": "https://hooks.example.com/app2email" }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/webhooks", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ url: "https://hooks.example.com/app2email" }),
    });
    const { webhook } = await res.json();
    console.log(webhook.id, webhook.secret); // store the secret: it signs every event
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/webhooks",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
        json={"url": "https://hooks.example.com/app2email"},
    )
    webhook = res.json()["webhook"]
    print(webhook["id"], webhook["secret"])  # store the secret: it signs every event
    ```

    </CodeGroup>

    **What you get back:** `webhook` with its `id` and its `secret` (`whsec_...`). Keep the secret on your server.

    No public address yet? `GET /v1/YOUR_NUMBER/events?wait=25` fetches the same events instead. Keep the answer's `cursor` and pass it as `after` on the next call.
  </Step>

  <Step title="Send the notification when the order ships">
    Send the template to the customer's number (country code first, digits only), with one value per placeholder in order.

    Two extras make it safe for production:

    - The `Idempotency-Key` header: a value that is unique for this notification, such as your order number and the event. If your job runs twice, or you retry after a timeout, the message is not sent again.
    - `callback_data`: your own short reference (up to 512 characters). It comes back as `data.callback_data` in this message's `message.status` events, so you can match a status to your order without storing the message id first.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/messages \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: order-1234-shipped" \
      -d '{
        "to": "61412345678",
        "type": "template",
        "template": {
          "name": "order_update",
          "language": { "code": "en" },
          "components": [
            {
              "type": "body",
              "parameters": [
                { "type": "text", "text": "John" },
                { "type": "text", "text": "#1234" }
              ]
            }
          ]
        },
        "callback_data": "order-1234"
      }'
    ```

    ```javascript Node.js
    async function sendShipped(order) {
      const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.A2E_KEY}`,
          "Content-Type": "application/json",
          "Idempotency-Key": `order-${order.id}-shipped`,
        },
        body: JSON.stringify({
          to: order.phone, // "61412345678"
          type: "template",
          template: {
            name: "order_update",
            language: { code: "en" },
            components: [
              {
                type: "body",
                parameters: [
                  { type: "text", text: order.firstName },
                  { type: "text", text: `#${order.id}` },
                ],
              },
            ],
          },
          callback_data: `order-${order.id}`,
        }),
      });
      const body = await res.json();
      if (!res.ok) throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
      return body.message_id; // keep it with the order
    }
    ```

    ```python Python
    def send_shipped(order):
        res = requests.post(
            "https://api.app2email.com/v1/YOUR_NUMBER/messages",
            headers={
                "Authorization": f"Bearer {os.environ['A2E_KEY']}",
                "Idempotency-Key": f"order-{order['id']}-shipped",
            },
            json={
                "to": order["phone"],  # "61412345678"
                "type": "template",
                "template": {
                    "name": "order_update",
                    "language": {"code": "en"},
                    "components": [
                        {
                            "type": "body",
                            "parameters": [
                                {"type": "text", "text": order["first_name"]},
                                {"type": "text", "text": f"#{order['id']}"},
                            ],
                        }
                    ],
                },
                "callback_data": f"order-{order['id']}",
            },
        )
        body = res.json()
        if not res.ok:
            raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']}")
        return body["message_id"]  # keep it with the order
    ```

    </CodeGroup>

    **What you get back** (HTTP 200): WhatsApp accepted the message. `text` is the message as the customer sees it.

    ```json
    {
      "success": true,
      "request_id": "kxrkf",
      "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
      "status": "accepted",
      "from": "4976659348270",
      "to": "61412345678",
      "template": { "name": "order_update", "language": "en", "category": "UTILITY" },
      "text": "Hi John, your order #1234 has shipped.",
      "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
      "note": "accepted by WhatsApp. delivery and read status appear in your app2email Activity Log (WhatsApp sent).",
      "contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
    }
    ```

    <Tip>
    Add `"dry_run": true` to the body while you build. Everything is checked as for a real send (template values, number, Do Not Call list, monthly limit) and the answer shows the exact WhatsApp message. Nothing is sent, logged or counted.
    </Tip>
  </Step>

  <Step title="Send the reminder the day before an appointment">
    The same call with the `appointment_reminder` template. You can send it now from your own daily job, or hand app2email the time with `send_at` (ISO 8601 with a time zone, 1 minute to 29 days ahead):

    ```json
    {
      "to": "61412345678",
      "type": "template",
      "template": {
        "name": "appointment_reminder",
        "language": { "code": "en" },
        "components": [
          {
            "type": "body",
            "parameters": [
              { "type": "text", "text": "Ava" },
              { "type": "text", "text": "haircut" },
              { "type": "text", "text": "10:30" }
            ]
          }
        ]
      },
      "send_at": "2026-12-01T09:00:00+11:00",
      "callback_data": "appt-5521"
    }
    ```

    A scheduled send answers HTTP 202 with `status: "scheduled"`, `scheduled_for` and a broadcast `code`. Everything is checked at once, and the Do Not Call list and the monthly limit are checked again when the time comes. If the appointment is cancelled, cancel the message with `POST /v1/YOUR_NUMBER/broadcasts/{code}/cancel`.

    <Note>
    Bookings made with app2email's own Book-and-Pay get their confirmations and reminders without any code: it creates its own utility templates and uses them when the window is closed. See [Appointment booking on WhatsApp](/guides/booking).
    </Note>
  </Step>

  <Step title="Optional: attach the invoice, or fill in a button">
    If the template was approved with a **document header**, send the PDF with each message as a `link` that app2email downloads, as base64 `data` with a `filename`, or as a media `id` from `POST /media`. Leave the header out to send the template's own sample document. Documents can be up to 100 MB.

    ```json
    {
      "to": "61412345678",
      "type": "template",
      "template": {
        "name": "invoice_ready",
        "language": { "code": "en" },
        "components": [
          {
            "type": "header",
            "parameters": [
              {
                "type": "document",
                "document": { "data": "JVBERi0xLjQKJ...", "filename": "invoice-1234.pdf" }
              }
            ]
          },
          {
            "type": "body",
            "parameters": [{ "type": "text", "text": "#1234" }]
          }
        ]
      }
    }
    ```

    If the template has a **URL button with a placeholder** (like the Template Library one above), give the end of the address as a button component. `index` is the button's position, from `"0"`:

    ```json
    {
      "type": "button",
      "sub_type": "url",
      "index": "0",
      "parameters": [{ "type": "text", "text": "order/1234" }]
    }
    ```

    Not sure what a template needs? `needs` and `example_request` in `GET /templates/{name}` list every header, body and button value.
  </Step>
</Steps>

## The result

The customer sees a message from your business name with the text of the template and your values in it, plus the document or button if the template has one. If they answer, the 24-hour window opens and you can reply with normal messages.

On your side, `message.status` events arrive as the message moves on. `status` is `sent`, `delivered`, `read` or `failed` (also `played` for a voice message, `clicked` and `deleted`).

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "message.status",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "to": "61412345678",
    "status": "delivered",
    "timestamp": "2026-11-06T01:00:00.000Z",
    "sent_by": "api",
    "whatsapp_status": "delivered",
    "recipient_user_id": "AU.1234567890123456",
    "pricing": { "billable": true, "pricing_model": "PMP", "type": "regular", "category": "utility" },
    "callback_data": "order-1234"
  }
}
```

A message that could not be delivered also comes as a `message.failed` event, with the same data and an `error` that has Meta's `code`, app2email's `error_code` and `how_to_fix`:

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "message.failed",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "to": "61412345678",
    "status": "failed",
    "timestamp": "2026-11-06T01:00:00.000Z",
    "error": {
      "code": 131026,
      "message": "Message Undeliverable.",
      "title": "Message undeliverable",
      "details": "Message Undeliverable.",
      "error_code": "recipient_unreachable",
      "how_to_fix": "WhatsApp could not deliver to this number. Check it is a WhatsApp number written with its country code (digits only, eg 61412345678), and that the person uses an up to date WhatsApp.",
      "is_retriable": false
    },
    "sent_by": "api",
    "whatsapp_status": "failed"
  }
}
```

Events can arrive out of order, so a `read` may come before its `delivered`. Keep the furthest status per `message_id` and do not move it back.

**Or ask for the status** with `GET /v1/YOUR_NUMBER/messages/{message_id}` (scope `messages:read`; URL-encode the id). It works for any message sent from the number, and has the status, the time of each step, why it failed, and the customer's reply or button tap.

<CodeGroup>

```bash cURL
curl -s "https://api.app2email.com/v1/YOUR_NUMBER/messages/wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA%3D" \
  -H "Authorization: Bearer $A2E_KEY"
```

```javascript Node.js
const id = encodeURIComponent(messageId);
const res = await fetch(`https://api.app2email.com/v1/YOUR_NUMBER/messages/${id}`, {
  headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
});
const msg = await res.json();
console.log(msg.status, msg.times);
```

```python Python
from urllib.parse import quote

res = requests.get(
    f"https://api.app2email.com/v1/YOUR_NUMBER/messages/{quote(message_id, safe='')}",
    headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
)
msg = res.json()
print(msg["status"], msg.get("times"))
```

</CodeGroup>

**What you get back:** `status` is one of `accepted`, `sent`, `delivered`, `read`, `failed`, `deleted`, `queued` or `unknown`. Steps not reached yet are left out of `times`.

```json
{
  "success": true,
  "request_id": "p4n8w",
  "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
  "to": "61412345678",
  "status": "read",
  "sent_by": "api",
  "text": "Hi John, your order #1234 has shipped.",
  "times": {
    "submitted": "2026-11-06T01:00:00Z",
    "accepted": "2026-11-06T01:00:01Z",
    "sent": "2026-11-06T01:00:02Z",
    "delivered": "2026-11-06T01:00:04Z",
    "read": "2026-11-06T01:12:40Z"
  },
  "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}
```

For many messages at once, `GET /v1/YOUR_NUMBER/messages?status=failed&since=2026-11-06T00:00:00Z` lists the failed ones, and `GET /v1/YOUR_NUMBER/stats?from=&to=` gives sent, delivered, read and failed counts for a period.

## What it costs

app2email charges a flat monthly plan; each notification counts as one message of the plan, with no per-message markup ([pricing](https://www.app2email.com/pricing)). Meta also charges for template messages, directly to the payment method on your WhatsApp Business Account. The price depends on the template's category and the customer's country, and utility templates cost less than marketing templates in most countries. That is one more reason to keep order and appointment updates strictly informational. The `pricing` object in the status events shows how Meta counted each message (`billable`, `category`), and `meta_pricing` in `GET /v1/YOUR_NUMBER/usage` adds up the month by category with an indicative cost. For an estimate before you start, use the [WhatsApp pricing calculator](https://www.app2email.com/tools/whatsapp-pricing-calculator).

## Production checklist

<AccordionGroup>
  <Accordion title="Check the webhook signature">
    Every event has the header `X-App2email-Signature: t=<unix seconds>,v1=<hex>`. The `v1` value is the HMAC-SHA256 of `"<t>.<raw body>"`, with the webhook's secret (`whsec_...`, prefix included) as the key. Check every `v1=` (there are two while an old secret is still kept after a rotation), compute it over the raw body exactly as received, and refuse an old `t`. `X-Hub-Signature-256: sha256=<hex>` (HMAC-SHA256 of the raw body, current secret only) is there too, for code written for Meta's webhooks.

    <CodeGroup>

    ```javascript Node.js
    import crypto from "node:crypto";
    import express from "express";

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

    const app = express();
    app.post("/app2email", express.raw({ type: "application/json" }), async (req, res) => {
      if (!verifyWebhook(req.body, req.get("X-App2email-Signature"), process.env.WEBHOOK_SECRET)) return res.sendStatus(401);
      const event = JSON.parse(req.body);
      if (await alreadySeen(req.get("X-App2email-Delivery"))) return res.sendStatus(200); // a retry
      if (event.type === "message.status") await saveStatus(event.data.callback_data, event.data.message_id, event.data.status, event.data.error);
      if (event.type === "template.status_changed") await saveTemplateStatus(event.data.template, event.data.status, event.data.reason);
      res.sendStatus(200); // within 10 seconds
    });
    ```

    ```python Python
    import hashlib, hmac, json, os, re, time
    from flask import Flask, request

    def verify_webhook(raw_body: 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 "")
        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_body, hashlib.sha256).hexdigest()
        return any(hmac.compare_digest(v, expected) for v in v1)

    app = Flask(__name__)

    @app.post("/app2email")
    def app2email():
        raw = request.get_data()
        if not verify_webhook(raw, request.headers.get("X-App2email-Signature"), os.environ["WEBHOOK_SECRET"]):
            return "", 401
        if already_seen(request.headers.get("X-App2email-Delivery")):
            return "", 200  # a retry
        event = json.loads(raw)
        if event["type"] == "message.status":
            d = event["data"]
            save_status(d.get("callback_data"), d["message_id"], d["status"], d.get("error"))
        return "", 200  # within 10 seconds
    ```

    </CodeGroup>
  </Accordion>

  <Accordion title="Drop repeated events">
    Answer with a 2xx status within 10 seconds. Otherwise the event is sent again after 10 s, 1 min, 5 min, 30 min, 1, 2, 4, 8 and 16 hours. `X-App2email-Delivery` (the event `id`, `evt_...`) is the same on every retry, so store it and skip an event you already handled. Do the slow work after you answer.
  </Accordion>

  <Accordion title="Never send the same notification twice">
    Send an `Idempotency-Key` header that belongs to the notification, not to the attempt: `order-1234-shipped`, `appt-5521-reminder`. The same request with the same key within 24 hours is not sent again; it gets the first answer, with the header `Idempotent-Replayed: true`.

    - Same key with a different body: `422 idempotency_key_reused`. Use a new key for a different message.
    - First request still running: `409 idempotency_request_in_progress`. Wait and retry with the same key.
    - First request did not finish within 15 minutes: `409 idempotency_request_interrupted`. The message may have gone out: check `GET /messages?to=61412345678` before you send with a new key.
    - A request refused before anything was sent leaves the key free, so a fixed request can use it.

    The key is kept for 24 hours. For a job that may run again days later, also keep the `message_id` with the order event in your own database and do not send when one is already there.
  </Accordion>

  <Accordion title="Retry the right errors, and only those">
    Every answer has `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (seconds until full again) and `X-RateLimit-Policy`. Over the limit you get `429 rate_limited` with a `Retry-After` header and `error.retry_after_seconds`: wait that long, then send the same request again.

    - `500`, `502`, `503` or a timeout: retry a few times with growing waits, with the same `Idempotency-Key`.
    - `429 too_many_messages_to_recipient` or `429 whatsapp_rate_limit`: WhatsApp's own limit. Back off for minutes, not seconds.
    - `429 monthly_limit_reached`: the plan's messages are used up. Do not retry until the next billing month or an upgrade.
    - Any other `4xx`: do not retry unchanged. Decide by `error.code` and follow `how_to_fix`. `error.is_retriable` tells you whether the same request can work later.
  </Accordion>

  <Accordion title="The 24-hour window">
    An approved template can go out at any time. A normal text, image or document only works within 24 hours of the customer's last message (app2email stops 15 minutes early). So when a customer answers "Can I change the address?", you can reply in free text. `GET /v1/YOUR_NUMBER/conversations/61412345678` shows `window_open` and `window_closes_at`.
  </Accordion>

  <Accordion title="Opt-out, Do Not Call and the category">
    The Do Not Call list and the opt-in rule (`/settings/optin`) apply to marketing templates. A customer on the Do Not Call list can still get utility templates such as order updates.

    Meta sets the category of every template itself, and can change it later. If a template becomes MARKETING, the Do Not Call list and the opt-in rule apply to it and it is billed as marketing. Watch for `template.status_changed` events, and keep promotions out of your notification texts.

    WhatsApp also rates each template's quality from how people react. A template with a RED `quality_score` can be paused, and a paused template answers `422 template_paused`.
  </Accordion>
</AccordionGroup>

## If it does not work

Every error is JSON with `error.code`, `message`, `how_to_fix` and a `request_id` to quote to support. See [Errors](/api/errors) for every code.

| Code | When | What to do |
| --- | --- | --- |
| `403 insufficient_scope` | The key lacks a scope (`details.required_scope`) | Use a key with `templates:manage`, `messages:send`, `messages:read` or `webhooks:manage` as needed |
| `403 sandbox_key` | Creating or editing a template with a sandbox key | Use a normal key for templates |
| `400 invalid_template_category` | `category` is not MARKETING, UTILITY or AUTHENTICATION | Use `UTILITY` for order and appointment updates |
| `400 invalid_template_components` | A component has no `type` (HEADER, BODY, FOOTER, BUTTONS) | Components are in WhatsApp's own format; compare with the example above |
| `409 template_already_exists` | The name and language exist (or are being deleted) | Use another name or language |
| `422 template_rejected` | WhatsApp did not accept the template | Fix it as `whatsapp_error` says and send it again |
| `404 template_not_found` | The name does not match a template of the account | Names are lower case and must match exactly; see `details.available_templates` |
| `422 template_not_approved` | The template is pending, rejected, paused or disabled | Wait for approval, or fix it; check `GET /templates/{name}` |
| `422 template_parameters_invalid` | The values do not match the template | Fix the body from `details.problems` and `example_request` |
| `422 template_parameter_count_mismatch` | Meta error 132000: the wrong number of values | Send one value per placeholder; see `example_request` |
| `422 template_paused` | Meta error 132015: paused for low quality | Use another template, or edit this one |
| `422 outside_24h_window` | You sent free text, not a template, outside the window | Send an approved template instead |
| `403 whatsapp_payment_issue` | Meta error 131042: Meta could not charge your WhatsApp account | Add or fix the payment method in WhatsApp Manager |
| `422 recipient_unreachable` | Meta error 131026 | Check the number has its country code and uses WhatsApp |
| `422 media_download_failed` | The document `link` could not be downloaded | Use a link that opens without a login, or send base64 `data` |
| `422 idempotency_key_reused` | Same `Idempotency-Key`, different body | Use a new key for a different message |
| `429 rate_limited` | Too many calls for this key | Wait `Retry-After` seconds, then retry |
| `429 monthly_limit_reached` | The plan's messages are used up this month | Wait for the next billing month, or upgrade |
| `404 message_not_found` | No message with that id from this number | Use the `message_id` from the send answer, URL-encoded |

## More how-to guides

<CardGroup cols={2}>
  <Card title="Build a WhatsApp chatbot with the API" href="/guides/how-to-whatsapp-chatbot">
    Receive messages by webhook and answer with text, buttons and lists.
  </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 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 an agent to the MCP server and let it read and send messages.
  </Card>
  <Card title="Hand a chat from your bot to a person and back" href="/guides/how-to-human-handoff">
    Set the conversation owner so your bot steps aside while a person answers.
  </Card>
  <Card title="Ask for a payment inside a WhatsApp chat" href="/guides/how-to-payment-links">
    Send a payment request in the chat and get an event when it is paid.
  </Card>
</CardGroup>

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