Developers
API referenceBusiness sign in

Webhooks

Webhooks

Webhooks push parcel, payment and order changes to your server as they happen, signed with a secret only you and Qoene know.

Register an endpoint

Webhooks are sent for LIVE events only. Register an endpoint with a LIVE key that has webhooks.write, or in the Business workspace under Manage → API & Webhooks.

const { endpoint, secret } = await qoene.webhookEndpoints.create({
  url: 'https://shop.example.com/webhooks/qoene',
  events: ['shipment.status_changed', 'shipment.pickup_expiring', 'payment.confirmed', 'order.shipped', 'order.failed'],
});
// secret (whsec_…) is shown only now: store it in your secret manager.
await qoene.webhookEndpoints.test(endpoint.id);
curl -X POST https://api.qoenedelivery.com/v1/webhook-endpoints \
  -H "Authorization: Bearer $QOENE_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"url":"https://shop.example.com/webhooks/qoene","events":["shipment.status_changed","payment.confirmed","order.shipped","order.failed"]}'
$response = $client->post('webhook-endpoints', ['json' => [
    'url' => 'https://shop.example.com/webhooks/qoene',
    'events' => ['shipment.status_changed', 'payment.confirmed', 'order.shipped', 'order.failed'],
]]);
$endpoint = json_decode((string) $response->getBody(), true)['data']['endpoint'];
response = requests.post(
    "https://api.qoenedelivery.com/v1/webhook-endpoints",
    headers=headers,
    json={"url": "https://shop.example.com/webhooks/qoene",
          "events": ["shipment.status_changed", "payment.confirmed", "order.shipped", "order.failed"]},
    timeout=30,
)
endpoint = response.json()["data"]["endpoint"]
  • The URL must be public HTTPS on port 443. Qoene checks DNS on every attempt, verifies the certificate and never follows redirects.
  • Up to 10 active endpoints per API client, with no duplicate active URL.
  • The whsec_ signing secret is returned only when the endpoint is created. To rotate, create a replacement endpoint, accept both secrets for a while, then disable the old endpoint.
  • shipment.status_changed covers every shipment transition. Order, claim and return events are sent only to endpoints that subscribe to them by name.

What Qoene sends

A POST with a JSON body and these headers:

Webhook headers
HeaderMeaning
X-Qoene-Event-IdStable event ID (same on retries).
X-Qoene-TimestampUnix seconds of this attempt.
X-Qoene-Signaturev1=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>. Compare in constant time; reject timestamps older than 5 minutes.
Body
{
  "id": "4f1c2c0e-1b7a-4bb5-9e44-0b1d5f2f3a10",
  "type": "shipment.ready_for_pickup",
  "created_at": "2026-10-28T14:02:11.000Z",
  "data": {
    "shipment": {
      "id": "QD-SHP-8F2A61C04B7D93E5A1C6F0B2",
      "tracking_number": "QDE-82AF7CCD60392C9372F5EBDB",
      "service": "RELAY",
      "status": "READY_FOR_PICKUP",
      "milestone": "READY_FOR_PICKUP",
      "view_mode": "READY_AT_POINT"
    }
  }
}

Bodies are small on purpose: no names, phone numbers, addresses, collection codes or proof. Read the parcel through the API when you need more. The body is frozen when the event happens, so a retry never changes it. See every event in the event catalogue.

Verify the signature

The signature is HMAC-SHA256(secret, "<X-Qoene-Timestamp>.<raw body>") as lowercase hex, sent as X-Qoene-Signature: v1=<hex>. For every request:

  1. Read the raw body bytes, before any JSON parsing.
  2. Reject a timestamp more than 5 minutes from your clock (replay protection).
  3. Compute the HMAC and compare it with a constant-time comparison.
  4. Parse the JSON and deduplicate by event ID: a retry has the same ID and body but a new timestamp and signature.
  5. Process durably (or put it on your own queue), then answer any 2xx.

Verify and deduplicate

import express from 'express';
import { verifyWebhook, QoeneWebhookSignatureError } from '@qoene/delivery';

const app = express();

// Use the RAW body for this route: a re-serialised JSON object will not verify.
app.post('/webhooks/qoene', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = await verifyWebhook({
      payload: req.body,                         // Buffer
      headers: req.headers,
      secret: process.env.QOENE_WEBHOOK_SECRET!, // whsec_…
      toleranceSeconds: 300,
    });
  } catch (error) {
    if (error instanceof QoeneWebhookSignatureError) return res.status(400).send('invalid signature');
    throw error;
  }

  // Deduplicate on the signed event id: retries resend the same id.
  const isNew = await db.query(
    'INSERT INTO qoene_webhook_events (id, type, received_at) VALUES ($1, $2, now()) ON CONFLICT (id) DO NOTHING',
    [event.id, event.type],
  ).then(result => result.rowCount === 1);

  if (isNew) await handleEvent(event);  // durable work (or enqueue it) BEFORE answering
  res.status(200).send('ok');
});
# Sign and send a test event to your own local endpoint.
SECRET='whsec_your_local_test_secret'
BODY='{"id":"evt-local-1","type":"webhook.test","created_at":"2026-10-27T10:00:00Z","data":{"business_id":"local"}}'
TS=$(date +%s)
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //')

curl -X POST http://localhost:3000/webhooks/qoene \
  -H "Content-Type: application/json" \
  -H "X-Qoene-Event-Id: evt-local-1" \
  -H "X-Qoene-Timestamp: $TS" \
  -H "X-Qoene-Signature: v1=$SIG" \
  --data "$BODY"
<?php
function qoene_verify_webhook(string $payload, array $headers, string $secret, int $tolerance = 300): array
{
    $headers = array_change_key_case($headers, CASE_LOWER);
    $timestamp = $headers['x-qoene-timestamp'] ?? '';
    $signature = $headers['x-qoene-signature'] ?? '';
    if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > $tolerance) {
        throw new RuntimeException('Webhook timestamp missing or too old');
    }
    if (!preg_match('/^v1=([a-f0-9]{64})$/', $signature, $match)) {
        throw new RuntimeException('Webhook signature header missing');
    }
    $expected = hash_hmac('sha256', $timestamp . '.' . $payload, $secret);
    if (!hash_equals($expected, $match[1])) {          // constant-time comparison
        throw new RuntimeException('Webhook signature does not match');
    }
    $event = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
    if (isset($headers['x-qoene-event-id']) && $headers['x-qoene-event-id'] !== $event['id']) {
        throw new RuntimeException('Event id mismatch');
    }
    return $event;
}

$payload = file_get_contents('php://input');         // the raw body
try {
    $event = qoene_verify_webhook($payload, getallheaders(), getenv('QOENE_WEBHOOK_SECRET'));
} catch (Throwable $error) {
    http_response_code(400);
    exit('invalid signature');
}

// Deduplicate on the event id, process durably, then answer 2xx.
$insert = $pdo->prepare('INSERT INTO qoene_webhook_events (id, type) VALUES (?, ?) ON CONFLICT (id) DO NOTHING');
$insert->execute([$event['id'], $event['type']]);
if ($insert->rowCount() === 1) {
    handle_event($event);
}
http_response_code(200);
echo 'ok';
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)


def verify_qoene_webhook(payload: bytes, headers, secret: str, tolerance: int = 300) -> dict:
    timestamp = headers.get("X-Qoene-Timestamp", "")
    signature = headers.get("X-Qoene-Signature", "")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > tolerance:
        raise ValueError("Webhook timestamp missing or too old")
    if not signature.startswith("v1="):
        raise ValueError("Webhook signature header missing")
    expected = hmac.new(secret.encode(), timestamp.encode() + b"." + payload, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature[3:]):  # constant-time comparison
        raise ValueError("Webhook signature does not match")
    event = json.loads(payload)
    event_id = headers.get("X-Qoene-Event-Id")
    if event_id and event_id != event["id"]:
        raise ValueError("Event id mismatch")
    return event


@app.post("/webhooks/qoene")
def qoene_webhook():
    try:
        event = verify_qoene_webhook(request.get_data(), request.headers, os.environ["QOENE_WEBHOOK_SECRET"])
    except ValueError:
        abort(400)
    # Deduplicate on event["id"], process durably, then answer 2xx.
    if record_event_once(event["id"], event["type"]):
        handle_event(event)
    return "ok", 200

Retries and failures

Retry behaviour
Your responseWhat Qoene does
Any 2xxDelivered. Nothing more is sent for this event.
Network error, timeout, 5xx, 408, 409, 425, 429Retries after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, then marks it failed
Any other 4xxFails immediately (no retry)
  • When a delivery finally fails, the Business's Owners and Admins get an in-app and email alert (without the event contents). They can see the last 50 deliveries and retry one in the workspace.
  • Events can arrive out of order, especially after retries. Use created_at, and when the current state matters, read the parcel with the API.
  • Answer quickly: do slow work after you have stored the event.
  • A 2xx only tells Qoene your endpoint received it. Keep your own processing log to reconcile.