Guides
Receiving webhooks

Receiving webhooks

This guide takes you from nothing to a webhook receiver that is safe to run in production: create an endpoint, verify every request, store events without losing or doubling any, test it, and rotate the secret without downtime. Field-by-field detail is in the Webhooks reference.

What you need

  • The restaurant holds Advanced API & Webhooks. Without it the Webhooks page is hidden and the API answers 402.
  • The restaurant's owner account. Only the owner can create an endpoint, rotate its secret, send a test or redeliver.
  • A public HTTPS URL for your receiver. Tahlib does not deliver to private or internal addresses (localhost, 10.x, 192.168.x …). To receive deliveries on a laptop, expose it through a tunnel.

1. Create an endpoint

  1. In the dashboard open Developers → Webhooks and choose Add endpoint.
  2. Give it a name, your receiver's URL, and the events you want.
  3. Copy the signing secret. It is shown once. Tahlib keeps it encrypted to sign deliveries and cannot show it again; if you lose it, rotate it.
  4. Put the secret in your server's environment, for example TAHLIB_WEBHOOK_SECRET. Keep it out of source code, repositories, chat and online tools.

The same can be done with POST /v1/webhooks; the response carries the secret once.

2. Rules for your receiver

Every sample below follows these six rules.

  1. Read the raw body. The signature covers the exact bytes Tahlib sent. Parse the JSON only after verifying; a body that is parsed and re-serialised has different bytes.
  2. Verify X-Tahlib-Signature. It is t=<unix seconds>,v1=<hex>, where v1 = HMAC-SHA256(secret, "<t>." + raw body). Right after a secret rotation the header carries two v1 values; accept the request when any of them matches. Compare in constant time.
  3. Reject old requests. Refuse a t more than 5 minutes from your clock, so a captured request cannot be replayed later. Keep your server's clock synchronised.
  4. Answer 2xx within 10 seconds. Store the event, answer, and do the work afterwards. A slow answer is a failure and the delivery is retried.
  5. Skip duplicates by id. The envelope's id is the event id: the same on every retry and on a manual redelivery. A unique key on it makes a repeat harmless.
  6. Keep the newest snapshot. Deliveries can arrive out of order. Every resource carries updatedAt; ignore a snapshot older than the one you have. Each event carries the whole resource, so the newest one is all you need.

Amounts are integers in the currency's minor unit. AED, SAR and INR have two decimals; KWD and OMR have three (1500 is KWD 1.500). Use the currency's decimals, never a fixed division by 100.

3. Sample receivers

Each sample verifies the signature, refuses anything that fails with 401, stores the event once and answers 200.

PHP

<?php
// tahlib-webhook.php — receives Tahlib webhooks.
// Environment: TAHLIB_WEBHOOK_SECRET, DB_DSN, DB_USER, DB_PASSWORD.
 
/**
 * True when one of the v1 signatures in X-Tahlib-Signature is
 * HMAC-SHA256(secret, "<t>.<raw body>") and t is within $tolerance seconds.
 * Pass $tolerance = 0 only when testing with a saved request.
 */
function tahlib_verify_signature(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
    $t = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't') {
            $t = $value;
        } elseif ($key === 'v1') {
            $signatures[] = strtolower($value);
        }
    }
    if ($secret === '' || $t === null || !ctype_digit($t) || $signatures === []) {
        return false;
    }
    if ($tolerance > 0 && abs(time() - (int) $t) > $tolerance) {
        return false;
    }
    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}
 
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}
 
$rawBody = file_get_contents('php://input');
$header  = $_SERVER['HTTP_X_TAHLIB_SIGNATURE'] ?? '';
$secret  = getenv('TAHLIB_WEBHOOK_SECRET') ?: '';
 
if (!tahlib_verify_signature($rawBody, $header, $secret)) {
    http_response_code(401);
    exit;
}
 
$event = json_decode($rawBody, true);
 
// Store first, process later. The primary key on id turns a repeat into a no-op.
$pdo = new PDO(getenv('DB_DSN'), getenv('DB_USER'), getenv('DB_PASSWORD'), [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$insert = $pdo->prepare(
    'INSERT IGNORE INTO tahlib_events (id, type, payload, received_at) VALUES (?, ?, ?, NOW())'
);
$insert->execute([$event['id'], $event['type'], $rawBody]);
 
http_response_code(200);

The table it writes to (MySQL / MariaDB):

CREATE TABLE tahlib_events (
  id           CHAR(36)    NOT NULL PRIMARY KEY,
  type         VARCHAR(64) NOT NULL,
  payload      JSON        NOT NULL,
  received_at  DATETIME    NOT NULL,
  processed_at DATETIME    NULL
);

On PostgreSQL write INSERT INTO … ON CONFLICT (id) DO NOTHING instead of INSERT IGNORE. A cron job or worker then reads the rows where processed_at is null, oldest first, applies them (rule 6) and sets processed_at.

Laravel

The same check as a controller. getContent() returns the raw body.

<?php
// app/Http/Controllers/TahlibWebhookController.php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
 
class TahlibWebhookController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $rawBody = $request->getContent(); // the exact bytes Tahlib signed
        $header = (string) $request->header('X-Tahlib-Signature', '');
        $secret = (string) config('services.tahlib.webhook_secret');
 
        if (! self::verify($rawBody, $header, $secret)) {
            return response('', 401);
        }
 
        $event = json_decode($rawBody, true);
 
        // Store first, process later (a queued job or a scheduled command reads
        // rows where processed_at is null). insertOrIgnore skips a repeated id.
        DB::table('tahlib_events')->insertOrIgnore([
            'id' => $event['id'],
            'type' => $event['type'],
            'payload' => $rawBody,
            'received_at' => now(),
        ]);
 
        return response('', 200);
    }
 
    private static function verify(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
    {
        $t = null;
        $signatures = [];
        foreach (explode(',', $header) as $part) {
            [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
            if ($key === 't') {
                $t = $value;
            } elseif ($key === 'v1') {
                $signatures[] = strtolower($value);
            }
        }
        if ($secret === '' || $t === null || ! ctype_digit($t) || $signatures === []) {
            return false;
        }
        if ($tolerance > 0 && abs(time() - (int) $t) > $tolerance) {
            return false;
        }
        $expected = hash_hmac('sha256', $t.'.'.$rawBody, $secret);
        foreach ($signatures as $signature) {
            if (hash_equals($expected, $signature)) {
                return true;
            }
        }
 
        return false;
    }
}

Wire it up:

// config/services.php
'tahlib' => [
    'webhook_secret' => env('TAHLIB_WEBHOOK_SECRET'),
],
 
// routes/api.php — API routes have no CSRF check.
// (Laravel 11+: run `php artisan install:api` first if the file does not exist.)
Route::post('/tahlib/webhooks', \App\Http\Controllers\TahlibWebhookController::class);

Node.js (Express)

// server.mjs — receives Tahlib webhooks (Node.js 18+, Express 4).
// Environment: TAHLIB_WEBHOOK_SECRET.
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
 
/**
 * True when one of the v1 signatures in X-Tahlib-Signature is
 * HMAC-SHA256(secret, "<t>.<raw body>") and t is within toleranceSec seconds.
 */
export function verifyTahlibSignature(rawBody, header, secret, toleranceSec = 300) {
  const parts = header.split(',').map((p) => p.trim());
  const t = parts.find((p) => p.startsWith('t='))?.slice(2);
  const signatures = parts.filter((p) => p.startsWith('v1=')).map((p) => p.slice(3));
  if (!secret || !t || !/^\d+$/.test(t) || signatures.length === 0) return false;
  if (toleranceSec > 0 && Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) return false;
 
  const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
  return signatures.some((s) => {
    const given = Buffer.from(s, 'hex');
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}
 
// Replace with an INSERT into a table keyed on event.id that returns
// false when the row already existed.
const seen = new Set();
async function saveEvent(event, rawBody) {
  if (seen.has(event.id)) return false;
  seen.add(event.id);
  return true;
}
 
const app = express();
 
// express.raw keeps the body as the exact bytes Tahlib signed.
app.post('/tahlib/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
  const header = req.get('X-Tahlib-Signature') ?? '';
  if (!Buffer.isBuffer(req.body) || !verifyTahlibSignature(req.body, header, process.env.TAHLIB_WEBHOOK_SECRET)) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body.toString('utf8'));
  await saveEvent(event, req.body); // store first, process later
  res.sendStatus(200);
});
 
app.listen(process.env.PORT ?? 3000);

Register express.raw on this route only, and before any express.json() that would otherwise consume the body.

Python (Flask)

# app.py — receives Tahlib webhooks (Python 3.9+, Flask).
# Environment: TAHLIB_WEBHOOK_SECRET.
import hashlib
import hmac
import json
import os
import time
 
from flask import Flask, request
 
 
def verify_tahlib_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    """True when one of the v1 signatures is HMAC-SHA256(secret, "<t>.<raw body>") and t is recent."""
    t = None
    signatures = []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            t = value
        elif key == "v1":
            signatures.append(value.lower())
    if not secret or not t or not t.isdigit() or not signatures:
        return False
    if tolerance > 0 and abs(time.time() - int(t)) > tolerance:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in signatures)
 
 
# Replace with an INSERT into a table keyed on event["id"] that returns
# False when the row already existed.
seen = set()
 
 
def save_event(event: dict, raw_body: bytes) -> bool:
    if event["id"] in seen:
        return False
    seen.add(event["id"])
    return True
 
 
app = Flask(__name__)
 
 
@app.post("/tahlib/webhooks")
def tahlib_webhook():
    raw_body = request.get_data()  # the exact bytes Tahlib signed
    header = request.headers.get("X-Tahlib-Signature", "")
    if not verify_tahlib_signature(raw_body, header, os.environ.get("TAHLIB_WEBHOOK_SECRET", "")):
        return "", 401
    event = json.loads(raw_body)
    save_event(event, raw_body)  # store first, process later
    return "", 200

4. Test before going live

Check your code against the test vectors

Both vectors use this body, byte for byte, and t = 1700000000. That timestamp is long past, so run your function with the time check switched off (tolerance 0).

{"id":"evt_1","type":"webhook.test","data":{"hello":"world"}}
CaseSecretX-Tahlib-SignatureExpected
One secretsuper-secret-stringt=1700000000,v1=b0b97e3addf7c105c1b0d8329df7d3ea972123f442cc12665760768a64510744valid
During a rotationsuper-secret-string or old-secret-stringt=1700000000,v1=b0b97e3addf7c105c1b0d8329df7d3ea972123f442cc12665760768a64510744,v1=87b7100815b1a522059553ad1560d546d27f85f37bde7ab4f6e9ea52de82cbf8valid with either
Wrong secretanything elseeither headerinvalid

With the default 5-minute tolerance both vectors must come out invalid: that proves the replay check works.

Send a signed request yourself

This script signs a webhook.test event the way Tahlib does and posts it to your receiver. It needs bash, openssl and curl, and prints the status your receiver answered.

#!/usr/bin/env bash
# Usage: TAHLIB_WEBHOOK_SECRET=... ./send-test.sh https://your-server/tahlib/webhooks
URL="$1"
BODY='{"id":"4a0b2d4f-6c8e-4a0b-9d2f-4b6e8a0c2d3e","apiVersion":"2026-11-10","type":"webhook.test","createdAt":"2026-11-10T11:00:00.000Z","restaurantId":"6b0c2c4e-1d1f-4f8e-9a51-2f3c8e7d9a10","deliveryId":"7b1d3f5a-9c0e-4b2d-8f4a-6c8e0a2c4e4f","data":{"hello":"world"}}'
T=$(date +%s)
SIG=$(printf '%s' "$T.$BODY" | openssl dgst -sha256 -hmac "$TAHLIB_WEBHOOK_SECRET" | awk '{print $NF}')
curl -s -o /dev/null -w '%{http_code}\n' -X POST "$URL" \
  -H 'Content-Type: application/json' \
  -H "X-Tahlib-Timestamp: $T" \
  -H "X-Tahlib-Signature: t=$T,v1=$SIG" \
  --data-raw "$BODY"

Expect 200 with the right secret and 401 with any other. Because it reuses one event id, the second run should be stored as a duplicate.

Send a test from Tahlib

On the endpoint's page choose Send test. Tahlib sends a webhook.test event at once and shows the status and the start of your answer. Test deliveries are kept in the log (tick Include test deliveries) and never count towards switching an endpoint off. You can send 5 a minute per endpoint.

When a check fails

Save what actually arrived and check that:

file_put_contents(__DIR__ . '/tahlib-body.json', file_get_contents('php://input'));
file_put_contents(__DIR__ . '/tahlib-header.txt', $_SERVER['HTTP_X_TAHLIB_SIGNATURE'] ?? '');

Then run your verify function on the saved body and header with tolerance 0. Use the body your server received: the delivery drawer in the dashboard shows only the event's data, pretty-printed, which is not what was signed. See Troubleshooting for the usual causes.

5. Rotate the secret

Rotate when a secret may have leaked, when someone who knew it leaves, or on a schedule.

  1. On the endpoint's page choose Rotate secret and pick how long to keep the old secret working: 24 hours, 72 hours, or Stop it now.
  2. Copy the new secret; it is shown once.
  3. Deploy it to your server at any point in that window. Until the window ends every delivery carries two v1 values, one per secret, so a receiver holding either secret keeps verifying.
  4. When the window ends, deliveries carry only the new secret's v1.

With Stop it now, the old secret stops at once and your receiver answers 401 until it has the new one. Those deliveries are retried (below), so deploy quickly.

Through the API: POST /v1/webhooks/:id/rotate-secret with { "previousSecretValidHours": 24 } (0, 24 or 72). The response is { "endpoint": { … }, "secret": "…" }; endpoint.previousSecretExpiresAt says when the old secret stops.

6. Failures, retries and redelivery

  • A delivery is tried at once, then again 10 s, 30 s, 5 min, 30 min and 2 h after each failure: six attempts. Then it is marked failed.
  • A non-2xx status, a redirect (redirects are not followed), or no answer within 10 seconds is a failure.
  • After 5 deliveries in a row end failed, the endpoint is switched off. Owners get a push notification and the endpoint shows the reason. Turning it back on resets the count.
  • Any delivery in the log can be sent again with Redeliver. A redelivery keeps the event id, so rule 5 makes it safe.

7. Catch up after downtime

Webhooks are best-effort. To fill a gap after an outage, or to check your copy, read orders through the read API.

  1. In Settings → API keys create a key with the orders:read scope (add menu:read to mirror the menu). The key is shown once.
  2. Send it as Authorization: ApiKey <key>.
  3. Ask for everything changed since your last good point, then follow nextCursor while hasMore is true:
curl "https://api.tahlib.com/v1/integration/orders?updatedSince=2026-11-15T00:00:00Z&limit=100" \
  -H "Authorization: ApiKey $TAHLIB_API_KEY"
{ "data": [ { "id": "…", "updatedAt": "…" } ], "hasMore": true, "nextCursor": "MjAyNi0xMS0x…" }

Store the last nextCursor and poll with ?cursor= next time to pick up anything changed since. Orders come back in the same shape as the order.* webhooks, so the same rule 6 applies.

RouteScope
GET /v1/integration/orders?updatedSince=&cursor=&limit=orders:read (limit 1–100, default 50)
GET /v1/integration/orders/:idorders:read
GET /v1/integration/menumenu:read (categories, items, modifier groups)

A key reads only the restaurant that issued it and is limited to 10,000 requests an hour. Answers: 401 for a missing, unknown or revoked key; 403 api_key_scope_missing; 402 module_not_included when the product is not active; 429 over the limit.

Go-live checklist

  • The secret is in the server's environment, not in code.
  • The body is read raw and verified before it is parsed.
  • Any matching v1 is accepted (rotation works).
  • Requests older than 5 minutes are refused; the clock is synchronised.
  • Events are stored with a unique key on id, and the answer comes in under 10 seconds.
  • Older snapshots (by updatedAt) never overwrite newer ones.
  • Amounts use the currency's decimals.
  • Both test vectors pass, and Send test shows 200.
  • You know who gets the "endpoint switched off" notification and how to catch up with the read API.

Troubleshooting

What you seeUsual cause
Every request is 401, with the right secretThe body was parsed or re-serialised before hashing; hash the raw bytes.
A saved request fails, a live one passesThe 5-minute window; test saved requests with tolerance 0.
Fails for a body copied from the dashboardThe drawer shows data only, pretty-printed. Capture the body at your server.
Fails right after you rotatedYour code reads only the first v1; accept any. Or the new secret is not deployed yet.
Fails with the secret decoded from base64The secret is used exactly as shown, as text. Don't decode it.
Fails for one delivery onlyThe header and the body come from different deliveries; each has its own t and signatures.
Fails behind a proxyThe proxy changed the body. Compare X-Tahlib-Body-SHA256 with the SHA-256 of what you received.
Same order processed twiceNo unique key on the event id; retries and redeliveries repeat it.
An order goes back to an older statusDeliveries arrived out of order; compare updatedAt before saving.
"signing secret unavailable" in the delivery logAn endpoint from before 10 November 2026 lost its stored secret. Rotate it.

Sources

  • Signing scheme and multiple v1 values: apps/api/src/modules/webhooks/webhook-signing.ts
  • Headers, timeout, retry schedule, auto-disable: apps/api/src/modules/webhooks/webhook-delivery.service.ts
  • Private addresses and redirects: apps/api/src/modules/webhooks/webhook-http.ts
  • Envelope, event list, rotation windows: packages/shared-types/src/webhook.ts
  • Read API and key scopes: apps/api/src/modules/integration-api/integration-api.controller.ts, packages/shared-types/src/api-keys.ts
  • Payload contract and examples for every event: docs/runbooks/webhooks-events.md
  • Test vectors: apps/api/test/webhook-signing.e2e-spec.ts; the rotation vector is signPayload(['super-secret-string', 'old-secret-string'], body, 1700000000)