# 用滴灌序列自动跟进

> 用已批准的模板创建带有间隔等待的滴灌序列，登记新客户，在客户回复或退订时停止，并查看每一步的报告。

在本指南中，您将构建一个包含三条消息的欢迎系列：客户注册当天发送欢迎消息，两天后发送一条养护小贴士，第 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`。通过二维码关联的个人 WhatsApp 号码不能发送模板，所以没有序列功能（403 `sequence_personal_number`）。
- **您在 Meta 的 WhatsApp Business Account 上有一个付款方式。** Meta 对每条送达的模板收费。
- **同意收到您消息的客户。** 序列遵循与群发相同的规则：Do Not Call 名单、营销模板的 opt-in 规则、您的套餐限额以及号码自己的月度上限。有关同意记录和 opt-in，请参阅[发送尊重 opt-in 的营销群发](/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 密钥页面创建）可以读取您的序列、它们的报告和登记情况，并且带有 `"dry_run": true` 的 `POST /sequences/{id}/enrolments` 会统计将被登记的人数，而不会登记任何人。创建、更改和删除序列以及真实的登记会返回 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 模板只会发给不在您的 Do Not Call 名单上的人；开启 opt-in 规则时，只会发给有 opt-in 记录的人。请用 [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`。在 Do Not Call 名单上的联系人、已经在这个序列中的联系人，以及不是电话号码的内容都会被跳过并计数。这使得该调用可以安全地重复发送：同一个联系人永远不会被登记两次。`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 天（“Do you deliver on Saturdays?”），您的 webhook 会收到 `message.received`，她的对话出现在收件箱中，优惠消息不会发出。`sequence.finished` 送达，其中 `result` 为 `stopped`，`reason` 为 `replied`，`steps_sent` 为 2。真人（或您的机器人）在她的消息所开启的 24 小时窗口内回答她。请参阅[把对话从机器人转交给真人，再转回](/guides/how-to-human-handoff)。

**当她回复 STOP 时**（或点按“Stop promotions”），她会立即进入 Do Not Call 名单。您的 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 Account 上的付款方式扣款。在大多数国家，营销是最贵的类别。较早回复的客户收到的步骤更少，所以花费也更少。

请用 [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 营销消息的客户。在 Do Not Call 名单上的联系人会在登记时被跳过，序列期间的退订会立即让它停止。开启 opt-in 规则（`PUT /settings/optin`）时，MARKETING 步骤只会发给有 opt-in 记录的号码；请用 `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` | 该号码是通过二维码关联的个人 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` | 某个步骤无法发给这位联系人，例如模板未获批准，或者开启 opt-in 规则时没有 opt-in 记录 | 阅读 `history` 中的 `error`；批准或修正模板，或记录 opt-in |
| 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="发送尊重 opt-in 的营销群发" href="/guides/how-to-marketing-broadcast">
    用一个营销模板发给一个列表或细分群体，附带同意记录和 Do Not Call 名单。
  </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)
