# 使用 API 建立 WhatsApp 聊天機器人

> 透過已簽署的 webhook 接收 WhatsApp 訊息，用您自己的程式碼回答常見問題，並在客戶要求時把對話轉交給真人。

在本指南中，您會建立一個小型 WhatsApp 機器人，它能回答營業時間和價格的問題，並在客戶要求時把對話轉交給真人。

**客戶看到的內容：** 他們傳訊息到您的 WhatsApp 號碼，訊息出現藍色勾號，顯示「輸入中...」，一秒後回覆就到了。當他們寫下「我可以和真人談談嗎？」，機器人會說會有專人回覆，之後就只由您的團隊回覆。

**您看到的內容：** app2email 收件匣（Inbox）和活動記錄（Activity Log）中的每一則訊息和回覆、每則回覆的送達與已讀勾號（以 webhook 事件呈現），以及機器人轉交對話時的對話摘要。

這個機器人用 Node.js（Express）或 Python（Flask）寫成，不到 100 行。它會檢查 webhook 簽章、忽略已處理過的事件、能安全地重試，並遵守 24 小時回覆視窗。

## 運作方式

1. 客戶傳送訊息到您的 WhatsApp 號碼。
2. app2email 向您的網址發送帶有事件 `message.received` 的已簽署 `POST`。
3. 您的程式碼檢查簽章、查詢對話（是否由真人處理？回覆視窗是否仍開啟？）、用輸入中提示把訊息標示為已讀，然後用 `POST /messages` 發送回覆。
4. 回覆在發送、送達和已讀時，app2email 會發送 `message.status` 事件。

您的網址必須在 10 秒內回應 2xx 狀態。如果沒有，app2email 稍後會再次發送同一個事件，所以短暫的中斷不會遺失任何內容。

## 您需要準備

- **已連接到 app2email 的 WhatsApp 號碼**，使用付費方案且處於上線狀態。沒有方案時，每次呼叫都會回應 403 `plan_not_allowed`；服務暫停時會回應 403 `service_not_live`。請參閱[入門指南](https://www.app2email.com/docs/onboarding)。
- **一把 API 金鑰**，從 [API 金鑰頁面](https://www.app2email.com/dashboard/apikey)取得，具備下列權限範圍：

| 權限範圍 | 機器人為何需要它 |
| --- | --- |
| `messages:send` | 發送回覆（`POST /messages`）、把訊息標示為已讀（`POST /messages/read`）、把對話轉交給真人（`PUT /conversations/{contact}/owner`） |
| `messages:read` | 查詢對話：處理者和回覆視窗（`GET /conversations/{contact}`） |
| `webhooks:manage` | 註冊一次 webhook（`POST /webhooks`）。您也可以不寫程式，直接在 API 金鑰頁面的 Webhooks 下新增 |

- **一個公開的 https 網址**，供 webhook 使用。在您自己的電腦上，可以用通道（tunnel）取得一個（見下方步驟 2）。
- **一個沒有佔位符的已核准範本**，用於回覆視窗已關閉後仍須發出的少數回覆（參閱 [24 小時視窗](#the-24-hour-window)）。

<Tip>
**上線前先試用。** **沙盒金鑰**（在 API 金鑰頁面建立、帶有沙盒標記的金鑰）會針對您自己的號碼執行所有檢查，不會向 WhatsApp 發送任何內容：回應帶有 `"sandbox": true`，訊息 id 以 `wamid.SANDBOX.` 開頭，`message.status` 事件仍會送達。完全不需要帳號時，**即時沙盒**會給您一把示範號碼 `12025550100` 的金鑰，並附有虛擬客戶：使用 `POST https://api.app2email.com/v1/account/sandbox`（不帶金鑰、不帶內容），或管理 MCP 伺服器的 `create_sandbox` 工具。它沒有 webhook：請改用 `GET /events?wait=25` 讀取事件（參閱常見問題）。詳情：[沙盒](/api/sandbox)。
</Tip>

## 四個步驟完成設定

<Steps>
  <Step title="檢查您的金鑰">
    `GET /me` 只要金鑰有效即可使用，並會顯示其權限範圍和限制。在每個請求中，`YOUR_NUMBER` 是您用來發送的 WhatsApp 號碼：國碼在前，只用數字。

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

    **您會收到的回應：**

    ```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` 必須是 `LIVE`，而 `key.scopes` 必須列出上表中的權限範圍（或 `*` 代表完整存取）。
  </Step>
  <Step title="為您的電腦取得公開網址">
    app2email 只能把事件發送到公開的 https 網址。開發期間，可以用通道把一個網址轉發到您的電腦。先在 3000 連接埠啟動機器人（程式碼在下方），然後在第二個終端機執行：

    ```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
    ```

    兩者都會印出一個 https 網址，例如 `https://a1b2-203-0-113-7.ngrok-free.app`。您的 webhook 網址就是該網址加上 `/webhook`。快速通道每次啟動時可能會取得新的網址：發生這種情況時，請用 `PATCH /webhooks/{id}` 和新的 `url` 更新 webhook。

    無法使用通道？`GET /events?wait=25` 不需要公開網址即可取得相同的事件（參閱常見問題）。
  </Step>
  <Step title="註冊 webhook">
    只需一次呼叫。回應中有**簽署密鑰**（`whsec_...`），用來簽署每個事件：請和您的金鑰放在一起保管，例如放在環境變數 `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>

    **您會收到的回應**（201 Created；已簡化：回應中還會在 `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"
      }
    }
    ```

    再次註冊相同的網址會回應 200，並帶有相同的 id 和密鑰，所以這個呼叫可以安全地重複執行。每個號碼最多有 5 個 webhook，而且每個 webhook 都會收到每個事件：您的程式碼依 `type` 挑選要處理的類型，其餘的回應 2xx 即可。本指南中請讓 `format` 維持 `app2email`（預設值）。
  </Step>
  <Step title="發送測試事件">
    `POST /webhooks/{id}/test` 會立即發送一個已簽署的範例，並告訴您網址的回應結果。帶上 `{"type": "message.received"}` 就會收到該事件的範例。

    ```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"}'
    ```

    **您會收到的回應**（已簡化）：

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

    `delivered: true` 表示您的網址在 10 秒內回應了 2xx。測試事件帶有 `"test": true` 和標頭 `X-App2email-Test: true`，其範例聯絡人是虛構的，所以下方的機器人會檢查簽章、記錄事件，但不會回覆它。每個號碼每小時最多 30 次測試。接著用您自己的手機向您的號碼發送一則真實的訊息：機器人就會回覆。
  </Step>
</Steps>

## 機器人使用的四個呼叫

每個呼叫都發送到 `https://api.app2email.com/v1/YOUR_NUMBER`，並帶有 `Authorization: Bearer YOUR_API_KEY`。

### 1. 讀取客戶傳來的內容

這是您的網址收到的 `message.received` 事件內容（一則文字訊息）：

```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`（也在標頭 `X-App2email-Delivery` 中）在每次重試時都相同：您用它來去除重複。
- `data.from` 是客戶的號碼。使用 WhatsApp 使用者名稱的聯絡人，可能只帶有 `from_user_id` 而沒有號碼；這個 id 在任何可用號碼的地方都能使用。
- `data.type` 可能是 `text`、`image`、`audio`、`interactive`（點選回覆按鈕或清單列，帶有 `interactive.id`）、`button`（範本的快速回覆按鈕，帶有 `button.payload`）等等。機器人只回答文字和點選，其餘留給您的團隊處理。

### 2. 查詢對話

`GET /conversations/{contact}`（權限範圍 `messages:read`）會告訴您由誰處理這則對話，以及現在是否可以發送自由格式的回覆。

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

**您會收到的回應：**

```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` 是空的。當它是 `human` 或 `paused` 時，表示有真人負責這則對話，機器人保持沉默；`whatsapp_ai` 表示由 WhatsApp 自己的 AI 代理負責。

### 3. 顯示藍色勾號和「輸入中...」

`POST /messages/read`（權限範圍 `messages:send`）會把訊息標示為已讀，並在帶有 `"typing": true` 時顯示輸入中提示，最長 25 秒，或直到您的回覆送達為止。它是免費的：不計入您的方案用量，也不受 24 小時視窗限制。

```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}'
```

**您會收到的回應：**

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

### 4. 發送回覆

在回覆視窗開啟期間，`POST /messages`（權限範圍 `messages:send`）搭配 `"type": "text"` 會向一位聯絡人發送自由格式的訊息。

| 項目 | 要填入什麼 |
| --- | --- |
| 發給誰 | `to`：客戶的號碼（`data.from`），或他們的 `from_user_id` |
| 哪一種訊息 | `type`：一般回覆用 `text`。視窗之外：`template` |
| 內容 | `text.body`：您的回覆。`text.preview_url`：設為 true 可顯示連結預覽 |
| 您的金鑰 | 標頭 `Authorization: Bearer YOUR_API_KEY` |
| 避免重複 | 標頭 `Idempotency-Key`：專屬於此回覆的值，例如 `text-` 加上客戶的 `message_id`。24 小時內以相同金鑰發送相同的請求，不會再次發送 |

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

**您會收到的回應**（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` 表示 WhatsApp 已收下訊息。是否送達和已讀，之後會以 `message.status` 事件告知。以相同 `Idempotency-Key` 重複發送的請求，會再次得到這個相同的回應，並附有標頭 `Idempotent-Replayed: true`，而且不會發送兩次。

**失敗時**，回應會帶有 `success: false` 和 `error` 物件。請依 `error.code` 判斷，絕不要依訊息文字判斷：

```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
  }
}
```

呼叫過多會回應 429 `rate_limited`，並帶有 `Retry-After` 標頭：

```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}}
```

### 把對話轉交給真人

當客戶要求找真人時，使用 `PUT /conversations/{contact}/owner`（權限範圍 `messages:send`），帶上 `"owner": "human"`、一個簡短的 `reason` 和一個 `summary`。之後 app2email 的自動回覆和其他代理就不會再處理這位聯絡人，透過電子郵件收到訊息的人會看到摘要，而且每個 webhook 都會收到 `conversation.owner_changed`。`until_minutes` 可以讓它變成暫時的：時間一到，對話會自動回到一般處理。

```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}'
```

回應中包含更新後的 `conversation`（欄位與 `GET /conversations/{contact}` 相同）。

## 完整的機器人

兩個版本做的事相同：驗證簽章、略過測試事件和已處理的事件、略過由真人負責的對話、用輸入中提示標示為已讀、在客戶提到「真人」時轉交、回答關鍵字，並在視窗已關閉時改用範本。請先設定三個環境變數：`NUMBER`（您的 WhatsApp 號碼，數字）、`API_KEY` 和 `WEBHOOK_SECRET`（步驟 3 的 `whsec_...` 值）。

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

**為何這樣設計：**

- 簽章是在解析任何內容之前，針對**原始請求內容**檢查的（`express.raw`、`request.get_data()`）。
- 事件只有在回覆發出之後才會標示為已處理。如果呼叫因 5xx 或速率限制而失敗，機器人會回應 503，app2email 稍後（10 秒、1 分鐘、5 分鐘……之後）會再次發送該事件。`Idempotency-Key` 確保重試絕不會發送兩次相同的回覆，即使第一次嘗試已經走到發送那一步。
- 短暫的 429 `rate_limited` 會在請求內部等待過去（最多 3 秒，以維持 10 秒的限制）。更長的等待則交還給 app2email 的重試機制。
- 重試也不會改變結果的錯誤（範本名稱錯誤、缺少權限範圍）會連同 `how_to_fix` 和 `request_id` 一起記錄，事件則回應 200，避免它一再回來。
- `FALLBACK` 是 `hello_world`，因為即時沙盒有它。在您自己的號碼上，請填入您其中一個已核准範本的名稱和語言（`GET /templates` 會列出它們，每個都附有完整的 `example_request`）。

## WhatsApp 上會發生什麼

1. 客戶寫下「你們的營業時間是什麼時候？」。
2. 他們的訊息出現藍色勾號，並顯示「輸入中...」。
3. 回覆送達。在收件匣和活動記錄中，您會看到這兩則訊息。
4. 您的 webhook 會收到該回覆的 `message.status`：先是 `sent`，然後是 `delivered`，再來是 `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"
  }
}
```

失敗的回覆會以帶有 `status: "failed"` 和 `error` 物件的 `message.status` 送達（`code` 是 Meta 的代碼，`error_code` 是 app2email 的代碼），同時也會以 `message.failed` 送達。

當客戶寫下「我可以和真人談談嗎？」時，他們會收到「我們團隊的專人很快會在這裡回覆您」，而您的 webhook 會收到：

```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"
  }
}
```

真人可以從收件匣、電子郵件或透過 API 回覆。機器人在下一則訊息時看到處理者是 `human`，便會保持沉默。

**交還給機器人：** `until_minutes` 過後，處理者會自動再次變回空白。真人也可以更早用 `PUT /conversations/{contact}/owner` 和 `{"owner": ""}` 把對話交還，這會再次發送 `conversation.owner_changed`。當真人負責對話時，請不要在程式碼中把對話收回。

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

## 24 小時視窗

WhatsApp 允許您在客戶最後一則訊息之後的 24 小時內發送自由格式的訊息（文字、圖片、按鈕）。app2email 會提早 15 分鐘停止；`window_closes_at` 是確切的時間。之後只有已核准的範本才能重新開啟對話。

幾秒內就回覆的機器人，幾乎一定在視窗之內。當事件延遲送達時才需要注意：重試會持續約 32 小時，所以回覆昨天的訊息可能需要使用範本。機器人在寫訊息之前會檢查 `window_open`，如果發送時回應 422 `outside_24h_window`，仍會改用範本。

Do Not Call 名單不適用於自由格式的回覆，因為是客戶先寫訊息給您。例外情況：當他們的最後一則訊息本身就是退出訊息時，回覆會得到 403 `recipient_opted_out`，直到他們再次寫訊息為止。

## 上線檢查清單

<Check>
**驗證每個事件。** 標頭 `X-App2email-Signature` 是 `t=<unix seconds>,v1=<hex>`：以文字 `t`、一個點和原始請求內容為資料，以 webhook 的密鑰（`whsec_...`，包含前綴）為金鑰計算 HMAC-SHA256。請檢查每一個 `v1=`（在使用 `keep_old_for_hours` 執行 `POST /webhooks/{id}/rotate-secret` 之後的一段時間內會有兩個），以固定時間方式比較，並拒絕比 5 分鐘更舊的 `t`。如果您的程式碼已經在檢查 Meta 的 webhook，`X-Hub-Signature-256`（`sha256=` 加上原始請求內容的 HMAC-SHA256，與 Meta 的簽署方式相同）也同樣提供；它不含時間，而且只使用目前的密鑰。
</Check>

<Check>
**快速回應。** 在 10 秒內回傳 2xx。不會跟隨重新導向。對於耗時的工作（資料庫、AI 模型），請先儲存事件、回應 200，然後從會自行重試的佇列中處理。
</Check>

<Check>
**去除重複。** 請把每個已處理事件的事件 `id`（`X-App2email-Delivery`）至少保留兩天：重試會持續約 32 小時。如果您執行多個處理程序，請把它存在資料庫或 Redis 中，而不是記憶體裡。事件也可能亂序抵達：請使用 `data.timestamp`，而不是它們抵達的順序。
</Check>

<Check>
**每則回覆只發送一次。** 為每個 `POST /messages` 提供由客戶的 `message_id` 組成的 `Idempotency-Key`。24 小時內相同的金鑰和相同的內容：會傳回第一次的回應，並附有 `Idempotent-Replayed: true`。相同的金鑰、不同的內容：422 `idempotency_key_reused`。409 `idempotency_request_in_progress`：請等待，並以相同的金鑰重試。
</Check>

<Check>
**遵守限制。** 每個回應都有 `X-RateLimit-Limit`、`X-RateLimit-Remaining`、`X-RateLimit-Reset`（距離恢復額滿的秒數）和 `X-RateLimit-Policy`；`GET /me` 會顯示您金鑰的 `limits`。超過限制時：429 `rate_limited`，附有 `Retry-After` 和 `error.retry_after_seconds`。WhatsApp 自己的限制（429 `whatsapp_rate_limit`、`too_many_messages_to_recipient`）需要等待數分鐘，而不是數秒。429 `monthly_limit_reached` 和 `daily_cap_reached` 現在重試沒有意義（`retry_after_seconds` 會說明到何時為止）：請通知真人。
</Check>

<Check>
**讓 webhook 保持開啟。** 如果連續 20 個事件在最初 4 次嘗試內都未能送達（持續至少 24 小時），app2email 會關閉該 webhook。`GET /webhooks/{id}/deliveries?status=failed` 會顯示哪些失敗以及原因；帶上 `{"active": true}` 的 `PATCH /webhooks/{id}` 可以重新開啟它，而 `POST /webhooks/{id}/deliveries/{event_id}/redeliver` 可以再次發送單一事件。
</Check>

<Check>
**當真人負責對話時，不要打擾客戶。** 每次回覆之前都要檢查 `owner`（`human`、`paused` 和 `whatsapp_ai` 的意思是：不要回覆），並在客戶要求時轉交。
</Check>

<Check>
**每個號碼只有一個回覆者。** 該號碼的自動回覆（新聯絡人收到的第一則回覆）、對話自動化和 AI 回覆，也都會看到每一則訊息。請檢查儀表板，避免新聯絡人收到兩次第一則回覆。
</Check>

<Check>
**把客戶的文字當作資料。** 它是由客戶寫的。絕不要把它當作指令執行；如果您把它傳給 AI 模型，請讓它與您的指示分開。
</Check>

<Check>
**最小權限。** 機器人的金鑰只需要 `messages:send` 和 `messages:read`。請把它放在伺服器上，絕不放在網頁或日誌中。金鑰可以限制為只允許您伺服器的 IP 位址、設定每日上限，或設定到期時間。
</Check>

## 如果無法運作

| 您看到的情況 | 原因 | 解決方法 |
| --- | --- | --- |
| 您的機器人對每個事件都回應 401 | 簽章不相符 | 使用這個 webhook 的 `whsec_...` 密鑰（含前綴）；檢查原始請求內容，要在任何 JSON 解析器處理它之前；檢查伺服器時鐘（`t` 必須在 5 分鐘內） |
| 401 `missing_api_key`、`invalid_api_key`、`api_key_revoked` | 沒有金鑰、金鑰錯誤，或金鑰已過舊 | 以 API 金鑰頁面上列出的金鑰發送 `Authorization: Bearer YOUR_API_KEY`，並在網址中使用該金鑰所屬的號碼 |
| 403 `insufficient_scope` | 金鑰缺少某項權限（`details.required_scope`） | 建立一把具備 `messages:send` 和 `messages:read` 的金鑰（註冊 webhook 時還需要 `webhooks:manage`） |
| 403 `plan_not_allowed`、`service_not_live` | 沒有付費方案，或服務已暫停 | 選擇方案；已暫停的服務可在設定頁面按「Go Live」重新上線 |
| 422 `invalid_webhook_url` | 網址不是公開的 https 位址 | 使用您通道或伺服器的 https 位址，並加上路徑（`/webhook`） |
| 409 `webhook_url_in_use` | 該號碼的另一個 webhook 使用了這個網址 | 用 `PATCH` 修改那個 webhook，或刪除其中一個 |
| 400 `too_many_webhooks` | 該號碼已有 5 個 webhook | 刪除一個您不再使用的 |
| 422 `outside_24h_window` | 客戶上次寫訊息已超過 24 小時 | 發送已核准的範本 |
| 404 `template_not_found`、422 `template_not_approved` | 備用範本的名稱或語言有誤，或尚未核准 | 從 `GET /templates` 選擇狀態為 APPROVED 的範本 |
| 422 `template_parameters_invalid` | 備用範本含有佔位符 | 使用沒有佔位符的範本，或依其 `example_request` 填入 |
| 403 `recipient_opted_out` | 客戶的最後一則訊息是退出訊息 | 在他們再次寫訊息之前不要回覆 |
| 429 `rate_limited` | 此金鑰的呼叫次數過多 | 等待 `Retry-After` 秒，然後重試 |
| 429 `whatsapp_rate_limit`、`too_many_messages_to_recipient` | WhatsApp 的限制 | 退避數分鐘 |
| 429 `too_many_tests` | 一小時內超過 30 個測試事件 | 等待，或改用您手機發送的訊息測試 |
| 403 `not_in_instant_sandbox` | 示範號碼沒有這個呼叫（例如 webhook） | 在該處改用 `GET /events`，或使用您自己號碼上的沙盒金鑰 |
| 完全沒有事件抵達 | webhook 已被關閉，或通道的位址已改變 | `GET /webhooks` 會顯示 `active` 和最後一次送達；用 `PATCH` 設定新的 `url` 或 `{"active": true}` |

每個回應都有 `request_id`。`GET /requests/{id}` 會顯示為它記錄的內容，support@app2email.com 也能查到。所有代碼請見[錯誤](/api/errors)。

## 回應客戶的其他方式

- **AI 回覆**：app2email 的助理會根據您的網站、PDF 和筆記回答，並在無法協助時把對話轉交給真人（Professional 方案和試用期）。它會回報 `ai.answered` 和 `ai.handover`。只有在對話沒有處理者，且沒有應用程式或自動化回覆過時，它才會回覆客戶，所以每個號碼請只選一個回覆者。請參閱 [AI 回覆設定](https://www.app2email.com/docs/api/ai-answers/get-ai-answers-settings)。
- **透過 MCP 的 AI 代理**：MCP 伺服器 `https://api.app2email.com/mcp` 以工具形式提供相同的呼叫（`send_text`、`mark_read`、`get_conversation`、`set_conversation_owner`、`list_events`、`wait_for_message` 等）。請參閱[讓 AI 代理透過 MCP 操作您的 WhatsApp](/guides/how-to-ai-agent-mcp)和 [MCP](/api/mcp)。
- **更深入的轉交說明**：[把對話從機器人轉交給真人，再轉回來](/guides/how-to-human-handoff)。

## 常見問題

<AccordionGroup>
  <Accordion title="沒有 WhatsApp 號碼也能建立和測試嗎？">
    可以。`POST https://api.app2email.com/v1/account/sandbox`（不帶金鑰、不帶內容）會回傳示範號碼 `12025550100` 的即時沙盒金鑰（`a2es_...`，有效期 7 天）。它的虛擬客戶包括 Ava（`12025550101`，會回覆每一則訊息）和 Eve（`12025550105`，要求找真人）。它有 `GET /conversations/{contact}`、`PUT /conversations/{contact}/owner`、`POST /messages` 和 `GET /events`，所以機器人的邏輯可以在那裡執行，而且它有用作備用的 `hello_world` 範本。它沒有 webhook：請用 `GET /events` 讀取事件（下一個問題）。`POST /messages/read` 也沒有；它會回應 403 `not_in_instant_sandbox`，機器人會記錄下來並繼續執行。不會有任何內容送到 WhatsApp。
  </Accordion>
  <Accordion title="沒有公開網址也能接收訊息嗎？">
    可以：`GET /events?wait=25`（權限範圍 `messages:read`）會保留回應，直到有事件抵達，最長 25 秒。每個事件的 JSON 與 webhook 收到的相同，`id` 也相同。請保存回應的 `cursor`，並在下次呼叫時把它作為 `after` 傳入；略過您已處理過的 id，因為回應遺失後，事件可能再次出現。`types=message.received` 只會回傳收到的訊息。第一次呼叫會開啟該號碼的事件串流；事件會保留 72 小時。

    ```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="客戶可以點選按鈕，而不必打字嗎？">
    可以，在 24 小時視窗之內。發送 `"type": "interactive"`，最多可帶 3 個回覆按鈕，或最多 10 列的清單。讓按鈕使用機器人已經看得懂的 id，點選後會以 `message.received` 送達，其中 `type` 為 `interactive`，並帶有 `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="每則回覆的費用是多少？">
    機器人發送的每則回覆，都算作您 app2email 方案的一則訊息。標示為已讀和輸入中提示是免費的。Meta 會直接向您收費：視窗內的回覆是服務訊息（每個號碼每月前 1,000 則免費），範本則按每則訊息收費。`GET /usage` 會顯示本月已用和剩餘的額度，Meta 的類別在 `meta_pricing` 中。
  </Accordion>
  <Accordion title="照片、語音訊息和文件會怎麼處理？">
    它們會以 `message.received` 送達，`type` 為 `image`、`audio`、`document` 等，並帶有 `media_url`：app2email 會保留一份副本，由 `GET /media/{message_id}` 提供。上面的機器人把它們留給您的團隊處理；您也可以在其中一種訊息抵達時，立即把對話轉交出去。
  </Accordion>
  <Accordion title="真人如何回覆，我又如何把對話交還給機器人？">
    從儀表板上的收件匣、從電子郵件（啟用電子郵件轉寄時），或透過 API。`until_minutes` 用完時，或更早用 `PUT /conversations/{contact}/owner` 和 `{"owner": ""}`，對話就會回到機器人手上。
  </Accordion>
  <Accordion title="我可以改用 Meta 自己的 webhook 格式嗎？">
    可以：帶有 `"format": "meta"` 的 webhook，會以 Meta 自己的內容格式（`entry[].changes[]`）收到來自 WhatsApp 的內容，簽署方式相同。app2email 自己的事件，例如 `conversation.owner_changed`，仍使用 app2email 的外層格式。本指南使用預設的 `app2email` 格式。
  </Accordion>
  <Accordion title="有些客戶的事件中沒有電話號碼。為什麼？">
    WhatsApp 正在轉向使用者名稱，並採用企業範圍的使用者 id（例如 `AU.1234567890123456`）。這類事件可能有 `from_user_id` 而沒有 `from`。請把該 id 放進 `to`：它在任何可用號碼的地方都能使用，包括 `/conversations/{contact}`。上面的機器人已經這樣做了。
  </Accordion>
</AccordionGroup>

## 更多操作指南

<CardGroup cols={2}>
  <Card title="發送訂單和預約通知" href="/guides/how-to-order-notifications">
    用於確認和提醒的已核准 utility 範本，並附有送達狀態。
  </Card>
  <Card title="發送尊重選擇加入的行銷群發" href="/guides/how-to-marketing-broadcast">
    把一個範本發給清單或分群，附有同意記錄和 Do Not Call 名單。
  </Card>
  <Card title="讓 AI 代理透過 MCP 操作您的 WhatsApp" href="/guides/how-to-ai-agent-mcp">
    以限定權限的金鑰和核准機制，把 Claude 或其他代理連接到您的號碼。
  </Card>
  <Card title="把對話從機器人轉交給真人，再轉回來" href="/guides/how-to-human-handoff">
    為您的團隊提供對話處理者、指派、備註和摘要。
  </Card>
  <Card title="在 WhatsApp 聊天中要求付款" href="/guides/how-to-payment-links">
    在聊天中發送付款連結，並在付款完成時收到通知。
  </Card>
</CardGroup>

[所有操作指南](https://www.app2email.com/docs#how-to)
