· 7 min read

Z-API Omni quickstart in PHP: send messages and verify webhooks


To send and receive messages with Z-API Omni in plain PHP, you need one file and three values: a Secret Key, a channel ID and a webhook secret. It uses the curl and zlib extensions. The file sends a TEXT message with cURL to POST /v1/channels/{channelId}/messages. It verifies Omni’s five-field HMAC with hash_equals, stores each event and answers 200; a separate command processes the queue. There is no framework and no Composer.

Set up the workspace

Use PHP 8.3 or later. PHP 8.4 and 8.5 are in active support, and 8.3 gets security fixes until 31 Dec 2027 (PHP supported versions, accessed 2026-11-05). Check both extensions first.

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

Generate the Secret Key

In the dashboard at app.omni.z-api.io, open the Security menu and generate a Secret Key. It authenticates every API call as a Bearer token and must stay on your backend (Omni authentication, accessed 2026-11-05). Don’t confuse it with the Public Key, which is for the channel-connection SDK.

Create and connect a channel

Create the channel by API so you get its ID back. The body uses the example values from the create-channel page.

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"}'

A 201 returns id, the channelId every later call uses, and a token (Omni create channel, accessed 2026-11-05). A 409 with "error": "channel_name_in_use" means the name is taken. Keep the id, because listing or reading channels requires the ENTERPRISE role. Then connect it to your number in the dashboard (“via dashboard or SDK”, per the page).

Register a signed webhook

This is the “With HMAC signature” example from the create-webhook page, with the URL replaced by a placeholder.

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}'

Save the 64-hex secret from the 201 as OMNI_WEBHOOK_SECRET now, since “it will not be shown again in any other call” (Omni create webhook, accessed 2026-11-05). Each PATCH with signing: true issues a new secret and invalidates the old one (Omni HMAC signing). Leave signing out of a PATCH unless you mean to rotate.

Give the webhook a public URL

Omni answers 400 to localhost, .localhost, .internal, dotless names, non-public IPs and hosts missing from DNS (Omni webhooks introduction, accessed 2026-11-05). So php -S on your laptop can’t be registered. Deploy the file behind a web server with HTTPS, or use a tunnel as in the local webhook testing guide.

The full file

<?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();

Set OMNI_API_BASE only to point the send at a mock. OMNI_DATA_DIR holds the stored events and the delivery markers, and it defaults to a folder under the system temp directory. Keep it outside the web root. Run php omni-quickstart.php selftest first. It checks the verifier against Omni’s signing-page example and prints three PASS lines.

Verify the signature over five fields

Omni’s HMAC covers five fields joined by a bare \n: t, topic, partition, offset and the raw body (Omni HMAC signing, accessed 2026-11-05). There is no \r and no trailing newline. t and v1 come from x-webhook-signature: t=...,v1=.... The other three come from x-idempotency-key, formatted {topic}:{partition}:{offset}.

Omni’s docs publish verification samples for Node.js and Python only, so verify_signature is a port of that logic. It splits the header on its last two colons and returns a reason string for your log.

Read the body and the headers

php://input is “a read-only stream that allows you to read raw data from the request body” (PHP I/O streams). The file verifies that string before any json_decode, because Omni’s signing page warns that re-serialized JSON no longer matches.

Headers arrive in $_SERVER “named HTTP_ followed by the header name, capitalized and with underscores instead of hyphens” (PHP $_SERVER). So x-webhook-signature is HTTP_X_WEBHOOK_SIGNATURE. Not every web server provides them, the same page warns, so a missing header fails as missing headers.

Decompress before you hash

“Requests of 1024 bytes or more are sent with content-encoding: gzip”, and the HMAC covers the uncompressed bytes. php://input hands you what arrived, so the file calls gzdecode, which returns the decoded string or false (PHP gzdecode). Without it, small events verify and large ones fail. If your web server decompresses first, use what it gives you, as Omni’s page advises.

Compare in constant time

hash_hmac('sha256', $canonical, $secret) returns lowercase hex. hash_equals is timing-attack safe, and PHP’s manual says “It is important to provide the user-supplied string as the second parameter” (PHP hash_equals).

The signing page calls a 5-minute window “a reasonable value”. The docs don’t say whether a retry hours later carries a new t. If retries show up in your log as stale, check this first.

Store, answer 200, process later

A delivery succeeds only on a 2xx “within 5 seconds”. Omni’s delivery page says to store the event, respond, and do the heavy work outside the request (Omni delivery and retries, accessed 2026-11-05). The web entry point writes the verified body to queue/ and returns 200. php omni-quickstart.php process handles the queue, from cron or a loop.

Your response What Omni does
2xx within 5 s Delivered, no retry
No response in 5 s, connection error, 408, 429 or 5xx Sends again after 1 min, 5 min, 30 min, 2 h, 6 h and 12 h
Any other 4xx, or 3xx No retry

That is up to 7 attempts within 23 hours. Meta’s equivalent is in webhook retries when the endpoint is down. Storage failures and a missing secret return 500 on purpose, so Omni retries. A failed signature returns 401, which is never retried. A bug in your verifier drops real events for good, so watch the rejected delivery lines.

PHP keeps no memory between requests, so dedupe can’t live in a variable. The file writes a marker per x-webhook-delivery-id and prunes markers older than 24 hours, the minimum Omni asks for. Two attempts arriving at the same instant could both pass, which a unique key in your database prevents (duplicate webhooks and idempotency). Order isn’t guaranteed, so sort by moment, not arrival.

Read the message text

The default format wraps every event in a message object plus messageEventType. That field is “currently NEW_MESSAGE for all message events” (Omni payload structure, accessed 2026-11-05). Text sits in message.contents[0].message when contents[0].type is TEXT. metadata.from_me is “true when sent by the business; false when received from the contact”.

The page’s only TEXT sample is an API send with from_me: true, and the payloads page shows no inbound or status sample. So handle_event prints text only when from_me is false and logs the rest without guessing at fields.

Send a message and read the errors

This is the request body from Omni’s send-text page, with the message string changed to Hello!.

{
  "recipient": { "identifier": "5511999999999" },
  "content": {
    "type": "TEXT",
    "body": { "message": "Hello!" }
  }
}
export OMNI_SECRET_KEY="YOUR_SECRET_KEY"
export OMNI_CHANNEL_ID="YOUR_CHANNEL_ID"
php omni-quickstart.php send 5511999999999 "Hello!"

A 200 returns messageId, a 32-character uppercase hex string (Omni send text, accessed 2026-11-05). That means the API accepted the message. Status updates arrive later as MESSAGE_STATUS events; add MESSAGE_DELIVERY to events for delivery confirmations. Branch on code and subCode, because the message text “may change”.

Status code / subCode Meaning
400 VALIDATION_ERROR The body does not fit the content type
401 "error": 401 Invalid or missing Secret Key
422 BUSINESS_RULE_VIOLATION / CHANNEL_DISCONNECTED Not sent and not kept: reconnect, then send again
422 BUSINESS_RULE_VIOLATION, no subCode Another send rule refused it; the reason is in message
502 varies A failure on Omni’s side

The rows come from Omni’s send errors table (accessed 2026-11-05). On WhatsApp, free-form text needs an open 24-hour window; outside it you send a TEMPLATE. With IP restriction on, a call from an unlisted IP gets a 400 (Omni IP restriction, accessed 2026-11-05).

Test the receiver locally

Sign a request yourself and post it to PHP’s built-in server. First terminal:

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

In the second, export the same two values. The sample is the TEXT payload from Omni’s payloads page, compacted to one line. The sed copy flips from_me to false so the inbound branch runs. Every request is gzipped, so gzdecode runs too.

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 protected]","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

All three requests print 200, and the third stores nothing because delivery ID test-2 already has a marker. process then prints skip ...: from_me is true, the text line and processed 2 event(s). Post with a different secret in the second terminal and the request gets 401, with bad signature in the server console.

How this differs from Meta’s raw webhook

Meta signs the body alone with your app secret in X-Hub-Signature-256. Its envelope is entry[].changes[].value (Laravel Cloud API webhooks, PHP Cloud API send). Omni signs five fields with a secret per webhook, adds a timestamp and sends a delivery ID for dedupe. Its body is Omni’s own message envelope, or the Z_API or CHATWOOT format if you set payloadFormat. The webhook pages describe no GET challenge step; you register the URL with an API call.

The same receiver is in the Express quickstart and the FastAPI quickstart. One Omni subscription covers WhatsApp, Messenger, Instagram and Telegram, with webhooks included without limit. View documentation

Z-API Omni team