# Invii il suo primo messaggio WhatsApp in 5 minuti

> Provi l'API WhatsApp di app2email con una chiave sandbox istantanea e senza account, poi colleghi il suo numero, invii il primo template, segua il suo stato e legga la risposta.

Questa guida la porta da zero a un messaggio WhatsApp e alla sua risposta, in due parti.

**Parte 1, la sandbox istantanea (circa 2 minuti, senza account):** ottiene una chiave per un numero demo, invia un template a un cliente fittizio, vede il messaggio passare da inviato a letto e legge la risposta del cliente. Nulla arriva su WhatsApp, ma ogni richiesta e ogni risposta hanno la forma dell'API reale, quindi lo stesso codice funzionerà anche più avanti.

**Parte 2, il suo numero:** si registra, collega il suo numero WhatsApp, crea una chiave API e invia lo stesso tipo di messaggio a un telefono reale.

**Cosa vede il cliente** (Parte 2): un messaggio WhatsApp con il nome della sua attività, per esempio "Ciao Ava, il tuo ordine #1234 è stato spedito." Quando il cliente risponde, Lei può rispondere con un normale testo per le 24 ore successive.

**Cosa vede Lei:** la risposta all'invio con un `message_id`, lo stato di quel messaggio (`sent`, `delivered`, `read`), la risposta del cliente come evento `message.received` e ogni messaggio nell'Activity Log e nell'Inbox di app2email.

## Cosa serve

- Per la Parte 1: un terminale con `curl`, oppure Node.js 18+, oppure Python 3.9+ con `requests`. Nient'altro.
- Per la Parte 2: un numero WhatsApp che può collegare (uno che non sia in uso nell'app WhatsApp, oppure che Lei trasferisce), un piano app2email a pagamento e una chiave API con gli scope qui sotto.

| Scope | A cosa serve in questa guida |
| --- | --- |
| `messages:send` | Inviare il template e la risposta (`POST /messages`) |
| `messages:read` | Elencare i template (`GET /templates`), leggere lo stato di un messaggio (`GET /messages/{message_id}`) e ottenere gli eventi (`GET /events`) |
| `webhooks:manage` | Solo se vuole che gli eventi vengano inviati al suo server (`POST /webhooks`) |

`GET /me` funziona con qualsiasi chiave valida, qualunque siano i suoi scope.

## Parte 1: la sandbox istantanea

La sandbox istantanea è un numero WhatsApp demo, `12025550100`, con cinque clienti fittizi che reagiscono come quelli reali. Per iniziare non servono né un account né una chiave.

Cosa offre:

- **Una chiave subito.** `POST https://api.app2email.com/v1/account/sandbox`, senza chiave e senza body, risponde con una chiave sandbox istantanea (`a2es_...`). Viene mostrata una sola volta ed è valida per **7 giorni**. Funziona solo sul numero demo.
- **Il suo stato personale.** Nessun altro vede i suoi messaggi. Ciò che invia resta in memoria per 24 ore dopo la sua ultima chiamata.
- **Clienti fittizi.** Sono gli unici numeri a cui la sandbox scrive. Qualsiasi altro numero risponde 422 `sandbox_recipient`.
- **Tre template:** `hello_world` (`en_US`, UTILITY), `order_update` (`en`, UTILITY) e `weekend_offer` (`en`, MARKETING). Vengono controllati dallo stesso codice dei template reali.
- **Queste chiamate:** `GET /me`, `GET /templates`, `POST /messages`, `GET /messages`, `GET /conversations`, `GET /conversations/{contact}`, `PUT /conversations/{contact}/owner`, `GET /events` e `POST /sandbox/inbound` (fa scrivere a Lei un cliente fittizio). Qualsiasi altra chiamata risponde 403 `not_in_instant_sandbox`.
- **Limiti:** 10 chiavi all'ora da uno stesso indirizzo. Niente webhook, caricamenti di media, contatti, broadcast in background o invii programmati: servono a un numero collegato. Gli eventi si ottengono con `GET /events` invece che con un webhook.

<Steps>
  <Step title="Ottenga una chiave sandbox istantanea">
    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/account/sandbox
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/account/sandbox", { method: "POST" });
    const { instant_sandbox } = await res.json();
    console.log(instant_sandbox.api_key, instant_sandbox.expires);
    ```

    ```python Python
    import requests

    res = requests.post("https://api.app2email.com/v1/account/sandbox", timeout=10)
    sandbox = res.json()["instant_sandbox"]
    print(sandbox["api_key"], sandbox["expires"])
    ```

    </CodeGroup>

    **Cosa riceve in risposta** (abbreviato: la risposta elenca anche le chiamate disponibili e le prime da fare, in `calls` e `try_first`):

    ```json
    {
      "success": true,
      "request_id": "s4ndb",
      "instant_sandbox": {
        "api_key": "a2es_000qlA9iTHS1NETB9JExample...",
        "expires": "2026-11-22T03:00:00.000Z",
        "number": "12025550100",
        "base_url": "https://api.app2email.com/v1/12025550100",
        "mcp_url": "https://api.app2email.com/mcp",
        "authorization": "Authorization: Bearer <api_key>",
        "test_contacts": [
          { "number": "12025550101", "name": "Ava", "behaviour": "answers every message a few seconds later" },
          { "number": "12025550102", "name": "Ben", "behaviour": "reads, never answers: a free-form message to him is 422 outside_24h_window" },
          { "number": "12025550103", "name": "Cara", "behaviour": "delivery fails: message.status failed and message.failed" },
          { "number": "12025550104", "name": "Dan", "behaviour": "answers STOP: contact.opted_out, then a marketing template to him is 403 recipient_opted_out" },
          { "number": "12025550105", "name": "Eve", "behaviour": "asks for a person: set the conversation's owner to human" }
        ],
        "templates": ["hello_world (en_US, UTILITY)", "order_update (en, UTILITY)", "weekend_offer (en, MARKETING)"],
        "not_here": "Webhooks (use GET /events), media uploads, contacts, broadcasts in the background, scheduled sends and every other call need a connected number: they answer 403 not_in_instant_sandbox here."
      },
      "next": "For a real WhatsApp number call create_account with the person's e-mail address: they confirm, connect their number and choose a plan.",
      "documentation_url": "https://www.app2email.com/docs/api/sandbox"
    }
    ```

    Conservi `api_key`: non viene mostrata di nuovo. Se la perde, ne ottenga una nuova. Più avanti, `SANDBOX_KEY` sta per questa chiave. Un rapido controllo per verificare che funzioni: `GET https://api.app2email.com/v1/12025550100/me` con `Authorization: Bearer SANDBOX_KEY`.
  </Step>
  <Step title="Veda cosa richiede il template">
    `GET /templates` elenca ogni template con i valori che richiede e un `example_request` completo che può inviare dopo aver cambiato i valori.

    <CodeGroup>

    ```bash cURL
    curl https://api.app2email.com/v1/12025550100/templates \
      -H "Authorization: Bearer SANDBOX_KEY"
    ```

    ```javascript Node.js
    const KEY = process.env.SANDBOX_KEY;
    const API = "https://api.app2email.com/v1/12025550100";

    const res = await fetch(`${API}/templates`, { headers: { Authorization: `Bearer ${KEY}` } });
    const { templates } = await res.json();
    for (const t of templates) console.log(t.name, t.language, t.status, t.needs);
    ```

    ```python Python
    import os, requests

    KEY = os.environ["SANDBOX_KEY"]
    API = "https://api.app2email.com/v1/12025550100"

    res = requests.get(f"{API}/templates", headers={"Authorization": f"Bearer {KEY}"}, timeout=10)
    for t in res.json()["templates"]:
        print(t["name"], t["language"], t["status"], t.get("needs"))
    ```

    </CodeGroup>

    Ogni voce ha `name`, `language`, `category`, `status`, `can_send`, `needs` e, per i template approvati, `example_request`. `order_update` richiede due valori di testo nel corpo: il nome del cliente e un numero d'ordine.
  </Step>
  <Step title="Invii un template ad Ava">
    Ava (`12025550101`) risponde a ogni messaggio pochi secondi dopo. Un template è il messaggio che può inviare in qualsiasi momento, anche a chi non Le ha ancora scritto.

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/12025550100/messages \
      -H "Authorization: Bearer SANDBOX_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "to": "12025550101",
        "type": "template",
        "template": {
          "name": "order_update",
          "language": { "code": "en" },
          "components": [
            { "type": "body", "parameters": [
              { "type": "text", "text": "Ava" },
              { "type": "text", "text": "#1234" }
            ] }
          ]
        }
      }'
    ```

    ```javascript Node.js
    const res = await fetch(`${API}/messages`, {
      method: "POST",
      headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        to: "12025550101",
        type: "template",
        template: {
          name: "order_update",
          language: { code: "en" },
          components: [
            { type: "body", parameters: [{ type: "text", text: "Ava" }, { type: "text", text: "#1234" }] },
          ],
        },
      }),
    });
    const sent = await res.json();
    console.log(res.status, sent.message_id, sent.status);
    ```

    ```python Python
    res = requests.post(
        f"{API}/messages",
        headers={"Authorization": f"Bearer {KEY}"},
        json={
            "to": "12025550101",
            "type": "template",
            "template": {
                "name": "order_update",
                "language": {"code": "en"},
                "components": [
                    {"type": "body", "parameters": [{"type": "text", "text": "Ava"}, {"type": "text", "text": "#1234"}]}
                ],
            },
        },
        timeout=10,
    )
    sent = res.json()
    print(res.status_code, sent.get("message_id"), sent.get("status"))
    ```

    </CodeGroup>

    **Cosa riceve in risposta** (HTTP 200, abbreviato): il messaggio è stato accettato. `text` è il messaggio così come lo vede il cliente.

    ```json
    {
      "success": true,
      "request_id": "kxrkf",
      "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
      "status": "accepted",
      "from": "12025550100",
      "to": "12025550101",
      "template": { "name": "order_update", "language": "en", "category": "UTILITY" },
      "text": "Hi Ava, your order #1234 has shipped."
    }
    ```

    Un valore errato torna come errore con un `error.code` stabile, un `how_to_fix` e, per gli errori di template, un `example_request` corretto e completo. Provi: ometta un parametro e otterrà 422 `template_parameters_invalid`.
  </Step>
  <Step title="Segua lo stato e legga la risposta di Ava">
    `GET /events?wait=25` attende fino a 25 secondi il prossimo evento, quindi non serve alcun indirizzo pubblico. Riceve `message.status` con `sent`, `delivered` e `read`, poi `message.received` con la risposta di Ava.

    <CodeGroup>

    ```bash cURL
    curl "https://api.app2email.com/v1/12025550100/events?wait=25" \
      -H "Authorization: Bearer SANDBOX_KEY"
    ```

    ```javascript Node.js
    let after = "";
    for (let i = 0; i < 5; i++) {
      const q = after ? `&after=${encodeURIComponent(after)}` : "";
      const res = await fetch(`${API}/events?wait=25${q}`, { headers: { Authorization: `Bearer ${KEY}` } });
      const page = await res.json();
      for (const e of page.events ?? []) console.log(e.type, e.data.status ?? e.data.text);
      after = page.cursor ?? after;
    }
    ```

    ```python Python
    after = ""
    for _ in range(5):
        params = {"wait": 25, **({"after": after} if after else {})}
        page = requests.get(f"{API}/events", params=params,
                            headers={"Authorization": f"Bearer {KEY}"}, timeout=40).json()
        for e in page.get("events", []):
            print(e["type"], e["data"].get("status") or e["data"].get("text"))
        after = page.get("cursor", after)
    ```

    </CodeGroup>

    **Cosa riceve in risposta** (abbreviato; le parole di Ava variano):

    ```json
    {
      "success": true,
      "request_id": "e7fd2",
      "events": [
        {
          "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
          "type": "message.status",
          "created": "2026-11-15T03:10:02.000Z",
          "number": "12025550100",
          "data": {
            "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
            "to": "12025550101",
            "status": "delivered",
            "timestamp": "2026-11-15T03:10:01.000Z",
            "sent_by": "api"
          }
        },
        {
          "id": "evt_Ab7c2d9Ef4Gh6Jk8Lm03",
          "type": "message.received",
          "created": "2026-11-15T03:10:09.000Z",
          "number": "12025550100",
          "data": {
            "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgASGBQzQUZCMTY0MDc2MUYwNzBDNTY5MAA=",
            "from": "12025550101",
            "name": "Ava",
            "type": "text",
            "text": "Thanks! When will it arrive?",
            "timestamp": "2026-11-15T03:10:08.000Z"
          }
        }
      ],
      "count": 2,
      "cursor": "ec_184467",
      "has_more": false
    }
    ```

    Passi `cursor` come `after` alla chiamata successiva per ottenere solo gli eventi più recenti. Ogni evento è lo stesso JSON che un webhook riceverà in seguito, con lo stesso `id`. `types=message.received` restituisce solo i messaggi in arrivo. Anche `GET /messages` elenca i messaggi, ciascuno di quelli inviati con il suo `status` e i suoi `times`.
  </Step>
  <Step title="Risponda con un testo normale">
    Ava ha appena scritto, quindi la sua finestra di 24 ore è aperta e può inviare testo libero:

    ```bash
    curl -X POST https://api.app2email.com/v1/12025550100/messages \
      -H "Authorization: Bearer SANDBOX_KEY" \
      -H "Content-Type: application/json" \
      -d '{"to": "12025550101", "type": "text", "text": {"body": "It arrives on Friday."}}'
    ```

    Lo stesso testo a Ben (`12025550102`), che non ha mai scritto, risponde 422 `outside_24h_window`: fuori dalla finestra si può inviare solo un template.
  </Step>
</Steps>

### Provi gli altri clienti fittizi

| Cliente | Cosa inviargli | Cosa impara |
| --- | --- | --- |
| Ben, `12025550102` | un testo | Legge ma non risponde mai: 422 `outside_24h_window` per il testo libero |
| Cara, `12025550103` | `hello_world` | La consegna fallisce: `message.status` con `failed` e `message.failed` |
| Dan, `12025550104` | `order_update`, poi `weekend_offer` | Risponde STOP: `contact.opted_out`, poi il template di marketing dà 403 `recipient_opted_out` |
| Eve, `12025550105` | qualsiasi template | Chiede di parlare con una persona: passi la chat con `PUT /conversations/{contact}/owner` e `"owner": "human"` |

<Tip>
**Da un assistente AI invece che da un terminale:** il server MCP di gestione `https://api.app2email.com/mcp/manage` ha lo strumento `create_sandbox`, e la chiave istantanea funziona anche sul server MCP `https://api.app2email.com/mcp` (`check_key`, `list_templates`, `send_template`, `list_events`, `wait_for_message` ...). Vedere [Lasci che un agente AI gestisca il suo WhatsApp con MCP](/guides/how-to-ai-agent-mcp) e [Sandbox](/api/sandbox).
</Tip>

## Parte 2: il suo numero

<Steps>
  <Step title="Si registri e colleghi il suo numero">
    1. Crei un account su [app2email.com/register](https://www.app2email.com/register) e confermi la sua e-mail.
    2. Colleghi il suo numero WhatsApp dalla home della dashboard. Si tratta dell'Embedded Signup di Meta e richiede pochi minuti.
    3. Scelga un piano nella [pagina dei prezzi](https://www.app2email.com/pricing). Ogni chiamata API, di lettura come di invio, richiede un piano a pagamento e un servizio LIVE.

    È Meta a decidere se i messaggi escono davvero: aggiunga un metodo di pagamento al suo WhatsApp Business Account, verifichi la sua azienda e faccia approvare il nome visualizzato. [Per iniziare](https://www.app2email.com/docs/onboarding) la guida passo dopo passo.
  </Step>
  <Step title="Crei una chiave API">
    Nella [pagina delle chiavi API](https://www.app2email.com/dashboard/apikey) crei una chiave con `messages:send` e `messages:read` (aggiunga `webhooks:manage` se vuole un webhook). La chiave (`a2en_...`) viene mostrata una sola volta: la tenga sul suo server, mai in una pagina web o in un log.

    Selezioni **Sandbox key** quando la crea, per provare prima sul suo numero: ogni controllo viene eseguito sul suo account, nulla va a WhatsApp, le risposte hanno `"sandbox": true`, gli id dei messaggi iniziano con `wamid.SANDBOX.` e gli eventi `message.status` arrivano comunque. Crei una seconda chiave senza questa opzione quando sarà pronto a inviare davvero.
  </Step>
  <Step title="Controlli la chiave">
    In ogni richiesta, `YOUR_NUMBER` è il numero WhatsApp da cui invia: prima il prefisso internazionale, solo cifre.

    <CodeGroup>

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

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

    ```python Python
    import os, requests

    res = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/me",
                       headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=10)
    print(res.json())
    ```

    </CodeGroup>

    **Cosa riceve in risposta:**

    ```json
    {
      "success": true,
      "request_id": "a7k3p",
      "key_valid": true,
      "api_version": "v1",
      "number": "4976659348270",
      "plan": "standard_5000",
      "service_status": "LIVE",
      "key": { "name": "First message", "scopes": ["messages:read", "messages:send"], "ip_allow": "" },
      "limits": { "max_numbers_per_request": 1000, "requests_per_second": 20, "burst": 50, "rate_limit_mode": "enforce", "webhooks_max": 5 }
    }
    ```

    `service_status` deve essere `LIVE` e `key.scopes` deve elencare gli scope che Le servono (oppure `*` per l'accesso completo). Una chiave sandbox mostra anche `"sandbox": true`.
  </Step>
  <Step title="Scelga un template approvato">
    `GET /v1/YOUR_NUMBER/templates` elenca i suoi template. Ne scelga uno con `"status": "APPROVED"` e `"can_send": true` e copi il suo `example_request`. Non ha ancora un template approvato? Ne crei uno nella pagina Template della dashboard, oppure veda [Inviare notifiche di ordini e appuntamenti](/guides/how-to-order-notifications) per crearne uno tramite l'API e farlo approvare.
  </Step>
  <Step title="Lo invii al suo telefono">
    Invii il template al suo numero di cellulare (non al numero dell'attività stessa: darebbe 422 `recipient_is_sender`). Aggiunga un `Idempotency-Key`: se riprova dopo un timeout, il messaggio non viene inviato due volte.

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: first-message-1" \
      -d '{
        "to": "61412345678",
        "type": "template",
        "template": {
          "name": "order_update",
          "language": { "code": "en" },
          "components": [
            { "type": "body", "parameters": [
              { "type": "text", "text": "John" },
              { "type": "text", "text": "#1234" }
            ] }
          ]
        }
      }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
        "Content-Type": "application/json",
        "Idempotency-Key": "first-message-1",
      },
      body: JSON.stringify({
        to: "61412345678",
        type: "template",
        template: {
          name: "order_update",
          language: { code: "en" },
          components: [
            { type: "body", parameters: [{ type: "text", text: "John" }, { type: "text", text: "#1234" }] },
          ],
        },
      }),
    });
    const sent = await res.json();
    console.log(res.status, sent.message_id ?? sent.error);
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/messages",
        headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": "first-message-1"},
        json={
            "to": "61412345678",
            "type": "template",
            "template": {
                "name": "order_update",
                "language": {"code": "en"},
                "components": [
                    {"type": "body", "parameters": [{"type": "text", "text": "John"}, {"type": "text", "text": "#1234"}]}
                ],
            },
        },
        timeout=10,
    )
    sent = res.json()
    print(res.status_code, sent.get("message_id") or sent.get("error"))
    ```

    </CodeGroup>

    Usi il nome, la lingua e i valori del suo template (il suo `example_request` li contiene). **Cosa riceve in risposta** (HTTP 200):

    ```json
    {
      "success": true,
      "request_id": "kxrkf",
      "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
      "status": "accepted",
      "from": "4976659348270",
      "to": "61412345678",
      "template": { "name": "order_update", "language": "en", "category": "UTILITY" },
      "text": "Hi John, your order #1234 has shipped.",
      "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
      "note": "accepted by WhatsApp. delivery and read status appear in your app2email Activity Log (WhatsApp sent).",
      "contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
    }
    ```

    <Tip>
    Aggiunga `"dry_run": true` al body per controllare tutto (valori del template, numero, lista Do Not Call, limite mensile) senza inviare. La risposta mostra l'esatto messaggio WhatsApp. Nulla viene inviato, registrato o conteggiato.
    </Tip>
  </Step>
  <Step title="Legga il suo stato">
    `GET /messages/{message_id}` (scope `messages:read`) mostra a che punto è il messaggio. Codifichi l'id nell'URL (URL-encode).

    ```bash
    curl "https://api.app2email.com/v1/YOUR_NUMBER/messages/wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA%3D" \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    **Cosa riceve in risposta:** `status` è uno tra `accepted`, `sent`, `delivered`, `read`, `failed`, `deleted`, `queued` o `unknown`. I passaggi non ancora raggiunti sono omessi da `times`, e `reply` compare quando il cliente risponde a questo messaggio.

    ```json
    {
      "success": true,
      "request_id": "p4n8w",
      "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
      "to": "61412345678",
      "status": "read",
      "sent_by": "api",
      "text": "Hi John, your order #1234 has shipped.",
      "times": {
        "submitted": "2026-11-06T01:00:00Z",
        "accepted": "2026-11-06T01:00:01Z",
        "sent": "2026-11-06T01:00:02Z",
        "delivered": "2026-11-06T01:00:04Z",
        "read": "2026-11-06T01:12:40Z"
      },
      "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
    }
    ```
  </Step>
  <Step title="Riceva la risposta">
    Risponda al messaggio dal suo telefono. Due modi per ottenere la risposta nel suo codice:

    - **Richiederla:** `GET /v1/YOUR_NUMBER/events?wait=25&types=message.received`, come nella Parte 1. Sul suo numero la prima chiamata attiva il feed degli eventi, e da quel momento gli eventi vengono conservati per 72 ore. Quindi la chiami una volta con `after=now` prima di inviare e conservi il `cursor`.
    - **Farsela inviare:** registri un webhook una sola volta con `POST /v1/YOUR_NUMBER/webhooks` e `{"url": "https://your-server.example/webhook"}` (scope `webhooks:manage`), oppure lo aggiunga nella pagina delle chiavi API sotto Webhooks. app2email invia poi ogni evento come `POST` firmato al suo URL. [Creare un chatbot WhatsApp](/guides/how-to-whatsapp-chatbot) contiene un ricevitore completo con il controllo della firma.

    La risposta arriva come `message.received`:

    ```json
    {
      "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
      "type": "message.received",
      "created": "2026-11-06T01:00:00.000Z",
      "number": "4976659348270",
      "data": {
        "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
        "from": "61412345678",
        "name": "John",
        "type": "text",
        "text": "Thanks! When will it arrive?",
        "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
        "timestamp": "2026-11-06T01:00:00.000Z"
      }
    }
    ```

    Ora può rispondere con `"type": "text"`, esattamente come nella Parte 1, fino a 24 ore dopo l'ultimo messaggio del cliente.
  </Step>
</Steps>

## Cosa succede su WhatsApp

1. Il suo telefono mostra il messaggio template inviato dalla sua attività, con il nome visualizzato una volta che Meta lo ha approvato.
2. Il suo codice riceve gli eventi `message.status`: `sent`, poi `delivered`, poi `read` quando lo apre. Un messaggio non riuscito arriva come `message.status` con `status: "failed"` e un oggetto `error`, e anche come `message.failed`.
3. La sua risposta arriva come `message.received` e si apre la finestra di 24 ore per le risposte libere.
4. L'Activity Log e l'Inbox della dashboard mostrano entrambi i messaggi.

## Checklist per la produzione

<Check>
**Invii ogni messaggio una sola volta.** Dia a ogni `POST /messages` un `Idempotency-Key` unico per quel messaggio, come il numero d'ordine e l'evento. La stessa richiesta con la stessa chiave entro 24 ore riceve di nuovo la prima risposta, con l'header `Idempotent-Replayed: true`. Stessa chiave con un altro body: 422 `idempotency_key_reused`.
</Check>
<Check>
**Elimini i duplicati degli eventi tramite il loro `id`.** Un evento può arrivare di nuovo, da `GET /events` dopo una risposta persa e da un webhook dopo un nuovo tentativo. Conservi gli id che ha già gestito per almeno due giorni.
</Check>
<Check>
**Controlli la firma del webhook.** Ogni evento del webhook ha `X-App2email-Signature: t=<unix seconds>,v1=<hex>`: l'HMAC-SHA256 di `t`, un punto e il body grezzo, con il segreto del webhook (`whsec_...`) come chiave. Rifiuti gli eventi che non corrispondono o che hanno un `t` vecchio.
</Check>
<Check>
**Rispetti il rate limit.** Ogni risposta ha `X-RateLimit-Limit`, `X-RateLimit-Remaining` e `X-RateLimit-Reset`. Oltre il limite riceve 429 `rate_limited` con `Retry-After`: attenda quel tempo, poi riprovi. Per inviare un template a molti numeri, li metta in una sola chiamata invece di una chiamata ciascuno.
</Check>
<Check>
**Template fuori dalla finestra di 24 ore.** Il testo libero funziona solo entro 24 ore dall'ultimo messaggio del cliente (app2email si ferma 15 minuti prima). Tutto il resto richiede un template approvato.
</Check>
<Check>
**Scriva solo a chi ha dato il consenso.** I template di marketing non vengono inviati ai numeri della sua lista Do Not Call, e un cliente che scrive STOP vi viene aggiunto (`contact.opted_out`). [Inviare un broadcast di marketing che rispetta gli opt-in](/guides/how-to-marketing-broadcast) tratta il consenso.
</Check>
<Check>
**Tenga la chiave segreta e limitata.** Una chiave su un server, mai in una pagina web. Le dia solo gli scope che servono e usi una chiave sandbox per i test.
</Check>

## Se non funziona

| Cosa vede | Perché | Soluzione |
| --- | --- | --- |
| 429 da `POST /v1/account/sandbox` | Più di 10 chiavi sandbox istantanee all'ora dal suo indirizzo | Attenda `Retry-After` secondi, oppure continui a usare la chiave che ha (valida 7 giorni) |
| 401 `missing_api_key`, `invalid_api_key`, `api_key_expired`, `api_key_revoked` | Nessuna chiave, una chiave sbagliata, scaduta (una chiave sandbox istantanea dura 7 giorni) o revocata | Invii `Authorization: Bearer YOUR_API_KEY` con una chiave valida; ottenga una nuova chiave istantanea, o una chiave dalla pagina delle chiavi API |
| 403 `api_key_number_mismatch` | La chiave è di un numero diverso da quello nell'URL | Metta nell'URL il numero della chiave. Una chiave sandbox istantanea funziona solo su `12025550100` |
| 400 `invalid_number_in_url` | Il numero nell'URL non è composto da cifre con prefisso internazionale | Usi il numero completo, solo cifre, senza `+` |
| 403 `not_in_instant_sandbox` | Il numero demo non ha questa chiamata (i webhook, per esempio) | Usi `GET /events` lì, oppure una chiave sandbox sul suo numero |
| 422 `sandbox_recipient` | La sandbox istantanea scrive solo ai suoi clienti fittizi | Invii da `12025550101` a `12025550105` |
| 403 `plan_not_allowed`, `service_not_live` | Nessun piano a pagamento, oppure il servizio è in pausa | Scelga un piano; un servizio in pausa torna attivo con "Go Live" nella pagina Impostazioni |
| 403 `insufficient_scope` | Alla chiave manca un permesso (`details.required_scope`) | Crei una chiave con `messages:send` e `messages:read` |
| 403 `sandbox_key` | Una chiave sandbox non può fare questo (template, impostazioni, approvazioni) | Usi una chiave senza l'opzione sandbox per quella chiamata |
| 404 `template_not_found`, `template_language_not_found` | Il nome o la lingua del template sono errati | Copi entrambi da `GET /templates` |
| 422 `template_not_approved` | Meta non ha (ancora) approvato il template | Attenda l'approvazione, oppure ne scelga uno con `can_send: true` |
| 422 `template_parameters_invalid`, `template_parameter_count_mismatch` | Numero o tipo di valori errato | Li corregga in base a `details` e all'`example_request` nell'errore |
| 422 `outside_24h_window` | Testo libero a chi non ha scritto nelle ultime 24 ore | Invii un template approvato |
| 422 `recipient_is_sender` | Ha inviato al numero dell'attività stessa | Invii a un altro telefono |
| 403 `recipient_opted_out` | Il cliente è nella sua lista Do Not Call | Non gli invii messaggi di marketing |
| 403 `whatsapp_payment_issue` | Nessun metodo di pagamento valido sul suo WhatsApp Business Account (errore Meta 131042) | Ne aggiunga uno in WhatsApp Manager sotto Fatturazione e pagamenti |
| 429 `rate_limited` | Troppe chiamate per questa chiave | Attenda `Retry-After` secondi, poi riprovi |
| `GET /events` resta vuoto sul suo numero | Il feed parte dalla sua prima chiamata | La chiami una volta prima di inviare (`after=now`), poi invii di nuovo |

Ogni risposta ha un `request_id`. `GET /requests/{id}` mostra cosa è stato registrato per essa sul suo numero, e anche support@app2email.com può trovarla. Tutti i codici: [Errori](/api/errors).

## Altre guide pratiche

<CardGroup cols={2}>
  <Card title="Creare un chatbot WhatsApp con l'API" href="/guides/how-to-whatsapp-chatbot">
    Risponda ai clienti dal suo codice tramite un webhook firmato e passi la chat a una persona.
  </Card>
  <Card title="Inviare notifiche di ordini e appuntamenti" href="/guides/how-to-order-notifications">
    Crei un template utility, lo faccia approvare e segua ogni consegna.
  </Card>
  <Card title="Lasci che un agente AI gestisca il suo WhatsApp con MCP" href="/guides/how-to-ai-agent-mcp">
    Colleghi Claude o un altro agente al suo numero con chiavi limitate e approvazioni.
  </Card>
  <Card title="Inviare messaggi WhatsApp da n8n, Zapier o Make" href="/guides/how-to-no-code-n8n-zapier-make">
    Le stesse chiamate da un flusso no-code, senza scrivere un server.
  </Card>
</CardGroup>

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