# 匯入聯絡人，並與您的 CRM 保持同步

> 一次匯入您的客戶名單，用 upsert 推送 CRM 中的每項變更，連同證據一起記錄同意，並以簽署的 webhook 事件，從 app2email 取回退訂、號碼變更和聯絡人變更。

在本指南中，您會把客戶名單載入 app2email，並讓它與您已經在使用的 CRM 或資料庫保持一致。CRM 中的變更會即時傳送到 app2email。WhatsApp 端的退訂、新號碼和其他變更，則會以 webhook 事件的形式傳回您的 CRM。

**客戶看到的內容：** 沒有任何新東西，而這正是重點。他們收到的訊息會帶有正確的名字和訂單編號，同意接收優惠的人會收到優惠，而在 WhatsApp 或您的 CRM 中表示 STOP 的人，不會再收到您的任何行銷訊息。

**您看到的內容：** app2email 中的每位聯絡人，都和您的 CRM 有相同的姓名、標籤、自訂欄位和行銷同意。對方一點選「Stop promotions」，一秒後您的 CRM 就會把他們標示為已退訂；他們在 WhatsApp 中更換電話號碼時，CRM 也會更新他們的電話號碼。

app2email 沒有針對特定 CRM 的內建連接器。您可以用下面的呼叫來連接您的 CRM：從您自己的程式碼，或從自動化工具（請參閱[從 n8n、Zapier 或 Make 發送 WhatsApp 訊息](/guides/how-to-no-code-n8n-zapier-make)）。

## 運作方式

1. **一次性：** 用 `POST /contacts/import` 匯入您現有的名單（CSV 或 JSON，每次呼叫最多 5000 列）。
2. **從您的 CRM 到 app2email：** 每當您的 CRM 中建立或變更聯絡人時，您的程式碼就把它送到 `POST /contacts`。這是一個 **upsert**：聯絡人是新的，app2email 就建立它；已存在，就更新它，並以電話號碼（或商家範圍的使用者 id）比對。
3. **從 app2email 到您的 CRM：** app2email 會向您的 URL 發送已簽署的 webhook 事件：有人停止接收優惠時是 `contact.opted_out`，聯絡人透過 API 被變更、或在 WhatsApp 中重新開啟行銷訊息時是 `contact.updated`，有人換到新號碼時是 `contact.changed_number`，有人傳訊息給您時是 `message.received`。
4. **不定期：** 您用 `GET /contacts`（逐頁）或 `GET /contacts/export.csv` 比對兩邊，以找出事件沒有涵蓋到的部分。

**用來比對的鍵**是聯絡人的 `identity`：他們的 WhatsApp 號碼，國碼在前，只有數字（+61 412 345 678 寫成 `61412345678`）。請在您的 CRM 中儲存相同的值。使用 WhatsApp 使用者名稱的聯絡人，可能會帶有商家範圍的使用者 id 而不是號碼（例如 `AU.1234567890123456`，這時 `identity_type` 為 `bsuid`）；它在任何可以使用號碼的地方都能使用。

## 聯絡人包含哪些資料

| 欄位 | 內容 | 限制 |
| --- | --- | --- |
| `phone` 或 `identity` | 指定哪位聯絡人。`identity` 接受號碼或商家範圍的使用者 id | 國碼在前，只有數字 |
| `name` | 聯絡人的姓名 | 最多 200 個字元 |
| `tags` | 標籤，例如 `vip` 或 `newsletter`。也可以使用以逗號分隔的字串 | 最多 50 個標籤，每個 40 個字元 |
| `custom_fields` | 您自己的文字值，例如 `first_name`、`order_id`、`crm_id`。在分群發送中用作具名的範本值 | 最多 50 個；名稱由字母、數字和底線組成 |
| `source` | 聯絡人的來源，例如 `crm` | 最多 50 個字元 |
| `consent` | 行銷同意及其證據：`marketing`（true 或 false）、`at`、`source`、`text`（他們同意的文字內容）、`evidence`（連結、檔案名稱、IP 位址或訊息 id） | `source` 100、`text` 1000、`evidence` 500 個字元 |

在回應中，聯絡人還會有 `identity_type`（`phone` 或 `bsuid`）、`consent.recorded`（只要有任何同意紀錄就是 true）、`last_inbound_at`、`last_outbound_at`、`created` 和 `updated`。沒有值的欄位不會出現在回應中。

**更新的運作方式：** 您提供的欄位會取代已儲存的欄位，您沒有提供的欄位則保持不變。`tags` 是整份清單一起被取代，所以請務必送出聯絡人應有的每一個標籤。`custom_fields` 則是**合併**：您送出的名稱會被設定，其他的保持不變。

## 您需要準備

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

| 權限範圍 | 用途 |
| --- | --- |
| `contacts:manage` | 匯入、建立、變更和刪除聯絡人、記錄同意、儲存分群（`POST /contacts/import`、`POST /contacts`、`PATCH /contacts/{identity}`、`DELETE /contacts/{identity}`、`POST /contacts/{identity}/consent`、`POST /segments`） |
| `messages:read` | 讀取聯絡人和分群、匯出、取得事件（`GET /contacts`、`GET /contacts/{identity}`、`GET /contacts/export.csv`、`GET /segments/{id}/contacts`、`GET /events`） |
| `webhooks:manage` | 註冊 webhook 一次（`POST /webhooks`）。您也可以在 API 金鑰頁面的 Webhooks 下新增，不需要程式碼 |
| `dnc:manage` | 把在 CRM 中退訂的人加入 Do Not Call 名單，並匯出合規紀錄（`POST /donotcall`、`GET /compliance/export.csv`） |
| `settings:manage` | 只有在您為行銷使用選擇加入規則時才需要：記錄選擇加入（`POST /optins`） |

- **一個公開的 https 位址**供 webhook 使用，或是改用 `GET /events` 取得事件的指令碼。

<Warning>
**請用幾位您自己的聯絡人來測試，不要使用沙盒金鑰。** 聯絡人不屬於即時沙盒的一部分（示範號碼 `12025550100` 會回應 403 `not_in_instant_sandbox`）。您自己號碼上的沙盒金鑰可以正常讀取聯絡人，但 `POST /contacts`、`POST /contacts/import`、`PATCH`、同意和分群**會變更您的真實資料**，而使用沙盒金鑰的 `DELETE /contacts/{identity}` 只是模擬，不會刪除任何東西。請給您的測試聯絡人一個標籤，例如 `test`，事後再用一般金鑰刪除它們。詳情：[沙盒](/api/sandbox)。
</Warning>

## 逐步設定同步

每個呼叫都送到 `https://api.app2email.com/v1/YOUR_NUMBER`，其中 `YOUR_NUMBER` 是您的 WhatsApp 號碼（國碼在前，只有數字），並帶有標頭 `Authorization: Bearer YOUR_API_KEY`。範例會從環境變數 `A2E_KEY` 讀取金鑰。

<Steps>
  <Step title="檢查您的金鑰">
    `GET /me` 會顯示金鑰的權限範圍和限額。

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

    **您會收到的回應**（已縮短）：

    ```json
    {
      "success": true,
      "request_id": "a7k3p",
      "key_valid": true,
      "number": "4976659348270",
      "service_status": "LIVE",
      "key": { "name": "CRM sync", "scopes": ["contacts:manage", "messages:read", "webhooks:manage", "dnc:manage"], "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` 必須列出您需要的權限範圍（或代表完整存取的 `*`）。`limits` 告訴您同步的呼叫速度可以多快。
  </Step>

  <Step title="一次匯入您現有的聯絡人">
    從 CRM 把您的名單匯出為帶有標題列的 CSV。app2email 認得的欄位有 `phone`（或 `identity`、`number`、`mobile`）、`name`（或 `first_name` + `last_name`）、`tags`（以 `|` 分隔）、`consent_marketing`（yes 或 no）、`consent_source`、`consent_text`、`consent_evidence`、`consent_at` 和 `source`。**其他每一欄都會變成自訂欄位**，所以名為 `crm_id` 的欄位，會把您 CRM 自己的 id 保存在每位聯絡人上。每次呼叫最多 5000 列。

    ```csv
    phone,name,first_name,crm_id,tags,consent_marketing,consent_source,consent_text,consent_evidence,consent_at,source
    61412345678,John Smith,John,C-1001,vip|newsletter,yes,web form,"Yes, send me offers on WhatsApp",https://example.com/forms/123,2026-10-01T09:00:00Z,crm
    61498765432,Mary Jones,Mary,C-1002,newsletter,no,,,,,crm
    ```

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/import \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: text/csv" \
      --data-binary @contacts.csv
    ```

    ```javascript Node.js
    import { readFile } from "node:fs/promises";

    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/contacts/import", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "text/csv",
      },
      body: await readFile("contacts.csv"),
    });
    const result = await res.json();
    console.log(res.status, result.saved, "saved,", result.skipped, "skipped");
    for (const e of result.errors ?? []) console.log(`row ${e.row}: ${e.problem}`);
    ```

    ```python Python
    import os, requests

    with open("contacts.csv", "rb") as f:
        res = requests.post(
            "https://api.app2email.com/v1/YOUR_NUMBER/contacts/import",
            headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}", "Content-Type": "text/csv"},
            data=f,
            timeout=120,
        )
    result = res.json()
    print(res.status_code, result.get("saved"), "saved,", result.get("skipped"), "skipped")
    for e in result.get("errors", []):
        print(f"row {e['row']}: {e['problem']}")
    ```

    </CodeGroup>

    **您會收到的回應：** 有問題的列會被略過並列出，其餘的會被儲存。

    ```json
    {
      "success": true,
      "request_id": "i2gka",
      "rows": 120,
      "saved": 118,
      "created": 90,
      "updated": 28,
      "skipped": 2,
      "errors": [
        {
          "row": 7,
          "problem": "'0412' must be a WhatsApp number with country code, digits only (8 to 15 digits), or a business-scoped user id like 61.AbC123"
        }
      ],
      "note": "Rows with a problem were skipped (the first 50 are listed); the rest were saved."
    }
    ```

    如何解讀：

    - `rows` 是 app2email 讀到的列數，`saved` = `created` + `updated`，而 `skipped` 是有問題的列數。
    - `errors` 會列出前 50 個有問題的列，附上列號和原因。請在 CRM 中修正這些列（通常是缺少國碼的號碼），然後只重新匯入這些列。重複匯入某一列是安全的：既有的聯絡人會被更新，而不會重複。
    - 超過 5000 列：請把檔案拆開，每個部分各呼叫一次。

    同一個呼叫也接受 `application/json`，內含採用 `POST /contacts` 格式的聯絡人清單（下一步）。匯入**不會**發送 `contact.updated` 事件，所以第一次大量載入不會讓您的 webhook 被事件淹沒。
  </Step>

  <Step title="用 upsert 推送 CRM 中的每項變更">
    當 CRM 中建立或變更聯絡人時（CRM webhook、資料庫觸發條件，或每隔幾分鐘執行的工作），把它送到 `POST /contacts`：一位聯絡人用一個物件，或用最多 1000 位的清單。

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "phone": "61412345678",
        "name": "John Smith",
        "tags": ["vip", "newsletter"],
        "custom_fields": { "first_name": "John", "crm_id": "C-1001", "order_id": "1234" },
        "source": "crm"
      }'
    ```

    ```javascript Node.js
    const BASE = "https://api.app2email.com/v1/YOUR_NUMBER";
    const headers = { Authorization: `Bearer ${process.env.A2E_KEY}`, "Content-Type": "application/json" };
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

    // crmRows: the contacts that changed in your CRM since the last run
    export async function pushToApp2email(crmRows) {
      const contacts = crmRows.map((c) => ({
        phone: c.mobile,                       // 61412345678: country code first, digits only
        name: c.fullName,
        tags: c.tags,                          // the whole list: it replaces the stored tags
        custom_fields: { first_name: c.firstName, crm_id: String(c.id) },
        source: "crm",
      }));
      for (let i = 0; i < contacts.length; i += 1000) {
        const batch = contacts.slice(i, i + 1000);
        for (let attempt = 1; ; attempt++) {
          const res = await fetch(`${BASE}/contacts`, { method: "POST", headers, body: JSON.stringify(batch) });
          const body = await res.json();
          if (res.ok) { console.log(`saved ${body.saved}: ${body.created} new, ${body.updated} updated`); break; }
          if (res.status === 429 || (res.status >= 500 && attempt < 5)) {
            const wait = Number(res.headers.get("Retry-After") ?? body.error?.retry_after_seconds ?? 2 ** attempt);
            await sleep(wait * 1000);
            continue; // the same batch again is safe: it is an upsert
          }
          throw new Error(`${body.error?.code}: ${body.error?.how_to_fix} (request ${body.request_id})`);
        }
      }
    }
    ```

    ```python Python
    import os, time, requests

    BASE = "https://api.app2email.com/v1/YOUR_NUMBER"
    HEADERS = {"Authorization": f"Bearer {os.environ['A2E_KEY']}"}

    def push_to_app2email(crm_rows):
        """crm_rows: the contacts that changed in your CRM since the last run."""
        contacts = [{
            "phone": c["mobile"],               # 61412345678: country code first, digits only
            "name": c["full_name"],
            "tags": c["tags"],                  # the whole list: it replaces the stored tags
            "custom_fields": {"first_name": c["first_name"], "crm_id": str(c["id"])},
            "source": "crm",
        } for c in crm_rows]
        for i in range(0, len(contacts), 1000):
            batch = contacts[i:i + 1000]
            for attempt in range(1, 6):
                res = requests.post(f"{BASE}/contacts", headers=HEADERS, json=batch, timeout=60)
                body = res.json()
                if res.ok:
                    print(f"saved {body['saved']}: {body['created']} new, {body['updated']} updated")
                    break
                if res.status_code == 429 or res.status_code >= 500:
                    wait = res.headers.get("Retry-After") or body.get("error", {}).get("retry_after_seconds") or 2 ** attempt
                    time.sleep(float(wait))
                    continue  # the same batch again is safe: it is an upsert
                raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']} (request {body['request_id']})")
    ```

    </CodeGroup>

    **您會收到的回應：** 儲存、建立和更新的數量，以及已儲存的前 100 位聯絡人。

    ```json
    {
      "success": true,
      "request_id": "u8wqb",
      "saved": 1,
      "created": 0,
      "updated": 1,
      "contacts": [
        {
          "identity": "61412345678",
          "identity_type": "phone",
          "phone": "61412345678",
          "name": "John Smith",
          "tags": ["vip", "newsletter"],
          "custom_fields": { "first_name": "John", "crm_id": "C-1001", "order_id": "1234" },
          "source": "crm",
          "consent": {
            "marketing": true,
            "at": "2026-10-01T09:00:00Z",
            "source": "web form",
            "text": "Yes, send me offers on WhatsApp",
            "evidence": "https://example.com/forms/123",
            "recorded": true
          },
          "last_inbound_at": "2026-10-26T01:20:44Z",
          "created": "2026-10-01T09:00:10Z",
          "updated": "2026-11-21T09:00:00Z"
        }
      ]
    }
    ```

    最多 50 位聯絡人的請求，會為每一位發送 `contact.updated`；更大的清單則不會。如果只要變更某一位聯絡人的少數幾個欄位，`PATCH /contacts/{identity}` 接受相同的欄位，而且只有您給的欄位會被變更：

    ```bash
    curl -s -X PATCH https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678 \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "tags": ["vip", "newsletter", "repeat_buyer"] }'
    ```

    對於 app2email 還沒有的聯絡人，`PATCH` 會回應 `404 contact_not_found`，所以同步最簡單的做法，就是到處都使用 `POST /contacts`。
  </Step>

  <Step title="記錄同意和撤回">
    當有人在您的 CRM 中同意接收行銷訊息（網頁表單、結帳時勾選的方塊），請把它連同文字內容和證據記錄在聯絡人上。您可以把相同的 `consent` 物件放在 `POST /contacts` 中送出，或使用同意呼叫，當聯絡人是新的時候，它也會建立該聯絡人。省略 `at` 時，它就是現在。

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "marketing": true,
        "source": "web form",
        "text": "Yes, send me offers on WhatsApp",
        "evidence": "https://example.com/forms/123"
      }'
    ```

    ```javascript Node.js
    await fetch("https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        marketing: true,
        source: "web form",
        text: "Yes, send me offers on WhatsApp",
        evidence: "https://example.com/forms/123",
      }),
    });
    ```

    ```python Python
    requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent",
        headers=HEADERS,
        json={
            "marketing": True,
            "source": "web form",
            "text": "Yes, send me offers on WhatsApp",
            "evidence": "https://example.com/forms/123",
        },
        timeout=10,
    )
    ```

    </CodeGroup>

    **您會收到的回應：** 聯絡人，帶有 `consent.recorded: true`，隨後會有一個 `contact.updated` 事件，帶有 `change: "consent"`。

    當有人**在您的 CRM 中退訂**時，請做兩件事：

    1. 在聯絡人上記錄撤回：用相同的呼叫，帶 `"marketing": false`。帶有 `consent_marketing: true` 的分群之後就會把他們排除。
    2. 把他們加入 Do Not Call 名單，這樣任何行銷範本都不會再送到他們那裡（權限範圍 `dnc:manage`，每次呼叫最多 1000 個號碼，全部成功或全部失敗）：

    ```bash
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/donotcall \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "numbers": [ { "number": "61498765432", "name": "Mary", "note": "Unsubscribed in our CRM" } ] }'
    ```

    回應會在 `added` 中列出已加入的號碼，並在 `already_on_list` 中列出原本就在名單上的號碼。

    只記錄您確實擁有的同意。如果您的號碼使用行銷的選擇加入規則（`PUT /settings/optin`），這項規則看的是**選擇加入紀錄**，它和聯絡人上的同意是分開保存的：請也用 `POST /optins` 記錄這些人（權限範圍 `settings:manage`）。做法請參閱[行銷群發指南](/guides/how-to-marketing-broadcast)。
  </Step>

  <Step title="為 app2email 端的變更註冊 webhook">
    一個呼叫即可。回應中包含為每個事件簽署的**簽署密鑰**（`whsec_...`）：請把它保存為 `WEBHOOK_SECRET`。

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

    **您會收到的回應**（201 Created，已縮短）：

    ```json
    {
      "success": true,
      "request_id": "w8hk2",
      "webhook": {
        "id": "wh_a1b2c3d4e5f6g7h8",
        "url": "https://crm-sync.example.com/app2email",
        "secret": "whsec_...",
        "active": true,
        "format": "app2email"
      }
    }
    ```

    號碼的每個 webhook 都會收到每一個事件（每個號碼最多 5 個 webhook），所以您的接收端要依 `type` 挑出它要處理的類型，並對其他所有類型回應 2xx。再次註冊相同的 URL，會回應那個既有的 webhook，所以這個呼叫可以安全地重複執行。

    沒有公開位址？`GET /events?types=contact.updated,contact.opted_out,contact.changed_number,message.received&wait=25` 可以取得相同的事件。請保留回應中的 `cursor`，並在下次呼叫時以 `after` 傳入。第一次呼叫會開啟事件饋送，從那時起事件會保留 72 小時。
  </Step>

  <Step title="把變更寫入您的 CRM">
    您的接收端會檢查簽章、略過已經處理過的事件、立刻回應 200，然後更新 CRM。

    <CodeGroup>

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

    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 eventId = req.get("X-App2email-Delivery");
      if (await alreadySeen(eventId)) return res.sendStatus(200); // a retry
      const event = JSON.parse(req.body);
      res.sendStatus(200); // answer within 10 seconds, then do the work
      if (event.test) return; // test events carry made-up contacts
      const d = event.data;

      switch (event.type) {
        case "contact.opted_out": // STOP, "Stop promotions" or one of your opt-out words
          await crm.markUnsubscribed(d.number, { channel: "whatsapp", reason: d.source, at: d.timestamp });
          break;
        case "contact.updated": {
          if (d.change === "marketing_resumed") {
            await crm.noteMarketingResumed(d.contact.identity, d.timestamp);
            break;
          }
          // upsert, patch or consent: write only what differs, so your own pushes do not loop
          const c = d.contact;
          const current = await crm.findByIdentity(c.identity);
          if (current && sameValues(current, c)) break;
          await crm.save(c.identity, { name: c.name, tags: c.tags, fields: c.custom_fields, consent: c.consent });
          break;
        }
        case "contact.changed_number":
          if (d.change === "user_changed_number") await crm.changePhone(d.previous.phone, d.new.phone);
          else await crm.changeUserId(d.previous.user_id, d.new.user_id);
          break;
        case "message.received": // someone wrote: a lead, or a "last contacted" date
          await crm.touch(d.from ?? d.from_user_id, { name: d.name, lastInboundAt: d.timestamp });
          break;
      }
      await markSeen(eventId);
    });

    app.listen(3000);
    ```

    ```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
        event_id = request.headers.get("X-App2email-Delivery")
        if already_seen(event_id):
            return "", 200  # a retry
        queue.put(json.loads(raw))  # a worker calls handle(event) after the answer
        mark_seen(event_id)
        return "", 200  # within 10 seconds

    def handle(event):
        if event.get("test"):
            return  # test events carry made-up contacts
        d = event["data"]
        t = event["type"]
        if t == "contact.opted_out":
            crm.mark_unsubscribed(d["number"], channel="whatsapp", reason=d["source"], at=d.get("timestamp"))
        elif t == "contact.updated":
            if d["change"] == "marketing_resumed":
                crm.note_marketing_resumed(d["contact"]["identity"], d.get("timestamp"))
                return
            c = d["contact"]
            current = crm.find_by_identity(c["identity"])
            if current and same_values(current, c):
                return  # your own push coming back: nothing to do
            crm.save(c["identity"], name=c.get("name"), tags=c.get("tags", []),
                     fields=c.get("custom_fields", {}), consent=c.get("consent"))
        elif t == "contact.changed_number":
            if d["change"] == "user_changed_number":
                crm.change_phone(d["previous"].get("phone"), d["new"].get("phone"))
            else:
                crm.change_user_id(d["previous"].get("user_id"), d["new"].get("user_id"))
        elif t == "message.received":
            crm.touch(d.get("from") or d.get("from_user_id"), name=d.get("name"), last_inbound_at=d.get("timestamp"))
    ```

    </CodeGroup>

    `crm.*`、`alreadySeen`、`markSeen` 和 `sameValues` 代表您自己的程式碼。請用 `POST /webhooks/{id}/test` 和類似 `{"type": "contact.opted_out"}` 的內容來測試接收端：您會得到該事件已簽署的範例，帶有 `"test": true`。
  </Step>

  <Step title="選用：用 CRM 的標籤和欄位建立分群">
    分群是對您的聯絡人儲存的篩選條件，所以您在 CRM 中維護的名單，不必到處複製號碼，就能成為受眾。您給的每個條件都必須成立：`tags_any`、`tags_all`、`consent_marketing`、`last_inbound_days`（在最近 N 天內傳訊息給您，1 到 3650）和 `search`（姓名或號碼的一部分）。每個號碼最多 100 個分群。

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/segments \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "VIP, consented",
        "filter": { "tags_any": ["vip"], "consent_marketing": true, "last_inbound_days": 90 }
      }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/segments", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        name: "VIP, consented",
        filter: { tags_any: ["vip"], consent_marketing: true, last_inbound_days: 90 },
      }),
    });
    const { segment } = await res.json();
    console.log(segment.id, segment.contacts);
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/segments",
        headers=HEADERS,
        json={"name": "VIP, consented",
              "filter": {"tags_any": ["vip"], "consent_marketing": True, "last_inbound_days": 90}},
        timeout=10,
    )
    segment = res.json()["segment"]
    print(segment["id"], segment["contacts"])
    ```

    </CodeGroup>

    **您會收到的回應**（HTTP 201）：分群，包含 `id`、`name`、`filter`、`created`、`updated`，以及 `contacts`，也就是目前符合條件的聯絡人數。`GET /segments/{id}/contacts` 會列出他們（以 `next_cursor` 分頁），路徑中可以使用 id 或完整名稱。

    分群會跟著您的聯絡人變動：當同步變更了某個標籤或同意，分群的成員也會隨之改變。要向它發送範本，請使用 `"segment": "VIP, consented"`，放在 `POST /messages` 上；沒有自己的值的具名範本值，會從每位聯絡人的 `custom_fields` 填入（`name` 取自聯絡人的姓名）。請參閱[發送尊重選擇加入的行銷群發](/guides/how-to-marketing-broadcast)。帶有 `enrol_tag` 的滴灌序列，會讓從那時起取得該標籤的聯絡人加入序列：請參閱[用滴灌序列自動跟進客戶](/guides/how-to-drip-sequence)。
  </Step>

  <Step title="不定期比對兩邊">
    事件涵蓋了 API 的變更、退訂和號碼變更，但 `contact.updated` 不會為匯入、超過 50 位聯絡人的 upsert 清單，或在 API 之外所做的變更而發送。每晚（或每週）一次，讀取每位聯絡人並比對。

    `GET /contacts` 會逐頁列出聯絡人，最新的在前，每頁最多 200 位。如果您只需要其中一部分，可以用 `tag`、`consent`（true 或 false）或 `q`（姓名或號碼的一部分）篩選。

    <CodeGroup>

    ```bash cURL
    curl -s "https://api.app2email.com/v1/YOUR_NUMBER/contacts?limit=200" \
      -H "Authorization: Bearer $A2E_KEY"
    # next page: add &cursor=<next_cursor of the previous answer>
    ```

    ```javascript Node.js
    export async function* allContacts() {
      let cursor;
      do {
        const url = new URL("https://api.app2email.com/v1/YOUR_NUMBER/contacts");
        url.searchParams.set("limit", "200");
        if (cursor) url.searchParams.set("cursor", cursor);
        const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.A2E_KEY}` } });
        const page = await res.json();
        yield* page.contacts;
        cursor = page.next_cursor;
      } while (cursor);
    }

    for await (const c of allContacts()) {
      if (new Date(c.updated) > lastReconcile) await compareWithCrm(c);
    }
    ```

    ```python Python
    def all_contacts():
        cursor = None
        while True:
            params = {"limit": 200}
            if cursor:
                params["cursor"] = cursor
            page = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/contacts",
                                headers=HEADERS, params=params, timeout=30).json()
            yield from page["contacts"]
            cursor = page.get("next_cursor")
            if not cursor:
                break

    for c in all_contacts():
        if c["updated"] > last_reconcile_iso:
            compare_with_crm(c)
    ```

    </CodeGroup>

    **您會收到的回應：** `contacts`（每位的格式如 upsert 步驟所示）、此頁的 `count`、`total`，以及在最後一頁之前都會出現的 `next_cursor`。

    如果要用於試算表或備份，`GET /contacts/export.csv` 會把每位聯絡人輸出成一個 CSV 檔案（最多 50,000 列）：每位聯絡人一列，標籤以 `|` 分隔，同意，以及以 JSON 表示的自訂欄位。

    ```bash
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/export.csv \
      -H "Authorization: Bearer $A2E_KEY" -o contacts-export.csv
    ```
  </Step>
</Steps>

## 結果

您的 CRM 和 app2email 現在擁有相同的人，並有相同的標籤、欄位和同意。以下是您的 webhook 會收到的內容，以及收到的時機。

| 事件 | 何時送達 | 您的 CRM 要做什麼 |
| --- | --- | --- |
| `contact.opted_out` | 聯絡人回覆 STOP（或您設定的其中一個退訂字詞），或點選了「Stop promotions」。他們現在已在 Do Not Call 名單上。`source` 是 `stop_promotions`、`whatsapp_stop` 或 `keyword` | 把他們標示為已退訂 WhatsApp 行銷 |
| `contact.updated`，`change` 為 `upsert`、`patch` 或 `consent` | 聯絡人透過 API 被建立或變更：來自您的同步、另一個整合，或使用 MCP 工具 `upsert_contact` 的 AI 代理 | 儲存有差異的內容 |
| `contact.updated`，帶有 `change: "marketing_resumed"` | 聯絡人在 WhatsApp 內重新開啟了來自您的行銷訊息 | 記下來。這不是新的同意：只有在您真的取得同意時才記錄同意 |
| `contact.changed_number` | 聯絡人換到新的 WhatsApp 號碼（`user_changed_number`），或他們商家範圍的使用者 id 改變了（`user_changed_user_id`） | 更新 CRM 紀錄上的電話或 id |
| `message.received` | 聯絡人傳訊息給您，或點選了按鈕 | 建立潛在客戶，或設定「最後聯絡時間」 |

**透過 API 儲存的聯絡人**（`contact.updated`）：

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "contact.updated",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": {
      "identity": "61412345678",
      "identity_type": "phone",
      "phone": "61412345678",
      "name": "Sample Contact",
      "tags": ["vip"],
      "custom_fields": { "city": "Sydney" },
      "source": "api",
      "consent": {
        "marketing": true,
        "at": "2026-11-06T01:00:00.000Z",
        "source": "website form",
        "recorded": true
      },
      "created": "2026-11-06T01:00:00.000Z",
      "updated": "2026-11-06T01:00:00.000Z"
    },
    "change": "upsert",
    "timestamp": "2026-11-06T01:00:00.000Z"
  }
}
```

**退訂**（`contact.opted_out`）：

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "contact.opted_out",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "number": "61412345678",
    "name": "Sample Contact",
    "source": "stop_promotions",
    "detail": "Stop promotions",
    "timestamp": "2026-11-06T01:00:00.000Z"
  }
}
```

**新號碼**（`contact.changed_number`）：

```json
{
  "id": "evt_Pa3k9m2Lw8Rt5Yp1Zs03",
  "type": "contact.changed_number",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "change": "user_changed_number",
    "previous": { "phone": "61412345678", "user_id": "AU.9876543210987654" },
    "new": { "phone": "61498765432", "user_id": "AU.1234567890123456" },
    "name": "Sample Contact",
    "body": "User Sample Contact changed from 61412345678 to 61498765432",
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
    "timestamp": "2026-11-06T01:00:00.000Z"
  }
}
```

在每個事件中，最上層的 `number` 是**您的** WhatsApp 號碼；聯絡人在 `data` 裡面。沒有值的欄位不會出現，所以除了您用來比對的欄位之外，請把每個欄位都當作選填來讀取。`GET /webhooks/samples` 會提供每種事件類型的範例。

## 當聯絡人在您的 CRM 中被刪除

`DELETE /contacts/{identity}` 會刪除聯絡人紀錄。Do Not Call 名單和選擇加入紀錄是分開的，而且會**保留**，所以表示過 STOP 的人在刪除之後依然受到保護。他們的預約、備註和付款也會保留，除非您加上 `?booking_data=erase`：這樣也會刪除或匿名化他們的預約和票券資料，無法復原，並且是為了處理刪除請求而設計的。當聯絡人持有一張即將到來的日期的有效票券時，這項操作會被拒絕，原因會寫在 `note` 中。

```bash
curl -s -X DELETE "https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678" \
  -H "Authorization: Bearer $A2E_KEY"
```

## 上線檢查清單

<AccordionGroup>
  <Accordion title="檢查 webhook 簽章">
    每個事件都有標頭 `X-App2email-Signature: t=<unix seconds>,v1=<hex>`。`v1` 的值是 `"<t>.<raw body>"` 的 HMAC-SHA256，以 webhook 的密鑰（`whsec_...`，包含前綴）作為金鑰。請檢查每一個 `v1=`（密鑰輪替之後，舊密鑰仍保留期間會有兩個），對原始內容以收到時的樣子原封不動地計算，並拒絕過舊的 `t`。上面的接收端就是這樣做的。請拒絕未通過檢查的事件：任何人都可以向公開的 URL 發送資料，而偽造的 `contact.opted_out` 或 `contact.changed_number` 會更動您的 CRM。
  </Accordion>

  <Accordion title="丟棄重複的事件，並避免循環">
    請在 10 秒內以 2xx 狀態回應。否則，事件會在 10 秒、1 分鐘、5 分鐘、30 分鐘、1、2、4、8 和 16 小時之後再次發送。`X-App2email-Delivery`（事件的 `id`，`evt_...`）在每次重試時都相同：請把它存起來，並略過已經處理過的事件。

    您自己最多 50 位聯絡人的 upsert，會以 `contact.updated` 傳回來。如果您的 CRM 每次儲存紀錄都會向 app2email 發送變更，把那個事件寫回 CRM 又會再次儲存紀錄，兩個系統就會不斷互相通知。請先比對，只寫入有差異的欄位。請用 `identity` 比對紀錄，而不是用姓名：姓名不是唯一的，而且人們會更改它。
  </Accordion>

  <Accordion title="安全的重試">
    聯絡人呼叫不需要 `Idempotency-Key` 標頭，也不必使用：以 `identity` 比對的 upsert，在逾時或 `500` 之後可以再次發送，聯絡人的結果會相同，而不會重複。匯入的每一列也是如此。只有在同意本身改變時才送出 `consent` 區塊，不要在每次同步時都送，這樣它的 `at` 時間和證據才會維持是真正同意當時的內容。`POST /donotcall` 會保持已經在名單上的號碼不變。
  </Accordion>

  <Accordion title="速率限制和批次大小">
    請發送清單，而不是每位聯絡人各呼叫一次：每個 `POST /contacts` 最多 1000 位聯絡人，每個 `POST /contacts/import` 最多 5000 列，`GET /contacts` 每頁 200 位聯絡人。每個回應都有 `X-RateLimit-Limit`、`X-RateLimit-Remaining`、`X-RateLimit-Reset`（距離恢復額滿的秒數）和 `X-RateLimit-Policy`；`limits` 在 `GET /me` 中，會顯示金鑰的 `requests_per_second` 和 `burst`。超過限制時，您會得到 `429 rate_limited`，並附有 `Retry-After` 標頭和 `error.retry_after_seconds`：等待那麼久，然後再次發送相同的請求。

    任何其他的 `4xx`：不要原封不動地重試。請依 `error.code` 判斷，遵循 `how_to_fix`，並向支援團隊提供 `request_id`。`error.is_retriable` 會告訴您相同的請求之後是否可能成功。
  </Accordion>

  <Accordion title="同意、退訂和 Do Not Call 名單">
    - 把同意保存在唯一的真實來源。聯絡人的 `consent` 是 Spam Act 2003 期望您能夠出示的證據：時間、地點、文字內容和證明。只記錄您確實擁有的同意。
    - 在 WhatsApp 中傳送 STOP，會自動把這個人加入 Do Not Call 名單，並發送 `contact.opted_out`。請把它寫入您的 CRM，除非對方再次同意，否則不要從 CRM 把他們移出名單。
    - 在 CRM 中退訂：在聯絡人上設定 `"marketing": false`，並呼叫 `POST /donotcall`。
    - `contact.updated` 帶有 `marketing_resumed` 時，表示這個人在 WhatsApp 內重新開啟了您的行銷訊息。這是一個訊號，不是附有證據的同意。
    - Do Not Call 名單和選擇加入規則只適用於 MARKETING 範本。訂單更新和其他 utility 範本仍會發出，您回覆主動來訊者的訊息也是如此。
    - `GET /compliance/export.csv`（權限範圍 `dnc:manage`）會把同意紀錄、Do Not Call 名單和選擇加入紀錄輸出成一個檔案。
  </Accordion>

  <Accordion title="24 小時視窗和範本">
    聯絡人和分群只決定誰會收到訊息。要開啟對話，或在聯絡人最後一則訊息已超過 24 小時之後發送訊息，仍然需要已核准的範本；在視窗之內，您可以發送一般訊息。`GET /conversations/{contact}` 會顯示 `window_state` 和 `window_closes_at`。請參閱[用範本發送訂單與預約通知](/guides/how-to-order-notifications)。
  </Accordion>

  <Accordion title="把金鑰留在您的伺服器上">
    同步金鑰可以讀取並變更每一位聯絡人。請把它保存在伺服器的環境變數中，絕對不要放在網頁，或其他使用者看得到的 CRM 欄位中。金鑰可以限制只允許您伺服器的 IP 位址（從其他地方呼叫會回應 `403 ip_not_allowed`），也可以設定到期；請只給它本指南需要的權限範圍。
  </Accordion>
</AccordionGroup>

## 如果無法運作

每個錯誤都是 JSON，帶有 `error.code`、`message`、`how_to_fix`，以及向支援團隊提供的 `request_id`。所有代碼請見[錯誤](/api/errors)，各項限制請見[限制](/api/limits)。

| 代碼 | 何時 | 該怎麼做 |
| --- | --- | --- |
| `403 insufficient_scope` | 金鑰缺少某項權限範圍（`details.required_scope`），常見的是預設金鑰缺少 `contacts:manage` | 建立一把具有上表中的權限範圍的金鑰，或使用完整存取 |
| `403 not_in_instant_sandbox` | 在示範號碼 `12025550100` 上呼叫聯絡人 | 使用您自己已連接的號碼 |
| `403 api_key_number_mismatch` | 金鑰和 URL 中的號碼不屬於同一組，例如把真實號碼的金鑰用在示範號碼上 | 使用 URL 中那個號碼的金鑰 |
| `401 missing_api_key`、`invalid_api_key`、`api_key_revoked`、`api_key_expired` | 沒有金鑰、金鑰錯誤，或金鑰已被撤銷或過期 | 以 API 金鑰頁面上列出的金鑰，發送 `Authorization: Bearer YOUR_API_KEY` |
| `403 plan_not_allowed`、`403 service_not_live` | 沒有付費方案，或服務已暫停 | 在儀表板中檢查方案和服務狀態 |
| `400 invalid_contacts` | 內容中的某位聯絡人無效，或沒有任何要變更的東西 | 發送 `{"phone": "61412345678", "name": "John", "tags": ["vip"]}` 或這類物件的清單 |
| `400 too_many_numbers` | 一個請求中的聯絡人超過允許的數量（`POST /contacts` 為 1000） | 拆分清單，或使用 `POST /contacts/import`（最多 5000 列） |
| `400 invalid_csv` | CSV 沒有標題列，或沒有任何聯絡人列 | 以 `text/csv` 發送一個標題列和至少一列資料 |
| `400 invalid_json` | 內容不是有效的 JSON | 檢查訊息中所指位置附近的引號、逗號和括號 |
| `413 request_too_large` | 內容太大 | 把檔案拆成較小的部分發送 |
| 匯入的 `errors` 中的一列 | 有一列無法讀取，例如缺少國碼的號碼 | 修正該列並重新匯入；其他列已被儲存 |
| `400 invalid_phone` | URL 中的聯絡人不是號碼，也不是商家範圍的使用者 id | 使用完整的號碼，國碼在前，只有數字（`/contacts/61412345678`） |
| `404 contact_not_found` | 對 app2email 沒有的聯絡人執行 `GET` 或 `PATCH` | 檢查 identity；`POST /contacts` 會建立它 |
| `400 invalid_numbers` | `POST /donotcall` 中有無效的號碼（`details.invalid`）；沒有任何東西被加入 | 修正所列出的號碼，再次發送呼叫 |
| `400 invalid_segment` | 分群名稱為空、超過 100 個字元，或只是一個數字 | 發送 `{"name": "VIP, consented", "filter": {...}}` |
| `409 segment_exists` | 已有同名的分群 | 使用另一個名稱，或用 `PUT /segments/{id}` 變更它 |
| `400 too_many_segments` | 這個號碼已有 100 個分群 | 刪除一個不再使用的分群 |
| `404 segment_not_found` | 沒有該 id 或名稱的分群 | `GET /segments` 會列出它們；使用 id 或完整名稱 |
| `400 invalid_cursor` | `cursor` 被更改過，或來自另一份清單 | 原封不動地傳入 `next_cursor`，第一頁則省略它 |
| `429 rate_limited` | 這把金鑰的呼叫次數太多 | 等待 `Retry-After` 秒，然後再次發送相同的請求 |
| 事件沒有送達 | webhook 在多次送達失敗之後被關閉，或您的 URL 沒有在 10 秒內回應 2xx | 查看 `GET /webhooks/{id}/deliveries`；用 `PATCH /webhooks/{id}` 和 `{"active": true}` 重新開啟 |
| 同步之後沒有 `contact.updated` | 匯入，以及超過 50 位聯絡人的 upsert 清單，不會發送事件 | 這是預期的行為；請改用 `GET /contacts` 比對 |

## 更多操作指南

<CardGroup cols={2}>
  <Card title="發送尊重選擇加入的行銷群發" href="/guides/how-to-marketing-broadcast">
    向同意接收的聯絡人分群發送範本，並追蹤每個號碼的結果。
  </Card>
  <Card title="用滴灌序列自動跟進客戶" href="/guides/how-to-drip-sequence">
    依標籤讓聯絡人加入，並依各自的時間表發送一系列範本。
  </Card>
  <Card title="從 n8n、Zapier 或 Make 發送 WhatsApp 訊息" href="/guides/how-to-no-code-n8n-zapier-make">
    從自動化工具執行同步和發送，不需要自己架設伺服器。
  </Card>
  <Card title="用範本發送訂單與預約通知" href="/guides/how-to-order-notifications">
    建立 utility 範本、取得核准，並追蹤每一則訊息。
  </Card>
</CardGroup>

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