# Creare un chatbot WhatsApp con l'API

> Riceva i messaggi WhatsApp su un webhook firmato, risponda alle domande più comuni dal suo codice e passi la chat a una persona quando il cliente la richiede.

In questa guida crea un piccolo bot WhatsApp che risponde a domande sui suoi orari di apertura e sui prezzi, e passa la chat a una persona quando il cliente la richiede.

**Cosa vede il cliente:** scrive al suo numero WhatsApp, il suo messaggio riceve le spunte blu, compare "sta scrivendo..." e la risposta arriva un secondo dopo. Quando scrive "posso parlare con una persona?", il bot dice che risponderà una persona e da quel momento risponde solo il suo team.

**Cosa vede Lei:** ogni messaggio e ogni risposta nell'Inbox e nell'Activity Log di app2email, le spunte di consegna e di lettura di ogni risposta come eventi webhook e un riepilogo della chat quando il bot la passa a una persona.

Il bot è lungo meno di 100 righe di Node.js (Express) o Python (Flask). Controlla la firma del webhook, ignora gli eventi già gestiti, riprova in modo sicuro e rispetta la finestra di risposta di 24 ore.

## Come funziona

1. Un cliente invia un messaggio al suo numero WhatsApp.
2. app2email invia un `POST` firmato con l'evento `message.received` al suo URL.
3. Il suo codice controlla la firma, consulta la conversazione (se ne occupa una persona? la finestra di risposta è aperta?), segna il messaggio come letto con l'indicatore di scrittura e invia la risposta con `POST /messages`.
4. app2email invia gli eventi `message.status` man mano che la risposta viene inviata, consegnata e letta.

Il suo URL deve rispondere con uno stato 2xx entro 10 secondi. In caso contrario, app2email invia di nuovo lo stesso evento più tardi, così una breve interruzione non fa perdere nulla.

## Cosa serve

- **Un numero WhatsApp collegato ad app2email**, con un piano a pagamento e attivo. Senza un piano ogni chiamata risponde 403 `plan_not_allowed`; un servizio in pausa risponde 403 `service_not_live`. Vedere [Per iniziare](https://www.app2email.com/docs/onboarding).
- **Una chiave API** dalla [pagina delle chiavi API](https://www.app2email.com/dashboard/apikey) con questi scope:

| Scope | Perché serve al bot |
| --- | --- |
| `messages:send` | Inviare le risposte (`POST /messages`), segnare i messaggi come letti (`POST /messages/read`), passare una chat a una persona (`PUT /conversations/{contact}/owner`) |
| `messages:read` | Consultare la conversazione: responsabile e finestra di risposta (`GET /conversations/{contact}`) |
| `webhooks:manage` | Registrare il webhook una sola volta (`POST /webhooks`). Può anche aggiungerlo nella pagina delle chiavi API sotto Webhooks, senza codice |

- **Un indirizzo https pubblico** per il webhook. Sul suo computer un tunnel ne fornisce uno (passo 2 qui sotto).
- **Un template approvato** senza segnaposto, per la rara risposta che esce dopo la chiusura della finestra di risposta (vedere [la finestra di 24 ore](#the-24-hour-window)).

<Tip>
**Provi prima di andare in produzione.** Una **chiave sandbox** (una chiave con l'opzione sandbox, creata nella pagina delle chiavi API) esegue ogni controllo sul suo numero e non invia nulla a WhatsApp: le risposte hanno `"sandbox": true` e id dei messaggi che iniziano con `wamid.SANDBOX.`, e gli eventi `message.status` arrivano comunque. Senza alcun account, la **sandbox istantanea** Le dà una chiave per il numero demo `12025550100` con clienti fittizi: `POST https://api.app2email.com/v1/account/sandbox` (senza chiave, senza body) oppure lo strumento `create_sandbox` del server MCP di gestione. Non ha webhook: legga gli eventi con `GET /events?wait=25` (vedere le FAQ). Dettagli: [Sandbox](/api/sandbox).
</Tip>

## Configurazione in quattro passi

<Steps>
  <Step title="Controlli la sua chiave">
    `GET /me` funziona con qualsiasi chiave valida e mostra i suoi scope e limiti. 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": "WhatsApp bot", "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 della tabella qui sopra (oppure `*` per l'accesso completo).
  </Step>
  <Step title="Dia al suo computer un indirizzo pubblico">
    app2email può inviare eventi solo a un indirizzo https pubblico. Durante lo sviluppo, un tunnel ne inoltra uno al suo computer. Avvii il bot sulla porta 3000 (il codice è più avanti), poi in un secondo terminale:

    ```bash
    # ngrok (https://ngrok.com)
    ngrok http 3000

    # or Cloudflare's cloudflared, no account needed for a quick tunnel
    cloudflared tunnel --url http://localhost:3000
    ```

    Entrambi stampano un indirizzo https come `https://a1b2-203-0-113-7.ngrok-free.app`. L'URL del suo webhook è quell'indirizzo più `/webhook`. Un tunnel rapido può ottenere un nuovo indirizzo a ogni avvio: quando succede, aggiorni il webhook con `PATCH /webhooks/{id}` e un nuovo `url`.

    Nessun tunnel possibile? `GET /events?wait=25` ottiene gli stessi eventi senza un indirizzo pubblico (vedere le FAQ).
  </Step>
  <Step title="Registri il webhook">
    Una sola chiamata. La risposta contiene il **segreto di firma** (`whsec_...`) che firma ogni evento: lo conservi insieme alla sua chiave, per esempio in una variabile d'ambiente `WEBHOOK_SECRET`.

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/webhooks", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ url: "https://a1b2-203-0-113-7.ngrok-free.app/webhook" }),
    });
    const { webhook } = await res.json();
    console.log(webhook.id, webhook.secret);
    ```

    ```python Python
    import os, requests

    res = requests.post("https://api.app2email.com/v1/YOUR_NUMBER/webhooks",
                        headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
                        json={"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}, timeout=10)
    webhook = res.json()["webhook"]
    print(webhook["id"], webhook["secret"])
    ```

    </CodeGroup>

    **Cosa riceve in risposta** (201 Created; abbreviato: la risposta elenca anche ogni tipo di evento in `events`):

    ```json
    {
      "success": true,
      "request_id": "w8hk2",
      "webhook": {
        "id": "wh_a1b2c3d4e5f6g7h8",
        "url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook",
        "secret": "whsec_...",
        "created": "2026-11-21T09:00:00.000Z",
        "active": true,
        "format": "app2email"
      }
    }
    ```

    Registrare di nuovo lo stesso URL risponde 200 con lo stesso id e lo stesso segreto, quindi la chiamata si può ripetere senza rischi. Un numero ha al massimo 5 webhook, e ogni webhook riceve ogni evento: il suo codice sceglie i tipi che gestisce in base a `type` e risponde 2xx a tutti gli altri. Per questa guida lasci `format` su `app2email` (il valore predefinito).
  </Step>
  <Step title="Invii un evento di prova">
    `POST /webhooks/{id}/test` invia subito un esempio firmato e Le dice come ha risposto il suo URL. Con `{"type": "message.received"}` ottiene l'esempio di quell'evento.

    ```bash
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks/wh_a1b2c3d4e5f6g7h8/test \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"type": "message.received"}'
    ```

    **Cosa riceve in risposta** (abbreviato):

    ```json
    {
      "success": true,
      "request_id": "t3ws9",
      "delivered": true,
      "http_status": 200,
      "response_ms": 38
    }
    ```

    `delivered: true` significa che il suo URL ha risposto 2xx entro 10 secondi. Un evento di prova contiene `"test": true` e l'header `X-App2email-Test: true`, e il suo contatto di esempio è inventato, quindi il bot qui sotto controlla la firma, registra l'evento e non gli risponde. Fino a 30 prove all'ora per numero. Poi invii un messaggio reale al suo numero dal suo telefono: il bot risponde.
  </Step>
</Steps>

## Le quattro chiamate che fa il bot

Ogni chiamata va a `https://api.app2email.com/v1/YOUR_NUMBER` con `Authorization: Bearer YOUR_API_KEY`.

### 1. Legga cosa ha inviato il cliente

Questo è il body dell'evento `message.received` che il suo URL riceve (un messaggio di testo):

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "message.received",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "from": "61412345678",
    "name": "Sample Contact",
    "type": "text",
    "text": "What are your opening hours?",
    "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
    "timestamp": "2026-11-06T01:00:00.000Z",
    "from_user_id": "AU.1234567890123456"
  }
}
```

- `id` (anche nell'header `X-App2email-Delivery`) è lo stesso a ogni nuovo tentativo: è ciò con cui elimina i duplicati.
- `data.from` è il numero del cliente. Un contatto che usa un nome utente WhatsApp può arrivare con `from_user_id` e senza numero; quell'id funziona ovunque funzioni un numero.
- `data.type` è `text`, `image`, `audio`, `interactive` (un tocco su un pulsante di risposta o su una riga di elenco, con `interactive.id`), `button` (un pulsante di risposta rapida di un template, con `button.payload`) e altri. Il bot risponde al testo e ai tocchi e lascia tutto il resto al suo team.

### 2. Consulti la conversazione

`GET /conversations/{contact}` (scope `messages:read`) dice chi gestisce la chat e se ora si può inviare una risposta libera.

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

**Cosa riceve in risposta:**

```json
{
  "success": true,
  "request_id": "c9slm",
  "contact": "61412345678",
  "identity_type": "phone",
  "phone": "61412345678",
  "name": "John",
  "window_state": "open",
  "window_open": true,
  "window_closes_at": "2026-11-07T00:45:00Z",
  "last_inbound_at": "2026-11-06T01:00:00Z",
  "messages": 12,
  "owner": "",
  "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}
```

`owner` è vuoto per la gestione normale. Quando è `human` o `paused`, la chat è in mano a una persona e il bot resta in silenzio; `whatsapp_ai` significa che la gestisce l'agente AI di WhatsApp.

### 3. Mostri le spunte blu e "sta scrivendo..."

`POST /messages/read` (scope `messages:send`) segna il messaggio come letto e, con `"typing": true`, mostra l'indicatore di scrittura per un massimo di 25 secondi o finché non arriva la sua risposta. È gratuito: non viene conteggiato nel suo piano e non è legato alla finestra di 24 ore.

```bash
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages/read \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=", "typing": true}'
```

**Cosa riceve in risposta:**

```json
{
  "success": true,
  "request_id": "k2rdq",
  "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
  "status": "read",
  "typing_indicator": true
}
```

### 4. Invii la risposta

`POST /messages` (scope `messages:send`) con `"type": "text"` invia un messaggio libero a un contatto mentre la finestra di risposta è aperta.

| Parte | Cosa inserire |
| --- | --- |
| Chi | `to`: il numero del cliente (`data.from`), oppure il suo `from_user_id` |
| Quale messaggio | `type`: `text` per una risposta normale. Fuori dalla finestra: `template` |
| Cosa dice | `text.body`: la sua risposta. `text.preview_url`: true per mostrare l'anteprima di un link |
| La sua chiave | l'header `Authorization: Bearer YOUR_API_KEY` |
| Niente doppioni | l'header `Idempotency-Key`: un valore unico per questa risposta, ad es. `text-` più il `message_id` del cliente. La stessa richiesta con la stessa chiave entro 24 ore non viene inviata di nuovo |

<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: text-wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=" \
  -d '{"to": "61412345678", "type": "text", "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": false}}'
```

```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": `text-${messageId}`,
  },
  body: JSON.stringify({
    to: "61412345678",
    type: "text",
    text: { body: "We are open Monday to Friday, 9 am to 5 pm.", preview_url: false },
  }),
});
console.log(res.status, await res.json());
```

```python Python
res = requests.post(
    "https://api.app2email.com/v1/YOUR_NUMBER/messages",
    headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"text-{message_id}"},
    json={"to": "61412345678", "type": "text",
          "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": False}},
    timeout=10,
)
print(res.status_code, res.json())
```

</CodeGroup>

**Cosa riceve in risposta** (200):

```json
{
  "success": true,
  "request_id": "kxrkf",
  "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
  "status": "accepted",
  "type": "text",
  "from": "4976659348270",
  "to": "61412345678",
  "window_closes_at": "2026-11-07T00:45:00Z",
  "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
  "contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
}
```

`accepted` significa che WhatsApp ha preso in carico il messaggio. Se sia stato consegnato e letto lo si saprà dopo, con gli eventi `message.status`. Una richiesta ripetuta con lo stesso `Idempotency-Key` riceve di nuovo questa stessa risposta con l'header `Idempotent-Replayed: true`, e nulla viene inviato due volte.

**Quando fallisce**, la risposta ha `success: false` e un oggetto `error`. Decida in base a `error.code`, mai in base al testo del messaggio:

```json
{
  "success": false,
  "request_id": "q2v8n",
  "error": {
    "code": "outside_24h_window",
    "message": "The contact has not written to this number in the last 24 hours (or never), so only a template message can be sent.",
    "how_to_fix": "Send an approved template message instead (\"type\": \"template\"). When the contact answers, normal messages work again for 24 hours.",
    "documentation_url": "https://www.app2email.com/docs/api/errors#outside_24h_window",
    "is_retriable": false
  }
}
```

Troppe chiamate rispondono 429 `rate_limited` con un header `Retry-After`:

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 2

{"success": false, "request_id": "r5lmt", "error": {"code": "rate_limited", "message": "Too many requests for this key.", "how_to_fix": "Wait, then send again.", "documentation_url": "https://www.app2email.com/docs/api/errors#rate_limited", "is_retriable": true, "retry_after_seconds": 2}}
```

### Passi la chat a una persona

Quando il cliente chiede una persona, `PUT /conversations/{contact}/owner` (scope `messages:send`) con `"owner": "human"`, un breve `reason` e un `summary`. La risposta automatica di app2email e gli altri agenti lasciano allora in pace il contatto, le persone che ricevono i messaggi per e-mail vedono il riepilogo e ogni webhook riceve `conversation.owner_changed`. `until_minutes` lo rende temporaneo: trascorso quel tempo la chat torna da sola alla gestione normale.

```bash
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"owner": "human", "reason": "customer asked for a person", "summary": "Wants to move the delivery to Monday.", "until_minutes": 240}'
```

La risposta contiene la `conversation` aggiornata (gli stessi campi di `GET /conversations/{contact}`).

## Il bot completo

Entrambe le versioni fanno lo stesso: verificano la firma, saltano gli eventi di prova e quelli già gestiti, saltano le chat di cui si occupa una persona, segnano come letto con l'indicatore di scrittura, passano la chat a una persona quando viene richiesta, rispondono alle parole chiave e ripiegano su un template quando la finestra è chiusa. Imposti prima tre variabili d'ambiente: `NUMBER` (il suo numero WhatsApp, cifre), `API_KEY` e `WEBHOOK_SECRET` (il valore `whsec_...` del passo 3).

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

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

const { NUMBER, API_KEY, WEBHOOK_SECRET, PORT = 3000 } = process.env;
const API = `https://api.app2email.com/v1/${NUMBER}`;
const FALLBACK = { name: "hello_world", language: { code: "en_US" } }; // an approved template without placeholders
const RETRY_LATER = new Set(["rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"]);
const done = new Set(); // handled event ids: use a database table or Redis in production

const ANSWERS = [
  [/\b(hours?|open|opening|closed)\b/i, "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."],
  [/\b(prices?|cost|how much)\b/i, "A standard service is $49, an express service $79. Full list: https://example.com/prices"],
];
const HUMAN = /\b(human|person|someone|staff)\b/i;
const MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team.";

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

async function api(method, path, body, idempotencyKey) {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(API + path, {
      method,
      signal: AbortSignal.timeout(4000),
      headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json",
                 ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}) },
      body: body ? JSON.stringify(body) : undefined,
    });
    const json = await res.json();
    if (res.ok) return json;
    const code = json.error?.code;
    const wait = Number(res.headers.get("Retry-After") ?? 1);
    if (code === "rate_limited" && attempt < 3 && wait <= 3) { await new Promise((r) => setTimeout(r, wait * 1000)); continue; }
    if (res.status >= 500 || RETRY_LATER.has(code)) throw new Error(`${code} ${json.request_id}`);
    console.warn(method, path, code, json.error?.how_to_fix, json.request_id);
    return json;
  }
}

async function reply(to, windowOpen, body, inReplyTo) {
  if (windowOpen) {
    const sent = await api("POST", "/messages", { to, type: "text", text: { body } }, `text-${inReplyTo}`);
    if (sent.error?.code !== "outside_24h_window") return sent;
  }
  return api("POST", "/messages", { to, type: "template", template: FALLBACK }, `tpl-${inReplyTo}`);
}

async function handle(m) {
  if (!["text", "interactive", "button"].includes(m.type)) return; // photos, voice notes ...: for the team
  const contact = encodeURIComponent(m.from || m.from_user_id);
  const text = m.interactive?.id || m.button?.payload || m.text || "";
  const conv = await api("GET", `/conversations/${contact}`);
  if (["human", "paused", "whatsapp_ai"].includes(conv.owner)) return; // someone else has this chat
  await api("POST", "/messages/read", { message_id: m.message_id, typing: true });
  const open = conv.window_open !== false;
  if (HUMAN.test(text)) {
    await api("PUT", `/conversations/${contact}/owner`, {
      owner: "human", reason: "customer asked for a person", summary: text.slice(0, 300), until_minutes: 240 });
    return reply(m.from || m.from_user_id, open, "Thanks! A person from our team will answer you here soon.", m.message_id);
  }
  const hit = ANSWERS.find(([pattern]) => pattern.test(text));
  return reply(m.from || m.from_user_id, open, hit ? hit[1] : MENU, m.message_id);
}

const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
  const event = JSON.parse(req.body);
  if (event.test) { console.log("test event ok:", event.type); return res.sendStatus(200); }
  if (event.type !== "message.received" || done.has(event.id)) return res.sendStatus(200);
  try {
    await handle(event.data);
    done.add(event.id); // only after it worked: a failed event comes again
    res.sendStatus(200);
  } catch (err) {
    console.error("not handled, app2email will send it again:", event.id, err.message);
    res.sendStatus(503);
  }
});
app.listen(PORT, () => console.log(`bot on http://localhost:${PORT}/webhook`));
```

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

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

NUMBER, API_KEY, SECRET = os.environ["NUMBER"], os.environ["API_KEY"], os.environ["WEBHOOK_SECRET"]
API = f"https://api.app2email.com/v1/{NUMBER}"
FALLBACK = {"name": "hello_world", "language": {"code": "en_US"}}  # an approved template without placeholders
RETRY_LATER = {"rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"}
done = set()  # handled event ids: use a database table or Redis in production

ANSWERS = [
    (re.compile(r"\b(hours?|open|opening|closed)\b", re.I), "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."),
    (re.compile(r"\b(prices?|cost|how much)\b", re.I), "A standard service is $49, an express service $79. Full list: https://example.com/prices"),
]
HUMAN = re.compile(r"\b(human|person|someone|staff)\b", re.I)
MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team."

def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
    v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "")  # two during a secret change
    if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
        return False
    expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(v, expected) for v in v1)

def api(method, path, body=None, idempotency_key=None):
    headers = {"Authorization": f"Bearer {API_KEY}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for attempt in (1, 2, 3):
        res = requests.request(method, API + path, json=body, headers=headers, timeout=4)
        data = res.json()
        if res.ok:
            return data
        code = data.get("error", {}).get("code")
        wait = int(res.headers.get("Retry-After", "1"))
        if code == "rate_limited" and attempt < 3 and wait <= 3:
            time.sleep(wait)
            continue
        if res.status_code >= 500 or code in RETRY_LATER:
            raise RuntimeError(f"{code} {data.get('request_id')}")
        print("not done:", method, path, code, data.get("error", {}).get("how_to_fix"), data.get("request_id"))
        return data

def reply(to, window_open, body, in_reply_to):
    if window_open:
        sent = api("POST", "/messages", {"to": to, "type": "text", "text": {"body": body}}, f"text-{in_reply_to}")
        if sent.get("error", {}).get("code") != "outside_24h_window":
            return sent
    return api("POST", "/messages", {"to": to, "type": "template", "template": FALLBACK}, f"tpl-{in_reply_to}")

def handle(m):
    if m.get("type") not in ("text", "interactive", "button"):
        return  # photos, voice notes ...: for the team
    contact = m.get("from") or m.get("from_user_id")
    text = (m.get("interactive") or {}).get("id") or (m.get("button") or {}).get("payload") or m.get("text") or ""
    conv = api("GET", f"/conversations/{contact}")
    if conv.get("owner") in ("human", "paused", "whatsapp_ai"):
        return  # someone else has this chat
    api("POST", "/messages/read", {"message_id": m["message_id"], "typing": True})
    window_open = conv.get("window_open") is not False
    if HUMAN.search(text):
        api("PUT", f"/conversations/{contact}/owner", {"owner": "human", "reason": "customer asked for a person",
                                                       "summary": text[:300], "until_minutes": 240})
        return reply(contact, window_open, "Thanks! A person from our team will answer you here soon.", m["message_id"])
    answer = next((a for pattern, a in ANSWERS if pattern.search(text)), MENU)
    return reply(contact, window_open, answer, m["message_id"])

app = Flask(__name__)

@app.post("/webhook")
def webhook():
    raw = request.get_data()
    if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
        return "bad signature", 401
    event = json.loads(raw)
    if event.get("test"):
        print("test event ok:", event["type"])
        return "", 200
    if event["type"] != "message.received" or event["id"] in done:
        return "", 200
    try:
        handle(event["data"])
    except Exception as err:
        print("not handled, app2email will send it again:", event["id"], err)
        return "", 503
    done.add(event["id"])  # only after it worked: a failed event comes again
    return "", 200
```

  </Tab>
</Tabs>

**Perché è costruito così:**

- La firma viene controllata sul **body grezzo** prima di analizzare qualsiasi cosa (`express.raw`, `request.get_data()`).
- Un evento viene segnato come gestito solo dopo che la risposta è uscita. Se una chiamata fallisce con un 5xx o con un rate limit, il bot risponde 503 e app2email invia di nuovo l'evento più tardi (dopo 10 s, 1 min, 5 min ...). L'`Idempotency-Key` garantisce che un nuovo tentativo non invii mai due volte la stessa risposta, anche quando il primo tentativo era arrivato fino all'invio.
- Un breve 429 `rate_limited` viene atteso all'interno della richiesta (al massimo 3 secondi, così il limite di 10 secondi è rispettato). Tutto ciò che dura di più torna ai nuovi tentativi di app2email.
- Gli errori che non cambiano riprovando (un nome di template errato, uno scope mancante) vengono registrati con `how_to_fix` e `request_id`, e all'evento si risponde 200 perché non continui a tornare.
- `FALLBACK` è `hello_world` perché la sandbox istantanea lo ha. Sul suo numero, inserisca il nome e la lingua di uno dei suoi template approvati (`GET /templates` li elenca, ciascuno con un `example_request` completo).

## Cosa succede su WhatsApp

1. Il cliente scrive "Quali sono i vostri orari di apertura?".
2. Il suo messaggio riceve le spunte blu e compare "sta scrivendo...".
3. La risposta arriva. Nell'Inbox e nell'Activity Log vede entrambi i messaggi.
4. Il suo webhook riceve `message.status` per la risposta: `sent`, poi `delivered`, poi `read`.

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs02",
  "type": "message.status",
  "created": "2026-11-06T01:00:03.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "to": "61412345678",
    "status": "delivered",
    "timestamp": "2026-11-06T01:00:03.000Z",
    "sent_by": "api",
    "whatsapp_status": "delivered"
  }
}
```

Una risposta non riuscita arriva come `message.status` con `status: "failed"` e un oggetto `error` (`code` è il codice di Meta, `error_code` quello di app2email), e anche come `message.failed`.

Quando il cliente scrive "posso parlare con una persona?", riceve "Una persona del nostro team Le risponderà qui a breve", e il suo webhook riceve:

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs03",
  "type": "conversation.owner_changed",
  "created": "2026-11-06T01:02:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "owner": "human",
    "previous_owner": "",
    "reason": "customer asked for a person",
    "summary": "can I talk to a person?",
    "until": "2026-11-06T05:02:00.000Z",
    "set_by": "api",
    "timestamp": "2026-11-06T01:02:00.000Z"
  }
}
```

Una persona risponde dall'Inbox, dall'e-mail o tramite l'API. Al messaggio successivo il bot vede il responsabile `human` e resta in silenzio.

**Tornare al bot:** dopo `until_minutes` il responsabile torna vuoto da solo. Anche una persona può restituire la chat prima con `PUT /conversations/{contact}/owner` e `{"owner": ""}`, che invia di nuovo `conversation.owner_changed`. Non riprenda una chat nel codice mentre è in mano a una persona.

<a id="the-24-hour-window"></a>

## La finestra di 24 ore

WhatsApp Le permette di inviare messaggi liberi (testo, immagini, pulsanti) per 24 ore dopo l'ultimo messaggio del cliente. app2email si ferma 15 minuti prima; `window_closes_at` è l'orario esatto. Dopo di allora solo un template approvato può riavviare la conversazione.

Un bot che risponde in pochi secondi è quasi sempre dentro la finestra. Conta quando un evento viene consegnato in ritardo: i nuovi tentativi proseguono per circa 32 ore, quindi la risposta a un messaggio di ieri può richiedere un template. Il bot controlla `window_open` prima di scrivere e ripiega comunque sul template se l'invio risponde 422 `outside_24h_window`.

La lista Do Not Call non si applica alle risposte libere, perché è stato il cliente a scriverle. L'eccezione: quando il suo ultimo messaggio era l'opt-out stesso, una risposta dà 403 `recipient_opted_out` finché non scrive di nuovo.

## Checklist per la produzione

<Check>
**Verifichi ogni evento.** L'header `X-App2email-Signature` è `t=<unix seconds>,v1=<hex>`: l'HMAC-SHA256 del testo `t`, un punto e il body grezzo, con il segreto del webhook (`whsec_...`, prefisso incluso) come chiave. Controlli ogni `v1=` (ce ne sono due per un po' dopo `POST /webhooks/{id}/rotate-secret` con `keep_old_for_hours`), confronti in tempo costante e rifiuti un `t` più vecchio di 5 minuti. È presente anche `X-Hub-Signature-256` (`sha256=` e l'HMAC-SHA256 del body grezzo, come firma Meta) se il suo codice controlla già i webhook di Meta; non contiene l'orario e usa solo il segreto corrente.
</Check>

<Check>
**Risponda in fretta.** Restituisca 2xx entro 10 secondi. I reindirizzamenti non vengono seguiti. Per il lavoro lento (un database, un modello AI), memorizzi l'evento, risponda 200 e lo elabori da una coda che riprova da sola.
</Check>

<Check>
**Elimini i duplicati.** Conservi l'`id` dell'evento (`X-App2email-Delivery`) di ogni evento gestito per almeno due giorni: i nuovi tentativi durano circa 32 ore. Lo tenga in un database o in Redis, non in memoria, quando esegue più di un processo. Gli eventi possono anche arrivare fuori ordine: usi `data.timestamp`, non l'ordine di arrivo.
</Check>

<Check>
**Invii ogni risposta una sola volta.** Dia a ogni `POST /messages` un `Idempotency-Key` costruito dal `message_id` del cliente. Stessa chiave e stesso body entro 24 ore: torna la prima risposta con `Idempotent-Replayed: true`. Stessa chiave, body diverso: 422 `idempotency_key_reused`. 409 `idempotency_request_in_progress`: attenda e riprovi con la stessa chiave.
</Check>

<Check>
**Rispetti i limiti.** Ogni risposta ha `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (secondi prima di tornare pieno) e `X-RateLimit-Policy`; `GET /me` mostra i `limits` della sua chiave. Oltre il limite: 429 `rate_limited` con `Retry-After` e `error.retry_after_seconds`. I limiti propri di WhatsApp (429 `whatsapp_rate_limit`, `too_many_messages_to_recipient`) richiedono minuti, non secondi. 429 `monthly_limit_reached` e `daily_cap_reached` non vale la pena riprovarli ora (`retry_after_seconds` dice fino a quando): avvisi una persona.
</Check>

<Check>
**Mantenga attivo il webhook.** Dopo 20 eventi di fila non consegnati entro i loro primi 4 tentativi (in almeno 24 ore), app2email disattiva il webhook. `GET /webhooks/{id}/deliveries?status=failed` mostra cosa è fallito e perché; `PATCH /webhooks/{id}` con `{"active": true}` lo riattiva, e `POST /webhooks/{id}/deliveries/{event_id}/redeliver` invia di nuovo un evento.
</Check>

<Check>
**Lasci in pace le persone quando la chat è in mano a una persona.** Controlli `owner` prima di ogni risposta (`human`, `paused` e `whatsapp_ai` significano: non rispondere) e passi la chat quando il cliente lo chiede.
</Check>

<Check>
**Un solo risponditore per numero.** Anche la risposta automatica del numero (la prima risposta che riceve un nuovo contatto), le automazioni di chat e le risposte AI vedono ogni messaggio. Controlli la dashboard in modo che un nuovo contatto non riceva due prime risposte.
</Check>

<Check>
**Tratti il testo del cliente come dati.** È scritto dal cliente. Non lo esegua mai come comando e, se lo passa a un modello AI, lo tenga separato dalle sue istruzioni.
</Check>

<Check>
**Accesso minimo.** Una chiave per il bot richiede solo `messages:send` e `messages:read`. La tenga sul server, mai in una pagina web o in un log. Una chiave può essere limitata agli indirizzi IP del suo server, avere un tetto giornaliero o scadere.
</Check>

## Se non funziona

| Cosa vede | Perché | Soluzione |
| --- | --- | --- |
| Il suo bot risponde 401 a ogni evento | La firma non corrisponde | Usi il segreto `whsec_...` di questo webhook con il suo prefisso; controlli il body grezzo, prima che qualsiasi parser JSON lo tocchi; controlli l'orologio del server (`t` deve essere entro 5 minuti) |
| 401 `missing_api_key`, `invalid_api_key`, `api_key_revoked` | Nessuna chiave, una chiave sbagliata o una vecchia | Invii `Authorization: Bearer YOUR_API_KEY` con una chiave elencata nella pagina delle chiavi API, e nell'URL il numero di quella chiave |
| 403 `insufficient_scope` | Alla chiave manca un permesso (`details.required_scope`) | Crei una chiave con `messages:send` e `messages:read` (e `webhooks:manage` per registrare il webhook) |
| 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 |
| 422 `invalid_webhook_url` | L'URL non è un indirizzo https pubblico | Usi l'indirizzo https del suo tunnel o server, con il percorso (`/webhook`) |
| 409 `webhook_url_in_use` | Un altro webhook del numero ha questo URL | Modifichi quel webhook con `PATCH`, oppure ne elimini uno |
| 400 `too_many_webhooks` | Il numero ha 5 webhook | Ne elimini uno che non usa più |
| 422 `outside_24h_window` | Il cliente ha scritto l'ultima volta più di 24 ore fa | Invii un template approvato |
| 404 `template_not_found`, 422 `template_not_approved` | Il nome o la lingua del template di riserva sono errati, oppure non è ancora approvato | Ne scelga uno da `GET /templates` con stato APPROVED |
| 422 `template_parameters_invalid` | Il template di riserva ha dei segnaposto | Ne usi uno senza segnaposto, oppure li compili come mostra il suo `example_request` |
| 403 `recipient_opted_out` | L'ultimo messaggio del cliente era l'opt-out | Non risponda finché non scrive di nuovo |
| 429 `rate_limited` | Troppe chiamate per questa chiave | Attenda `Retry-After` secondi, poi riprovi |
| 429 `whatsapp_rate_limit`, `too_many_messages_to_recipient` | Limite di WhatsApp | Rallenti per alcuni minuti |
| 429 `too_many_tests` | Più di 30 eventi di prova in un'ora | Attenda, oppure provi con un messaggio dal suo telefono |
| 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 |
| Non arriva alcun evento | Il webhook è disattivato, oppure l'indirizzo del tunnel è cambiato | `GET /webhooks` mostra `active` e l'ultima consegna; faccia `PATCH` del nuovo `url` o di `{"active": true}` |

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

## Altri modi per rispondere ai clienti

- **Risposte AI**: l'assistente di app2email risponde a partire dal suo sito web, dai PDF e dagli appunti e passa la chat a una persona quando non può aiutare (piano Professional e periodo di prova). Segnala `ai.answered` e `ai.handover`. Risponde a un cliente solo finché la conversazione non ha un responsabile e nessuna app o automazione ha risposto, quindi scelga un solo risponditore per numero. Vedere le [impostazioni delle risposte AI](https://www.app2email.com/docs/api/ai-answers/get-ai-answers-settings).
- **Un agente AI tramite MCP**: il server MCP `https://api.app2email.com/mcp` ha le stesse chiamate come strumenti (`send_text`, `mark_read`, `get_conversation`, `set_conversation_owner`, `list_events`, `wait_for_message` ...). Vedere [Lasci che un agente AI gestisca il suo WhatsApp con MCP](/guides/how-to-ai-agent-mcp) e [MCP](/api/mcp).
- **Passaggi di consegne più in dettaglio**: [Passare una chat dal suo bot a una persona e viceversa](/guides/how-to-human-handoff).

## FAQ

<AccordionGroup>
  <Accordion title="Posso creare e provare tutto questo senza un numero WhatsApp?">
    Sì. `POST https://api.app2email.com/v1/account/sandbox` (senza chiave, senza body) risponde con una chiave sandbox istantanea (`a2es_...`, valida 7 giorni) per il numero demo `12025550100`. Tra i suoi clienti fittizi ci sono Ava (`12025550101`, risponde a ogni messaggio) ed Eve (`12025550105`, chiede una persona). Ha `GET /conversations/{contact}`, `PUT /conversations/{contact}/owner`, `POST /messages` e `GET /events`, quindi la logica del bot funziona lì, e ha il template `hello_world` usato come riserva. Non ha webhook: legga gli eventi con `GET /events` (domanda successiva). Anche `POST /messages/read` non c'è; risponde 403 `not_in_instant_sandbox`, che il bot registra e prosegue. Nulla arriva su WhatsApp.
  </Accordion>
  <Accordion title="Posso ricevere messaggi senza un URL pubblico?">
    Sì: `GET /events?wait=25` (scope `messages:read`) trattiene la risposta finché non arriva un evento, fino a 25 secondi. Ogni evento è lo stesso JSON che riceve un webhook, con lo stesso `id`. Conservi il `cursor` della risposta e lo passi come `after` alla chiamata successiva; salti gli id che ha già gestito, perché dopo una risposta persa un evento può arrivare di nuovo. `types=message.received` restituisce solo i messaggi in arrivo. La prima chiamata attiva il feed del numero; gli eventi vengono conservati 72 ore.

    ```javascript
    let after = "now";
    for (;;) {
      const page = await api("GET", `/events?wait=25&types=message.received&after=${after}`);
      for (const event of page.events ?? []) if (!done.has(event.id)) { await handle(event.data); done.add(event.id); }
      after = page.cursor ?? after;
    }
    ```
  </Accordion>
  <Accordion title="Il cliente può toccare dei pulsanti invece di scrivere?">
    Sì, entro la finestra di 24 ore. Invii `"type": "interactive"` con fino a 3 pulsanti di risposta, oppure un elenco di fino a 10 righe. Dia ai pulsanti gli id che il bot già comprende, e un tocco arriva come `message.received` con `type` `interactive` e `interactive.id`:

    ```json
    {
      "to": "61412345678",
      "type": "interactive",
      "interactive": {
        "type": "button",
        "body": { "text": "What would you like to know?" },
        "action": {
          "buttons": [
            { "type": "reply", "reply": { "id": "hours", "title": "Opening hours" } },
            { "type": "reply", "reply": { "id": "prices", "title": "Prices" } },
            { "type": "reply", "reply": { "id": "person", "title": "Talk to a person" } }
          ]
        }
      }
    }
    ```
  </Accordion>
  <Accordion title="Quanto costa ogni risposta?">
    Ogni risposta inviata dal bot conta come un messaggio del suo piano app2email. Segnare come letto e l'indicatore di scrittura sono gratuiti. Meta Le fattura direttamente: le risposte entro la finestra sono messaggi di servizio (i primi 1.000 al mese per numero sono gratuiti), i template vengono addebitati per messaggio. `GET /usage` mostra quanto è stato usato e quanto resta questo mese, con le categorie di Meta in `meta_pricing`.
  </Accordion>
  <Accordion title="Cosa succede con foto, note vocali e documenti?">
    Arrivano come `message.received` con `type` `image`, `audio`, `document` e così via, e un `media_url`: app2email conserva una copia, fornita da `GET /media/{message_id}`. Il bot qui sopra li lascia al suo team; potrebbe anche passare la chat appena ne arriva uno.
  </Accordion>
  <Accordion title="Come risponde una persona, e come restituisco la chat al bot?">
    Dall'Inbox della dashboard, dall'e-mail (quando l'inoltro e-mail è attivo) o tramite l'API. La chat torna al bot quando `until_minutes` scade, o prima con `PUT /conversations/{contact}/owner` e `{"owner": ""}`.
  </Accordion>
  <Accordion title="Posso ottenere il formato webhook originale di Meta?">
    Sì: un webhook con `"format": "meta"` riceve ciò che arriva da WhatsApp nel body originale di Meta (`entry[].changes[]`), firmato allo stesso modo. Gli eventi propri di app2email, come `conversation.owner_changed`, mantengono l'envelope di app2email. Questa guida usa il formato predefinito `app2email`.
  </Accordion>
  <Accordion title="Alcuni clienti non hanno un numero di telefono nell'evento. Perché?">
    WhatsApp sta passando ai nomi utente con id utente legati all'attività (come `AU.1234567890123456`). Un evento di questo tipo può avere `from_user_id` e nessun `from`. Metta l'id in `to`: funziona ovunque funzioni un numero, compreso `/conversations/{contact}`. I bot qui sopra lo fanno già.
  </Accordion>
</AccordionGroup>

## Altre guide pratiche

<CardGroup cols={2}>
  <Card title="Inviare notifiche di ordini e appuntamenti" href="/guides/how-to-order-notifications">
    Template utility approvati per conferme e promemoria, con stato di consegna.
  </Card>
  <Card title="Inviare un broadcast di marketing che rispetta gli opt-in" href="/guides/how-to-marketing-broadcast">
    Un template a una lista o a un segmento, con registri del consenso e lista Do Not Call.
  </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="Passare una chat dal suo bot a una persona e viceversa" href="/guides/how-to-human-handoff">
    Responsabili della conversazione, assegnazione, note e riepiloghi per il suo team.
  </Card>
  <Card title="Chiedere un pagamento all'interno di una chat WhatsApp" href="/guides/how-to-payment-links">
    Invii un link di pagamento nella chat e sappia quando è stato pagato.
  </Card>
</CardGroup>

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