# Quickstart di Z-API Omni in Node.js: invia e ricevi con Express

> Invia un testo WhatsApp con l'API di Z-API Omni e ricevi webhook firmati in Express: auth Bearer, HMAC su cinque campi, gzip, replay e deduplica.

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

Per inviare e ricevere messaggi con Z-API Omni in Node.js ti servono un file e tre valori: una Secret Key, un ID di canale e un secret del webhook. Il file Express qui sotto invia un messaggio TEXT con `POST /v1/channels/{channelId}/messages` e riceve webhook firmati su una sola route. Richiede Node.js 24 o successivo ed Express 5, nient'altro.

## Prepara il workspace

Node.js 24 e 26 sono entrambe linee LTS, e la 26 è la più recente ([release di Node.js](https://nodejs.org/en/about/previous-releases), consultato il 2026-11-05).

```bash
npm install express@5
```

### Genera la Secret Key

Nella dashboard su app.omni.z-api.io, apri il menu Security e genera una Secret Key. Va nell'header `Authorization: Bearer` di ogni chiamata API 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`. Un 409 con `"error": "channel_name_in_use"` significa che il nome è già in uso ([creare un canale in Omni](https://developer.omni.z-api.io/en/channels/create-channel), consultato il 2026-11-05). 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

Il corpo qui sotto è 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 -->

Il 201 contiene un `secret` di 64 caratteri esadecimali. Salvalo subito come `OMNI_WEBHOOK_SECRET`, 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` successiva con `signing: true` genera 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 rifiuta con un 400 `localhost`, `.localhost`, `.internal`, i nomi senza punto, gli IP non pubblici e gli host assenti dal DNS ([introduzione ai webhook di Omni](https://developer.omni.z-api.io/en/webhooks/introduction), consultato il 2026-11-05). Pubblica il file su un host pubblico, oppure metti un tunnel davanti alla porta 3000 come nella [guida al test locale dei webhook](/academy/it/articles/whatsapp-webhook-local-testing-ngrok/).

## Il file completo

```javascript
// omni-quickstart.js
// node omni-quickstart.js selftest
// node omni-quickstart.js send 5511999999999 "Hello!"
// node omni-quickstart.js serve
const express = require('express');
const crypto = require('node:crypto');

const API_BASE = process.env.OMNI_API_BASE || 'https://api.omni.z-api.io';
const PORT = Number(process.env.PORT || 3000);
const TOLERANCE_SECONDS = 300;
const KEEP_MS = 24 * 60 * 60 * 1000;

async function sendText(phone, text) {
  const { OMNI_SECRET_KEY, OMNI_CHANNEL_ID } = process.env;
  if (!OMNI_SECRET_KEY || !OMNI_CHANNEL_ID) throw new Error('Set OMNI_SECRET_KEY and OMNI_CHANNEL_ID');
  const res = await fetch(`${API_BASE}/v1/channels/${encodeURIComponent(OMNI_CHANNEL_ID)}/messages`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${OMNI_SECRET_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      recipient: { identifier: phone },
      content: { type: 'TEXT', body: { message: text } },
    }),
  });
  const raw = await res.text();
  let data = {};
  try {
    data = JSON.parse(raw) ?? {};
  } catch {}
  if (res.ok && data.messageId) return data.messageId;
  if (res.status === 422 && data.subCode === 'CHANNEL_DISCONNECTED') {
    throw new Error('Channel disconnected: reconnect it in the dashboard, then send again');
  }
  throw new Error(`Send refused: HTTP ${res.status} ${raw}`);
}

// Returns null when the request is valid, or the reason it is not.
function verifySignature(secret, body, signatureHeader, idempotencyKey, now = Math.floor(Date.now() / 1000)) {
  if (typeof signatureHeader !== 'string' || typeof idempotencyKey !== 'string') return 'missing headers';
  const parts = {};
  for (const pair of signatureHeader.split(',')) {
    const i = pair.indexOf('=');
    if (i > 0) parts[pair.slice(0, i).trim()] = pair.slice(i + 1).trim();
  }
  const { t, v1 } = parts;
  if (!/^[0-9]{1,12}$/.test(t ?? '') || !/^[0-9a-f]{64}$/.test(v1 ?? '')) return 'malformed signature header';

  const last = idempotencyKey.lastIndexOf(':');
  const prev = last > 0 ? idempotencyKey.lastIndexOf(':', last - 1) : -1;
  if (prev < 0) return 'malformed idempotency key';
  const topic = idempotencyKey.slice(0, prev);
  const partition = idempotencyKey.slice(prev + 1, last);
  const offset = idempotencyKey.slice(last + 1);

  const canonical = Buffer.concat([Buffer.from(`${t}\n${topic}\n${partition}\n${offset}\n`, 'utf8'), body]);
  const expected = crypto.createHmac('sha256', secret).update(canonical).digest();
  if (!crypto.timingSafeEqual(expected, Buffer.from(v1, 'hex'))) return 'bad signature';
  if (Math.abs(now - Number(t)) > TOLERANCE_SECONDS) return 'stale timestamp';
  return null;
}

const seen = new Map(); // delivery id -> first seen (ms). Demo only: use a table with a unique key in production.

function firstDelivery(deliveryId) {
  const now = Date.now();
  for (const [id, at] of seen) {
    if (now - at <= KEEP_MS) break; // Map keeps insertion order, so the oldest entries come first
    seen.delete(id);
  }
  if (seen.has(deliveryId)) return false;
  seen.set(deliveryId, now);
  return true;
}

function handleEvent(payload) {
  const msg = payload?.message;
  if (!msg || typeof msg !== 'object') {
    console.log('event without a message object');
    return;
  }
  if (msg.metadata?.from_me !== false) {
    console.log(`skip ${msg._id}: from_me is ${msg.metadata?.from_me}`);
    return;
  }
  const first = msg.contents?.[0];
  if (first?.type === 'TEXT') {
    console.log(`text from ${msg.sender?.identifier} on channel ${msg.channel_id}: ${first.message}`);
  } else {
    console.log(`non-text message ${msg._id}`);
  }
}

function serve() {
  const secret = process.env.OMNI_WEBHOOK_SECRET;
  if (!secret) {
    console.error('Set OMNI_WEBHOOK_SECRET');
    process.exit(1);
  }
  const app = express();
  // inflate: true (the default) hands us the gzip body already decompressed.
  const rawJson = express.raw({ type: 'application/json', inflate: true, limit: '1mb' });

  app.post('/webhooks/omni', rawJson, (req, res) => {
    if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
    const deliveryId = req.get('x-webhook-delivery-id');
    const problem = verifySignature(secret, req.body, req.get('x-webhook-signature'), req.get('x-idempotency-key'));
    if (problem) {
      console.warn(`rejected delivery ${deliveryId ?? '-'}: ${problem}`);
      return res.sendStatus(401);
    }
    let payload;
    try {
      payload = JSON.parse(req.body.toString('utf8'));
    } catch {
      return res.sendStatus(400);
    }
    if (deliveryId && !firstDelivery(deliveryId)) return res.sendStatus(200);
    res.sendStatus(200);
    setImmediate(() => {
      try {
        handleEvent(payload);
      } catch (err) {
        console.error('handler failed', err);
      }
    });
  });

  app.listen(PORT, () => console.log(`listening on ${PORT}`));
}

function selfTest() {
  // Test vector from the HMAC signing page of the Omni docs.
  const secret = 'a7f3c81e9d2b4605f1a8c3e7b9d40f6218273645a8b9c0d1e2f3041526374859';
  const body = Buffer.from('[{"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"}]', 'utf8');
  const signature = 't=1789474359,v1=c9a6812419c87dc26841fd802f1b4704f7dfe868b178ba55f9c432642be67230';
  const key = 'webhook.delivery.event:0:539402';
  const t = 1789474359;
  const checks = [
    ['doc vector', verifySignature(secret, body, signature, key, t), null],
    ['tampered body', verifySignature(secret, Buffer.concat([body, Buffer.from(' ')]), signature, key, t), 'bad signature'],
    ['stale t', verifySignature(secret, body, signature, key, t + TOLERANCE_SECONDS + 1), 'stale timestamp'],
  ];
  let ok = body.length === 364;
  console.log(`body length ${body.length} bytes (content-length in the doc: 364)`);
  for (const [name, got, want] of checks) {
    const pass = got === want;
    ok = ok && pass;
    console.log(`${pass ? 'PASS' : 'FAIL'} ${name}: ${got ?? 'valid'}`);
  }
  return ok;
}

const [command, ...args] = process.argv.slice(2);
if (command === 'selftest') {
  process.exitCode = selfTest() ? 0 : 1;
} else if (command === 'send' && args[0]) {
  sendText(args[0], args.slice(1).join(' ') || 'Hello!')
    .then((id) => console.log(`accepted, messageId ${id}`))
    .catch((err) => {
      console.error(err.message);
      process.exitCode = 1;
    });
} else if (command === 'serve') {
  serve();
} else {
  console.error('usage: node omni-quickstart.js selftest | send PHONE [TEXT] | serve');
  process.exitCode = 2;
}
```
<!-- TODO:test Omni: sendText against a live channel, and a real signed delivery (plain and gzip) accepted by the serve route -->

Imposta `OMNI_API_BASE` solo per puntare l'invio verso un mock. Esegui prima `node omni-quickstart.js 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}`. Il topic può contenere punti, quindi il codice divide quell'header sugli ultimi due segni di due punti.

Il verificatore segue l'esempio Node di Omni, con un argomento `now` per i test. Restituisce una stringa con il motivo, utile per il tuo log. Rifiuta un `v1` che non sia di 64 caratteri esadecimali minuscoli, così `timingSafeEqual` non solleva mai un'eccezione per lunghezze diverse.

### Gzip ed express.raw

«Le richieste di 1024 byte o più vengono inviate con `content-encoding: gzip`», e l'HMAC copre i byte non compressi. `express.raw()` «supporta la decompressione automatica delle codifiche `gzip` e `deflate`», con `inflate` attivo per impostazione predefinita ([API di Express 5](https://expressjs.com/en/5x/api/express/)). Quindi `req.body` contiene già i byte decompressi. Per questo non passare alcuna codifica al verificatore, come dice la pagina di Omni: «Se il tuo framework HTTP decomprime il corpo per te, usa il corpo che ti restituisce».

`type` vale per impostazione predefinita `application/octet-stream`, quindi senza `type: 'application/json'` il corpo è `undefined`. Omni non pubblica una dimensione massima del payload, quindi il limite di `1mb` (predefinito `100kb`) è una scelta di questa guida. Monta il parser solo su questa route, perché un `express.json()` globale registrato prima consumerebbe lo stream.

### Rifiuta i timestamp scaduti

La pagina sulla firma definisce 5 minuti «un valore ragionevole», e i suoi esempi usano `toleranceSeconds = 300`. Tieni sincronizzato l'orologio del server. 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 -->

## Rispondi 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 risponde 200 e passa il payload a `setImmediate`.

| 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/). Un controllo della firma fallito restituisce 401, che non viene mai ritentato. Va bene per le richieste contraffatte, ma un bug nel tuo verificatore fa perdere per sempre eventi reali. Tieni d'occhio le righe di log `rejected delivery` dopo il passaggio in produzione.

La pagina sulla consegna dice di deduplicare su `x-webhook-delivery-id` e di conservare gli ID elaborati «per almeno 24 ore». La `Map` perde tutto al riavvio, quindi usa una chiave univoca nel tuo database ([webhook duplicati e idempotenza](/academy/it/articles/n8n-duplicate-webhooks-idempotency/)). Il controllo avviene dopo la verifica, così una richiesta contraffatta non può aggiungere un ID.

Se il processo muore dopo il 200, l'evento è perso. Per tutto ciò che non puoi perdere, scrivi prima il corpo grezzo in una coda o in una tabella ([architettura a coda per i webhook](/academy/it/articles/whatsapp-webhook-queue-architecture-workers/)). Neanche l'ordine è garantito: ordina per `moment` nel corpo e non far mai tornare indietro uno stato ([webhook fuori ordine](/academy/it/articles/whatsapp-webhooks-out-of-order-message-sequencing/)).

## Leggi il testo del messaggio

Nel formato predefinito, ogni evento ha un oggetto `message` di primo livello e un `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 `handleEvent` 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"
node omni-quickstart.js 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. Gestisci i rifiuti in base a `code` e `subCode`, perché il testo del messaggio «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, un TEXT in forma libera richiede una finestra di 24 ore aperta; fuori da quella invii un `TEMPLATE`. Se il workspace ha 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 il server 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"
node omni-quickstart.js serve
```

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:3000/webhooks/omni
post_signed inbound.json 2 http://localhost:3000/webhooks/omni
post_signed inbound.json 2 http://localhost:3000/webhooks/omni
```

Tutte e tre stampano `200`. Il server registra `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`, quindi non registra nulla. Esporta un `OMNI_WEBHOOK_SECRET` diverso solo nel terminale di test e il server 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 Express](/academy/it/articles/whatsapp-webhook-nodejs-express-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 FastAPI](/academy/it/articles/z-api-omni-quickstart-python-fastapi/) 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*
