# Quickstart de Z-API Omni en Node.js: enviar y recibir con Express

> Envía un texto de WhatsApp con la API de Z-API Omni y recibe webhooks firmados en Express: auth Bearer, HMAC sobre cinco campos, gzip, replay y deduplicación.

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

Para enviar y recibir mensajes con Z-API Omni en Node.js, necesitas un archivo y tres valores: una Secret Key, un ID de canal y un secreto de webhook. El archivo de Express de abajo envía un mensaje TEXT con `POST /v1/channels/{channelId}/messages` y recibe webhooks firmados en una sola ruta. Necesita Node.js 24 o posterior y Express 5, nada más.

## Prepara el workspace

Node.js 24 y 26 son líneas LTS, y la 26 es la más reciente ([versiones de Node.js](https://nodejs.org/en/about/previous-releases), consultado el 2026-11-05).

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

### Genera la Secret Key

En el panel de app.omni.z-api.io, abre el menú Security y genera una Secret Key. Va en el encabezado `Authorization: Bearer` de cada llamada a la API y debe quedarse en tu backend ([autenticación de Omni](https://developer.omni.z-api.io/en/authentication), consultado el 2026-11-05). No la confundas con la Public Key, que es para el SDK de conexión de canales.

### Crea y conecta un canal

Crea el canal por API para recibir su ID en la respuesta. El cuerpo usa los valores de ejemplo de la página de creación de canales.

```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 devuelve `id`, el channelId que usan todas las llamadas posteriores, y un `token`. Un 409 con `"error": "channel_name_in_use"` significa que el nombre ya está en uso ([crear canal en Omni](https://developer.omni.z-api.io/en/channels/create-channel), consultado el 2026-11-05). Guarda el `id`, porque listar o leer canales requiere el rol ENTERPRISE. Después, conéctalo a tu número en el panel ("por el panel o por el SDK", según la página).

### Registra un webhook firmado

El cuerpo de abajo es el ejemplo "With HMAC signature" (con firma HMAC) de la página de creación de webhooks, con la URL sustituida por un placeholder.

```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 -->

El 201 trae un `secret` de 64 caracteres hexadecimales. Guárdalo ahora como `OMNI_WEBHOOK_SECRET`, porque "no se volverá a mostrar en ninguna otra llamada" ([crear webhook en Omni](https://developer.omni.z-api.io/en/webhooks/create-webhook), consultado el 2026-11-05). Cada `PATCH` posterior con `signing: true` genera un secreto nuevo e invalida el anterior ([firma HMAC de Omni](https://developer.omni.z-api.io/en/webhooks/signature)). No incluyas `signing` en un PATCH salvo que quieras rotarlo.

### Dale al webhook una URL pública

Omni rechaza con un 400 `localhost`, `.localhost`, `.internal`, los nombres sin punto, las IP no públicas y los hosts que no están en el DNS ([introducción a los webhooks de Omni](https://developer.omni.z-api.io/en/webhooks/introduction), consultado el 2026-11-05). Despliega el archivo en un host público, o pon un túnel delante del puerto 3000 como en [la guía para probar webhooks en local](/academy/es/articles/whatsapp-webhook-local-testing-ngrok/).

## El archivo 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 -->

Define `OMNI_API_BASE` solo para apuntar el envío a un mock. Ejecuta primero `node omni-quickstart.js selftest`. Comprueba el verificador con el ejemplo de la página de firma de Omni e imprime tres líneas PASS.

## Verifica la firma sobre cinco campos

El HMAC de Omni cubre cinco campos unidos por un `\n` simple: `t`, `topic`, `partition`, `offset` y el cuerpo sin procesar ([firma HMAC de Omni](https://developer.omni.z-api.io/en/webhooks/signature), consultado el 2026-11-05). No hay `\r` ni salto de línea final. `t` y `v1` vienen de `x-webhook-signature: t=...,v1=...`. Los otros tres vienen de `x-idempotency-key`, con el formato `{topic}:{partition}:{offset}`. El topic puede contener puntos, así que el código divide ese encabezado por sus dos últimos caracteres `:`.

El verificador sigue el ejemplo de Node de Omni, con un argumento `now` para las pruebas. Devuelve un texto con el motivo para tu log. Rechaza un `v1` que no tenga 64 caracteres hexadecimales en minúscula, así `timingSafeEqual` nunca lanza un error por longitudes distintas.

### Gzip y express.raw

"Las solicitudes de 1024 bytes o más se envían con `content-encoding: gzip`", y el HMAC cubre los bytes sin comprimir. `express.raw()` "admite la descompresión automática de las codificaciones `gzip` y `deflate`", con `inflate` activado por defecto ([API de Express 5](https://expressjs.com/en/5x/api/express/)). Eso significa que `req.body` ya contiene los bytes descomprimidos. Así que no le pases ninguna codificación al verificador, como dice la página de Omni: "Si tu framework HTTP descomprime el cuerpo por ti, usa el cuerpo que te entrega".

`type` vale `application/octet-stream` por defecto, así que sin `type: 'application/json'` el cuerpo es `undefined`. Omni no publica un tamaño máximo de payload, así que el límite de `1mb` (por defecto `100kb`) es una elección de esta guía. Monta el parser solo en esta ruta, porque un `express.json()` global registrado antes consumiría el stream.

### Rechaza las marcas de tiempo vencidas

La página de firma llama a 5 minutos "un valor razonable", y sus ejemplos usan `toleranceSeconds = 300`. Mantén sincronizado el reloj del servidor. La documentación no dice si un reintento horas después lleva un `t` nuevo. Si los reintentos aparecen en tu log como vencidos, revisa esto primero.
<!-- TODO:test Omni: confirm a retried delivery (x-webhook-attempt > 1) carries a fresh t in x-webhook-signature -->

## Responde 200 en menos de 5 segundos y después deduplica

Una entrega solo tiene éxito con un 2xx "en menos de 5 segundos" ([entrega y reintentos en Omni](https://developer.omni.z-api.io/en/webhooks/delivery), consultado el 2026-11-05). La ruta responde 200 y le pasa el payload a `setImmediate`.

| Tu respuesta | Qué hace Omni |
|---|---|
| 2xx en menos de 5 s | Entregado, sin reintento |
| Sin respuesta en 5 s, error de conexión, 408, 429 o 5xx | Vuelve a enviar después de 1 min, 5 min, 30 min, 2 h, 6 h y 12 h |
| Cualquier otro 4xx, o 3xx | Sin reintento |

Son hasta 7 intentos en 23 horas. El equivalente de Meta está en [reintentos de webhooks cuando el endpoint está caído](/academy/es/articles/whatsapp-webhook-retries-endpoint-down/). Una verificación de firma fallida devuelve 401, que nunca se reintenta. Eso sirve contra solicitudes falsificadas, pero un bug en tu verificador descarta eventos reales para siempre. Vigila las líneas de log `rejected delivery` después de salir a producción.

La página de entrega dice que hay que deduplicar por `x-webhook-delivery-id` y guardar los ID procesados "durante al menos 24 horas". El `Map` lo pierde todo al reiniciar, así que usa una clave única en tu base de datos ([webhooks duplicados e idempotencia](/academy/es/articles/n8n-duplicate-webhooks-idempotency/)). La comprobación corre después de la verificación, así que una solicitud falsificada no puede añadir un ID.

Si el proceso muere después del 200, el evento se pierde. Para todo lo que no puedas perder, escribe primero el cuerpo sin procesar en una cola o una tabla ([arquitectura de colas para webhooks](/academy/es/articles/whatsapp-webhook-queue-architecture-workers/)). Tampoco está garantizado el orden: ordena por `moment` en el cuerpo y nunca hagas retroceder un estado ([webhooks fuera de orden](/academy/es/articles/whatsapp-webhooks-out-of-order-message-sequencing/)).

## Lee el texto del mensaje

En el formato por defecto, cada evento tiene un objeto `message` en el nivel superior y un `messageEventType`. Ese campo es "actualmente `NEW_MESSAGE` para todos los eventos de mensaje" ([estructura del payload en Omni](https://developer.omni.z-api.io/en/webhooks/payloads), consultado el 2026-11-05). El texto está en `message.contents[0].message` cuando `contents[0].type` es `TEXT`. `metadata.from_me` es "`true` cuando lo envía la empresa; `false` cuando se recibe del contacto".

El único ejemplo TEXT de la página es un envío por API con `from_me: true`, y la página de payloads no muestra ningún ejemplo entrante ni de estado. Por eso `handleEvent` imprime el texto solo cuando `from_me` es `false` y registra el resto sin adivinar campos.

## Envía un mensaje y lee los errores

Este es el cuerpo de la solicitud de la página de envío de texto de Omni, con el texto del mensaje cambiado a `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 devuelve `messageId`, una cadena hexadecimal en mayúsculas de 32 caracteres ([enviar texto en Omni](https://developer.omni.z-api.io/en/messages/send-text), consultado el 2026-11-05). Significa que la API aceptó el mensaje. Las actualizaciones de estado llegan después como eventos `MESSAGE_STATUS`; añade `MESSAGE_DELIVERY` a `events` para recibir confirmaciones de entrega. Maneja los rechazos por `code` y `subCode`, porque el texto del mensaje "puede cambiar".

| Estado | `code` / `subCode` | Significado |
|---|---|---|
| 400 | `VALIDATION_ERROR` | El cuerpo no corresponde al tipo de contenido |
| 401 | `"error": 401` | Secret Key inválida o ausente |
| 422 | `BUSINESS_RULE_VIOLATION` / `CHANNEL_DISCONNECTED` | No se envió ni se guardó: reconecta y vuelve a enviar |
| 422 | `BUSINESS_RULE_VIOLATION`, sin `subCode` | Otra regla de envío lo rechazó; el motivo está en `message` |
| 502 | variable | Un fallo del lado de Omni |

Las filas vienen de la [tabla de errores de envío](https://developer.omni.z-api.io/en/messages/introduction) de Omni (consultada el 2026-11-05). En WhatsApp, un TEXT libre necesita una ventana de atención al cliente de 24 horas abierta; fuera de ella, envías un `TEMPLATE`. Si el workspace tiene activada la restricción por IP, una llamada desde una IP que no está en la lista recibe un 400 ([restricción por IP en Omni](https://developer.omni.z-api.io/en/security/ip-restriction), consultado el 2026-11-05).

## Prueba el receptor en local

Firma tú mismo una solicitud y envíala a `localhost`. Arranca el servidor con el secreto del webhook, y exporta el mismo valor en la terminal desde la que pruebas.

```bash
export OMNI_WEBHOOK_SECRET="YOUR_WEBHOOK_SECRET"
node omni-quickstart.js serve
```

El ejemplo es el payload TEXT de la página de payloads de Omni, compactado en una línea. La copia con `sed` cambia `from_me` a `false` para que corra la rama de entrada. Cada solicitud va comprimida con gzip, así que también corre la ruta de descompresión.

```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
```

Las tres imprimen `200`. El servidor registra `skip ... from_me is true` para la primera y la línea de texto para la segunda. La tercera reutiliza el ID de entrega `test-2`, así que no registra nada. Exporta un `OMNI_WEBHOOK_SECRET` distinto solo en la terminal de prueba y el servidor responde 401 con `bad signature`.

## En qué se diferencia del webhook directo de Meta

Meta firma solo el cuerpo con el secreto de tu app en `X-Hub-Signature-256`. Su envoltorio es `entry[].changes[].value`, como muestra [la guía de webhooks de la Cloud API con Express](/academy/es/articles/whatsapp-webhook-nodejs-express-receive-messages/). Omni firma cinco campos con un secreto por webhook, añade una marca de tiempo y envía un ID de entrega para deduplicar. Su cuerpo es el envoltorio `message` propio de Omni, o el formato `Z_API` o `CHATWOOT` si defines `payloadFormat`. Las páginas de webhooks no describen ningún paso de verificación por GET; registras la URL con una llamada a la API.

El mismo receptor está en [el quickstart de FastAPI](/academy/es/articles/z-api-omni-quickstart-python-fastapi/) y en [el quickstart de PHP](/academy/es/articles/z-api-omni-quickstart-php/). Una suscripción de Omni cubre WhatsApp, Messenger, Instagram y Telegram, con webhooks incluidos sin límite. [Ver la documentación](https://developer.omni.z-api.io/es)

*Equipo de Z-API Omni*
