# Quickstart di Z-API Omni in Python: invia e ricevi con FastAPI

> Invia un testo WhatsApp con l'API di Z-API Omni tramite urllib e verifica webhook firmati in FastAPI: HMAC su cinque campi, gzip, finestra di 300 s e deduplica.

Published 2026-11-05. Z-API Omni team.

Per inviare e ricevere messaggi con Z-API Omni in Python ti servono un file e tre valori: una Secret Key, un ID di canale e un secret del webhook. Il file FastAPI invia un messaggio TEXT con `POST /v1/channels/{channelId}/messages` tramite `urllib.request`. Riceve i webhook con `await request.body()` e decomprime da sé il gzip, perché FastAPI non lo fa. Richiede Python 3.10 o successivo e FastAPI.

## Prepara il workspace

Il tutorial di FastAPI installa con `pip install "fastapi[standard]"` dentro un ambiente virtuale e avvia l'app con `fastapi dev` ([tutorial di FastAPI](https://fastapi.tiangolo.com/tutorial/), consultato il 2026-11-05). Il file usa annotazioni `str | None`, come l'esempio Python di Omni, quindi richiede Python 3.10 o successivo.

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install "fastapi[standard]"
```

### Genera la Secret Key

Nella dashboard su app.omni.z-api.io, apri il menu Security e genera una Secret Key. Autentica ogni chiamata API come Bearer token e deve restare sul tuo backend ([autenticazione di Omni](https://developer.omni.z-api.io/en/authentication), consultato il 2026-11-05). Non confonderla con la Public Key, che serve all'SDK di connessione dei canali.

### Crea e collega un canale

Crea il canale via API, così ottieni il suo ID in risposta. Il corpo usa i valori di esempio della pagina di creazione del canale.

```bash
export OMNI_SECRET_KEY="YOUR_SECRET_KEY"
curl -s -X POST https://api.omni.z-api.io/v1/channels \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "My WhatsApp channel", "type": "META_WHATSAPP"}'
```
<!-- TODO:test Omni: POST /v1/channels returns 201 with id and token; a repeated name returns 409 channel_name_in_use -->

Un 201 restituisce `id`, il channelId che usano tutte le chiamate successive, e un `token` ([creare un canale in Omni](https://developer.omni.z-api.io/en/channels/create-channel), consultato il 2026-11-05). Un 409 con `"error": "channel_name_in_use"` significa che il nome è già in uso. Conserva l'`id`, perché elencare o leggere i canali richiede il ruolo ENTERPRISE. Poi collegalo al tuo numero nella dashboard («tramite dashboard o SDK», secondo la pagina).

### Registra un webhook firmato

Questo è l'esempio "With HMAC signature" della pagina di creazione del webhook, con l'URL sostituito da un segnaposto.

```bash
export OMNI_CHANNEL_ID="YOUR_CHANNEL_ID"
curl -s -X POST "https://api.omni.z-api.io/v1/channels/$OMNI_CHANNEL_ID/webhooks" \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://YOUR_DOMAIN/webhooks/omni", "events": ["MESSAGE_RECEIVED", "MESSAGE_STATUS"], "signing": true}'
```
<!-- TODO:test Omni: POST /v1/channels/{channelId}/webhooks with signing true returns 201 with a 64-character hex secret -->

Salva subito come `OMNI_WEBHOOK_SECRET` il `secret` esadecimale di 64 caratteri restituito dal 201, perché «non verrà più mostrato in nessun'altra chiamata» ([creare un webhook in Omni](https://developer.omni.z-api.io/en/webhooks/create-webhook), consultato il 2026-11-05). Ogni `PATCH` con `signing: true` emette un nuovo secret e invalida il precedente ([firma HMAC di Omni](https://developer.omni.z-api.io/en/webhooks/signature)). Lascia `signing` fuori da una PATCH, a meno che tu non voglia ruotare il secret.

### Dai al webhook un URL pubblico

Omni risponde 400 a `localhost`, `.localhost`, `.internal`, ai nomi senza punto, agli IP non pubblici e agli host assenti dal DNS ([introduzione ai webhook di Omni](https://developer.omni.z-api.io/en/webhooks/introduction), consultato il 2026-11-05). Esegui l'app su un host pubblico, oppure metti un tunnel davanti alla porta 8000 come nella [guida al test locale dei webhook](/academy/it/articles/whatsapp-webhook-local-testing-ngrok/).

## Il file completo

```python
# omni_quickstart.py
#   python omni_quickstart.py selftest
#   python omni_quickstart.py send 5511999999999 "Hello!"
#   fastapi dev omni_quickstart.py
import gzip
import hashlib
import hmac
import json
import os
import re
import sys
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import zlib

from fastapi import BackgroundTasks, FastAPI, Request, Response

API_BASE = os.environ.get("OMNI_API_BASE", "https://api.omni.z-api.io")
TOLERANCE_SECONDS = 300
KEEP_SECONDS = 24 * 60 * 60

def send_text(phone: str, text: str) -> str:
    secret_key = os.environ.get("OMNI_SECRET_KEY")
    channel_id = os.environ.get("OMNI_CHANNEL_ID")
    if not secret_key or not channel_id:
        raise RuntimeError("Set OMNI_SECRET_KEY and OMNI_CHANNEL_ID")
    body = {"recipient": {"identifier": phone}, "content": {"type": "TEXT", "body": {"message": text}}}
    req = urllib.request.Request(
        f"{API_BASE}/v1/channels/{urllib.parse.quote(channel_id, safe='')}/messages",
        data=json.dumps(body).encode(),
        method="POST",
        headers={"Authorization": f"Bearer {secret_key}", "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.loads(resp.read())["messageId"]
    except urllib.error.HTTPError as err:
        raw = err.read().decode("utf-8", "replace")
        try:
            data = json.loads(raw)
        except ValueError:
            data = None
        if err.code == 422 and isinstance(data, dict) and data.get("subCode") == "CHANNEL_DISCONNECTED":
            raise RuntimeError("Channel disconnected: reconnect it in the dashboard, then send again") from None
        raise RuntimeError(f"Send refused: HTTP {err.code} {raw}") from None

def verify_signature(
    secret: str,
    body: bytes,
    signature_header: str | None,
    idempotency_key: str | None,
    now: int | None = None,
) -> str | None:
    """Return None when the request is valid, or the reason it is not."""
    if not signature_header or not idempotency_key:
        return "missing headers"
    parts = {}
    for pair in signature_header.split(","):
        key, sep, value = pair.partition("=")
        if sep:
            parts[key.strip()] = value.strip()
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not re.fullmatch(r"[0-9]{1,12}", t) or not re.fullmatch(r"[0-9a-f]{64}", v1):
        return "malformed signature header"
    pieces = idempotency_key.rsplit(":", 2)
    if len(pieces) != 3:
        return "malformed idempotency key"
    topic, partition, offset = pieces

    canonical = b"\n".join([t.encode(), topic.encode(), partition.encode(), offset.encode(), body])
    expected = hmac.new(secret.encode(), canonical, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, v1):
        return "bad signature"
    if abs((int(time.time()) if now is None else now) - int(t)) > TOLERANCE_SECONDS:
        return "stale timestamp"
    return None

seen: dict[str, float] = {}  # delivery id -> first seen. Demo only: use a unique key in a database.

def first_delivery(delivery_id: str) -> bool:
    now = time.time()
    for old in [k for k, at in seen.items() if now - at > KEEP_SECONDS]:
        del seen[old]
    if delivery_id in seen:
        return False
    seen[delivery_id] = now
    return True

def handle_event(payload) -> None:
    try:
        msg = payload.get("message") if isinstance(payload, dict) else None
        if not isinstance(msg, dict):
            print("event without a message object", flush=True)
            return
        from_me = (msg.get("metadata") or {}).get("from_me")
        if from_me is not False:
            print(f"skip {msg.get('_id')}: from_me is {from_me}", flush=True)
            return
        contents = msg.get("contents") or [{}]
        first = contents[0] if isinstance(contents[0], dict) else {}
        if first.get("type") == "TEXT":
            sender = (msg.get("sender") or {}).get("identifier")
            print(f"text from {sender} on channel {msg.get('channel_id')}: {first.get('message')}", flush=True)
        else:
            print(f"non-text message {msg.get('_id')}", flush=True)
    except Exception:
        traceback.print_exc()

app = FastAPI()

@app.post("/webhooks/omni")
async def omni_webhook(request: Request, background_tasks: BackgroundTasks):
    secret = os.environ.get("OMNI_WEBHOOK_SECRET")
    if not secret:
        print("Set OMNI_WEBHOOK_SECRET", flush=True)
        return Response(status_code=500)  # 5xx is retried: Omni keeps retrying for up to 23 hours while you fix it
    raw = await request.body()
    body = raw
    if request.headers.get("content-encoding") == "gzip":
        try:
            body = gzip.decompress(raw)
        except (OSError, EOFError, zlib.error):
            return Response(status_code=400)
    delivery_id = request.headers.get("x-webhook-delivery-id")
    problem = verify_signature(
        secret, body, request.headers.get("x-webhook-signature"), request.headers.get("x-idempotency-key")
    )
    if problem:
        print(f"rejected delivery {delivery_id or '-'}: {problem}", flush=True)
        return Response(status_code=401)
    try:
        payload = json.loads(body)
    except ValueError:
        return Response(status_code=400)
    if delivery_id and not first_delivery(delivery_id):
        return Response(status_code=200)
    background_tasks.add_task(handle_event, payload)
    return Response(status_code=200)

def self_test() -> bool:
    # Test vector from the HMAC signing page of the Omni docs.
    secret = "a7f3c81e9d2b4605f1a8c3e7b9d40f6218273645a8b9c0d1e2f3041526374859"
    body = b'[{"field":"message_template_status_update","identifier":"01A0A4FBC8CD7DCBBBFAA8382F5514A5","type":"TEMPLATE_STATUS","value":{"event":"APPROVED","message_template_category":"UTILITY","message_template_id":"1587155656151346","message_template_language":"pt_BR","message_template_name":"exemplo_teste_assinatura_webhook","reason":"NONE"},"waba_id":"845974408299669"}]'
    signature = "t=1789474359,v1=c9a6812419c87dc26841fd802f1b4704f7dfe868b178ba55f9c432642be67230"
    key = "webhook.delivery.event:0:539402"
    t = 1789474359
    checks = [
        ("doc vector", verify_signature(secret, body, signature, key, t), None),
        ("tampered body", verify_signature(secret, body + b" ", signature, key, t), "bad signature"),
        ("stale t", verify_signature(secret, body, signature, key, t + TOLERANCE_SECONDS + 1), "stale timestamp"),
    ]
    ok = len(body) == 364
    print(f"body length {len(body)} bytes (content-length in the doc: 364)")
    for name, got, want in checks:
        ok = ok and got == want
        print(f"{'PASS' if got == want else 'FAIL'} {name}: {got or 'valid'}")
    return ok

if __name__ == "__main__":
    command = sys.argv[1] if len(sys.argv) > 1 else ""
    if command == "selftest":
        sys.exit(0 if self_test() else 1)
    if command == "send" and len(sys.argv) >= 3:
        try:
            print("accepted, messageId", send_text(sys.argv[2], " ".join(sys.argv[3:]) or "Hello!"))
        except RuntimeError as err:
            sys.exit(str(err))
        sys.exit(0)
    sys.exit("usage: python omni_quickstart.py selftest | send PHONE [TEXT]   (serve: fastapi dev omni_quickstart.py)")
```
<!-- TODO:test Omni: send_text against a live channel, and a real signed delivery (plain and gzip) accepted by /webhooks/omni -->

Imposta `OMNI_API_BASE` solo per puntare l'invio verso un mock. Esegui prima `python omni_quickstart.py selftest`. Controlla il verificatore sull'esempio della pagina sulla firma di Omni e stampa tre righe PASS.

## Verifica la firma su cinque campi

L'HMAC di Omni copre cinque campi uniti da un semplice `\n`: `t`, `topic`, `partition`, `offset` e il corpo grezzo ([firma HMAC di Omni](https://developer.omni.z-api.io/en/webhooks/signature), consultato il 2026-11-05). Non c'è alcun `\r` né un a capo finale. `t` e `v1` vengono da `x-webhook-signature: t=...,v1=...`. Gli altri tre vengono da `x-idempotency-key`, nel formato `{topic}:{partition}:{offset}`. `rsplit(":", 2)` divide quell'header solo sugli ultimi due segni di due punti, come fa l'esempio di Omni.

`verify_signature` segue l'esempio Python di Omni, con un argomento `now` per i test e una stringa con il motivo per il tuo log. Rifiuta anche un `v1` che non sia di 64 caratteri esadecimali minuscoli, così un header spazzatura riceve 401 prima che `compare_digest` possa sollevare un'eccezione.

### Leggi il corpo grezzo e decomprimilo da te

La route riceve una `Request`, non un modello Pydantic. Quando leggi il corpo direttamente dalla `Request`, FastAPI «non lo validerà, non lo convertirà e non lo documenterà» ([FastAPI, usare direttamente la Request](https://fastapi.tiangolo.com/advanced/using-request-directly/)). Un modello riserializzerebbe i byte, e la pagina sulla firma di Omni avverte che questo rompe la corrispondenza.

«Le richieste di 1024 byte o più vengono inviate con `content-encoding: gzip`», e l'HMAC copre i byte non compressi. La documentazione di FastAPI costruisce una sottoclasse `GzipRequest` per decomprimere i corpi delle richieste ([FastAPI, request e route personalizzate](https://fastapi.tiangolo.com/how-to/custom-request-and-route/)). Quindi la `Request` predefinita ti consegna byte compressi. La route chiama `gzip.decompress` quando l'header indica `gzip`. Se salti questo passaggio, gli eventi piccoli superano la verifica e quelli grandi falliscono. Se un proxy decomprime prima e rimuove l'header, il codice verifica ciò che riceve, come consiglia la pagina di Omni.

### Rifiuta i timestamp scaduti

La pagina sulla firma definisce 5 minuti «un valore ragionevole», e i suoi esempi usano 300 secondi. La documentazione non dice se un nuovo tentativo ore dopo porta un nuovo `t`. Se i nuovi tentativi compaiono nel log come scaduti, controlla prima questo.
<!-- TODO:test Omni: confirm a retried delivery (x-webhook-attempt > 1) carries a fresh t in x-webhook-signature -->

## Restituisci 200 entro 5 secondi, poi deduplica

Una consegna riesce solo con un 2xx «entro 5 secondi» ([consegna e nuovi tentativi di Omni](https://developer.omni.z-api.io/en/webhooks/delivery), consultato il 2026-11-05). La route accoda `handle_event` con `BackgroundTasks`, che viene eseguito dopo l'invio della risposta. Vedi [la guida al webhook della Cloud API con FastAPI](/academy/it/articles/whatsapp-webhook-python-fastapi-receive-messages/) per capire come funziona con una `Response` restituita.

| La tua risposta | Cosa fa Omni |
|---|---|
| 2xx entro 5 s | Consegnato, nessun nuovo tentativo |
| Nessuna risposta in 5 s, errore di connessione, 408, 429 o 5xx | Invia di nuovo dopo 1 min, 5 min, 30 min, 2 h, 6 h e 12 h |
| Qualsiasi altro 4xx, o 3xx | Nessun nuovo tentativo |

Sono fino a 7 tentativi entro 23 ore. L'equivalente di Meta è in [nuovi tentativi dei webhook quando l'endpoint è giù](/academy/it/articles/whatsapp-webhook-retries-endpoint-down/). Una firma non valida restituisce 401, che non viene mai ritentato. Un bug nel tuo verificatore fa perdere per sempre eventi reali, quindi tieni d'occhio le righe `rejected delivery`.

Conserva i valori `x-webhook-delivery-id` elaborati «per almeno 24 ore», come dice la pagina sulla consegna. Il dizionario `seen` si perde al riavvio, e ogni processo worker ne tiene una copia propria. In produzione, è una chiave univoca nel tuo database a decidere cosa è nuovo ([webhook duplicati e idempotenza](/academy/it/articles/n8n-duplicate-webhooks-idempotency/)).

I `BackgroundTasks` girano nello stesso processo, quindi un evento è perso se il processo muore dopo il 200. Scrivi prima il corpo in una coda o in una tabella se non puoi perderlo ([architettura a coda per i webhook](/academy/it/articles/whatsapp-webhook-queue-architecture-workers/)). Neanche l'ordine è garantito: ordina per `moment` e non far mai tornare indietro uno stato.

## Leggi il testo del messaggio

Il formato predefinito avvolge ogni evento in un oggetto `message` più `messageEventType`. Quel campo è «attualmente `NEW_MESSAGE` per tutti gli eventi di messaggio» ([struttura del payload di Omni](https://developer.omni.z-api.io/en/webhooks/payloads), consultato il 2026-11-05). Il testo si trova in `message.contents[0].message` quando `contents[0].type` è `TEXT`. `metadata.from_me` è «`true` quando inviato dall'azienda; `false` quando ricevuto dal contatto».

L'unico esempio TEXT della pagina è un invio via API con `from_me: true`, e la pagina dei payload non mostra esempi in entrata né di stato. Per questo `handle_event` stampa il testo solo quando `from_me` è `False` e registra il resto nel log senza tirare a indovinare sui campi.

## Invia un messaggio e leggi gli errori

Questo è il corpo della richiesta della pagina di invio testo di Omni, con la stringa del messaggio cambiata in `Hello!`.

```json
{
  "recipient": { "identifier": "5511999999999" },
  "content": {
    "type": "TEXT",
    "body": { "message": "Hello!" }
  }
}
```

```bash
export OMNI_SECRET_KEY="YOUR_SECRET_KEY"
export OMNI_CHANNEL_ID="YOUR_CHANNEL_ID"
python omni_quickstart.py send 5511999999999 "Hello!"
```
<!-- TODO:test Omni: send TEXT returns 200 with messageId; a disconnected channel returns 422 BUSINESS_RULE_VIOLATION / CHANNEL_DISCONNECTED -->

Un 200 restituisce `messageId`, una stringa esadecimale maiuscola di 32 caratteri ([invio testo di Omni](https://developer.omni.z-api.io/en/messages/send-text), consultato il 2026-11-05). Significa che l'API ha accettato il messaggio. Gli aggiornamenti di stato arrivano dopo come eventi `MESSAGE_STATUS`; aggiungi `MESSAGE_DELIVERY` a `events` per le conferme di consegna. `urllib` solleva `HTTPError` su un 4xx o 5xx, e `send_text` si dirama in base a `code` e `subCode`, perché il testo di `message` «può cambiare».

| Stato | `code` / `subCode` | Significato |
|---|---|---|
| 400 | `VALIDATION_ERROR` | Il corpo non corrisponde al tipo di contenuto |
| 401 | `"error": 401` | Secret Key non valida o assente |
| 422 | `BUSINESS_RULE_VIOLATION` / `CHANNEL_DISCONNECTED` | Non inviato e non conservato: ricollega, poi invia di nuovo |
| 422 | `BUSINESS_RULE_VIOLATION`, senza `subCode` | L'ha rifiutato un'altra regola di invio; il motivo è in `message` |
| 502 | variabile | Un errore dal lato di Omni |

Le righe vengono dalla [tabella degli errori di invio](https://developer.omni.z-api.io/en/messages/introduction) di Omni (consultato il 2026-11-05). Su WhatsApp, il testo in forma libera richiede una finestra di 24 ore aperta; fuori da quella invii un `TEMPLATE`. Con la restrizione IP attiva, una chiamata da un IP non in elenco riceve un 400 ([restrizione IP di Omni](https://developer.omni.z-api.io/en/security/ip-restriction), consultato il 2026-11-05).

## Prova il ricevitore in locale

Firma tu stesso una richiesta e inviala a `localhost`. Avvia l'app con il secret del webhook, ed esporta lo stesso valore nel terminale da cui fai i test.

```bash
export OMNI_WEBHOOK_SECRET="YOUR_WEBHOOK_SECRET"
fastapi dev omni_quickstart.py
```

L'esempio è il payload TEXT della pagina dei payload di Omni, compattato in una riga. La copia fatta con `sed` imposta `from_me` a `false`, così viene eseguito il ramo dei messaggi in entrata. Ogni richiesta è compressa con gzip, così viene eseguito anche il percorso di decompressione.

```bash
cat > sample.json <<'EOF'
{"message":{"_id":"019E6F1A93FE78DCB54332F9FF0CCAE7","tenant":"019DCEB3E93B7077B2447616B6DC8B91","tenant_owner":"email@z-api.io","channel_id":"019E4C54B1B375A28970B605CA9B03C3","created_by":"BARLING","created":1779980473342,"metadata":{"@class":".Metadata","forwarded":false,"from_api":true,"from_me":true,"middleware":"META_WHATSAPP","moment":1779980473342},"sender":{"@class":".Sender","identifier":"BARLING_SYSTEM","name":"Barling System"},"recipient":{"@class":".Recipient","identifier":"5544936181064","name":"5544936181064"},"contents":[{"@class":".TextContent","identifier":"019E6F1A93FE78DCB542303FF18D389A","internal_information":{},"message":"Hello! We have incredible news waiting for you.","state_items":[{"@class":".StateItem","identifier":"019E6F1A93FE78DCB5418E8D9D007FFB","integration_message_ids":[],"moment":1779980473342,"state":{"@class":".Pending","name":"PENDING"}}],"type":"TEXT"}],"attachments":[],"actions":[],"webhook_processed":false},"messageEventType":"NEW_MESSAGE"}
EOF
sed 's/"from_me":true/"from_me":false/' sample.json > inbound.json

post_signed() { # FILE OFFSET URL
  T=$(date +%s)
  SIG=$( { printf '%s\nwebhook.delivery.event\n0\n%s\n' "$T" "$2"; cat "$1"; } \
    | openssl dgst -sha256 -hmac "$OMNI_WEBHOOK_SECRET" | awk '{print $NF}')
  gzip -c "$1" | curl -s -o /dev/null -w '%{http_code}\n' -X POST "$3" \
    -H 'content-type: application/json' -H 'content-encoding: gzip' \
    -H "x-idempotency-key: webhook.delivery.event:0:$2" \
    -H "x-webhook-signature: t=$T,v1=$SIG" \
    -H "x-webhook-delivery-id: test-$2" -H 'x-webhook-attempt: 1' \
    --data-binary @-
}

post_signed sample.json 1 http://localhost:8000/webhooks/omni
post_signed inbound.json 2 http://localhost:8000/webhooks/omni
post_signed inbound.json 2 http://localhost:8000/webhooks/omni
```

Tutte e tre le richieste stampano `200`. La console mostra `skip ... from_me is True` per la prima e la riga di testo per la seconda. La terza riusa l'ID di consegna `test-2` e non stampa nulla. Esporta un secret diverso solo nel terminale di test e l'app risponde 401 con `bad signature`.

## Cosa cambia rispetto al webhook grezzo di Meta

Meta firma solo il corpo con il secret della tua app in `X-Hub-Signature-256`. La sua busta è `entry[].changes[].value`, come mostra [la guida al webhook della Cloud API con FastAPI](/academy/it/articles/whatsapp-webhook-python-fastapi-receive-messages/). Omni firma cinque campi con un secret per webhook, aggiunge un timestamp e invia un ID di consegna per la deduplica. Il suo corpo è la busta `message` propria di Omni, oppure il formato `Z_API` o `CHATWOOT` se imposti `payloadFormat`. Le pagine sui webhook non descrivono alcun passaggio di challenge in GET; registri l'URL con una chiamata API.

Lo stesso ricevitore si trova nel [quickstart con Express](/academy/it/articles/z-api-omni-quickstart-nodejs-express/) e nel [quickstart con PHP](/academy/it/articles/z-api-omni-quickstart-php/). Un solo abbonamento a Omni copre WhatsApp, Messenger, Instagram e Telegram, con webhook inclusi senza limite. [Vedi la documentazione](https://developer.omni.z-api.io/en)

*Il team di Z-API Omni*
