# Inviare un broadcast di marketing che rispetta gli opt-in

> Importi i suoi contatti con il loro consenso, crei un template di marketing, lo invii a chi ha acconsentito, segua il risultato per ogni numero e ricontatti chi ha risposto o cliccato.

Importa il suo elenco di clienti, Meta approva un template di marketing e una chiamata API per ogni lotto lo invia. Ogni cliente riceve un messaggio WhatsApp dalla sua attività: "Ciao John, i saldi invernali iniziano oggi: 20% di sconto su tutto fino a domenica." Se non vuole più offerte, risponde STOP e non ne riceve mai più.

app2email invia solo alle persone che possono riceverlo. I numeri della sua lista Do Not Call vengono saltati e, con la regola dell'opt-in attiva, anche tutti quelli senza un record di opt-in. Riceve il risultato per ogni numero (accettato, consegnato, letto, risposto, non riuscito, saltato) come eventi webhook, dall'API, come file CSV e nella pagina del report del broadcast nell'Activity Log.

## Le regole per i messaggi di marketing

- **Solo a chi ha acconsentito.** WhatsApp e leggi come lo Spam Act 2003 australiano si aspettano il consenso prima che si inviino promozioni. app2email conserva le prove per Lei: il consenso su ogni contatto, i record di opt-in e la lista Do Not Call. `GET /compliance/export.csv` mette tutti e tre in un solo file.
- **Sempre un template.** Un broadcast avvia conversazioni, quindi deve essere un template approvato con la categoria MARKETING. Meta lo esamina prima.
- **Smettere è facile.** Un cliente che risponde STOP (o tocca "Stop promotions") viene messo subito nella lista Do Not Call e i template di marketing non gli vengono più inviati.
- **Il marketing costa di più.** Meta addebita ogni template di marketing consegnato, e il marketing è la categoria più costosa nella maggior parte dei paesi. Vedere [Quanto costa](#what-it-costs).
- **Le liste sbagliate danneggiano il numero.** Le persone che La bloccano o La segnalano abbassano la sua valutazione di qualità. Una valutazione bassa può mettere in pausa il suo template, mettere in pausa il suo broadcast e abbassare il suo limite di messaggistica. Vedere [Valutazione di qualità e limiti](#quality-rating-and-limits).

## Cosa serve

- Un numero WhatsApp collegato ad app2email, con un piano a pagamento e il servizio LIVE.
- Un metodo di pagamento sul suo WhatsApp Business Account presso Meta. Senza, gli invii di template falliscono con l'errore Meta 131042 (`403 whatsapp_payment_issue`).
- Una chiave API da https://www.app2email.com/dashboard/apikey con questi scope:

| Scope | A cosa serve in questa guida |
| --- | --- |
| `contacts:manage` | Importare contatti, registrare il consenso, salvare segmenti (`POST /contacts/import`, `POST /contacts/{identity}/consent`, `POST /segments`) |
| `settings:manage` | Attivare la regola dell'opt-in e registrare gli opt-in (`PUT /settings/optin`, `POST /optins`) |
| `dnc:manage` | La lista Do Not Call (`POST /donotcall`, `GET /donotcall`) e l'esportazione di conformità |
| `templates:manage` | Creare il template di marketing (`POST /templates`) |
| `messages:send` | Inviare il broadcast, annullarlo, inviare un follow-up (`POST /messages`, `POST /broadcasts/{code}/cancel`, `POST /broadcasts/{code}/retarget`) |
| `messages:read` | Stato del template, contatti del segmento, risultati del broadcast, clic, utilizzo, salute del numero |
| `webhooks:manage` | Aggiungere il webhook che riceve gli eventi (`POST /webhooks`) |

La chiave Default (creata prima che le chiavi avessero permessi) ha solo `messages:send`, `messages:read`, `dnc:manage` e `webhooks:manage`. Crei una chiave con gli scope qui sopra, oppure con accesso completo (`*`). `GET /v1/YOUR_NUMBER/me` mostra gli scope della chiave che ha.

<Info>
**Provare prima.** Una **chiave sandbox** sul suo numero (una chiave con l'opzione sandbox, nella pagina delle chiavi API) controlla ogni invio per davvero e non invia nulla a WhatsApp. La risposta ha `"sandbox": true`, gli id dei messaggi iniziano con `wamid.SANDBOX.` e gli eventi `message.status` arrivano comunque.

Attenzione: con una chiave sandbox, l'importazione di contatti, il salvataggio di segmenti, gli opt-in e la lista Do Not Call **modificano i suoi dati reali**. La creazione di template, `PUT /settings/optin` e il retargeting (tranne con `dry_run`) rispondono `403 sandbox_key`.

Senza alcun account, `POST https://api.app2email.com/v1/account/sandbox` (senza chiave, senza body), oppure lo strumento `create_sandbox` del server MCP di gestione, fornisce una **chiave sandbox istantanea** per il numero demo `12025550100`. Ha il template MARKETING `weekend_offer`, e il suo cliente fittizio `12025550104` risponde STOP: riceve `contact.opted_out`, e il successivo template di marketing a lui risponde `403 recipient_opted_out`. Quella chiave ha solo poche chiamate (`GET /templates`, `POST /messages`, `GET /events` e qualche altra), quindi le chiamate su contatti e broadcast di questa guida richiedono una chiave sul suo numero. Vedere [Sandbox](/api/sandbox).
</Info>

## Inviare un broadcast, passo dopo passo

<Steps>
  <Step title="Importi i suoi contatti con il loro consenso">
    Invii un file CSV con una riga di intestazione. Le colonne che app2email conosce sono `phone` (o `identity`, `number`, `mobile`), `name` (o `first_name` + `last_name`), `tags` (separati da `|`), `consent_marketing` (yes o no), `consent_source`, `consent_text`, `consent_evidence`, `consent_at` e `source`. Ogni altra colonna diventa un campo personalizzato. I numeri hanno prima il prefisso internazionale, solo cifre. Fino a 5000 righe per chiamata.

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

    **Cosa riceve in risposta:** quante righe sono state salvate e le righe saltate con il motivo. Le altre vengono salvate.

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

    La stessa chiamata accetta `application/json`: un elenco di contatti nel formato di `POST /contacts`. Quando qualcuno acconsente più tardi (un modulo web, una casella di controllo al checkout), lo registri sul contatto con la sua prova:

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

    Registri solo il consenso che ha davvero.
  </Step>

  <Step title="Registri gli opt-in e attivi la regola dell'opt-in">
    La **regola dell'opt-in** è un'impostazione del numero. Quando è attiva, i template MARKETING vanno solo ai numeri con un **record di opt-in**. Tutti gli altri vengono saltati con `recipient_not_opted_in`. I template utility e le risposte non sono interessati. Per impostazione predefinita è disattivata.

    I record di opt-in sono conservati separatamente dal consenso su un contatto, quindi registri qui anche ogni persona che ha acconsentito. Fino a 1000 per chiamata, tutto o niente.

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

    **Cosa riceve in risposta:** `{"success": true, "request_id": "o9ahv", "saved": 2}` per gli opt-in e `{"require_optin_for_marketing": true}` per l'impostazione. `GET /v1/YOUR_NUMBER/optins?number=61412345678` controlla un numero (`opted_in` è true o false).
  </Step>

  <Step title="Metta nella lista Do Not Call chi ha detto no">
    I template di marketing non vengono mai inviati a un numero nella lista Do Not Call, qualunque cosa dicano i record di opt-in. Chi risponde STOP viene aggiunto da app2email stessa. Aggiunga chi si è cancellato altrove (il suo negozio, la sua lista e-mail, una telefonata). Fino a 1000 numeri, tutto o niente.

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

    **Cosa riceve in risposta:** i numeri aggiunti (`added`), quelli già presenti (`already_on_list`) e quanti sono ora nella lista.

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

    `GET /v1/YOUR_NUMBER/donotcall?number=61400111222` controlla un numero (`on_list`). `DELETE /v1/YOUR_NUMBER/donotcall/61400111222` toglie un numero dalla lista: lo faccia solo quando la persona ha chiesto di ricevere di nuovo offerte.
  </Step>

  <Step title="Crei un template MARKETING">
    Scriva l'offerta con un segnaposto numerato per il nome, indichi un valore di esempio in `example` e aggiunga un piè di pagina che spiega come smettere. STOP e le sue traduzioni sono parole di opt-out che app2email conosce già.

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

    **Cosa riceve in risposta** (HTTP 201): il template è in revisione presso Meta.

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

    La revisione richiede da minuti a un giorno. L'evento `template.status_changed` Le comunica il risultato (`status` APPROVED con `can_send: true`, oppure REJECTED con un `reason`), oppure lo chieda con `GET /v1/YOUR_NUMBER/templates/winter_sale`. Il suo `example_request` è un invio completo che può copiare, e `quality_score` (GREEN, YELLOW o RED) mostra in seguito come reagiscono le persone. Per tutta la storia della revisione vedere [Inviare notifiche di ordini e appuntamenti con i template](/guides/how-to-order-notifications).

    I template appartengono al WhatsApp Business Account: ogni numero di quell'account può usarli.
  </Step>

  <Step title="Scelga il pubblico con un segmento">
    Un segmento è un filtro salvato sui suoi contatti. Ogni condizione deve essere soddisfatta: `tags_any`, `tags_all`, `consent_marketing`, `last_inbound_days` (ha scritto a Lei negli ultimi N giorni) e `search`. Fino a 100 segmenti.

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

    **Cosa riceve in risposta** (HTTP 201): il segmento, con quanti contatti corrispondono ora.

    ```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` elenca i contatti che corrispondono, pagina per pagina (`next_cursor`). Il segmento è un filtro, non una copia: un contatto che ritira il consenso ne esce.
  </Step>

  <Step title="Invii il broadcast">
    `recipients` dà a ogni numero i suoi valori: qui il nome dall'importazione. Invii una richiesta per ogni lotto di fino a `max_numbers_per_request` numeri (in `GET /usage` e `GET /me`; il limite del broadcast, fino a 1000).

    - `"background": true` risponde non appena tutto è stato controllato e invia dopo.
    - `campaign_name` è il nome del broadcast nell'Activity Log sotto Broadcasts.
    - L'header `Idempotency-Key` appartiene al lotto: se il suo processo viene eseguito due volte entro 24 ore, il lotto non viene inviato di nuovo.

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

    **Cosa riceve in risposta** (HTTP 202): i controlli sono stati superati e l'invio è iniziato. Conservi `broadcast.code`: ogni chiamata successiva su questo broadcast lo usa.

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

    Ogni numero viene controllato prima che venga inviato qualcosa. I numeri nella lista Do Not Call e (con la regola dell'opt-in attiva) i numeri senza un record di opt-in vengono saltati e conteggiati, non inviati.

    <Tip>
    **Prima una prova.** Aggiunga `"dry_run": true` allo stesso body. Tutto viene controllato come per un invio reale (valori del template, numeri, lista Do Not Call, regola dell'opt-in, limite mensile) e la risposta mostra l'esatto messaggio WhatsApp per ogni numero. Nulla viene inviato, registrato o conteggiato, e l'`Idempotency-Key` viene ignorato.
    </Tip>

    <Tip>
    **Direttamente al segmento.** `"segment": "Newsletter, consented"` (il suo id o il nome esatto) al posto di `recipients` invia a ogni contatto del segmento in una sola chiamata. I valori vengono presi da ogni contatto per un template con segnaposto **con nome** (`{{first_name}}`, creato con `"parameter_format": "NAMED"`): un parametro con un `parameter_name` e senza `text` viene compilato dai `custom_fields` del contatto (`name` dal nome del contatto).

    ```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="Facoltativo: lo programmi per più tardi">
    Aggiunga `send_at` (ISO 8601 con fuso orario, da 1 minuto a 29 giorni in anticipo) allo stesso body. La mattina nel fuso orario dei suoi clienti di solito funziona meglio che nel cuore della notte.

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

    La risposta è HTTP 202 con `status: "scheduled"`, `scheduled_for` (UTC), `scheduled` (quanti messaggi) e il `code` del broadcast. Tutto viene controllato subito, e la lista Do Not Call e il limite mensile vengono ricontrollati quando arriva il momento, quindi chi nel frattempo dice STOP non lo riceve.
  </Step>

  <Step title="Segua l'avanzamento e ottenga il risultato per ogni numero">
    `GET /v1/YOUR_NUMBER/broadcasts/{code}` è aggiornato in tempo reale mentre il broadcast viene inviato.

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

    **Cosa riceve in risposta:** il broadcast, i suoi conteggi e un risultato per ogni numero. `status` è `scheduled`, `inprogress`, `completed`, `cancelled`, `missed`, `interrupted`, `pending` o `unknown`. Ogni risultato è il messaggio (con `status`, `times` e la `reply` del cliente), oppure `skipped`, `not_sent` o `pending` con un `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` ha una riga per messaggio: il numero, lo stato, `message_id`, l'orario di ogni passaggio, la risposta e l'errore (più `clicks` e `first_click_at` quando i link erano tracciati). I valori che iniziano con `=`, `+`, `-` o `@` ricevono un `'` davanti, così un foglio di calcolo non li esegue come formule. `GET /v1/YOUR_NUMBER/broadcasts` elenca i suoi ultimi broadcast, dal più recente.
  </Step>

  <Step title="Lo annulli se serve">
    Prezzo sbagliato nell'offerta? `POST /v1/YOUR_NUMBER/broadcasts/{code}/cancel` (scope `messages:send`) ferma un broadcast API programmato o ancora in invio.

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

    **Cosa riceve in risposta:** HTTP 200 per un broadcast programmato (nulla è stato inviato), oppure HTTP 202 per uno in invio: i messaggi già consegnati a WhatsApp restano inviati, gli altri non vengono inviati.

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

    Segue un evento `broadcast.completed` con `status: "cancelled"`. I broadcast terminati e quelli avviati dalla dashboard rispondono `409 broadcast_not_cancellable`.
  </Step>

  <Step title="Ricontatti chi ha risposto o cliccato">
    **Un broadcast API:** costruisca Lei stesso la lista successiva a partire dal risultato. Ogni risultato in `GET /broadcasts/{code}` ha lo `status` del messaggio e la `reply` del cliente, quindi può scegliere, per esempio, tutti quelli che hanno letto l'offerta e non hanno risposto, e inviare loro un secondo template con `POST /messages` come sopra.

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

    **Un broadcast avviato dalla pagina Broadcast della dashboard** offre altre due cose che l'API può usare:

    - **Link tracciati.** Con Track clicks attivo (l'impostazione predefinita lì), ogni destinatario riceve il proprio link breve `https://www.app2email.com/l/<code>` per un link nei valori del broadcast. `GET /broadcasts/{code}/clicks` fornisce il totale, i clic unici, il tasso di clic e i clic di ogni destinatario (le anteprime dei link e i crawler non vengono conteggiati). Gli stessi dati sono in `clicks` di `GET /broadcasts/{code}`, e per ogni clic arriva un evento `link.clicked`.
    - **Retargeting in una sola chiamata.** `POST /broadcasts/{code}/retarget` crea un nuovo broadcast con lo stesso template, gli stessi valori e gli stessi media, per un solo `audience`: `not_read`, `read_not_clicked`, `clicked`, `replied` (ha risposto entro 7 giorni dall'invio) o `not_replied`. Prima conti con `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>

    **Cosa riceve in risposta:** con `dry_run`, il conteggio (HTTP 200). Senza, HTTP 202 e il nuovo broadcast, che viene inviato in background.

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

    La lista Do Not Call e il limite del piano vengono ricontrollati, e valgono il limite di approvazione e il tetto giornaliero della chiave. Retarget, resume e retry funzionano solo sui broadcast della dashboard: una lista API risponde `403 broadcast_not_resumable`.

    Un follow-up è un altro messaggio di marketing, fatturato di nuovo. Lo invii a un gruppo piccolo e interessato (`clicked`, `replied`), non a tutti quelli che hanno ignorato il primo.
  </Step>
</Steps>

## Il risultato

Il cliente vede un messaggio con il nome della sua attività con l'offerta, il suo nome al suo interno e il piè di pagina "Reply STOP to opt out". Se risponde, si apre la finestra di 24 ore e Lei può rispondere con testo libero dall'API o per e-mail.

Dal suo lato arrivano questi eventi (aggiunga un webhook con `POST /v1/YOUR_NUMBER/webhooks` e un `url` https pubblico; scope `webhooks:manage`). Non ha ancora un indirizzo pubblico? `GET /v1/YOUR_NUMBER/events?wait=25` fornisce gli stessi eventi.

**`message.status`** per ogni messaggio, man mano che avanza: `sent`, `delivered`, `read` o `failed`. `broadcast_code` indica a quale broadcast appartiene e `pricing.category` come l'ha conteggiato Meta.

```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`** quando un messaggio non è stato possibile consegnarlo. Uno che vedrà con il marketing è l'errore Meta 131049: WhatsApp ha trattenuto il messaggio perché la persona ha ricevuto di recente molti messaggi di marketing. Non lo invii di nuovo entro 24 ore; riprovare prima prolunga il blocco.

```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`** quando un cliente risponde: `text` per una risposta scritta, `button` per un pulsante toccato.

**`contact.opted_out`** quando un cliente si è messo nella lista Do Not Call. `source` è `stop_promotions` (ha toccato "Stop promotions"), `whatsapp_stop` o `keyword` (ha inviato una parola di opt-out).

```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`** per ogni clic su un link tracciato (broadcast della dashboard). `first_click` è true per il primo clic sul link di quel destinatario.

```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`** una volta per broadcast, quando è terminato, è stato annullato o ha perso l'orario programmato.

```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=` somma i conteggi e i tassi di inviati, consegnati, letti, non riusciti e risposti per un periodo, su tutti i broadcast.

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

## Quanto costa

Due fatture:

- **app2email:** un piano mensile fisso. Ogni messaggio del broadcast conta come un messaggio del piano, senza alcun ricarico per messaggio ([prezzi](https://www.app2email.com/pricing)). Quando i messaggi del piano finiscono, i restanti vengono saltati (`skipped_monthly_limit`) o rispondono `429 monthly_limit_reached`.
- **Meta:** addebita ogni template consegnato direttamente sul metodo di pagamento del suo WhatsApp Business Account. Il prezzo dipende dalla categoria e dal paese del cliente, e **il marketing è la categoria più costosa**. Un broadcast a 10.000 numeri è un costo reale, quindi scriva a chi lo vuole, non a tutti quelli che ha.

Ne faccia una stima prima di inviare con il [calcolatore dei prezzi WhatsApp](https://www.app2email.com/tools/whatsapp-pricing-calculator). Dopo, `meta_pricing` in `GET /v1/YOUR_NUMBER/usage` conta i messaggi del mese di fatturazione per categoria di Meta con un costo indicativo, e `GET /v1/YOUR_NUMBER/usage/meta` lo fornisce per giorno.

<Note>
Una volta che Meta ha integrato il suo account nella Marketing Messages API, i template di marketing passano di là per impostazione predefinita (l'impostazione del numero `messages.marketing_route`, `auto`). `GET /v1/YOUR_NUMBER/marketing` mostra il percorso, e `sent_via` nella risposta all'invio indica da che parte è passato un messaggio. La sua richiesta non cambia.
</Note>

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

## Valutazione di qualità e limiti

WhatsApp osserva come reagiscono le persone ai suoi messaggi. Molti blocchi e segnalazioni abbassano la sua **valutazione di qualità**. Allora:

- il `quality_score` del template (in `GET /templates/{name}`) diventa YELLOW, poi RED, e un template RED può essere messo in pausa (`422 template_paused`, errore Meta 132015);
- il **limite di messaggistica** del suo numero (con quante persone può avviare conversazioni in 24 ore) smette di crescere o diminuisce;
- WhatsApp può rallentare il suo broadcast. Un broadcast della dashboard si mette allora in pausa da solo (stato `paused_by_meta`, con il motivo in `status_notes`); corregga la causa e `POST /broadcasts/{code}/resume` prosegue.

`GET /v1/YOUR_NUMBER/health` (scope `messages:read`) mostra il `quality_rating` e il `messaging_limit` del numero:

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

Come mantenerla verde:

- Scriva solo a chi ha dato l'opt-in e tenga aggiornata la lista Do Not Call.
- Controlli la valutazione prima di un grande broadcast. Se la sua lista è più grande del suo limite di messaggistica, la invii in più parti nell'arco di alcuni giorni.
- Parta dai contatti più coinvolti (`last_inbound_days` nel filtro del segmento) e osservi letture e opt-out sulla prima parte prima di inviare il resto.
- Faccia un'offerta che valga la pena di leggere, dica chi è e mantenga la riga STOP nel piè di pagina.
- Non invii marketing alla stessa persona ogni giorno. La stessa WhatsApp trattiene i messaggi alle persone che ne ricevono troppi (131049).

## Checklist per la produzione

<AccordionGroup>
  <Accordion title="Controlli la firma del webhook">
    Ogni evento ha l'header `X-App2email-Signature: t=<unix seconds>,v1=<hex>`. Il valore `v1` è l'HMAC-SHA256 di `"<t>.<raw body>"`, con il segreto del webhook (`whsec_...`, prefisso incluso) come chiave. Controlli ogni `v1=` (ce ne sono due finché un vecchio segreto viene ancora conservato dopo una rotazione), lo calcoli sul body grezzo esattamente come ricevuto e rifiuti un `t` vecchio. È presente anche `X-Hub-Signature-256: sha256=<hex>` (HMAC-SHA256 del body grezzo, solo con il segreto corrente), per il codice scritto per i webhook di 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="Scarti gli eventi ripetuti e fuori ordine">
    Risponda con uno stato 2xx entro 10 secondi. In caso contrario l'evento viene inviato di nuovo dopo 10 s, 1 min, 5 min, 30 min, 1, 2, 4, 8 e 16 ore. `X-App2email-Delivery` (l'`id` dell'evento, `evt_...`) è lo stesso a ogni nuovo tentativo, quindi lo memorizzi e salti un evento che ha già gestito.

    Gli eventi possono arrivare fuori ordine: un `read` può arrivare prima del suo `delivered`. Conservi lo stato più avanzato per ogni `message_id` e non lo riporti indietro. Per un broadcast, identifichi i suoi record con `broadcast_code` e `to`.
  </Accordion>

  <Accordion title="Non invii mai due volte lo stesso broadcast">
    Dia a ogni lotto un `Idempotency-Key` che appartiene alla campagna e al lotto, non al tentativo: `winter-sale-2026-batch-0`, `winter-sale-2026-batch-1`. La stessa richiesta con la stessa chiave entro 24 ore non viene inviata di nuovo; riceve la prima risposta, con l'header `Idempotent-Replayed: true`.

    - Stessa chiave con un body diverso: `422 idempotency_key_reused`. Mantenga i lotti nello stesso ordine, oppure usi nuove chiavi per una nuova lista.
    - Prima richiesta ancora in esecuzione: `409 idempotency_request_in_progress`. Attenda e riprovi con la stessa chiave.
    - La prima richiesta non si è conclusa entro 15 minuti: `409 idempotency_request_interrupted`. Alcuni messaggi potrebbero essere partiti: controlli `GET /broadcasts` prima di inviare con una nuova chiave.
    - Una richiesta rifiutata prima che venisse inviato qualcosa lascia libera la chiave, quindi una richiesta corretta può usarla.

    La chiave viene conservata per 24 ore. Conservi anche il `broadcast.code` di ogni lotto nel suo database e non invii un lotto che ne ha già uno.
  </Accordion>

  <Accordion title="Rate limit e nuovi tentativi">
    Invii una lista con una chiamata per lotto, non una chiamata per numero. Ogni risposta ha `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (secondi prima di tornare pieno) e `X-RateLimit-Policy`; `limits` in `GET /me` mostra `requests_per_second` e `burst` della chiave. Oltre il limite riceve `429 rate_limited` con un header `Retry-After` e `error.retry_after_seconds`: attenda quel tempo, poi invii di nuovo la stessa richiesta.

    - `500`, `502`, `503` o un timeout: riprovi alcune volte con attese crescenti, con lo stesso `Idempotency-Key`.
    - `429 whatsapp_rate_limit` o `429 too_many_messages_to_recipient`: limite proprio di WhatsApp. Rallenti per minuti, non per secondi.
    - `429 monthly_limit_reached`, `429 monthly_cap_reached` o `429 daily_cap_reached`: un limite del piano, del numero o della chiave. Non riprovi finché non si azzera, oppure lo aumenti.
    - Qualsiasi altro `4xx`: non riprovi senza modifiche. Decida in base a `error.code` e segua `how_to_fix`. `error.is_retriable` dice se la stessa richiesta può funzionare più tardi.
  </Accordion>

  <Accordion title="Soglia di approvazione e tetti sulla chiave">
    Una chiave può avere un tetto giornaliero e una soglia di approvazione (`GET /me` li mostra). Un invio a più contatti di quanti la soglia consenta risponde HTTP 202 con `status: "pending_approval"` e `approval.url`: non è un errore. Una persona lo approva nella dashboard, segue l'evento `approval.resolved` e i messaggi escono. Nel frattempo non invii la stessa lista in un altro modo. È una buona rete di sicurezza per una chiave che invia marketing.
  </Accordion>

  <Accordion title="Opt-out, consenso e lista Do Not Call">
    - I clienti che rispondono STOP (o le sue traduzioni) o toccano "Stop promotions" finiscono da soli nella lista Do Not Call, e `contact.opted_out` Le segnala l'evento. Aggiunga le sue parole di opt-out con `PUT /v1/YOUR_NUMBER/settings/number` e `{"compliance": {"stop_keywords_extra": ["UNSUBSCRIBE"]}}` (scope `settings:manage`).
    - Quando qualcuno ritira il consenso, lo registri anche sul contatto (`POST /contacts/{identity}/consent` con `"marketing": false`), così i segmenti con `consent_marketing: true` lo escludono, e lo metta nella lista Do Not Call se si è cancellato altrove.
    - Un cliente può anche disattivare il marketing da parte sua all'interno di WhatsApp: gli invii verso di lui rispondono `403 recipient_stopped_marketing` (errore Meta 131050). Se lo riattiva, arriva `contact.updated` con `change: "marketing_resumed"`.
    - La lista Do Not Call e la regola dell'opt-in si applicano solo ai template MARKETING. Gli aggiornamenti sugli ordini e gli altri template utility escono comunque, così come le sue risposte a chi Le ha scritto.
    - `GET /v1/YOUR_NUMBER/compliance/export.csv` (scope `dnc:manage`) fornisce i record di consenso, la lista Do Not Call e gli opt-in come un unico file, i record che lo Spam Act 2003 si aspetta che Lei sappia mostrare.
  </Accordion>

  <Accordion title="La finestra di 24 ore">
    Un broadcast è un template, quindi può uscire in qualsiasi momento. Quando un cliente risponde, si apre la finestra di 24 ore e può rispondere con testo normale, immagini o pulsanti (app2email si ferma 15 minuti prima). `GET /v1/YOUR_NUMBER/conversations/61412345678` mostra `window_state` e `window_closes_at`. Se il suo ultimo messaggio era l'opt-out stesso, una risposta dà `403 recipient_opted_out` finché non scrive di nuovo.
  </Accordion>
</AccordionGroup>

## Se non funziona

Ogni errore è un JSON con `error.code`, `message`, `how_to_fix` e un `request_id` da citare all'assistenza. Vedere [Errori](/api/errors) per tutti i codici e [Limiti](/api/limits) per i limiti.

| Codice | Quando | Cosa fare |
| --- | --- | --- |
| `403 insufficient_scope` | Alla chiave manca uno scope (`details.required_scope`) | Usi una chiave con gli scope della tabella qui sopra |
| `403 sandbox_key` | Un template, `PUT /settings/optin` o un retarget con una chiave sandbox | Usi una chiave normale per quelle chiamate |
| `400 invalid_csv` | Il CSV non ha riga di intestazione o non ha righe di contatti | Invii una riga di intestazione e almeno una riga, fino a 5000 righe |
| `400 invalid_template_category` | `category` non è MARKETING, UTILITY o AUTHENTICATION | Usi `MARKETING` per le promozioni |
| `422 template_not_approved` | Il template è in attesa, rifiutato, in pausa o disabilitato | Attenda l'approvazione, oppure lo corregga; controlli `GET /templates/{name}` |
| `422 template_parameters_invalid` | I valori non corrispondono al template | Corregga il body in base a `details.problems` e `example_request` |
| `422 template_paused` | Errore Meta 132015: in pausa per bassa qualità | Usi un altro template, oppure modifichi questo; invii a meno persone, più mirate |
| `400 too_many_recipients` | Più numeri di quanti il numero possa inviarne in una richiesta | Divida in lotti di `details.max_recipients` |
| `400 to_and_recipients` | Sia `to` sia `recipients` | Ne usi uno solo |
| `400 segment_and_recipients` | `segment` insieme a `to`, `recipient` o `recipients` | Usi solo `segment` |
| `400 segment_empty` | Il segmento non corrisponde ad alcun contatto | Controlli `GET /segments/{id}/contacts`, aggiunga contatti o cambi il filtro |
| `404 segment_not_found` | Nessun segmento con quell'id o nome | `GET /segments` li elenca; usi l'id o il nome esatto |
| `403 recipient_opted_out` | Un solo numero, ed è nella lista Do Not Call | Non gli invii marketing; in una lista viene saltato |
| `403 recipient_not_opted_in` | Un solo numero, la regola dell'opt-in è attiva e non ha un record di opt-in | Prima registri il suo consenso con `POST /optins`; in una lista viene saltato |
| `403 recipient_stopped_marketing` | Errore Meta 131050: ha disattivato il suo marketing in WhatsApp | Non gli invii template di marketing |
| `422 marketing_per_user_limit` | Errore Meta 131049: ha ricevuto di recente molti messaggi di marketing | Non reinvii entro 24 ore |
| `403 messaging_limit_restricted` | Errore Meta 131064: Meta ha abbassato il limite di messaggistica per categorie di template errate | Controlli le categorie dei suoi template; il limite torna dopo il periodo di Meta |
| `403 whatsapp_payment_issue` | Errore Meta 131042: Meta non ha potuto addebitare il suo account WhatsApp | Aggiunga o corregga il metodo di pagamento in WhatsApp Manager |
| `400 send_at_too_far` | `send_at` è oltre 29 giorni in avanti | Usi un orario da 1 minuto a 29 giorni da adesso, con un fuso orario |
| `422 idempotency_key_reused` | Stesso `Idempotency-Key`, body diverso | Usi una nuova chiave per una lista diversa |
| `429 rate_limited` | Troppe chiamate per questa chiave | Attenda `Retry-After` secondi, poi riprovi |
| `429 whatsapp_rate_limit` | Rate limit di WhatsApp (Meta 130429, 131048 e altri) | Rallenti e riprovi tra un minuto o più |
| `429 monthly_limit_reached` | I messaggi del piano sono esauriti questo mese | Attenda il prossimo mese di fatturazione, oppure faccia l'upgrade |
| `429 daily_cap_reached` | Il tetto giornaliero della chiave | Attenda la mezzanotte UTC, oppure aumenti il tetto |
| `409 broadcast_not_cancellable` | Il broadcast è terminato, già annullato, o è stato avviato dalla dashboard | Si possono annullare solo gli invii API programmati o ancora in corso |
| `403 broadcast_not_resumable` | Retarget, resume o retry su una lista API | Per una lista API, invii di nuovo i numeri che desidera con `POST /messages` |
| `400 invalid_retarget_audience` | `audience` non è uno dei cinque valori | Usi `not_read`, `read_not_clicked`, `clicked`, `replied` o `not_replied` |
| `409 broadcast_nothing_to_send` | Nessuno è rimasto in quel pubblico | Non c'è nulla da fare |
| `403 campaign_approval_needed` | Un retarget invierebbe più del limite di approvazione della chiave | Lo avvii dalla dashboard, oppure usi una chiave senza limite di approvazione |

## Altre guide pratiche

<CardGroup cols={2}>
  <Card title="Creare un chatbot WhatsApp con l'API" href="/guides/how-to-whatsapp-chatbot">
    Riceva i messaggi tramite webhook e risponda con testo, pulsanti ed elenchi.
  </Card>
  <Card title="Inviare notifiche di ordini e appuntamenti con i template" href="/guides/how-to-order-notifications">
    Un template utility per ogni ordine o prenotazione, con stato di consegna e di lettura.
  </Card>
  <Card title="Lasci che un agente AI gestisca il suo WhatsApp con MCP" href="/guides/how-to-ai-agent-mcp">
    Colleghi un agente al server MCP e lo lasci leggere e inviare messaggi.
  </Card>
  <Card title="Passare una chat dal suo bot a una persona e viceversa" href="/guides/how-to-human-handoff">
    Imposti il responsabile della conversazione perché il suo bot si faccia da parte mentre risponde una persona.
  </Card>
  <Card title="Chiedere un pagamento all'interno di una chat WhatsApp" href="/guides/how-to-payment-links">
    Invii una richiesta di pagamento nella chat e riceva un evento quando viene pagata.
  </Card>
</CardGroup>

[Tutte le guide pratiche](https://www.app2email.com/docs#how-to)
