# 用滴灌序列自動跟進客戶

> 用已核准的範本建立滴灌序列，並在各則訊息之間設定等待時間，讓新客戶加入序列，在客戶回覆或退訂時停止，並追蹤每個步驟的報告。

在本指南中，您會建立一個三則訊息的歡迎系列：客戶註冊當天發送歡迎訊息，兩天後發送照顧小提示，第 7 天發送折扣優惠。您只需建立一次。之後，您讓每位客戶加入序列，他們就會依自己的時程收到這些訊息。

**客戶看到的內容：** 他們註冊後，立刻收到來自您企業的 WhatsApp 訊息：「Hi Jane, welcome to Green Leaf Plants!」兩天後收到您植物照顧指南的連結。第 7 天收到下次訂購可用的 10% 優惠碼。如果他們在任何時間點回覆，序列就會停止，由您的團隊接手對話。如果他們回覆 STOP，就不會再收到您的行銷訊息。

**您看到的內容：** 每個步驟已送出、已發送、已送達、已讀、失敗和已點擊的訊息數量。每位客戶收到了哪些步驟、下一則何時到期，以及停止的原因。當客戶點擊連結以及離開序列時，webhook 事件會通知您的系統。

## 運作方式

1. 您建立三個**範本**，並等待 Meta 核准。序列只發送範本，所以在 24 小時視窗之外也能運作。
2. 您用 `POST /sequences` 建立**序列**：1 到 20 個步驟，每個步驟是一個範本，帶有它的值和等待時間。
3. 您用 `POST /sequences/{id}/enrolments` **加入**聯絡人，或讓 app2email 自動加入所有獲得某個標籤的人。
4. 等待時間過後，app2email 會發送每個步驟。每次等待都從前一個步驟起算；第一個步驟則從聯絡人加入序列的那一刻起算。
5. 當每個步驟都已發送、聯絡人回覆（除非您關閉這項設定）、退訂，或您把他們移出時，聯絡人就會離開序列。每次您的 webhook 都會收到 `sequence.finished`。

在您讓他們加入之前，沒有人會收到任何訊息。建立序列本身不會發送任何內容。

## 您需要準備

- **已連接到 app2email 的 WhatsApp Business API 號碼**，且服務處於 LIVE 狀態。滴灌序列包含在 Standard 和 Professional 方案及試用版中；其他方案會回應 403 `sequences_not_enabled`。以 QR code 連結的個人 WhatsApp 號碼無法發送範本，所以沒有序列功能（403 `sequence_personal_number`）。
- **您在 Meta 的 WhatsApp Business 帳號上有付款方式。** Meta 對每則送達的範本收費。
- **同意接收您訊息的客戶。** 序列遵循與廣播相同的規則：「請勿聯絡」名單、行銷範本的加入同意規則、您的方案上限，以及號碼自己的每月上限。有關同意記錄和加入同意，請參閱[發送尊重加入同意的行銷廣播](/guides/how-to-marketing-broadcast)。
- **一把 API 金鑰**，從 [API 金鑰頁面](https://www.app2email.com/dashboard/apikey)取得，具備下列權限範圍：

| 權限範圍 | 在本指南中的用途 |
| --- | --- |
| `templates:manage` | 建立三個範本（`POST /templates`） |
| `messages:send` | 建立、變更、暫停和刪除序列，加入聯絡人並把他們移出（`POST /sequences`、`PUT /sequences/{id}`、`DELETE /sequences/{id}`、`POST /sequences/{id}/enrolments`、`DELETE /sequences/{id}/enrolments/{contact}`） |
| `messages:read` | 範本狀態、序列的報告、序列中有誰（`GET /templates`、`GET /sequences/{id}`、`GET /sequences/{id}/enrolments`、`GET /broadcasts/{code}`） |
| `contacts:manage` | 只有在您依標籤加入時才需要：為聯絡人加上標籤（`PATCH /contacts/{identity}`） |
| `webhooks:manage` | 新增接收事件的 webhook（`POST /webhooks`）。您也可以在 API 金鑰頁面新增，不需要寫程式 |

`GET /v1/YOUR_NUMBER/me` 會顯示您目前金鑰的權限範圍。

<Tip>
**先試用看看。** 在您自己號碼上的**沙盒金鑰**（在 API 金鑰頁面建立、帶有沙盒標記的金鑰）可以讀取您的序列、它們的報告和加入記錄，而 `POST /sequences/{id}/enrolments` 搭配 `"dry_run": true` 會計算有多少人會被加入，但不會真的加入任何人。建立、變更和刪除序列，以及真正的加入動作，會回應 403 `sandbox_key`：這些請使用一般金鑰。**即時沙盒**（從 `POST https://api.app2email.com/v1/account/sandbox` 取得的示範號碼 `12025550100`）沒有序列功能；它會回應 403 `not_in_instant_sandbox`。詳情：[沙盒](/api/sandbox)。
</Tip>

## 每個步驟的類別

每個步驟都是一個範本，Meta 依範本的**類別**和客戶所在的國家收費。請選擇與訊息內容相符的類別：

| 天數 | 步驟 | 範本 | 類別 |
| --- | --- | --- | --- |
| 0 | 歡迎 | `welcome_new_customer` | MARKETING。只有當歡迎訊息嚴格限於客戶剛建立的帳號或訂單，且不含任何促銷內容時，才可以是 UTILITY |
| 2 | 照顧小提示 | `plant_care_tips` | MARKETING。小提示和內容與交易無關 |
| 7 | 優惠 | `welcome_offer` | MARKETING。任何折扣或促銷都屬於行銷 |

Meta 會連同範本一起審核類別，以 UTILITY 發送的促銷內容會被拒絕或改為 MARKETING。MARKETING 範本只會發送給不在您「請勿聯絡」名單上的人，而且在開啟加入同意規則時，只會發送給有加入同意記錄的人。請用 [WhatsApp 定價計算器](https://www.app2email.com/tools/whatsapp-pricing-calculator)估算這個系列的費用：每位客戶三則行銷範本，乘以您預期每月的客戶數。

## 逐步建立序列

每次呼叫都發送到 `https://api.app2email.com/v1/YOUR_NUMBER`，並帶上 `Authorization: Bearer YOUR_API_KEY`。`YOUR_NUMBER` 是您的 WhatsApp 號碼：國碼在前，只用數字。

<Steps>
  <Step title="建立三個範本">
    每則訊息都用編號佔位符撰寫，在 `example` 中為每個佔位符提供範例值，並加上說明如何停止接收的頁尾。STOP 及其翻譯是 app2email 已經認得的退訂字詞。請把每個連結放在佔位符中，而不是固定文字中：這樣 app2email 就可以為每位客戶提供他們專屬的追蹤連結（見步驟 2）。

    | 範本 | 內文 | 值 |
    | --- | --- | --- |
    | `welcome_new_customer` | Hi \{\{1\}\}, welcome to Green Leaf Plants! We are happy you are here. Reply to this message any time if you have a question. | 姓名 |
    | `plant_care_tips` | Hi \{\{1\}\}, here is our quick guide to keeping your new plants happy: \{\{2\}\} Happy growing! | 姓名、連結 |
    | `welcome_offer` | Hi \{\{1\}\}, thanks for being with us this week. Use the code \{\{2\}\} for 10% off your next order: \{\{3\}\} The code is valid for 7 days. | 姓名、優惠碼、連結 |

    以優惠為例的單一請求（其他兩個相同，只是文字和範例值各自不同）：

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/templates \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "welcome_offer",
        "language": "en",
        "category": "MARKETING",
        "components": [
          {
            "type": "BODY",
            "text": "Hi {{1}}, thanks for being with us this week. Use the code {{2}} for 10% off your next order: {{3}} The code is valid for 7 days.",
            "example": { "body_text": [["Jane", "WELCOME10", "https://www.example.com/shop"]] }
          },
          { "type": "FOOTER", "text": "Reply STOP to opt out" }
        ]
      }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/templates", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        name: "welcome_offer",
        language: "en",
        category: "MARKETING",
        components: [
          {
            type: "BODY",
            text: "Hi {{1}}, thanks for being with us this week. Use the code {{2}} for 10% off your next order: {{3}} The code is valid for 7 days.",
            example: { body_text: [["Jane", "WELCOME10", "https://www.example.com/shop"]] },
          },
          { type: "FOOTER", text: "Reply STOP to opt out" },
        ],
      }),
    });
    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['API_KEY']}"},
        json={
            "name": "welcome_offer",
            "language": "en",
            "category": "MARKETING",
            "components": [
                {
                    "type": "BODY",
                    "text": "Hi {{1}}, thanks for being with us this week. Use the code {{2}} for 10% off your next order: {{3}} The code is valid for 7 days.",
                    "example": {"body_text": [["Jane", "WELCOME10", "https://www.example.com/shop"]]},
                },
                {"type": "FOOTER", "text": "Reply STOP to opt out"},
            ],
        },
        timeout=10,
    )
    print(res.status_code, res.json())
    ```

    </CodeGroup>

    **您會收到的回應**（201 Created）：範本已交給 Meta 審核。

    ```json
    {
      "success": true,
      "request_id": "c3ppl",
      "template": {
        "id": "2234567890",
        "name": "welcome_offer",
        "language": "en",
        "category": "MARKETING",
        "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/welcome_offer."
    }
    ```

    審核需要幾分鐘到一天。`template.status_changed` 事件會告訴您結果（`status` 為 APPROVED 且 `can_send: true`，或 REJECTED 並附上 `reason`），也可以查詢 `GET /templates/welcome_offer`。請等三個範本都是 APPROVED 之後，再讓任何人加入。有關範本審核的更多說明：[使用範本發送訂單和預約通知](/guides/how-to-order-notifications)。
  </Step>
  <Step title="建立序列">
    一次呼叫就包含三個步驟。等待時間從前一個步驟起算，所以第 7 天是在第 2 天的小提示之後 **5** 天：

    | 步驟 | 等待 | 發送時間 |
    | --- | --- | --- |
    | `welcome_new_customer` | `wait_days: 0` | 第 0 天，加入後立即發送 |
    | `plant_care_tips` | `wait_days: 2` | 第 2 天 |
    | `welcome_offer` | `wait_days: 5` | 第 7 天 |

    等待時間可以用 `wait_minutes`、`wait_hours` 或 `wait_days` 指定；同時使用時會相加。每次等待為 0 到 90 天。

    在步驟的值中，`{name}` 是聯絡人的姓名。當姓名未知時，會改用 `name_fallback`（預設為 "there"）。`track_clicks` 預設為開啟：值中的每個網址都會為每位聯絡人變成各自專屬的追蹤連結，讓您看到誰點擊了。

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/sequences \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Welcome series",
        "stop_on_reply": true,
        "steps": [
          { "wait_days": 0, "template_name": "welcome_new_customer", "language": "en",
            "parameters": { "body": ["{name}"], "name_fallback": "there" } },
          { "wait_days": 2, "template_name": "plant_care_tips", "language": "en",
            "parameters": { "body": ["{name}", "https://www.example.com/plant-care"], "name_fallback": "there" } },
          { "wait_days": 5, "template_name": "welcome_offer", "language": "en",
            "parameters": { "body": ["{name}", "WELCOME10", "https://www.example.com/shop"], "name_fallback": "there" } }
        ]
      }'
    ```

    ```javascript Node.js
    const step = (wait_days, template_name, body) => ({
      wait_days, template_name, language: "en", parameters: { body, name_fallback: "there" },
    });

    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/sequences", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        name: "Welcome series",
        stop_on_reply: true,
        steps: [
          step(0, "welcome_new_customer", ["{name}"]),
          step(2, "plant_care_tips", ["{name}", "https://www.example.com/plant-care"]),
          step(5, "welcome_offer", ["{name}", "WELCOME10", "https://www.example.com/shop"]),
        ],
      }),
    });
    const { sequence } = await res.json();
    console.log(res.status, sequence.id, sequence.steps.map((s) => s.id));
    ```

    ```python Python
    def step(wait_days, template_name, body):
        return {"wait_days": wait_days, "template_name": template_name, "language": "en",
                "parameters": {"body": body, "name_fallback": "there"}}

    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/sequences",
        headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
        json={
            "name": "Welcome series",
            "stop_on_reply": True,
            "steps": [
                step(0, "welcome_new_customer", ["{name}"]),
                step(2, "plant_care_tips", ["{name}", "https://www.example.com/plant-care"]),
                step(5, "welcome_offer", ["{name}", "WELCOME10", "https://www.example.com/shop"]),
            ],
        },
        timeout=10,
    )
    sequence = res.json()["sequence"]
    print(res.status_code, sequence["id"], [s["id"] for s in sequence["steps"]])
    ```

    </CodeGroup>

    **您會收到的回應**（201 Created；`steps` 和 `report` 只保留第一個步驟，已縮短）：

    ```json
    {
      "success": true,
      "request_id": "s2new",
      "sequence": {
        "id": 12,
        "name": "Welcome series",
        "status": "active",
        "stop_on_reply": true,
        "enrol_tag": "",
        "enrol_tag_since": null,
        "created_by": "api",
        "created_at": "2026-11-19T01:00:00.000Z",
        "updated_at": "2026-11-19T01:00:00.000Z",
        "steps": [
          {
            "id": 31,
            "position": 0,
            "wait_days": 0,
            "wait_minutes": 0,
            "template_name": "welcome_new_customer",
            "language": "en",
            "parameters": { "body": ["{name}"], "name_fallback": "there" },
            "track_clicks": true,
            "report_code": null
          }
        ],
        "counts": { "enrolled": 0, "active": 0, "finished": 0, "stopped": 0, "stopped_by_reply": 0, "opted_out": 0 },
        "report": [
          { "step_id": 31, "position": 0, "template_name": "welcome_new_customer", "posted": 0, "sent": 0, "delivered": 0, "read": 0, "failed": 0, "clicked": 0, "clicks": 0, "report_url": null }
        ]
      }
    }
    ```

    請保留 `sequence.id` 和各步驟的 `id`：之後若要變更步驟又不想遺失它們的報告，就需要步驟 id。其他兩個步驟會以相同方式回傳，`wait_minutes` 分別為 2880 和 7200。`stop_on_reply` 預設為 true；無論它怎麼設定，退訂一律會讓聯絡人停止。一個號碼最多可以有 100 個序列。

    <Note>
    `POST /sequences` 不接受 `Idempotency-Key`。如果回應遺失了，請在再次建立之前先查看 `GET /sequences`，以免最後出現兩個序列。
    </Note>
  </Step>
  <Step title="加入您的第一批聯絡人">
    可以發送號碼（`numbers`）、附有姓名的號碼（`contacts`）、已儲存客群的所有聯絡人（`segment_id`），或帶有某個標籤的所有聯絡人（`tag`），每次呼叫最多 5000 個。請先用 `"dry_run": true` 開始：它會計算有多少人會被加入，但不會加入任何人。

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "contacts": [
          { "number": "61412345678", "name": "Jane" },
          { "number": "61498765432", "name": "Tom" }
        ],
        "dry_run": true
      }'
    ```

    ```javascript Node.js
    async function enrol(sequenceId, contacts, dryRun = false) {
      const res = await fetch(`https://api.app2email.com/v1/YOUR_NUMBER/sequences/${sequenceId}/enrolments`, {
        method: "POST",
        headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
        body: JSON.stringify({ contacts, dry_run: dryRun }),
      });
      return res.json();
    }

    const contacts = [{ number: "61412345678", name: "Jane" }, { number: "61498765432", name: "Tom" }];
    console.log(await enrol(12, contacts, true)); // count only
    console.log(await enrol(12, contacts));       // for real
    ```

    ```python Python
    def enrol(sequence_id, contacts, dry_run=False):
        res = requests.post(
            f"https://api.app2email.com/v1/YOUR_NUMBER/sequences/{sequence_id}/enrolments",
            headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
            json={"contacts": contacts, "dry_run": dry_run},
            timeout=10,
        )
        return res.json()

    contacts = [{"number": "61412345678", "name": "Jane"}, {"number": "61498765432", "name": "Tom"}]
    print(enrol(12, contacts, dry_run=True))  # count only
    print(enrol(12, contacts))                # for real
    ```

    </CodeGroup>

    **您會收到的回應**（200，使用或不使用 `dry_run` 的格式相同）：

    ```json
    {
      "success": true,
      "request_id": "s7enr",
      "sequence_id": 12,
      "enrolled": 2,
      "already_in_it": 0,
      "on_do_not_call_list": 0,
      "not_a_number": 0,
      "first_step_at": "2026-11-19T01:00:00.000Z",
      "note": null
    }
    ```

    接著發送相同的內容，但不帶 `dry_run`。在「請勿聯絡」名單上的聯絡人、已經在這個序列中的聯絡人，以及任何不是電話號碼的項目都會被略過並計數。這讓這個呼叫可以安全地重複執行：聯絡人絕不會被加入兩次。`first_step_at` 是第一個步驟發出的時間。

    在您的註冊程式碼中，請在每位新客戶註冊時就帶著他們的姓名加入，這樣歡迎訊息就能立刻送達。
  </Step>
  <Step title="新增接收事件的 webhook">
    一次呼叫即可（或在 API 金鑰頁面的 Webhooks 下新增）。請保留回應中的 `whsec_...` 密鑰：它會為每個事件簽章。

    ```bash
    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://www.example.com/whatsapp/webhook"}'
    ```

    每個 webhook 都會收到所有事件類型；您的程式碼依 `type` 挑出 `sequence.finished`、`link.clicked` 和下面列出的其他事件，並在 10 秒內對其餘事件回應 2xx。如何設定並檢查簽章，以及在您自己電腦上使用通道的方法：[使用 API 建立 WhatsApp 聊天機器人](/guides/how-to-whatsapp-chatbot)。

    沒有公開網址？`GET /events?wait=25&types=sequence.finished`（權限範圍 `messages:read`）可以取得相同的事件。
  </Step>
  <Step title="追蹤進度">
    `GET /sequences/{id}` 提供各項計數和每個步驟的報告。`GET /sequences/{id}/enrolments` 提供每位聯絡人的資料。

    <CodeGroup>

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

    # who is still in it, with the next step and when it is due
    curl "https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments?status=active&limit=100" \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    ```javascript Node.js
    const headers = { Authorization: `Bearer ${process.env.API_KEY}` };
    const { sequence } = await (await fetch("https://api.app2email.com/v1/YOUR_NUMBER/sequences/12", { headers })).json();
    console.log(sequence.counts);
    for (const row of sequence.report) console.log(row.template_name, row.delivered, row.read, row.clicked);

    const { enrolments } = await (await fetch(
      "https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments?status=active&limit=100", { headers })).json();
    for (const e of enrolments) console.log(e.contact, e.steps_sent, e.next_at);
    ```

    ```python Python
    headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
    sequence = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/sequences/12", headers=headers, timeout=10).json()["sequence"]
    print(sequence["counts"])
    for row in sequence["report"]:
        print(row["template_name"], row["delivered"], row["read"], row["clicked"])

    enrolments = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments",
                              params={"status": "active", "limit": 100}, headers=headers, timeout=10).json()["enrolments"]
    for e in enrolments:
        print(e["contact"], e["steps_sent"], e["next_at"])
    ```

    </CodeGroup>

    **您會收到的回應**，一週後的 `GET /sequences/12`（已縮短：省略 `steps`）：

    ```json
    {
      "success": true,
      "request_id": "s3get",
      "sequence": {
        "id": 12,
        "name": "Welcome series",
        "status": "active",
        "stop_on_reply": true,
        "enrol_tag": "",
        "counts": { "enrolled": 120, "active": 64, "finished": 31, "stopped": 25, "stopped_by_reply": 21, "opted_out": 3 },
        "report": [
          { "step_id": 31, "position": 0, "template_name": "welcome_new_customer", "posted": 120, "sent": 120, "delivered": 118, "read": 97, "failed": 2, "clicked": 0, "clicks": 0,
            "report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e" },
          { "step_id": 32, "position": 1, "template_name": "plant_care_tips", "posted": 81, "sent": 81, "delivered": 80, "read": 66, "failed": 0, "clicked": 29, "clicks": 41,
            "report_url": "https://www.app2email.com/dashboard/log/broadcast/m7TqW2xRb9LpZc4d8e1f" },
          { "step_id": 33, "position": 2, "template_name": "welcome_offer", "posted": 34, "sent": 34, "delivered": 34, "read": 30, "failed": 0, "clicked": 12, "clicks": 15,
            "report_url": "https://www.app2email.com/dashboard/log/broadcast/p2HsK8vYc3NwQf6g9h2j" }
        ]
      }
    }
    ```

    - `counts`：有多少人被加入、還在序列中、收到了每個步驟（`finished`），或提早離開（`stopped`，其中 `stopped_by_reply` 是回覆的人，`opted_out` 是退訂的人）。
    - `report`，每個步驟：`posted`、`sent`、`delivered`、`read`、`failed`，以及 `clicked`（點擊了該步驟某個追蹤連結的聯絡人；`clicks` 計算每一次點擊）。
    - 每個步驟在第一次發送後，會在 `steps` 中有一個 `report_code`。用它呼叫 `GET /broadcasts/{code}` 可以取得該步驟逐一號碼的結果，與廣播報告相同；`report_url` 會在儀表板中開啟它。

    來自 `GET /sequences/12/enrolments` 的**一筆加入記錄**：

    ```json
    {
      "success": true,
      "request_id": "s6enl",
      "sequence_id": 12,
      "enrolments": [
        {
          "id": 501,
          "contact": "61412345678",
          "name": "Jane",
          "status": "active",
          "stop_reason": null,
          "steps_sent": 1,
          "next_step": 2,
          "next_at": "2026-11-21T01:00:00.000Z",
          "last_sent_at": "2026-11-19T01:00:00.000Z",
          "enrolled_at": "2026-11-19T01:00:00.000Z",
          "enrolled_by": "api",
          "finished_at": null,
          "history": [
            { "step": 31, "position": 0, "at": "2026-11-19T01:00:00.000Z", "ok": true, "error": "" }
          ]
        }
      ]
    }
    ```

    `status` 是 `active`、`finished` 或 `stopped`；`stop_reason` 說明聯絡人停止的原因。`history` 包含每個步驟的每一次嘗試：當步驟無法發出時，會是 `ok: false` 並附上 `error`。`limit` 為 1 到 500（預設 100），最新的在前。
  </Step>
</Steps>

## 結果

以 Jane 為例，她在 11 月 19 日加入：

**第 0 天：**「Hi Jane, welcome to Green Leaf Plants!」在她註冊後片刻送達。您的 webhook 會收到它的 `message.status` 事件（`sent`、`delivered`、`read`），與任何訊息一樣。

**第 2 天：** 照顧小提示送達。其中的連結是她專屬的追蹤連結（`https://www.app2email.com/l/...`）。當她開啟時，您的 webhook 會收到帶有序列和步驟的 `link.clicked`：

```json
{
  "id": "evt_Cmp3k9m2Lw8Rt5Yp1Zs03",
  "type": "link.clicked",
  "created": "2026-11-21T08:12:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "url": "https://www.example.com/plant-care",
    "broadcast_code": null,
    "sequence_id": 12,
    "step_id": 32,
    "first_click": true,
    "clicks": 1,
    "browser": "Safari",
    "timestamp": "2026-11-21T08:12:00.000Z"
  }
}
```

每次點擊都會有 `link.clicked`；只有她的第一次點擊，`first_click` 才是 true。連結預覽和爬蟲不會被計算。

**第 7 天：** 優惠送達。當它是最後一個步驟時，您的 webhook 會收到 `sequence.finished`，其中 `result` 為 `completed`：

```json
{
  "id": "evt_Cmp3k9m2Lw8Rt5Yp1Zs02",
  "type": "sequence.finished",
  "created": "2026-11-26T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "sequence_id": 12,
    "sequence": "Welcome series",
    "contact": "61412345678",
    "result": "completed",
    "reason": null,
    "steps_sent": 3,
    "steps": 3,
    "enrolled_at": "2026-11-19T01:00:00.000Z",
    "by": "api",
    "timestamp": "2026-11-26T01:00:00.000Z"
  }
}
```

**當她回覆時**，例如在第 3 天（「你們週六有送貨嗎？」），您的 webhook 會收到 `message.received`，她的對話會出現在收件匣中，而優惠不會發送。`sequence.finished` 送達，其中 `result` 為 `stopped`、`reason` 為 `replied`、`steps_sent` 為 2。真人（或您的機器人）在她的訊息所開啟的 24 小時視窗內回覆她。請參閱[把對話從機器人轉交給真人，再轉回來](/guides/how-to-human-handoff)。

**當她回覆 STOP 時**（或點選「停止促銷」），她會立刻被加入「請勿聯絡」名單。您的 webhook 會收到 `contact.opted_out`，以及 `reason` 為 `opted_out` 的 `sequence.finished`。

`result` 為 `stopped` 的所有原因：

| `reason` | 發生了什麼 |
| --- | --- |
| `replied` | 聯絡人回覆了（只有在 `stop_on_reply` 為 true 時） |
| `opted_out` | 聯絡人退訂了 |
| `removed` | 您用 `DELETE /sequences/{id}/enrolments/{contact}` 把他們移出 |
| `sequence_deleted` | 您刪除了序列 |
| `failed`, `not_allowed` | 有一個步驟無法發送給這位聯絡人。加入記錄的 `history` 中有該步驟的 `error` |

## 變更、暫停或停止

**暫停所有人**，讓他們停在目前的位置：使用 `PUT /sequences/{id}` 和 `{"status": "paused"}`；`{"status": "active"}` 則會繼續。只發送有變更的內容。回應是完整的序列。

```bash
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/sequences/12 \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"status": "paused"}'
```

**變更步驟**：在同一個呼叫中帶上 `steps`。它會依順序取代整份清單：發送步驟的 `id` 可保留該步驟和它的報告，沒有 `id` 的步驟是新增的，被省略的步驟會被刪除。已經超過最後一個步驟的聯絡人會結束序列。這裡把優惠從第 7 天改到第 10 天：

```bash
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/sequences/12 \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "steps": [
      { "id": 31, "wait_days": 0, "template_name": "welcome_new_customer", "language": "en", "parameters": { "body": ["{name}"] } },
      { "id": 32, "wait_days": 2, "template_name": "plant_care_tips", "language": "en", "parameters": { "body": ["{name}", "https://www.example.com/plant-care"] } },
      { "id": 33, "wait_days": 8, "template_name": "welcome_offer", "language": "en", "parameters": { "body": ["{name}", "WELCOME10", "https://www.example.com/shop"] } }
    ]
  }'
```

**把一位聯絡人移出**，例如當他們在優惠送達之前就已購買：

```bash
curl -X DELETE https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments/61412345678 \
  -H "Authorization: Bearer YOUR_API_KEY"
```

```json
{
  "success": true,
  "request_id": "s8rem",
  "sequence_id": 12,
  "contact": "61412345678",
  "status": "stopped",
  "stop_reason": "removed"
}
```

接著會發送 `reason` 為 `removed` 的 `sequence.finished`。目前不在序列中的聯絡人會回應 404 `enrolment_not_found`。

**封存序列**：使用 `DELETE /sequences/{id}`。仍在序列中的所有人都會停止（每個人都會有 `reason` 為 `sequence_deleted` 的 `sequence.finished`），報告則會保留：`GET /sequences?all=true` 仍會列出它。

```json
{
  "success": true,
  "request_id": "s5del",
  "id": 12,
  "status": "archived",
  "stopped": 4
}
```

## 用標籤自動加入

與其在您的註冊程式碼中呼叫 `POST /sequences/{id}/enrolments`，不如為序列設定 `enrol_tag`。從現在起獲得該標籤的聯絡人，會由 app2email 加入，每人只加入一次。`""` 會關閉這項功能。之前就有該標籤的聯絡人不會被加入；如果您也想加入他們，請用 `{"tag": "new-customer"}` 加入一次。

```bash
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/sequences/12 \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"enrol_tag": "new-customer"}'
```

然後在聯絡人註冊時為他們加上標籤（權限範圍 `contacts:manage`）。您發送的 `tags` 會取代聯絡人原有的標籤，所以請發送完整的清單：

```bash
curl -X PATCH https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678 \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "Jane", "tags": ["new-customer"]}'
```

序列中的 `enrol_tag_since` 會顯示標籤從何時開始計算。聯絡人也可以從儀表板或透過自動化加入。

## 對事件做出反應

一個小型處理程式，會檢查簽章、忽略已經看過的事件，並記錄誰完成了序列、誰點擊了連結。請把 `WEBHOOK_SECRET` 設為您 webhook 的 `whsec_...` 值。

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

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

const { WEBHOOK_SECRET, PORT = 3000 } = process.env;
const done = new Set(); // handled event ids: use a database table or Redis in production

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]);
  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)));
}

const app = express();
app.post("/whatsapp/webhook", express.raw({ type: "application/json" }), (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 || done.has(event.id)) return res.sendStatus(200);
  const d = event.data;
  if (event.type === "sequence.finished") {
    // result completed, or stopped with reason replied | opted_out | removed | failed | not_allowed | sequence_deleted
    console.log(`sequence ${d.sequence_id}: ${d.contact} ${d.result} ${d.reason ?? ""} after ${d.steps_sent}/${d.steps} steps`);
  } else if (event.type === "link.clicked" && d.sequence_id && d.first_click) {
    console.log(`sequence ${d.sequence_id} step ${d.step_id}: ${d.contact} opened ${d.url}`);
  } else if (event.type === "contact.opted_out") {
    console.log(`${d.number} opted out (${d.source}): mark it in your CRM too`);
  }
  done.add(event.id);
  res.sendStatus(200);
});
app.listen(PORT, () => console.log(`listening on http://localhost:${PORT}/whatsapp/webhook`));
```

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

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

SECRET = os.environ["WEBHOOK_SECRET"]
done = set()  # handled event ids: use a database table or Redis in production

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

app = Flask(__name__)

@app.post("/whatsapp/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") or event["id"] in done:
        return "", 200
    d = event["data"]
    if event["type"] == "sequence.finished":
        # result completed, or stopped with reason replied | opted_out | removed | failed | not_allowed | sequence_deleted
        print(f"sequence {d['sequence_id']}: {d['contact']} {d['result']} {d.get('reason') or ''} after {d.get('steps_sent')}/{d.get('steps')} steps")
    elif event["type"] == "link.clicked" and d.get("sequence_id") and d.get("first_click"):
        print(f"sequence {d['sequence_id']} step {d['step_id']}: {d['contact']} opened {d['url']}")
    elif event["type"] == "contact.opted_out":
        print(f"{d['number']} opted out ({d['source']}): mark it in your CRM too")
    done.add(event["id"])
    return "", 200
```

  </Tab>
</Tabs>

<a id="what-it-costs"></a>

## 費用

- **app2email：** 固定的月費方案。每個已發送的步驟算作方案中的一則訊息，不加收任何每則訊息的加價（[定價](https://www.app2email.com/pricing)）。號碼自己的每月上限也適用於這些步驟。
- **Meta：** 依類別和客戶所在的國家，直接向您 WhatsApp Business 帳號上的付款方式，對每則送達的範本收費。在大多數國家，行銷是最貴的類別。提早回覆的客戶收到的步驟較少，所以成本也較低。

請用 [WhatsApp 定價計算器](https://www.app2email.com/tools/whatsapp-pricing-calculator)估算。之後，`GET /usage` 中的 `meta_pricing` 會依 Meta 的類別統計該計費月份的訊息，並附上參考費用，而 `message.status` 事件中的 `pricing` 物件則顯示 Meta 如何計算每則訊息。

## 上線檢查清單

<Check>
**先核准，再加入。** 每個步驟的範本都必須以該步驟的語言處於 APPROVED 狀態。範本無法發送的步驟，會在加入記錄的 `history` 中顯示 `ok: false` 並附上 `error`，聯絡人可能會以 `reason` 為 `failed` 而停止。請留意 `template.status_changed`：之後被 Meta 暫停或停用的範本同樣無法發送。
</Check>

<Check>
**只針對同意的人。** 只讓已同意接收 WhatsApp 行銷訊息的客戶加入。在「請勿聯絡」名單上的聯絡人會在加入時被略過，序列期間的退訂會立刻讓序列停止。開啟加入同意規則（`PUT /settings/optin`）時，MARKETING 步驟只會發送給有加入同意記錄的號碼；請用 `POST /optins` 記錄。
</Check>

<Check>
**頁尾保留 STOP。** 每個行銷範本都要說明如何停止接收。大量的封鎖和檢舉會降低您的品質評等，而低評等可能使範本被暫停，並降低您的訊息上限。`GET /health` 會顯示 `quality_rating`。
</Check>

<Check>
**保持 `stop_on_reply` 開啟。** 回覆的客戶想要的是回答，而不是下一個步驟。請在收件匣或從您的機器人，在他們的訊息所開啟的 24 小時視窗內回覆他們。
</Check>

<Check>
**驗證每個事件。** 用 webhook 的 `whsec_...` 密鑰，以固定時間比較的方式，對原始內容檢查 `X-App2email-Signature`，並拒絕早於 5 分鐘的 `t`。上面的程式碼就是這樣做的。
</Check>

<Check>
**以事件 id 去除重複。** 把每個已處理事件的 `id`（也在標頭 `X-App2email-Delivery` 中）至少保存兩天：沒有回應 2xx 的 webhook，之後會以相同的 id 再次收到相同的事件。在您自己的記錄中，聯絡人在序列中的位置是 `sequence_id` 和 `contact` 這一組；每次點擊則是 `step_id`、`contact` 和 `clicks`。
</Check>

<Check>
**安全地重試加入。** 序列相關呼叫不接受 `Idempotency-Key`。`POST /sequences/{id}/enrolments` 可以安全地重複發送：已經在序列中的聯絡人會被略過，並計入 `already_in_it`。不要盲目重複 `POST /sequences`；請先檢查 `GET /sequences`。
</Check>

<Check>
**遵守限制。** 每次加入呼叫最多 5000 位聯絡人（超過會回應 400 `sequence_too_many_contacts`）、每個序列 20 個步驟、每個號碼 100 個序列。每個回應都有 `X-RateLimit-Limit`、`X-RateLimit-Remaining` 和 `X-RateLimit-Reset`；超過限制時，您會收到 429 `rate_limited` 並附帶 `Retry-After`。請參閱[限制](/api/limits)。
</Check>

<Check>
**最小權限。** 讓新客戶加入的程式碼只需要 `messages:send`。請把金鑰放在您的伺服器上，絕不要放在網頁或日誌中。
</Check>

## 如果無法運作

| 您看到的情況 | 原因 | 解決方法 |
| --- | --- | --- |
| 403 `sequences_not_enabled` | 號碼的方案不包含滴灌序列 | 它們包含在 Standard 和 Professional 方案及試用版中：請在帳單頁面變更方案 |
| 403 `sequence_personal_number` | 這個號碼是以 QR code 連結的個人 WhatsApp 號碼，無法發送範本 | 使用 WhatsApp Business API 號碼 |
| 403 `plan_not_allowed`, `service_not_live` | 沒有包含 API 的方案，或服務已暫停 | 選擇方案；暫停的服務可在設定頁面按「Go Live」恢復上線 |
| 403 `insufficient_scope` | 金鑰缺少某項權限（訊息中會指出） | 使用具備 `messages:send`（報告則需 `messages:read`）的金鑰 |
| 403 `sandbox_key` | 沙盒金鑰無法建立、變更或刪除序列，也無法真正加入聯絡人 | 使用一般金鑰；沙盒金鑰只能讀取和執行 `dry_run` 加入 |
| 403 `not_in_instant_sandbox` | 示範號碼沒有序列功能 | 使用您自己已連接號碼的金鑰 |
| 400 `invalid_sequence` | 序列或某個步驟無效（缺少 `template_name`、等待超過 90 天、超過 20 個步驟 ...） | 修正訊息中指出的問題；`error.details.problems` 會列出每個問題 |
| 409 `sequence_limit` | 這個號碼已有 100 個序列 | 刪除不再使用的序列 |
| 409 `sequence_empty` | 序列沒有步驟 | 在加入聯絡人之前，先用 `PUT /sequences/{id}` 新增步驟 |
| 400 `sequence_no_contacts` | 沒有可加入的人：沒有號碼、聯絡人、客群，或標籤下沒有聯絡人 | 發送 `numbers`、`contacts`、`segment_id`，或有聯絡人的 `tag` |
| 400 `sequence_too_many_contacts` | 一次呼叫超過 5000 位聯絡人 | 分成較小的批次發送 |
| 404 `sequence_not_found` | 這個號碼上沒有這個序列，或已被刪除 | `GET /sequences` 會列出它們 |
| 404 `enrolment_not_found` | 該聯絡人目前不在序列中 | `GET /sequences/{id}/enrolments?status=active` 會列出目前在序列中的人 |
| `enrolled` 為 0，而 `on_do_not_call_list` 或 `already_in_it` 不為 0 | 聯絡人已退訂，或已經在這個序列中 | 不需要修正：聯絡人絕不會被加入兩次，也絕不會違反退訂意願被加入 |
| `history` 顯示 `ok: false`，或 `sequence.finished` 的 `reason` 為 `failed` 或 `not_allowed` | 有一個步驟無法發送給這位聯絡人，例如範本尚未核准，或開啟加入同意規則時沒有加入同意記錄 | 閱讀 `history` 中的 `error`；核准或修正範本，或記錄加入同意 |
| 429 `rate_limited` | 此金鑰的呼叫太多 | 等待 `Retry-After` 秒，然後重試 |
| 503 `sequences_not_ready` | 滴灌序列目前無法使用 | 請稍後再試；如果持續發生，請帶著 `request_id` 聯絡 support@app2email.com |

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

## 從 AI 代理執行

MCP 伺服器 `https://api.app2email.com/mcp/sequences` 以工具提供相同的呼叫：`list_sequences`、`get_sequence`、`create_sequence`、`update_sequence`、`delete_sequence`、`enrol_in_sequence`、`list_sequence_enrolments` 和 `remove_from_sequence`。這樣代理就能回答「歡迎系列的成效如何？」或「把 Jane 移出，她已經買了」。請參閱[用 MCP 讓 AI 代理管理您的 WhatsApp](/guides/how-to-ai-agent-mcp) 和 [MCP](/api/mcp)。

## 更多操作指南

<CardGroup cols={2}>
  <Card title="發送尊重加入同意的行銷廣播" href="/guides/how-to-marketing-broadcast">
    把一個行銷範本發送給名單或客群，並附有同意記錄和「請勿聯絡」名單。
  </Card>
  <Card title="使用範本發送訂單和預約通知" href="/guides/how-to-order-notifications">
    建立範本，取得核准，並在訂單出貨時發送。
  </Card>
  <Card title="匯入聯絡人並與您的 CRM 保持同步" href="/guides/how-to-contacts-crm-sync">
    附有姓名、標籤和同意的聯絡人，由您自己的系統保持最新。
  </Card>
  <Card title="把對話從機器人轉交給真人，再轉回來" href="/guides/how-to-human-handoff">
    當客戶回覆某個步驟時，讓您的團隊接手對話。
  </Card>
</CardGroup>

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