# Quickstart di Z-API Omni in PHP: invia messaggi e verifica i webhook

> Invia un testo WhatsApp con l'API di Z-API Omni tramite cURL e verifica webhook firmati in PHP puro: php://input, gzdecode, hash_equals e deduplica.

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

Per inviare e ricevere messaggi con Z-API Omni in PHP puro ti servono un file e tre valori: una Secret Key, un ID di canale e un secret del webhook. Usa le estensioni `curl` e `zlib`. Il file invia un messaggio TEXT con cURL a `POST /v1/channels/{channelId}/messages`. Verifica l'HMAC a cinque campi di Omni con `hash_equals`, salva ogni evento e risponde 200; un comando separato elabora la coda. Niente framework e niente Composer.

## Prepara il workspace

Usa PHP 8.3 o successivo. PHP 8.4 e 8.5 sono in supporto attivo, e la 8.3 riceve correzioni di sicurezza fino al 31 dicembre 2027 ([versioni supportate di PHP](https://www.php.net/supported-versions.php), consultato il 2026-11-05). Controlla prima entrambe le estensioni.

```bash
php -v
php -m | grep -E '^(curl|zlib)$'
```

### 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/omni-quickstart.php", "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). Quindi non puoi registrare `php -S` sul tuo portatile. Pubblica il file dietro un web server con HTTPS, oppure usa un tunnel come nella [guida al test locale dei webhook](/academy/it/articles/whatsapp-webhook-local-testing-ngrok/).

## Il file completo

```php
<?php
// omni-quickstart.php
//   php omni-quickstart.php selftest
//   php omni-quickstart.php send 5511999999999 "Hello!"
//   php omni-quickstart.php process
//   php -S 127.0.0.1:8000 omni-quickstart.php   (local receiver)
declare(strict_types=1);

const TOLERANCE_SECONDS = 300;
const KEEP_SECONDS = 86400;

function send_text(string $phone, string $text): string
{
    $secretKey = getenv('OMNI_SECRET_KEY');
    $channelId = getenv('OMNI_CHANNEL_ID');
    if ($secretKey === false || $secretKey === '' || $channelId === false || $channelId === '') {
        throw new RuntimeException('Set OMNI_SECRET_KEY and OMNI_CHANNEL_ID');
    }
    $base = getenv('OMNI_API_BASE') ?: 'https://api.omni.z-api.io';
    $ch = curl_init($base . '/v1/channels/' . rawurlencode($channelId) . '/messages');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $secretKey,
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'recipient' => ['identifier' => $phone],
            'content' => ['type' => 'TEXT', 'body' => ['message' => $text]],
        ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
    ]);
    $raw = curl_exec($ch);
    if ($raw === false) {
        throw new RuntimeException('cURL error: ' . curl_error($ch));
    }
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $data = json_decode($raw, true);
    $data = is_array($data) ? $data : [];
    if ($status >= 200 && $status < 300 && isset($data['messageId'])) {
        return (string) $data['messageId'];
    }
    if ($status === 422 && ($data['subCode'] ?? null) === 'CHANNEL_DISCONNECTED') {
        throw new RuntimeException('Channel disconnected: reconnect it in the dashboard, then send again');
    }
    throw new RuntimeException("Send refused: HTTP $status $raw");
}

// Returns null when the request is valid, or the reason it is not.
function verify_signature(string $secret, string $body, ?string $signatureHeader, ?string $idempotencyKey, ?int $now = null): ?string
{
    if ($signatureHeader === null || $signatureHeader === '' || $idempotencyKey === null || $idempotencyKey === '') {
        return 'missing headers';
    }
    $parts = [];
    foreach (explode(',', $signatureHeader) as $pair) {
        $i = strpos($pair, '=');
        if ($i !== false) {
            $parts[trim(substr($pair, 0, $i))] = trim(substr($pair, $i + 1));
        }
    }
    $t = (string) ($parts['t'] ?? '');
    $v1 = (string) ($parts['v1'] ?? '');
    if (preg_match('/^[0-9]{1,12}\z/', $t) !== 1 || preg_match('/^[0-9a-f]{64}\z/', $v1) !== 1) {
        return 'malformed signature header';
    }
    $pieces = explode(':', $idempotencyKey);
    if (count($pieces) < 3) {
        return 'malformed idempotency key';
    }
    $offset = array_pop($pieces);
    $partition = array_pop($pieces);
    $topic = implode(':', $pieces); // the topic may contain dots: split on the last two colons only

    $canonical = $t . "\n" . $topic . "\n" . $partition . "\n" . $offset . "\n" . $body;
    $expected = hash_hmac('sha256', $canonical, $secret);
    if (!hash_equals($expected, $v1)) {
        return 'bad signature';
    }
    if (abs(($now ?? time()) - (int) $t) > TOLERANCE_SECONDS) {
        return 'stale timestamp';
    }
    return null;
}

function data_dir(): string
{
    $dir = getenv('OMNI_DATA_DIR') ?: sys_get_temp_dir() . '/omni-quickstart';
    foreach (['seen', 'queue'] as $sub) {
        if (!is_dir("$dir/$sub") && !mkdir("$dir/$sub", 0700, true) && !is_dir("$dir/$sub")) {
            throw new RuntimeException("Cannot create $dir/$sub");
        }
    }
    return $dir;
}

function receive_webhook(): void
{
    $secret = getenv('OMNI_WEBHOOK_SECRET');
    if ($secret === false || $secret === '') {
        error_log('omni: set OMNI_WEBHOOK_SECRET');
        http_response_code(500); // 5xx is retried: Omni keeps retrying for up to 23 hours while you fix it
        return;
    }
    $body = (string) file_get_contents('php://input');
    if (($_SERVER['HTTP_CONTENT_ENCODING'] ?? '') === 'gzip') {
        $body = gzdecode($body);
        if ($body === false) {
            http_response_code(400);
            return;
        }
    }
    $deliveryId = (string) ($_SERVER['HTTP_X_WEBHOOK_DELIVERY_ID'] ?? '');
    $problem = verify_signature(
        $secret,
        $body,
        $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? null,
        $_SERVER['HTTP_X_IDEMPOTENCY_KEY'] ?? null
    );
    if ($problem !== null) {
        error_log('omni: rejected delivery ' . ($deliveryId !== '' ? $deliveryId : '-') . ": $problem");
        http_response_code(401);
        return;
    }
    try {
        json_decode($body, true, 512, JSON_THROW_ON_ERROR);
    } catch (JsonException) {
        http_response_code(400);
        return;
    }
    try {
        $dir = data_dir();
        $marker = $deliveryId === '' ? null : "$dir/seen/" . hash('sha256', $deliveryId);
        if ($marker !== null && is_file($marker)) {
            http_response_code(200); // already stored once
            return;
        }
        $name = sprintf('%s/queue/%016d-%s', $dir, (int) (microtime(true) * 1e6), bin2hex(random_bytes(6)));
        if (file_put_contents("$name.tmp", $body) === false || !rename("$name.tmp", "$name.json")) {
            throw new RuntimeException('Cannot store the event');
        }
        if ($marker !== null) {
            touch($marker);
        }
    } catch (Throwable $e) {
        error_log('omni: ' . $e->getMessage());
        http_response_code(500);
        return;
    }
    http_response_code(200);
}

function handle_event(mixed $payload): void
{
    $msg = is_array($payload) ? ($payload['message'] ?? null) : null;
    if (!is_array($msg)) {
        echo "event without a message object\n";
        return;
    }
    $fromMe = $msg['metadata']['from_me'] ?? null;
    if ($fromMe !== false) {
        echo 'skip ', $msg['_id'] ?? '?', ': from_me is ', var_export($fromMe, true), "\n";
        return;
    }
    $first = $msg['contents'][0] ?? null;
    if (is_array($first) && ($first['type'] ?? null) === 'TEXT') {
        echo 'text from ', $msg['sender']['identifier'] ?? '?', ' on channel ', $msg['channel_id'] ?? '?', ': ', $first['message'] ?? '', "\n";
    } else {
        echo 'non-text message ', $msg['_id'] ?? '?', "\n";
    }
}

function process_events(): int
{
    $dir = data_dir();
    $files = glob("$dir/queue/*.json") ?: [];
    sort($files);
    foreach ($files as $file) {
        $body = file_get_contents($file);
        handle_event($body === false ? null : json_decode($body, true));
        unlink($file);
    }
    foreach (glob("$dir/seen/*") ?: [] as $marker) {
        $mtime = filemtime($marker);
        if ($mtime !== false && $mtime < time() - KEEP_SECONDS) {
            unlink($marker);
        }
    }
    printf("processed %d event(s)\n", count($files));
    return 0;
}

function self_test(): int
{
    // Test vector from the HMAC signing page of the Omni docs.
    $secret = 'a7f3c81e9d2b4605f1a8c3e7b9d40f6218273645a8b9c0d1e2f3041526374859';
    $body = '[{"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), null],
        'tampered body' => [verify_signature($secret, $body . ' ', $signature, $key, $t), 'bad signature'],
        'stale t' => [verify_signature($secret, $body, $signature, $key, $t + TOLERANCE_SECONDS + 1), 'stale timestamp'],
    ];
    $ok = strlen($body) === 364;
    printf("body length %d bytes (content-length in the doc: 364)\n", strlen($body));
    foreach ($checks as $name => [$got, $want]) {
        $ok = $ok && $got === $want;
        printf("%s %s: %s\n", $got === $want ? 'PASS' : 'FAIL', $name, $got ?? 'valid');
    }
    return $ok ? 0 : 1;
}

function cli_main(array $argv): int
{
    $command = $argv[1] ?? '';
    try {
        if ($command === 'selftest') {
            return self_test();
        }
        if ($command === 'process') {
            return process_events();
        }
        if ($command === 'send' && isset($argv[2])) {
            $text = implode(' ', array_slice($argv, 3));
            $messageId = send_text($argv[2], $text !== '' ? $text : 'Hello!');
            echo "accepted, messageId $messageId\n";
            return 0;
        }
    } catch (Throwable $e) {
        fwrite(STDERR, $e->getMessage() . "\n");
        return 1;
    }
    fwrite(STDERR, "usage: php omni-quickstart.php selftest | send PHONE [TEXT] | process\n");
    return 2;
}

if (PHP_SAPI === 'cli') {
    exit(cli_main($argv));
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    http_response_code(405);
    exit;
}
receive_webhook();
```
<!-- TODO:test Omni: send_text against a live channel, and a real signed delivery (plain and gzip) accepted by the web entry point -->

Imposta `OMNI_API_BASE` solo per puntare l'invio verso un mock. `OMNI_DATA_DIR` contiene gli eventi salvati e i marcatori di consegna, e per impostazione predefinita è una cartella dentro la directory temporanea di sistema. Tienila fuori dalla web root. Esegui prima `php omni-quickstart.php 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}`.

La documentazione di Omni pubblica esempi di verifica solo per Node.js e Python, quindi `verify_signature` è un porting di quella logica. Divide l'header sugli ultimi due segni di due punti e restituisce una stringa con il motivo per il tuo log.

### Leggi il corpo e gli header

`php://input` è «uno stream di sola lettura che permette di leggere i dati grezzi dal corpo della richiesta» ([stream di I/O di PHP](https://www.php.net/manual/en/wrappers.php.php)). Il file verifica quella stringa prima di qualsiasi `json_decode`, perché la pagina sulla firma di Omni avverte che il JSON riserializzato non corrisponde più.

Gli header arrivano in `$_SERVER` «con il nome `HTTP_` seguito dal nome dell'header, in maiuscolo e con trattini bassi al posto dei trattini» ([PHP $_SERVER](https://www.php.net/manual/en/reserved.variables.server.php)). Quindi `x-webhook-signature` diventa `HTTP_X_WEBHOOK_SIGNATURE`. Non tutti i web server li forniscono, avverte la stessa pagina, quindi un header mancante fallisce come `missing headers`.

### Decomprimi prima di calcolare l'hash

«Le richieste di 1024 byte o più vengono inviate con `content-encoding: gzip`», e l'HMAC copre i byte non compressi. `php://input` ti consegna ciò che è arrivato, quindi il file chiama `gzdecode`, che restituisce la stringa decodificata o `false` ([PHP gzdecode](https://www.php.net/manual/en/function.gzdecode.php)). Senza questo passaggio, gli eventi piccoli superano la verifica e quelli grandi falliscono. Se il tuo web server decomprime prima, usa ciò che ti consegna, come consiglia la pagina di Omni.

### Confronta in tempo costante

`hash_hmac('sha256', $canonical, $secret)` restituisce esadecimale minuscolo. `hash_equals` è sicura contro i timing attack, e il manuale di PHP dice «È importante passare la stringa fornita dall'utente come secondo parametro» ([PHP hash_equals](https://www.php.net/manual/en/function.hash-equals.php)).

La pagina sulla firma definisce una finestra di 5 minuti «un valore ragionevole». 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 -->

## Salva, rispondi 200, elabora dopo

Una consegna riesce solo con un 2xx «entro 5 secondi». La pagina sulla consegna di Omni dice di salvare l'evento, rispondere e fare il lavoro pesante fuori dalla richiesta ([consegna e nuovi tentativi di Omni](https://developer.omni.z-api.io/en/webhooks/delivery), consultato il 2026-11-05). L'entry point web scrive il corpo verificato in `queue/` e restituisce 200. `php omni-quickstart.php process` gestisce la coda, da cron o in un ciclo.

| 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/). Gli errori di salvataggio e un secret mancante restituiscono 500 di proposito, così Omni ritenta. 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`.

PHP non conserva memoria tra le richieste, quindi la deduplica non può stare in una variabile. Il file scrive un marcatore per ogni `x-webhook-delivery-id` ed elimina i marcatori più vecchi di 24 ore, il minimo richiesto da Omni. Due tentativi che arrivano nello stesso istante potrebbero passare entrambi, cosa che una chiave univoca nel tuo database impedisce ([webhook duplicati e idempotenza](/academy/it/articles/n8n-duplicate-webhooks-idempotency/)). L'ordine non è garantito, quindi ordina per `moment`, non per arrivo.

## 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"
php omni-quickstart.php 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. Diramati 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 al server integrato di PHP. Primo terminale:

```bash
export OMNI_WEBHOOK_SECRET="YOUR_WEBHOOK_SECRET"
export OMNI_DATA_DIR="/tmp/omni-quickstart"
php -S 127.0.0.1:8000 omni-quickstart.php
```

Nel secondo, esporta gli stessi due valori. 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 `gzdecode`.

```bash
export OMNI_WEBHOOK_SECRET="YOUR_WEBHOOK_SECRET"
export OMNI_DATA_DIR="/tmp/omni-quickstart"
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://127.0.0.1:8000/omni-quickstart.php
post_signed inbound.json 2 http://127.0.0.1:8000/omni-quickstart.php
post_signed inbound.json 2 http://127.0.0.1:8000/omni-quickstart.php
php omni-quickstart.php process
```

Tutte e tre le richieste stampano `200`, e la terza non salva nulla perché l'ID di consegna `test-2` ha già un marcatore. `process` stampa poi `skip ...: from_me is true`, la riga di testo e `processed 2 event(s)`. Invia con un secret diverso nel secondo terminale e la richiesta riceve 401, con `bad signature` nella console del server.

## 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` ([webhook della Cloud API con Laravel](/academy/it/articles/whatsapp-webhook-laravel-receive-messages/), [invio con la Cloud API in PHP](/academy/it/articles/send-whatsapp-message-php-cloud-api/)). 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 FastAPI](/academy/it/articles/z-api-omni-quickstart-python-fastapi/). 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*
