app2email API 收費

文件

使用範本發送訂單和預約通知

建立 utility 範本、取得 Meta 核准,在訂單出貨或預約的前一天發送給單一客戶,並追蹤送達與已讀狀態。

當訂單出貨或預約就在明天時,您的系統只需一次 API 呼叫,客戶就會收到來自您企業的 WhatsApp 訊息:「John 您好,您的訂單 #1234 已出貨。」

訊息往後的狀態(已發送、已送達、已讀,或失敗及原因),您可以透過 webhook 或向 API 查詢取得。該訊息也會顯示在 app2email 活動記錄(Activity Log)和對話中。

為什麼通知需要範本

WhatsApp 只允許企業在客戶最後一次傳訊息到您號碼後的 24 小時內,發送自己的自由文字。為了安全起見,app2email 會提早 15 分鐘停止。出貨通知或預約提醒,通常是在客戶最後一次寫訊息的好幾天之後才發出,所以一般的文字訊息會被拒絕,並回應 422 outside_24h_window。

範本是經過 Meta 審查並核准的訊息文字。它可以隨時發送,佔位符({{1}}、{{2}}、...)中可填入您自己的值。

範本有類別。訂單、配送、帳號和預約更新屬於 UTILITY。促銷屬於 MARKETING。最終類別由 Meta 自行決定,所以請讓 utility 範本不含優惠和銷售用語。

您需要準備

  • 一個已連接到 app2email 的 WhatsApp 號碼,使用付費方案,且服務處於 LIVE 狀態。
  • 在 Meta 的 WhatsApp Business Account 上設定付款方式。沒有付款方式時,範本發送會失敗,並出現 Meta 錯誤 131042(whatsapp_payment_issue)。
  • 一把 API 金鑰,從 https://www.app2email.com/dashboard/apikey 取得,具備下列權限範圍:
權限範圍在本指南中的用途
templates:manage建立和編輯範本(POST /templates、PATCH /templates/{name})
messages:read讀取範本的狀態(GET /templates/{name})和訊息的狀態(GET /messages/{message_id})
messages:send發送通知(POST /messages)
webhooks:manage新增接收狀態事件的 webhook(POST /webhooks)

預設金鑰(在金鑰有權限之前建立的)沒有 templates:manage。請建立一把具備該權限的金鑰,或具備完整存取(*)的金鑰。GET /v1/YOUR_NUMBER/me 會顯示您目前這把金鑰的權限範圍。

Info

先試用。 在您自己號碼上的沙盒金鑰(在 API 金鑰頁面建立、帶有沙盒標記的金鑰)會真實執行所有檢查,但不會向 WhatsApp 發送任何內容。回應帶有 "sandbox": true,訊息 id 以 wamid.SANDBOX. 開頭,已發送、已送達和已讀的 message.status 事件仍會送達。沙盒金鑰無法建立範本(403 sandbox_key),所以請用一般金鑰建立範本。

完全不需要帳號時,POST https://api.app2email.com/v1/account/sandbox(不帶金鑰、不帶內容),或管理 MCP 伺服器的 create_sandbox 工具,會給您示範號碼 12025550100 的即時沙盒金鑰。它有 GET /templates 和 POST /messages,所以您可以把示範號碼的其中一個範本發送給它的虛擬客戶:12025550101 會回覆,12025550103 會失敗。請參閱沙盒。

一步一步發送通知

  1. 1. 建立 utility 範本

    傳送帶有編號佔位符的文字,並在 example 中為每個佔位符提供一個範例值。Meta 的審查人員會閱讀這些範例。名稱可以使用小寫字母、數字和底線。

    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"]] }
          }
        ]
      }'
    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
    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())

    您會收到的回應(HTTP 201):範本已送交 Meta 審查。

    {
      "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."
    }

    預約的部分,請用同樣的方式再建立第二個範本,例如 appointment_reminder,文字為 Hi {{1}}, this is a reminder of your {{2}} tomorrow at {{3}}. Reply to this message if you need to change it.,範例為 [["Ava", "haircut", "10:30"]]。

    範本屬於 WhatsApp Business Account:該帳號下的每個號碼都可以使用。

    Tip

    由 Meta 撰寫的追蹤按鈕。 Meta 的範本庫(Template Library)有現成的 utility 文字:GET /template-library?topic=ORDER_MANAGEMENT&usecase=SHIPMENT_CONFIRMATION 會列出它們。建立時請用 library_template_name 取代 components,並提供其按鈕的網站:

    {
      "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"
          }
        }
      ]
    }
  2. 2. 等待 Meta 審查

    審查需要幾分鐘到一天。您可以用兩種方式得知結果。

    template.status_changed webhook 事件(會發送給該 WhatsApp Business Account 的每個號碼):

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

    或者主動查詢: GET /v1/YOUR_NUMBER/templates/order_update(權限範圍 messages:read)。它是從 WhatsApp 讀取的,而不是從快取,所以剛變更的狀態也會顯示。

    cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates/order_update \
      -H "Authorization: Bearer $A2E_KEY"
    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
    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"))

    您會收到的回應: 每種語言在 versions 中有一個項目,內含 status、can_send、它 needs 哪些值,以及一個完整的 example_request,您改好值後即可直接發送。

    {
      "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" }
                  ]
                }
              ]
            }
          }
        }
      ]
    }

    遭到拒絕時的樣子:status 是 REJECTED,can_send 是 false,而 rejected_reason(在 GET /templates/{name} 中)或 reason(在 template.status_changed 事件中)會說明原因。請修正文字,並用 PATCH /v1/YOUR_NUMBER/templates/order_update 和新的 components 重新送出。只有 APPROVED、REJECTED 或 PAUSED 的範本可以編輯,已核准的範本每天最多編輯一次,30 天內最多 10 次。

    如果 Meta 把範本歸到另一個類別,GET /templates/{name} 中的 previous_category 和 correct_category 會顯示出來。

  3. 3. 新增接收狀態事件的 webhook

    每個系統一個 webhook 就夠了:該號碼的每個 webhook 都會收到每個事件,您再挑選要處理的類型。每個號碼最多 5 個。權限範圍 webhooks:manage。

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

    您會收到的回應: webhook,含有它的 id 和 secret(whsec_...)。請把密鑰保存在您的伺服器上。

    還沒有公開網址?GET /v1/YOUR_NUMBER/events?wait=25 可以取得相同的事件。請保存回應的 cursor,並在下次呼叫時把它作為 after 傳入。

  4. 4. 訂單出貨時發送通知

    把範本發送到客戶的號碼(國碼在前,只用數字),並依順序為每個佔位符提供一個值。

    兩個額外設定可確保正式上線時的安全:

    • Idempotency-Key 標頭:專屬於這則通知的值,例如您的訂單編號加上事件。如果您的工作執行了兩次,或在逾時後重試,訊息不會再次發送。
    • callback_data:您自己的簡短參照(最多 512 個字元)。它會以 data.callback_data 的形式,出現在這則訊息的 message.status 事件中,所以您不必先儲存訊息 id,就能把狀態對應到您的訂單。
    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"
      }'
    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
    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

    您會收到的回應(HTTP 200):WhatsApp 已接受訊息。text 是客戶看到的訊息內容。

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

    在開發期間,請在請求內容中加入 "dry_run": true。所有項目都會像真實發送一樣被檢查(範本值、號碼、Do Not Call 名單、每月限額),回應會顯示確切的 WhatsApp 訊息。不會發送、記錄或計數。

  5. 5. 在預約前一天發送提醒

    用 appointment_reminder 範本進行相同的呼叫。您可以從自己的每日排程工作立即發送,或用 send_at 把時間交給 app2email(含時區的 ISO 8601,從 1 分鐘後到 29 天內):

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

    排程發送會回應 HTTP 202,帶有 status: "scheduled"、scheduled_for 和群發 code。所有項目會一次檢查完畢,而 Do Not Call 名單和每月限額會在時間到時再檢查一次。如果預約被取消,請用 POST /v1/YOUR_NUMBER/broadcasts/{code}/cancel 取消該訊息。

    Note

    使用 app2email 自家 Book-and-Pay 完成的預約,不需要任何程式碼就能收到確認和提醒:它會自行建立 utility 範本,並在視窗已關閉時使用。請參閱 WhatsApp 上的預約服務。

  6. 6. 選用:附上發票,或填入按鈕

    如果範本是以文件標頭核准的,請隨每則訊息發送 PDF:可以是由 app2email 下載的 link、帶有 filename 的 base64 data,或來自 POST /media 的媒體 id。省略標頭則會發送範本自己的範例文件。文件最大可達 100 MB。

    {
      "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" }]
          }
        ]
      }
    }

    如果範本有帶佔位符的網址按鈕(像上面的範本庫範例),請以按鈕元件的形式提供位址的結尾。index 是按鈕的位置,從 "0" 開始:

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

    不確定範本需要什麼?GET /templates/{name} 中的 needs 和 example_request 會列出每個標頭、內文和按鈕的值。

結果

客戶會看到來自您企業名稱的訊息,內含範本文字和您填入的值,如果範本有文件或按鈕,也會一併顯示。如果他們回覆,24 小時視窗就會開啟,您可以用一般訊息回覆。

在您這一端,訊息往後的進展會以 message.status 事件送達。status 是 sent、delivered、read 或 failed(語音訊息還有 played,另外還有 clicked 和 deleted)。

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

無法送達的訊息也會以 message.failed 事件送達,資料相同,並帶有 error,其中有 Meta 的 code、app2email 的 error_code 和 how_to_fix:

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

事件可能亂序抵達,所以 read 可能先於它的 delivered 出現。請為每個 message_id 保留最靠前的狀態,不要退回。

或者主動查詢狀態,使用 GET /v1/YOUR_NUMBER/messages/{message_id}(權限範圍 messages:read;請對 id 進行 URL 編碼)。它適用於從該號碼發送的任何訊息,內有狀態、每個步驟的時間、失敗原因,以及客戶的回覆或按鈕點選。

cURL
curl -s "https://api.app2email.com/v1/YOUR_NUMBER/messages/wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA%3D" \
  -H "Authorization: Bearer $A2E_KEY"
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
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"))

您會收到的回應: status 是 accepted、sent、delivered、read、failed、deleted、queued 或 unknown 其中之一。尚未到達的步驟不會出現在 times 中。

{
  "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_..."
}

若要一次查看多則訊息,GET /v1/YOUR_NUMBER/messages?status=failed&since=2026-11-06T00:00:00Z 會列出失敗的訊息,GET /v1/YOUR_NUMBER/stats?from=&to= 則會給出某段期間的已發送、已送達、已讀和失敗數量。

費用

app2email 收取固定的月費方案;每則通知計為方案中的一則訊息,沒有每則訊息的加價(價格)。Meta 也會對範本訊息收費,直接向您 WhatsApp Business Account 上的付款方式收取。價格取決於範本的類別和客戶所在的國家,在大多數國家,utility 範本比行銷範本便宜。這也是為什麼要讓訂單和預約更新維持純粹資訊性的另一個原因。狀態事件中的 pricing 物件會顯示 Meta 如何計算每則訊息(billable、category),而 GET /v1/YOUR_NUMBER/usage 中的 meta_pricing 會按類別加總整個月,並附上參考費用。若要在開始之前先估算,請使用 WhatsApp 價格計算器。

上線檢查清單

檢查 webhook 簽章

每個事件都有標頭 X-App2email-Signature: t=<unix seconds>,v1=<hex>。v1 的值是 "<t>.<raw body>" 的 HMAC-SHA256,以 webhook 的密鑰(whsec_...,包含前綴)為金鑰。請檢查每一個 v1=(輪換之後,舊密鑰仍保留期間會有兩個),針對完全按收到原樣的原始請求內容計算,並拒絕過舊的 t。X-Hub-Signature-256: sha256=<hex>(原始請求內容的 HMAC-SHA256,只使用目前的密鑰)也同樣提供,供為 Meta webhook 撰寫的程式碼使用。

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
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
丟棄重複的事件

請在 10 秒內回應 2xx 狀態。否則該事件會在 10 秒、1 分鐘、5 分鐘、30 分鐘、1、2、4、8 和 16 小時之後再次發送。X-App2email-Delivery(事件 id,evt_...)在每次重試時都相同,所以請把它儲存起來,並略過您已處理過的事件。耗時的工作請在回應之後再做。

絕不重複發送同一則通知

請發送一個屬於該通知、而不是屬於該次嘗試的 Idempotency-Key 標頭:order-1234-shipped、appt-5521-reminder。24 小時內以相同的金鑰發送相同的請求,不會再次發送;它會得到第一次的回應,並附有標頭 Idempotent-Replayed: true。

  • 相同的金鑰搭配不同的內容:422 idempotency_key_reused。不同的訊息請使用新的金鑰。
  • 第一個請求仍在執行中:409 idempotency_request_in_progress。請等待,並以相同的金鑰重試。
  • 第一個請求在 15 分鐘內沒有完成:409 idempotency_request_interrupted。訊息可能已經發出:在用新的金鑰發送之前,請先檢查 GET /messages?to=61412345678。
  • 在任何內容發送之前就被拒絕的請求,會讓金鑰保持可用,所以修正後的請求可以使用它。

金鑰會保留 24 小時。如果某個工作可能在數天後再次執行,請同時把 message_id 與訂單事件一起存在您自己的資料庫中,如果已經有記錄,就不要發送。

只重試正確的錯誤,而且只重試那些

每個回應都有 X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset(距離恢復額滿的秒數)和 X-RateLimit-Policy。超過限制時,您會得到帶有 Retry-After 標頭和 error.retry_after_seconds 的 429 rate_limited:等待該段時間,然後再次發送相同的請求。

  • 500、502、503 或逾時:以逐漸加長的等待時間重試幾次,並使用相同的 Idempotency-Key。
  • 429 too_many_messages_to_recipient 或 429 whatsapp_rate_limit:WhatsApp 自己的限制。請退避數分鐘,而不是數秒。
  • 429 monthly_limit_reached:方案的訊息額度已用完。在下個計費月或升級之前不要重試。
  • 其他任何 4xx:不要不加修改就重試。請依 error.code 判斷並照著 how_to_fix 處理。error.is_retriable 會告訴您相同的請求日後是否可能成功。
24 小時視窗

已核准的範本可以隨時發出。一般的文字、圖片或文件,只有在客戶最後一則訊息後的 24 小時內才有效(app2email 會提早 15 分鐘停止)。所以當客戶回覆「我可以更改地址嗎?」時,您可以用自由文字回覆。GET /v1/YOUR_NUMBER/conversations/61412345678 會顯示 window_open 和 window_closes_at。

退出、Do Not Call 和類別

Do Not Call 名單和選擇加入規則(/settings/optin)適用於行銷範本。Do Not Call 名單上的客戶仍然可以收到訂單更新之類的 utility 範本。

每個範本的類別都由 Meta 自行設定,日後也可能改變。如果某個範本變成 MARKETING,Do Not Call 名單和選擇加入規則就會適用於它,並按行銷計費。請留意 template.status_changed 事件,並讓促銷內容遠離您的通知文字。

WhatsApp 也會依人們的反應,為每個範本評估品質。quality_score 為 RED 的範本可能被暫停,被暫停的範本會回應 422 template_paused。

如果無法運作

每個錯誤都是帶有 error.code、message、how_to_fix 的 JSON,以及一個可向支援團隊提供的 request_id。所有代碼請見錯誤。

代碼發生時機處理方式
403 insufficient_scope金鑰缺少某項權限(details.required_scope)視需要使用具備 templates:manage、messages:send、messages:read 或 webhooks:manage 的金鑰
403 sandbox_key用沙盒金鑰建立或編輯範本範本請使用一般金鑰
400 invalid_template_categorycategory 不是 MARKETING、UTILITY 或 AUTHENTICATION訂單和預約更新請使用 UTILITY
400 invalid_template_components某個元件沒有 type(HEADER、BODY、FOOTER、BUTTONS)元件採用 WhatsApp 自己的格式;請與上方的範例比對
409 template_already_exists名稱和語言已存在(或正在刪除中)使用另一個名稱或語言
422 template_rejectedWhatsApp 沒有接受該範本依 whatsapp_error 的說明修正後重新送出
404 template_not_found名稱與帳號中的任何範本都不相符名稱是小寫的,而且必須完全相符;請參閱 details.available_templates
422 template_not_approved範本正在審核中、已被拒絕、已暫停或已停用等待核准,或修正它;請檢查 GET /templates/{name}
422 template_parameters_invalid值與範本不符依 details.problems 和 example_request 修正內容
422 template_parameter_count_mismatchMeta 錯誤 132000:值的數量有誤每個佔位符發送一個值;請參閱 example_request
422 template_pausedMeta 錯誤 132015:因品質偏低而暫停使用另一個範本,或編輯這個範本
422 outside_24h_window您在視窗之外發送了自由文字,而不是範本改為發送已核准的範本
403 whatsapp_payment_issueMeta 錯誤 131042:Meta 無法向您的 WhatsApp 帳號扣款在 WhatsApp Manager 中新增或修正付款方式
422 recipient_unreachableMeta 錯誤 131026檢查號碼是否含有國碼,並且有使用 WhatsApp
422 media_download_failed無法下載文件的 link使用不需要登入就能開啟的連結,或發送 base64 data
422 idempotency_key_reused相同的 Idempotency-Key,不同的內容不同的訊息請使用新的金鑰
429 rate_limited此金鑰的呼叫次數過多等待 Retry-After 秒,然後重試
429 monthly_limit_reached本月方案的訊息額度已用完等待下個計費月,或升級
404 message_not_found該號碼沒有符合該 id 的訊息使用發送回應中的 message_id,並進行 URL 編碼

更多操作指南

所有操作指南