# Thumela umsakazo wokukhangisa ohlonipha ukuvunywa

> Ngenisa oxhumana nabo ngokuvuma kwabo, dala i-template yokukhangisa, uthumele kubantu abavumile, ulandele umphumela ngenombolo ngayinye, bese ulandela abaphendule noma abachofoze.

Ulayisha uhlu lwamakhasimende akho, i-Meta igunyaza i-template eyodwa yokukhangisa, futhi ucingo olulodwa ngeqoqo ngalinye lulithumela. Ikhasimende ngalinye lithola umlayezo we-WhatsApp osuka egameni lebhizinisi lakho: "Hi John, our winter sale starts today: 20% off everything until Sunday." Uma lingafuni ukuthola izintengiso, lithi STOP futhi aliyikuthola enye.

I-app2email ithumela kubantu abafanele kuphela. Izinombolo ezikuhlu lwakho Lokungashayi ziyadlulwa, futhi uma umthetho wokuvuma uvuliwe, nabo abangenarekhodi lokuvuma bayadlulwa. Uthola umphumela wenombolo ngayinye (ifikile, ilethiwe, ifundiwe, iphendulwe, yehlulekile, idlulisiwe) njengezenzakalo ze-webhook, ku-API, njengefayela le-CSV, nasekhasini lombiko womsakazo ku-Activity Log.

## Imithetho yemilayezo yokukhangisa

- **Kubantu abavumile kuphela.** I-WhatsApp nemithetho efana ne-Spam Act 2003 yase-Australia ilindele ukuvuma ngaphambi kokuthumela izintengiso. I-app2email igcina ubufakazi bakho: ukuvuma kwekhasimende ngalinye, amarekhodi okuvuma, nohlu Lokungashayi. `GET /compliance/export.csv` ibeka konke lokhu kufayela elilodwa.
- **Njalo kuba yi-template.** Umsakazo uqala izingxoxo, ngakho kumele ube yi-template egunyaziwe enesigaba MARKETING. I-Meta iyibuyekeza kuqala.
- **Ukuyeka kulula.** Ikhasimende elithi STOP (noma lithinte "Stop promotions") lingeniswa kuhlu Lokungashayi ngokushesha, futhi ama-template okukhangisa aseyekwa ukuthunyelwa kulo.
- **Ukukhangisa kubiza kakhulu.** I-Meta ikhokhisa yonke i-template yokukhangisa elethiwe, futhi ukukhangisa kubiza kakhulu emazweni amaningi. Bona [Kubiza malini](#what-it-costs).
- **Uhlu olubi lulimaza inombolo.** Abantu abakuvimbelayo noma abakubikela behlisa isilinganiso sakho sekhwalithi. Isilinganiso esiphansi singama i-template yakho ukuthi imiswe, siyime umsakazo wakho futhi sehlise umkhawulo wemilayezo. Bona [Isilinganiso sekhwalithi nemikhawulo](#quality-rating-and-limits).

## Okudingekayo

- Inombolo ye-WhatsApp exhunywe ku-app2email, ku-plan ekhokhelwayo, nenkonzo isebenza (LIVE).
- Indlela yokukhokha ku-akhawunti yakho ye-WhatsApp Business ku-Meta. Ngaphandle kwayo, ukuthunyelwa kwama-template kuhluleka nge-Meta error 131042 (`403 whatsapp_payment_issue`).
- Ukhiye we-API ovela ku-https://www.app2email.com/dashboard/apikey unezimvume ezilandelayo:

| Imvume | Isetshenziselwa ini kule ncwadi |
| --- | --- |
| `contacts:manage` | Ngenisa oxhumana nabo, rekhoda ukuvuma, gcina amasegimenti (`POST /contacts/import`, `POST /contacts/{identity}/consent`, `POST /segments`) |
| `settings:manage` | Vula umthetho wokuvuma nerekhodi lokuvuma (`PUT /settings/optin`, `POST /optins`) |
| `dnc:manage` | Uhlu Lokungashayi (`POST /donotcall`, `GET /donotcall`) nokuthunyelwa kwe-compliance |
| `templates:manage` | Dala i-template yokukhangisa (`POST /templates`) |
| `messages:send` | Thumela umsakazo, uwukhansele, uthumele okulandelayo (`POST /messages`, `POST /broadcasts/{code}/cancel`, `POST /broadcasts/{code}/retarget`) |
| `messages:read` | Isimo se-template, oxhumana nabo bamasegimenti, imiphumela yomsakazo, ukuchofoza, ukusetshenziswa, impilo yenombolo |
| `webhooks:manage` | Engeza iwebhu ethola izenzakalo (`POST /webhooks`) |

Ukhiye we-Default (owenziwe ngaphambi kokuthi kube nezimvume) unawo kuphela `messages:send`, `messages:read`, `dnc:manage` kanye `webhooks:manage`. Dala ukhiye onalezi zimvume, noma ogcwele (Full access, `*`). `GET /v1/YOUR_NUMBER/me` ikhombisa izimvume zokhiye onawo.

<Info>
**Ukuzama kuqala.** Ukhiye we-**sandbox** kunombolo yakho (ukhiye onesibonakaliso se-sandbox, ekhasini lokhiye we-API) uhlola yonke imithumelo ngempela, kodwa awuthumeli lutho ku-WhatsApp. Impendulo inawo `"sandbox": true`, ama-id emilayezo aqala nge-`wamid.SANDBOX.`, futhi izenzakalo ze-`message.status` ziyafika.

Qaphela: ngokhiye we-sandbox, ukungenisa oxhumana nabo, ukugcina amasegimenti, ukuvuma kanye nohlu Lokungashayi **kushintsha idatha yakho yangempela**. Ukudala ama-template, `PUT /settings/optin` kanye nokuphinda-khangisa (ngaphandle kwe-`dry_run`) kuphendula nge-`403 sandbox_key`.

Ngaphandle kwe-akhawunti, `POST https://api.app2email.com/v1/account/sandbox` (akukho khiye, akukho body), noma ithuluzi `create_sandbox` le-Management MCP server, linikeza ukhiye we-**instant sandbox** wenombolo yedemo `12025550100`. Inayo i-template yokukhangisa `weekend_offer`, nekhasimende lakhe lokuzenzisa `12025550104` lithi STOP: uthola `contact.opted_out`, nale template elandelayo yokukhangisa kuye ithola `403 recipient_opted_out`. Lo khiye unezicelo ezimbalwa kuphela (`GET /templates`, `POST /messages`, `GET /events` nezinye ezimbalwa), ngakho izingcingo zoxhumana nabo nomsakazo kule ncwadi zidinga ukhiye wenombolo yakho. Bona [Sandbox](/api/sandbox).
</Info>

## Thumela umsakazo, sinyathelo ngesinyathelo

<Steps>
  <Step title="Ngenisa oxhumana nabo ngokuvuma kwabo">
    Thumela ifayela le-CSV nomugqa wekhanda. Amakholomu i-app2email ayaziyo ngu-`phone` (noma `identity`, `number`, `mobile`), `name` (noma `first_name` + `last_name`), `tags` (ahlukaniswe nge-`|`), `consent_marketing` (yes noma no), `consent_source`, `consent_text`, `consent_evidence`, `consent_at` kanye ne-`source`. Yonke enye ikholomu iba yinsimu yangokwezifiso. Izinombolo zinekhodi yezwe iqala, izinombolo kuphela. Kufika kumigqa engu-5000 ngocingo ngalunye.

    ```csv
    phone,name,first_name,tags,consent_marketing,consent_source,consent_text,consent_evidence,consent_at
    61412345678,John Smith,John,vip|newsletter,yes,web form,"Yes, send me offers on WhatsApp",https://example.com/forms/123,2026-10-01T09:00:00Z
    61498765432,Mary Jones,Mary,newsletter,yes,checkout,"Yes, send me offers on WhatsApp",order 5521,2026-10-12T02:30:00Z
    ```

    <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"),
    });
    console.log(res.status, await res.json());
    ```

    ```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,
        )
    print(res.status_code, res.json())
    ```

    </CodeGroup>

    **Lokho okuthola emuva:** ukuthi mingaki imigqa egciniwe, nemigqa eyeqiwe nesizathu. Eyasele iyagcinwa.

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

    Ucingo olufanayo luthatha futhi `application/json`: uhlu lwoxhumana nabo ngefomu lika `POST /contacts`. Lapho othile evuma kamuva (ifomu lewebhu, ibhokisi lokuhlola ekukhokheni), rekhoda kukhasimende nobufakazo bakhe:

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

    Rekhoda kuphela ukuvuma osenakho ngempela.
  </Step>

  <Step title="Rekhoda ukuvuma kwabakhethayo bese uvula umthetho wokuvuma">
    **Umthetho wokuvuma** ungumsethingo wenombolo. Uma uvulekile, ama-template OKUKHANGISA athunyelwa kuphela kuzinombolo ezinerekhodi lokuvuma (**opt-in record**). Abanye bonke bayeqwa nge-`recipient_not_opted_in`. Ama-template e-utility nezimpendulo azithintwa. Awuvulekile ngokuzenzakalelayo.

    Amarekhodi okuvuma agcinwa ahlukile kokuvuma okusekhasimendeni, ngakho rekhoda nomuntu ngamunye ovumile lapha futhi. Kufika kwabangu-1000 ngecingo ngalinye, konke noma lutho.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/optins \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "numbers": [
          { "number": "61412345678", "name": "John", "source": "web form", "note": "ticked the box", "at": "2026-10-01T09:00:00Z" },
          { "number": "61498765432", "name": "Mary", "source": "checkout", "at": "2026-10-12T02:30:00Z" }
        ]
      }'

    curl -s -X PUT https://api.app2email.com/v1/YOUR_NUMBER/settings/optin \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "require_optin_for_marketing": true }'
    ```

    ```javascript Node.js
    const headers = {
      Authorization: `Bearer ${process.env.A2E_KEY}`,
      "Content-Type": "application/json",
    };

    await fetch("https://api.app2email.com/v1/YOUR_NUMBER/optins", {
      method: "POST",
      headers,
      body: JSON.stringify({
        numbers: [
          { number: "61412345678", name: "John", source: "web form", note: "ticked the box", at: "2026-10-01T09:00:00Z" },
          { number: "61498765432", name: "Mary", source: "checkout", at: "2026-10-12T02:30:00Z" },
        ],
      }),
    });

    await fetch("https://api.app2email.com/v1/YOUR_NUMBER/settings/optin", {
      method: "PUT",
      headers,
      body: JSON.stringify({ require_optin_for_marketing: true }),
    });
    ```

    ```python Python
    headers = {"Authorization": f"Bearer {os.environ['A2E_KEY']}"}

    requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/optins",
        headers=headers,
        json={
            "numbers": [
                {"number": "61412345678", "name": "John", "source": "web form", "note": "ticked the box", "at": "2026-10-01T09:00:00Z"},
                {"number": "61498765432", "name": "Mary", "source": "checkout", "at": "2026-10-12T02:30:00Z"},
            ]
        },
    )

    requests.put(
        "https://api.app2email.com/v1/YOUR_NUMBER/settings/optin",
        headers=headers,
        json={"require_optin_for_marketing": True},
    )
    ```

    </CodeGroup>

    **Lokho okuthola emuva:** `{"success": true, "request_id": "o9ahv", "saved": 2}` yokuvuma, kanye ne-`{"require_optin_for_marketing": true}` yomsethingo. `GET /v1/YOUR_NUMBER/optins?number=61412345678` ihlola inombolo eyodwa (`opted_in` ingu-true noma false).
  </Step>

  <Step title="Beka abathe cha ohlwini Lokungashayi (Do Not Call)">
    Ama-template okukhangisa awasoze athunyelwe kunombolo ekuhlu Lokungashayi, nakancane amarekhodi okuvuma nini. Abathi STOP bangeniswa yi-app2email ngokwayo. Engeza labo ababhalisa ngaphandle (esitolo sakho, uhlu lwakho lwemeyili, ucingo). Kufika kwizinombolo ezingu-1000, konke noma lutho.

    <CodeGroup>

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

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/donotcall", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        numbers: ["61400111222", { number: "61400333444", name: "Sam", note: "Unsubscribed in our CRM" }],
      }),
    });
    console.log(await res.json());
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/donotcall",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
        json={"numbers": ["61400111222", {"number": "61400333444", "name": "Sam", "note": "Unsubscribed in our CRM"}]},
    )
    print(res.json())
    ```

    </CodeGroup>

    **Lokho okuthola emuva:** izinombolo `added`, ezi-`already_on_list`, nokuthi zingaki ohlwini manje.

    ```json
    {
      "success": true,
      "request_id": "d4nca",
      "added": ["61400111222", "61400333444"],
      "already_on_list": [],
      "count": 37
    }
    ```

    `GET /v1/YOUR_NUMBER/donotcall?number=61400111222` ihlola inombolo eyodwa (`on_list`). `DELETE /v1/YOUR_NUMBER/donotcall/61400111222` isusa inombolo ohlwini: yenze kuphela uma umuntu esecele ukuthola okukhangisayo futhi.
  </Step>

  <Step title="Dala i-template YOKUKHANGISA">
    Bhala isiphakamiso ngesikhonkwane esinenombolo segama lokuqala, unike inani lesampula kuso ku-`example`, bese wengeza umlandu ongezansi otshela indlela yokuyeka. I-STOP namagama ayo ahunyiwe ngamagama okuphuma i-app2email ayiwazi kakade.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "winter_sale",
        "language": "en",
        "category": "MARKETING",
        "components": [
          {
            "type": "BODY",
            "text": "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
            "example": { "body_text": [["John"]] }
          },
          { "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.A2E_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: "winter_sale",
        language: "en",
        category: "MARKETING",
        components: [
          {
            type: "BODY",
            text: "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
            example: { body_text: [["John"]] },
          },
          { type: "FOOTER", text: "Reply STOP to opt out" },
        ],
      }),
    });
    console.log(res.status, await res.json());
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/templates",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
        json={
            "name": "winter_sale",
            "language": "en",
            "category": "MARKETING",
            "components": [
                {
                    "type": "BODY",
                    "text": "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
                    "example": {"body_text": [["John"]]},
                },
                {"type": "FOOTER", "text": "Reply STOP to opt out"},
            ],
        },
    )
    print(res.status_code, res.json())
    ```

    </CodeGroup>

    **Lokho okuthola emuva** (HTTP 201): i-template isiyo-Meta ukuze ibuyekezwe.

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

    Ukubuyekezwa kuthatha imizuzu kuya kolunye usuku. Umcimbi we-`template.status_changed` ukutshela umphumela (`status` APPROVED nge-`can_send: true`, noma REJECTED nesizathu `reason`), noma buza `GET /v1/YOUR_NUMBER/templates/winter_sale`. I-`example_request` yayo ingumthumelo ophelele ongawukopisha, futhi i-`quality_score` (GREEN, YELLOW noma RED) ikhombisa kamuva ukuthi abantu basabela kanjani kuyo. Ukuze uthole indaba egcwele yokubuyekezwa, bona [Thumela izaziso zama-oda nezikhathi zokuhlangana ngama-template](/guides/how-to-order-notifications).

    Ama-template aphethwe yi-WhatsApp Business Account: yonke inombolo kuleyo akhawunti ingawasebenzisa.
  </Step>

  <Step title="Khetha izethameli ngesegimenti">
    Isegimenti ngumhlungo ogciniwe phezu koxhumana nabo. Zonke izimo kumele zibe khona: `tags_any`, `tags_all`, `consent_marketing`, `last_inbound_days` (ubhale kuwe kwizinsuku ezingu-N ezedlule) kanye ne-`search`. Kufika kumasegimenti angu-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": "Newsletter, consented",
        "filter": { "tags_any": ["newsletter"], "consent_marketing": true }
      }'
    ```

    ```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: "Newsletter, consented",
        filter: { tags_any: ["newsletter"], consent_marketing: true },
      }),
    });
    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={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
        json={"name": "Newsletter, consented", "filter": {"tags_any": ["newsletter"], "consent_marketing": True}},
    )
    segment = res.json()["segment"]
    print(segment["id"], segment["contacts"])
    ```

    </CodeGroup>

    **Lokho okuthola emuva** (HTTP 201): isegimenti, nokuthi mangaki oxhumana nabo ahambisanayo manje.

    ```json
    {
      "success": true,
      "request_id": "s5gmt",
      "segment": {
        "id": 12,
        "name": "Newsletter, consented",
        "filter": { "tags_any": ["newsletter"], "consent_marketing": true },
        "contacts": 240,
        "created": "2026-11-21T01:00:00Z",
        "updated": "2026-11-21T01:00:00Z"
      }
    }
    ```

    `GET /v1/YOUR_NUMBER/segments/12/contacts?limit=200` ibala oxhumana nabo ahambisanayo, ikhasi ngekhasi (`next_cursor`). Isegimenti ingumhlungo, hhayi ikhophi: ikhasimende elihoxisa ukuvuma kwalo liphuma kuwo.
  </Step>

  <Step title="Thumela umsakazo">
    `recipients` inika inombolo ngayinye amanani ayo: lapha igama lokuqala elisuka kokungenisiwe. Thumela isicelo esisodwa ngeqoqo ngalinye lama-`max_numbers_per_request` izinombolo (ku-`GET /usage` ne-`GET /me`; umkhawulo womsakazo, kuze kufike ku-1000).

    - `"background": true` iphendula ngokushesha uma konke sekuhloliwe, bese ithumela ngemva kwalokho.
    - `campaign_name` iyigama lomsakazo ku-Activity Log ngaphansi kwe-Broadcasts.
    - Ikhanda elithi `Idempotency-Key` lelo qoqo: uma umsebenzi wakho uqhuba kabili ngaphakathi kwamahora angu-24, leli qoqo alithunyelwa futhi.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/messages \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: winter-sale-2026-batch-0" \
      -d '{
        "type": "template",
        "campaign_name": "Winter sale 2026",
        "background": true,
        "template": { "name": "winter_sale", "language": { "code": "en" } },
        "recipients": [
          {
            "to": "61412345678",
            "components": [{ "type": "body", "parameters": [{ "type": "text", "text": "John" }] }]
          },
          {
            "to": "61498765432",
            "components": [{ "type": "body", "parameters": [{ "type": "text", "text": "Mary" }] }]
          }
        ]
      }'
    ```

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

    async function call(path, init = {}) {
      for (;;) {
        const res = await fetch(BASE + path, { ...init, headers: { ...headers, ...init.headers } });
        if (res.status === 429) {
          const body = await res.json();
          if (body.error.code !== "rate_limited") throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
          await sleep(Number(res.headers.get("Retry-After") ?? 5) * 1000);
          continue;
        }
        const body = await res.json();
        if (!res.ok) throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
        return body;
      }
    }

    // 1. Everyone the segment matches, page by page
    const contacts = [];
    let cursor = "";
    do {
      const page = await call(`/segments/12/contacts?limit=200${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
      contacts.push(...page.contacts);
      cursor = page.next_cursor;
    } while (cursor);

    // 2. The most numbers per request
    const { max_numbers_per_request: max } = await call("/usage");

    // 3. One request per batch, each with its own Idempotency-Key
    for (let i = 0, n = 0; i < contacts.length; i += max, n++) {
      const batch = contacts.slice(i, i + max);
      const body = await call("/messages", {
        method: "POST",
        headers: { "Idempotency-Key": `winter-sale-2026-batch-${n}` },
        body: JSON.stringify({
          type: "template",
          campaign_name: `Winter sale 2026 (${n + 1})`,
          background: true,
          template: { name: "winter_sale", language: { code: "en" } },
          recipients: batch.map((c) => ({
            to: c.identity,
            components: [
              { type: "body", parameters: [{ type: "text", text: c.custom_fields?.first_name || c.name || "there" }] },
            ],
          })),
        }),
      });
      if (body.status === "pending_approval") console.log("waiting for approval:", body.approval.url);
      else console.log(body.status, body.broadcast.code, body.queued, body.skipped);
    }
    ```

    ```python Python
    import os, time, requests

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

    def call(method, path, **kw):
        while True:
            res = requests.request(method, BASE + path, headers={**HEADERS, **kw.pop("headers", {})}, **kw)
            body = res.json()
            if res.status_code == 429 and body["error"]["code"] == "rate_limited":
                time.sleep(int(res.headers.get("Retry-After", "5")))
                continue
            if not res.ok:
                raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']}")
            return body

    # 1. Everyone the segment matches, page by page
    contacts, cursor = [], None
    while True:
        page = call("GET", "/segments/12/contacts", params={"limit": 200, **({"cursor": cursor} if cursor else {})})
        contacts += page["contacts"]
        cursor = page.get("next_cursor")
        if not cursor:
            break

    # 2. The most numbers per request
    size = call("GET", "/usage")["max_numbers_per_request"]

    # 3. One request per batch, each with its own Idempotency-Key
    for n, i in enumerate(range(0, len(contacts), size)):
        batch = contacts[i : i + size]
        body = call(
            "POST",
            "/messages",
            headers={"Idempotency-Key": f"winter-sale-2026-batch-{n}"},
            json={
                "type": "template",
                "campaign_name": f"Winter sale 2026 ({n + 1})",
                "background": True,
                "template": {"name": "winter_sale", "language": {"code": "en"}},
                "recipients": [
                    {
                        "to": c["identity"],
                        "components": [
                            {
                                "type": "body",
                                "parameters": [
                                    {"type": "text", "text": c.get("custom_fields", {}).get("first_name") or c.get("name") or "there"}
                                ],
                            }
                        ],
                    }
                    for c in batch
                ],
            },
        )
        if body["status"] == "pending_approval":
            print("waiting for approval:", body["approval"]["url"])
        else:
            print(body["status"], body["broadcast"]["code"], body.get("queued"), body.get("skipped"))
    ```

    </CodeGroup>

    **Lokho okuthola emuva** (HTTP 202): okuhlolwe kudlule futhi ukuthunyelwa sekuqalile. Gcina i-`broadcast.code`: zonke izingcingo zamuva ngalo msakazo zisebenzisa leyo khodi.

    ```json
    {
      "success": true,
      "request_id": "t7wpe",
      "status": "queued",
      "from": "4976659348270",
      "template": { "name": "winter_sale", "language": "en", "category": "MARKETING" },
      "broadcast": {
        "name": "Winter sale 2026",
        "code": "k3XbQ9rTzP2mWv7a1c9e",
        "report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e",
        "status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e"
      },
      "recipients": 2,
      "queued": 2,
      "skipped": 0,
      "results": [],
      "note": "Sending in the background. GET broadcast.status_url for progress and the result for each number, or use the broadcast.completed webhook."
    }
    ```

    Yonke inombolo ihlolwa ngaphambi kokuthunyelwa kwanoma yini. Izinombolo ezikuhlu Lokungashayi, nezinombolo ngaphandle kwerekhodi lokuvuma (uma umthetho uvuliwe), ziyeqwa futhi ziyabalwa, azithunyelwa.

    <Tip>
    **Hlola kuqala.** Engeza `"dry_run": true` emzimbeni ofanayo. Konke kuhlolwa njengokuthunyelwa kwangempela (amanani ama-template, izinombolo, uhlu Lokungashayi, umthetho wokuvuma, umkhawulo wenyanga) bese impendulo ikhombisa umlayezo ngqo ngenombolo ngayinye. Akukho okuthunyelwa, okulogwa noma okubalwa, futhi i-`Idempotency-Key` iyeqwa.
    </Tip>

    <Tip>
    **Ngqo esegimenteni.** `"segment": "Newsletter, consented"` (i-id yayo noma igama eliqondile) esikhundleni se-`recipients` kuthumela kubo bonke oxhumana nabo besegimenti ngocingo olulodwa. Amanani avela kumuntu ngamunye kwi-template enezikhonkwane **ezinamagama** (`{{first_name}}`, edalwe nge-`"parameter_format": "NAMED"`): umlandu nge-`parameter_name` ongenalo `text` ugcwaliswa kusuka ku-`custom_fields` yoxhumana naye (`name` kusuka egameni loxhumana naye).

    ```json
    {
      "segment": "Newsletter, consented",
      "type": "template",
      "campaign_name": "November offer",
      "template": {
        "name": "november_offer",
        "language": { "code": "en" },
        "components": [
          { "type": "body", "parameters": [{ "type": "text", "parameter_name": "first_name" }] }
        ]
      }
    }
    ```
    </Tip>
  </Step>

  <Step title="Okukhethwayo: hlela ukuthi kuzothunyelwa kamuva">
    Engeza `send_at` (ISO 8601 nesikhathi sesifunda, kusukela kumzuzu oyodwa kuya kuizinsuku ezingu-29 phambili) emzimbeni ofanayo. Ukuthumela ngesikhathi somakhasimende akho kuvame ukusebenza kangcono kunasebusuku.

    ```json
    {
      "type": "template",
      "campaign_name": "Winter sale 2026",
      "template": { "name": "winter_sale", "language": { "code": "en" } },
      "recipients": [
        { "to": "61412345678", "components": [{ "type": "body", "parameters": [{ "type": "text", "text": "John" }] }] }
      ],
      "send_at": "2026-12-01T09:00:00+11:00"
    }
    ```

    Impendulo iyi-HTTP 202 nge-`status: "scheduled"`, `scheduled_for` (UTC), `scheduled` (imilayezo emingaki) kanye nekhodi `code` yomsakazo. Konke kuhlolwa ngasikhathi sinye, futhi uhlu Lokungashayi nomkhawulo wenyanga kuhlolwa futhi lapho isikhathi sifika, ngakho umuntu osho STOP phakathi nendawo akasoze akuthole.
  </Step>

  <Step title="Landela inqubekelaphambili uthole umphumela ngenombolo ngayinye">
    `GET /v1/YOUR_NUMBER/broadcasts/{code}` iyaphila ngenkathi umsakazo uthumela.

    <CodeGroup>

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

    # one row per message, for a spreadsheet
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/results.csv \
      -H "Authorization: Bearer $A2E_KEY" -o winter-sale.csv
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e", {
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
    });
    const { broadcast, counts } = await res.json();
    console.log(broadcast.status, counts);
    ```

    ```python Python
    res = requests.get(
        "https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
    )
    body = res.json()
    print(body["broadcast"]["status"], body["counts"])
    ```

    </CodeGroup>

    **Lokho okuthola emuva:** umsakazo, izibalo zawo, nomphumela oyedwa ngenombolo ngayinye. `status` ingu-`scheduled`, `inprogress`, `completed`, `cancelled`, `missed`, `interrupted`, `pending` noma `unknown`. Umphumela ngamunye ungumlayezo (unesimo `status`, `times` nempendulo `reply` yekhasimende), noma `skipped`, `not_sent` noma `pending` nesizathu `reason`.

    ```json
    {
      "success": true,
      "request_id": "b6rsl",
      "broadcast": {
        "code": "k3XbQ9rTzP2mWv7a1c9e",
        "name": "Winter sale 2026",
        "created": "2026-12-01T09:00:00Z",
        "status": "completed",
        "sent_by": "api",
        "template": { "name": "winter_sale", "language": "en" },
        "report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e"
      },
      "counts": {
        "numbers": 240,
        "skipped_do_not_call": 3,
        "skipped_monthly_limit": 0,
        "posted": 237,
        "accepted": 236,
        "sent": 236,
        "delivered": 229,
        "read": 171,
        "failed": 1,
        "replied": 19,
        "opted_out": 2
      },
      "results": [
        {
          "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
          "to": "61412345678",
          "status": "read",
          "sent_by": "api",
          "broadcast_code": "k3XbQ9rTzP2mWv7a1c9e",
          "text": "Hi John, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
          "times": {
            "submitted": "2026-12-01T09:00:00Z",
            "accepted": "2026-12-01T09:00:01Z",
            "sent": "2026-12-01T09:00:02Z",
            "delivered": "2026-12-01T09:00:04Z",
            "read": "2026-12-01T09:14:40Z"
          },
          "reply": { "at": "2026-12-01T09:15:10Z", "text": "Do you have it in blue?" },
          "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
        },
        { "to": "61400111222", "status": "skipped", "reason": "On the Do Not Call list" }
      ]
    }
    ```

    `results.csv` inomugqa oyodwa ngomlayezo ngamunye: inombolo, isimo, `message_id`, isikhathi sesinyathelo ngasinye, impendulo nephutha (kanye ne-`clicks` ne-`first_click_at` uma kulandelelwa izixhumanisi). Amanani aqala nge-`=`, `+`, `-` noma `@` athola `'` phambili, ukuze i-spreadsheet ingawasebenzisi njengamafomula. `GET /v1/YOUR_NUMBER/broadcasts` ibala imisakazo yakho yakamuva, eyokugcina kuqala.
  </Step>

  <Step title="Yikhansele uma udinga">
    Inkokhelo engalungile esiphakamisweni? `POST /v1/YOUR_NUMBER/broadcasts/{code}/cancel` (scope `messages:send`) imisa umsakazo we-API ohleliwe noma osathumela.

    <CodeGroup>

    ```bash cURL
    curl -s -X POST https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel \
      -H "Authorization: Bearer $A2E_KEY"
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
    });
    console.log(res.status, await res.json());
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
    )
    print(res.status_code, res.json())
    ```

    </CodeGroup>

    **Lokho okuthola emuva:** HTTP 200 ye-broadcast ehleliwe (akukho okuthunyelwe), noma HTTP 202 yoyo osathumela: imilayezo esevele inikezwe i-WhatsApp ihlala ithunyelwe, eyaseleyo ayithunyelwa.

    ```json
    {
      "success": true,
      "request_id": "u1nqd",
      "broadcast": { "code": "k3XbQ9rTzP2mWv7a1c9e", "status": "cancelling" },
      "note": "Cancelling. Messages already handed to WhatsApp stay sent; the rest are not sent. GET https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e shows the result."
    }
    ```

    Kulandela umcimbi we-`broadcast.completed` onesimo `status: "cancelled"`. Imisakazo eqedile, kanye nalena eqalwe kudeshibhodi, iphendula nge-`409 broadcast_not_cancellable`.
  </Step>

  <Step title="Landela abantu abaphendule noma abachofoze">
    **Umsakazo we-API:** akha uhlu olulandelayo ngokwakho ngomphumela. Umphumela ngamunye ku-`GET /broadcasts/{code}` unesimo `status` somlayezo nempendulo `reply` yekhasimende, ngakho ungakhetha, isibonelo, bonke abafunde isiphakamiso kodwa abangaphendulanga, bese uthumela kubo i-template yesibili nge-`POST /messages` njengasenhla.

    ```javascript
    const { results } = await (await fetch(`${BASE}/broadcasts/k3XbQ9rTzP2mWv7a1c9e`, { headers })).json();
    const readNoReply = results.filter((r) => r.status === "read" && !r.reply).map((r) => r.to);
    ```

    **Umsakazo oqalwe ekhasini le-Broadcast kudeshibhodi** unezinto ezimbili ezengeziwe i-API ongazisebenzisa:

    - **Izixhumanisi ezilandelelwayo.** Uma i-Track clicks ivulekile (okuzenzakalelayo lapho), ngamunye umamukeli uthola isixhumanisi sakhe esifushane `https://www.app2email.com/l/<code>` sesixhumanisi esisemlayezweni womsakazo. `GET /broadcasts/{code}/clicks` inikeza inani eliphelele, izinkinobho ezihlukile, izinga lokuchofoza kanye nokuchofoza kwengxenye ngayinye. Izibalo ezifanayo ziku-`clicks` ye-`GET /broadcasts/{code}`, futhi isenzakalo se-`link.clicked` sifika ngokuchofoza ngakunye.
    - **Ukuphinda-khangisa ngocingo olulodwa.** `POST /broadcasts/{code}/retarget` yenza omunye umsakazo nge-template, amanani nemidiya efanayo, ngalabo `audience` abalandelayo: `not_read`, `read_not_clicked`, `clicked`, `replied` (baphendule phakathi kwezinsuku ezingu-7 kusukela ekuthunyelweni) noma `not_replied`. Bala kuqala nge-`dry_run`:

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "audience": "read_not_clicked", "dry_run": true }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ audience: "read_not_clicked", dry_run: true }),
    });
    console.log(await res.json());
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
        json={"audience": "read_not_clicked", "dry_run": True},
    )
    print(res.json())
    ```

    </CodeGroup>

    **Lokho okuthola emuva:** nge-`dry_run`, inani (HTTP 200). Ngaphandle kwayo, HTTP 202 nomsakazo omusha, othumela ngemuva.

    ```json
    {
      "success": true,
      "request_id": "c3rtg",
      "audience": "read_not_clicked",
      "recipients": 131,
      "broadcast": {
        "code": "Mx8Pq2Lw5Rt7Yz3",
        "name": "Summer sale - read not clicked",
        "status": "inprogress",
        "status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/Mx8Pq2Lw5Rt7Yz3",
        "report_url": "https://www.app2email.com/dashboard/log/broadcast/Mx8Pq2Lw5Rt7Yz3"
      },
      "note": "The new broadcast is sending in the background."
    }
    ```

    Uhlu Lokungashayi nomkhawulo wepulani kuhlolwa futhi, kanti umkhawulo wokuvuma wokhiye nomkhawulo wansuku zonke usebenza. Ukuphinda-khangisa, ukuqhubeka nokuzama kabusha kusebenza kumisakazo yedeshibhodi kuphela; uhlu lwe-API luphendula nge-`403 broadcast_not_resumable`.

    Ukulandelela kuwumlayezo wokukhangisa omunye, futhi uyakhokhelwa. Uwuthumele eqenjini elincane elinentshisekelo (`clicked`, `replied`), hhayi kubo bonke abalinganwe ukuyeka okokuqala.
  </Step>
</Steps>

## Umphumela

Ikhasimende libona umlayezo ovela egameni lebhizinisi lakho, nesiphakamiso, negama lakhe lokuqala kuwo, nesigxivizo "Reply STOP to opt out". Uma lipendula, iwindi lamahora angu-24 liyavuleka, futhi ungaphendula ngombhalo wamahhala nge-API noma ngemeyili.

Ohlangothini lwakho lezi zenzakalo ziyafika (engeza iwebhu nge-`POST /v1/YOUR_NUMBER/webhooks` nekheli le-https elivulekile `url`; scope `webhooks:manage`). Awukabi nekheli elivulekile? `GET /v1/YOUR_NUMBER/events?wait=25` inikeza izenzakalo ezifanayo.

**`message.status`** kuwo wonke umlayezo njengoba unyakaza: `sent`, `delivered`, `read`, noma `failed`. `broadcast_code` ikhomba umsakazo oyiwo, kanti `pricing.category` ikhombisa ukuthi i-Meta yawubala kanjani.

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "message.status",
  "created": "2026-12-01T09:00:04.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "to": "61412345678",
    "status": "delivered",
    "timestamp": "2026-12-01T09:00:04.000Z",
    "sent_by": "api",
    "broadcast_code": "k3XbQ9rTzP2mWv7a1c9e",
    "whatsapp_status": "delivered",
    "recipient_user_id": "AU.1234567890123456",
    "pricing": { "billable": true, "pricing_model": "PMP", "type": "regular", "category": "marketing" }
  }
}
```

**`message.failed`** lapho umlayezo ungalethwanga. Esingawubona nokukhangisa ngu-Meta error 131049: i-WhatsApp ibambe umlayezo ngoba umuntu uthole imilayezo eminingi yokukhangisa kwakamuva. Ungawuthumeli futhi ngaphakathi kwamahora angu-24; ukuzama ngaphambi kwalokho kugcina isithiyo side.

```json
{
  "id": "evt_Pa3k9m2Lw8Rt5Yp1Zs011",
  "type": "message.failed",
  "created": "2026-12-01T09:00:03.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "to": "61412345678",
    "status": "failed",
    "timestamp": "2026-12-01T09:00:03.000Z",
    "sent_by": "broadcast",
    "whatsapp_status": "failed",
    "error": {
      "code": 131049,
      "message": "This message was not delivered to maintain healthy ecosystem engagement.",
      "title": "This message was not delivered to maintain healthy ecosystem engagement.",
      "error_code": "marketing_per_user_limit",
      "how_to_fix": "WhatsApp held this marketing message back: the person has had many marketing messages lately. Do not send it again within 24 hours, because retrying sooner keeps the block longer.",
      "is_retriable": false,
      "retry_after_seconds": 86400
    }
  }
}
```

**`message.received`** lapho ikhasimende liphendula: `text` kumpendulo ebhalwe, `button` kwinkinobho ecindezelwe.

**`contact.opted_out`** lapho ikhasimende lizifaka ohlwini Lokungashayi. `source` ingu-`stop_promotions` (uthinte "Stop promotions"), `whatsapp_stop` noma `keyword` (uthumele igama lokuphuma).

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "contact.opted_out",
  "created": "2026-12-01T09:20:00.000Z",
  "number": "4976659348270",
  "data": {
    "number": "61412345678",
    "name": "John Smith",
    "source": "stop_promotions",
    "detail": "Stop promotions",
    "timestamp": "2026-12-01T09:20:00.000Z"
  }
}
```

**`link.clicked`** kuwo wonke ukuchofoza isixhumanisi esilandelelwayo (imisakazo yedeshibhodi). `first_click` ingu-true ukuchofoza kokuqala kwesixhumanisi somamukeli ngamunye.

```json
{
  "id": "evt_Cmp3k9m2Lw8Rt5Yp1Zs01",
  "type": "link.clicked",
  "created": "2026-11-19T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "url": "https://example.com/sale",
    "broadcast_code": "k3XbQ9rTzP2mWv7",
    "sequence_id": null,
    "step_id": null,
    "first_click": true,
    "clicks": 1,
    "browser": "Chrome",
    "timestamp": "2026-11-19T01:00:00.000Z"
  }
}
```

**`broadcast.completed`** kanye ngomsakazo ngamunye, lapho uqedile, ukhanseliwe noma ufinyelele isikhathi sawo esihleliwe.

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "broadcast.completed",
  "created": "2026-12-01T09:04:00.000Z",
  "number": "4976659348270",
  "data": {
    "code": "k3XbQ9rTzP2mWv7a1c9e",
    "name": "Winter sale 2026",
    "status": "completed",
    "sent_by": "api",
    "numbers": 240,
    "posted": 237,
    "accepted": 236,
    "errors": 1,
    "skipped_do_not_call": 3,
    "skipped_monthly_limit": 0,
    "status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e",
    "report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e"
  }
}
```

`GET /v1/YOUR_NUMBER/stats?from=&to=` ifingqa izibalo nezilinganiso zokuthunyelwe, zilethiwe, zifundiwe, zehlulekile nezaphendulwa ngesikhathi esithile, kuyo yonke imisakazo.

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

## Kubiza malini

Imali ezimbili:

- **i-app2email:** i-plan yenyanga engashintshi. Umlayezo ngamunye womsakazo ubalwa njengomlayezo oyodwa we-plan, ngaphandle kokwengezwa kwentengo ngomlayezo ngamunye ([intengo](https://www.app2email.com/pricing)). Lapho imilayezo ye-plan iphela, okusalayo kuyeqwa (`skipped_monthly_limit`) noma kuphendula nge-`429 monthly_limit_reached`.
- **I-Meta:** ikhokhisa yonke i-template elethiwe ngqo kwindlela yokukhokha ku-WhatsApp Business Account yakho. Intengo incike esigabeni nasezweni lekhasimende, futhi **ukukhangisa kubiza kakhulu**. Umsakazo wamanani angu-10,000 ubiza ngempela, ngakho thumela kubantu abayifunayo, hhayi kubo bonke osebakhumbule.

Libale ngaphambi kokuthumela nge-[WhatsApp pricing calculator](https://www.app2email.com/tools/whatsapp-pricing-calculator). Ngemva kokuthumela, i-`meta_pricing` ku-`GET /v1/YOUR_NUMBER/usage` ibala imilayezo yenyanga yokukhokhisa ngesigaba se-Meta ngentengo ecatshangwayo, kanti i-`GET /v1/YOUR_NUMBER/usage/meta` iyinikeza ngosuku.

<Note>
Uma i-Meta isingenisile i-akhawunti yakho ku-Marketing Messages API yayo, ama-template okukhangisa ahamba ngaleyo ndlela ngokuzenzakalelayo (umsethingo wenombolo `messages.marketing_route`, `auto`). `GET /v1/YOUR_NUMBER/marketing` ikhombisa indlela, nempendulo yokuthumela i-`sent_via` ikhombisa ukuthi umlayezo uhambe ngaziphi. Akukho okushintshayo kwisicelo sakho.
</Note>

<a id="quality-rating-and-limits"></a>

## Isilinganiso sekhwalithi nemikhawulo

I-WhatsApp iyabona ukuthi abantu basabela kanjani kumilayezo yakho. Izivimbo eziningi nokubikwa kuyehlisa **isilinganiso sekhwalithi** sakho. Khona-ke:

- i-`quality_score` yale template (ku-`GET /templates/{name}`) iba YELLOW, bese RED, futhi i-template ebomvu ingamiswa (`422 template_paused`, Meta error 132015);
- **umkhawulo wemilayezo** yenombolo yakho (abantu ongabaqalisa nabo izingxoxo ngamahora angu-24) uyeka ukukhula, noma wehla;
- i-WhatsApp ingahle inciphise umsakazo wakho: umsakazo wedeshibhodi uzima ngokwawo (isimo `paused_by_meta`, nesizathu ku-`status_notes`); lungisa imbangela, bese i-`POST /broadcasts/{code}/resume` iqhubeka.

`GET /v1/YOUR_NUMBER/health` (scope `messages:read`) ikhombisa i-`quality_rating` kanye ne-`messaging_limit` yenombolo:

```json
{
  "success": true,
  "request_id": "h7q2m",
  "health": {
    "can_send_message": "AVAILABLE",
    "quality_rating": "GREEN",
    "messaging_limit": "TIER_2K",
    "throughput": "STANDARD",
    "status": "CONNECTED",
    "name_status": "APPROVED",
    "account_mode": "LIVE"
  },
  "fetched_at": "2026-11-06T01:00:00.000Z"
}
```

Ukuyigcina iluhlaza:

- Thumela kubantu abavumile kuphela, futhi gcina uhlu Lokungashayi lusha.
- Hlola isilinganiso ngaphambi komsakazo omkhulu. Uma uhlu lwakho lukhulu kunomkhawulo wemilayezo yakho, lithumele ngezingxenye ezinsukwini ezimbalwa.
- Qala ngoxhumana nabo abazibandakanya kakhulu (`last_inbound_days` kwisihlungi sesegimenti), bese ubheka ukufundwa nokuphuma kwengxenye yokuqala ngaphambi kokuthumela esasele.
- Yenza isiphakamiso sibe nesizathu sokufundwa, tshela ukuthi ungubani, futhi gcina umugqa we-STOP kumlandu ongezansi.
- Ungathumeli umuntu okukhangisayo nsuku zonke. I-WhatsApp ngokwayo ibamba imilayezo kwabathola kakhulu (131049).

## Uhlu lokuhlola lokukhiqiza

<AccordionGroup>
  <Accordion title="Hlola isayina yewebhu">
    Isenzakalo ngasinye sinekhanda `X-App2email-Signature: t=<unix seconds>,v1=<hex>`. Inani le-`v1` yi-HMAC-SHA256 ye-`"<t>.<raw body>"`, nemfihlo yewebhu (`whsec_...`, kanye nesiqalo) njengokhiye. Hlola wonke ama-`v1=` (kunamabili uma imfihlo endala isagcinwa ngemva kokushintsha), bala kusetshenziswa umzimba oluhlaza njengoba ufika, futhi wenqabe `t` endala. `X-Hub-Signature-256: sha256=<hex>` (HMAC-SHA256 yomzimba oluhlaza, imfihlo yamanje kuphela) nayo ikhona, ngekhodi ebhalelwe amawebhu ka-Meta.

    <CodeGroup>

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

    export function verifyWebhook(rawBody, header, secret, toleranceSeconds = 300) {
      const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
      const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]);
      if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) return false;
      const expected = crypto.createHmac("sha256", secret).update(t + ".").update(rawBody).digest("hex");
      return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
    }

    const app = express();
    app.post("/app2email", express.raw({ type: "application/json" }), async (req, res) => {
      if (!verifyWebhook(req.body, req.get("X-App2email-Signature"), process.env.WEBHOOK_SECRET)) return res.sendStatus(401);
      if (await alreadySeen(req.get("X-App2email-Delivery"))) return res.sendStatus(200); // a retry
      const event = JSON.parse(req.body);
      res.sendStatus(200); // answer within 10 seconds, then do the work
      switch (event.type) {
        case "message.status":
        case "message.failed":
          await saveStatus(event.data.broadcast_code, event.data.to, event.data.message_id, event.data.status, event.data.error);
          break;
        case "contact.opted_out":
          await markUnsubscribed(event.data.number, event.data.source); // in your CRM too
          break;
        case "broadcast.completed":
          await saveBroadcastTotals(event.data);
          break;
      }
    });
    ```

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

    </CodeGroup>
  </Accordion>

  <Accordion title="Yeqa imicimbi ephindaphindiwe engalandelani">
    Phendula ngekhodi 2xx ngaphakathi kwemizuzwana engu-10. Uma kungenjalo, isenzakalo sithunyelwa kabusha emva kwe-10 s, 1 min, 5 min, 30 min, 1, 2, 4, 8 kanye ne-16 amahora. `X-App2email-Delivery` (i-`id` yesenzakalo, `evt_...`) ifana kuzo zonke izinzame, ngakho yigcine futhi weqe isenzakalo owasiphatha kakade.

    Izenzakalo zingafika zingalandelani: i-`read` ingafika ngaphambi kwe-`delivered` yayo. Gcina isimo esiphambili kakhulu ngamunye nge-`message_id` futhi ungasibuyiseli emuva. Kumsakazo, faka amarekhodi akho ngokhiye we-`broadcast_code` ne-`to`.
  </Accordion>

  <Accordion title="Ungathumeli umsakazo ngaphezu kwesisodwa">
    Nika iqoqo ngalinye `Idempotency-Key` ehlobene nomkhankaso neqoqo, hhayi nomzamo: `winter-sale-2026-batch-0`, `winter-sale-2026-batch-1`. Isicelo esifanayo nokhiye ofanayo ngaphakathi kwamahora angu-24 asithunyelwa futhi; sithola impendulo yokuqala, nekhanda `Idempotent-Replayed: true`.

    - Ukhiye ofanayo nomzimba omehlukile: `422 idempotency_key_reused`. Gcina amaqoqo ngokulandelana okufanayo, noma sebenzisa okhiye abasha kuhlu olusha.
    - Isicelo sokuqala sisasebenza: `409 idempotency_request_in_progress`. Linda bese uzama futhi ngokhiye ofanayo.
    - Isicelo sokuqala asiqedanga ngaphakathi kwemizuzu engu-15: `409 idempotency_request_interrupted`. Ezinye imilayezo ingase iphume: hlola i-`GET /broadcasts` ngaphambi kokuthumela ngokhiye omusha.
    - Isicelo esinqatshwe ngaphambi kokuthunyelwa asiphethi ukhiye, ngakho isicelo esilungisiwe singawusebenzisa.

    Ukhiye ugcinwa amahora angu-24. Gcina futhi i-`broadcast.code` yeqoqo ngalinye kudatabeyisi yakho, futhi ungathumeli iqoqo elinayo ngaphambili.
  </Accordion>

  <Accordion title="Imikhawulo nokuzama kabusha">
    Thumela uhlu ngocingo olulodwa ngeqoqo ngalinye, hhayi ucingo ngalunye ngenombolo. Yonke impendulo inawo `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (imizuzwana kuze kugcwale futhi) kanye ne-`X-RateLimit-Policy`; i-`limits` ku-`GET /me` ikhombisa `requests_per_second` kanye ne-`burst` zokhiye. Ngaphezu komkhawulo uthola `429 rate_limited` nekhanda `Retry-After` kanye ne-`error.retry_after_seconds`: linda leso sikhathi, bese uthumela isicelo esifanayo futhi.

    - `500`, `502`, `503` noma i-timeout: zama kabusha izikhathi ezimbalwa nokulinda okukhulayo, nge-`Idempotency-Key` efanayo.
    - `429 whatsapp_rate_limit` noma `429 too_many_messages_to_recipient`: umkhawulo we-WhatsApp uqobo. Yima amaminithi, hhayi imizuzwana.
    - `429 monthly_limit_reached`, `429 monthly_cap_reached` noma `429 daily_cap_reached`: umkhawulo we-plan, wenombolo, noma wokhiye. Ungazami kabusha uze uphinde usethe, noma ukhulise.
    - Noma yimuphi omunye `4xx`: ungazami kabusha ngaphandle kokushintsha. Yenza isinqumo ngo-`error.code` ulandele i-`how_to_fix`. I-`error.is_retriable` ikutshela ukuthi lesi sicelo singasebenza kamuva yini.
  </Accordion>

  <Accordion title="Umkhawulo wokuvuma nokukhawula kukhiye">
    Ukhiye ungaba nomkhawulo wansuku zonke nesango lokuvuma (`GET /me` iyawakhombisa). Ukuthumela kumakhasimende amaningi kunalokho isango eliwuvumelayo kuphendula nge-HTTP 202 nge-`status: "pending_approval"` kanye ne-`approval.url`: akuyona iphutha. Umuntu uvuma kudeshibhodi, kulandele isenzakalo se-`approval.resolved`, bese imilayezo iyaphuma. Ungathumeli uhlu olufanayo ngenye indlela kulesi sikhathi. Lokhu kuyisivikelo esihle sokhiye othumela okukhangisayo.
  </Accordion>

  <Accordion title="Ukuphuma, ukuvuma kanye nohlu Lokungashayi">
    - Abathi STOP (noma izinhlobo zalo ezihunyiwe) noma bachofoze "Stop promotions" bangeniswa ohlwini Lokungashayi ngokwabo, futhi `contact.opted_out` iyakutshela. Engeza amagama akho okuphuma nge-`PUT /v1/YOUR_NUMBER/settings/number` ne-`{"compliance": {"stop_keywords_extra": ["UNSUBSCRIBE"]}}` (scope `settings:manage`).
    - Uma umuntu eyeka, rekhoda lokho nakoxhumana naye (`POST /contacts/{identity}/consent` nge-`"marketing": false`), ukuze amasegimenti anezi-`consent_marketing: true` amhlanganise, futhi umbeke ohlwini Lokungashayi uma ephume kwezinye izindawo.
    - Ikhasimende lingavala ukukhangisa kuwe ngaphakathi kwe-WhatsApp: izithumelo kulo ziphendula nge-`403 recipient_stopped_marketing` (Meta error 131050). Uma libuyisela, i-`contact.updated` iyafika nge-`change: "marketing_resumed"`.
    - Uhlu Lokungashayi nomthetho wokuvuma kusebenza kuma-template OKUKHANGISA kuphela. Izibuyekezo zama-oda namanye ama-template e-utility asaphuma, njengezimpendulo zakho kumuntu ongathi kuwe.
    - `GET /v1/YOUR_NUMBER/compliance/export.csv` (scope `dnc:manage`) inika amarekhodi okuvuma, uhlu Lokungashayi namarekhodi okuvuma njengefayela elilodwa, amarekhodi uMthetho we-Spam Act 2003 ulindele ukuthi ukwazi ukuwakhombisa.
  </Accordion>

  <Accordion title="Iwindi lamahora angu-24">
    Umsakazo uyithemplethi, ngakho ungaphuma noma nini. Lapho ikhasimende lipendula, iwindi lamahora angu-24 liyavuleka futhi ungaphendula ngombhalo ojwayelekile, izithombe noma izinkinobho (i-app2email imisa imizuzu engu-15 ngaphambili). `GET /v1/YOUR_NUMBER/conversations/61412345678` ikhombisa `window_state` kanye ne-`window_closes_at`. Uma umlayezo wokugcina wawuwukuphuma uqobo, impendulo iphendula nge-`403 recipient_opted_out` kuze kube yilapho libhala futhi.
  </Accordion>
</AccordionGroup>

## Uma kungasebenzi

Iphutha ngalinye liyi-JSON enokuthi `error.code`, `message`, `how_to_fix` kanye ne-`request_id` ongayikhomba kusupport. Bona [Errors](/api/errors) zazo zonke ikhodi, ne-[Limits](/api/limits) zemikhawulo.

| Ikhodi | Nini | Okufanele wenze |
| --- | --- | --- |
| `403 insufficient_scope` | Ukhiye awunayo imvume (`details.required_scope`) | Sebenzisa ukhiye onezimvume ezikutafula ngenhla |
| `403 sandbox_key` | I-template, `PUT /settings/optin` noma ukuphinda-khangisa nokhiye we-sandbox | Sebenzisa ukhiye ojwayelekile kulezo zingcingo |
| `400 invalid_csv` | I-CSV ayinawo umugqa wekhanda noma umugqa wokuxhumana naye | Thumela umugqa wekhanda nomugqa owodwa osebenzayo, kufika kwimigqa engu-5000 |
| `400 invalid_template_category` | `category` ayiyona MARKETING, UTILITY noma AUTHENTICATION | Sebenzisa `MARKETING` ukukhangisa |
| `422 template_not_approved` | I-template ilinde, yenqatshiwe, imisiwe noma ikhubaziwe | Linda ukugunyazwa, noma uyilungise; hlola `GET /templates/{name}` |
| `422 template_parameters_invalid` | Amanani awahambisani ne-template | Lungisa umzimba ngokusuka ku-`details.problems` ne-`example_request` |
| `422 template_paused` | Meta error 132015: imisiwe ngenxa yekhwalithi ephansi | Sebenzisa enye template, noma hlela le; thumela kwabambalwa, abahambisana kangcono |
| `400 too_many_recipients` | Izinombolo eziningi kakhulu ukuthi inombolo ingathumela ngesicelo esisodwa | Hlukanisa ngamaqoqo we-`details.max_recipients` |
| `400 to_and_recipients` | Kokubili `to` no `recipients` | Sebenzisa esisodwa kuzo |
| `400 segment_and_recipients` | `segment` kanye no `to`, `recipient` noma `recipients` | Sebenzisa i-`segment` kuphela |
| `400 segment_empty` | Isegimenti alihambisani nakoxhumana nabo | Hlola `GET /segments/{id}/contacts`, engeza oxhumana nabo noma shintsha isihlungi |
| `404 segment_not_found` | Akukho segimenti nalelo id noma igama | `GET /segments` iyabadweba; sebenzisa i-id noma igama eliqondile |
| `403 recipient_opted_out` | Inombolo eyodwa, futhi isohlwini Lokungashayi | Ungabathumeli ukukhangisa; kuhlu ikhishwa |
| `403 recipient_not_opted_in` | Inombolo eyodwa, umthetho wokuvuma uvuliwe futhi awunalo irekhodi lokuvuma | Rekhoda ukuvuma kwabo kuqala nge-`POST /optins`; kuhlu ikhishwa |
| `403 recipient_stopped_marketing` | Meta error 131050: bavale ukukhangisa kwakho ku-WhatsApp | Ungabathumeli ama-template okukhangisa |
| `422 marketing_per_user_limit` | Meta error 131049: bathole imilayezo eminingi yokukhangisa kwakamuva | Ungaphindi ngaphakathi kwamahora angu-24 |
| `403 messaging_limit_restricted` | Meta error 131064: i-Meta yehlise umkhawulo wemilayezo ngenxa yezigaba ezingalungile zama-template | Hlola izigaba zama-template akho; umkhawulo uyabuya ngemva kwesikhathi se-Meta |
| `403 whatsapp_payment_issue` | Meta error 131042: i-Meta ayikwazanga ukukhokhisa i-akhawunti yakho ye-WhatsApp | Engeza noma lungisa indlela yokukhokha ku-WhatsApp Manager |
| `400 send_at_too_far` | `send_at` ingaphezu kwezinsuku ezingu-29 phambili | Sebenzisa isikhathi kusukela emizuzwini engu-1 kuya kuizinsuku ezingu-29 kusukela manje, nesifunda sesikhathi |
| `422 idempotency_key_reused` | `Idempotency-Key` efanayo, umzimba omehlukile | Sebenzisa ukhiye omusha kuhlu oluhlukile |
| `429 rate_limited` | Izicelo eziningi kakhulu kulo khiye | Linda imizuzwana ye-`Retry-After`, bese uzama futhi |
| `429 whatsapp_rate_limit` | Umkhawulo we-WhatsApp (Meta 130429, 131048 nezinye) | Ncipisa bese uzama futhi kumizuzu engu-1 noma ngaphezulu |
| `429 monthly_limit_reached` | Imilayezo ye-plan iphelile kule nyanga | Linda inyanga yokukhokha elandelayo, noma khuphula |
| `429 daily_cap_reached` | Umkhawulo wansuku zonke wokhiye | Linda kuze kufike ebusuku be-UTC, noma khulisa umkhawulo |
| `409 broadcast_not_cancellable` | Umsakazo uqedile, usuhlu ukhanseliwe, noma uqalwe kudeshibhodi | Kuphela ukuthumela kwe-API okuhleliwe noma okusathumela kungakhanseliwa |
| `403 broadcast_not_resumable` | Ukuphinda-khangisa, ukuqhubeka noma ukuzama kabusha kuluhlu lwe-API | Kuluhlu lwe-API, thumela izinombolo ozifunayo futhi nge-`POST /messages` |
| `400 invalid_retarget_audience` | `audience` ayiyo enye yezinhlobo ezinhlanu | Sebenzisa `not_read`, `read_not_clicked`, `clicked`, `replied` noma `not_replied` |
| `409 broadcast_nothing_to_send` | Akekho osele kuleyo audience | Akukho okufanele wenze |
| `403 campaign_approval_needed` | Ukuphinda-khangisa kuzothumela ngaphezu komkhawulo wokuvuma wokhiye | Qala kusuka kudeshibhodi, noma sebenzisa ukhiye ongenawo umkhawulo wokuvuma |

## Eminye imiqondiso yokusebenza

<CardGroup cols={2}>
  <Card title="Yakha ibhothi ye-WhatsApp nge-API" href="/guides/how-to-whatsapp-chatbot">
    Thola imilayezo ku-webhook esayiniwe, bese uyiphendula ngombhalo, izinkinobho nezinhlu.
  </Card>
  <Card title="Thumela izaziso zama-oda nezikhathi ngama-template" href="/guides/how-to-order-notifications">
    Ithemplethi ye-utility ngayinye ngoda noma ngokuhlelwa, ngesimo sokulethwa nokufundwa.
  </Card>
  <Card title="Vumela ijenti ye-AI iphathe i-WhatsApp yakho nge-MCP" href="/guides/how-to-ai-agent-mcp">
    Xhuma ijenti ku-MCP server bese uvumela ifunde futhi ithumele imilayezo.
  </Card>
  <Card title="Dlulisa ingxoxo ebhothini iye kumuntu nakuyo" href="/guides/how-to-human-handoff">
    Setha umnikazi wengxoxo ukuze ibhothi yakho ishintshe indawo kuyilapho umuntu ephendula.
  </Card>
  <Card title="Cela inkokhelo engxoxweni ye-WhatsApp" href="/guides/how-to-payment-links">
    Thumela isicelo sokukhokha engxoxweni bese uthola isenzakalo lapho sikhokhwa.
  </Card>
</CardGroup>

[Zonke izincwadi zokusebenza](https://www.app2email.com/docs#how-to)
