Webhooks

Webhooks

Cybooks can POST a small signed JSON envelope to your HTTPS endpoint whenever
something changes in a company's books. Subscriptions are managed through the
REST API (/v1/webhook-subscriptions) with the webhooks:read and
webhooks:write scopes; the credential's user needs the Manage
integrations
permission.

Subscriptions

The full list of event types, with what triggers each one, is in
Event types.

OperationRequest
List subscriptionsGET /v1/webhook-subscriptions
Create a subscriptionPOST /v1/webhook-subscriptions
Read oneGET /v1/webhook-subscriptions/{id}
Update, pause or resumePATCH /v1/webhook-subscriptions/{id}
DeleteDELETE /v1/webhook-subscriptions/{id}
Rotate the signing secretPOST /v1/webhook-subscriptions/{id}/rotate-secret
Send a test eventPOST /v1/webhook-subscriptions/{id}/test
List event typesGET /v1/event-types
List deliveriesGET /v1/webhook-deliveries
Read one deliveryGET /v1/webhook-deliveries/{id}
Replay a deliveryPOST /v1/webhook-deliveries/{id}/replay

Every write except /test needs an Idempotency-Key header. A test event is
not stored, so retrying /test simply sends another one.

  • url must be an absolute https URL on port 443 or 1024–65535, without
    credentials or a fragment. The host must be a public domain name (not an IP
    address) that resolves only to public addresses. Redirects are never
    followed.
  • event_types is a list of exact types from GET /v1/event-types, or
    ["*"] for every current and future type. Types marked preview are
    delivered but may still change before their family is promoted to stable.
  • api_version pins the envelope and fetch_url shape (default v1). Change
    it with PATCH when you are ready to move.
  • A company can have at most 20 subscriptions.
  • A subscription belongs to the company, not to the person or API key that
    created it. It keeps delivering when that person leaves the company or the
    key is revoked; pause or delete it to stop it.

The signing secret (whsec_…) is returned once, in the create and rotate
responses. Store it then; no other response contains it.

The envelope

{
  "id": "0b0f6f7e-1f67-4d3a-9e57-4a8c4b3f1c2d",
  "object": "event",
  "type": "invoice.paid",
  "api_version": "v1",
  "occurred_at": "2026-09-28T10:15:00Z",
  "tenant_id": "your-company-id",
  "sequence": 4812,
  "resource": { "type": "invoice", "id": "9a4…", "version": 7 },
  "change_kind": "paid",
  "changed_fields": ["status", "unpaid_amount"],
  "actor": { "kind": "user" },
  "request_id": "5c1…",
  "fetch_url": "https://api.cybooks.com.cy/v1/invoices/9a4…"
}

Payloads are thin: they never carry the resource or its amounts. Fetch the
current resource from fetch_url rather than trusting a copy; that request
needs the resource's own read scope (for example invoices:read for an
invoice), not just webhooks:read. fetch_url values name the canonical API host,
https://api.cybooks.com.cy/v1. actor.kind is api_client, user or system — never a
person's identity. sequence is the company's change-feed position, so you
can recover anything you missed from GET /v1/changes.

FieldTypeDescription
idstringThe event's immutable id. Retries and manual replays keep it, so use it to deduplicate.
objectstringAlways event.
typestringThe event type, for example invoice.paid. See Event types.
api_versionstringThe subscription's pinned API version, for example v1. It fixes this envelope's shape and fetch_url.
occurred_atstringWhen the change happened, as an ISO 8601 UTC timestamp.
tenant_idstringThe company whose books changed.
sequenceinteger or nullThe event's position in the company's change feed; it only increases. null on a test event.
resource.typestringThe changed resource's type, for example invoice.
resource.idstringThe changed resource's id.
resource.versionintegerThe resource's version after this change. A lower version than one you already hold is stale.
change_kindstringWhat kind of change this is: created, updated, archived, deleted or a lifecycle verb such as applied, merged or tested.
changed_fieldsarray of stringsThe names of the fields the change touched. Never their values.
actor.kindstringWho made the change: api_client, user or system.
request_idstring or nullThe id of the request or operation that caused the change. For a change made through the API it is that request's X-Request-Id.
fetch_urlstring or nullWhere to GET the current resource under the pinned API version; null for a resource type without a public read endpoint.

Each request carries these headers:

HeaderMeaning
Cybooks-Event-IdThe event's immutable id (same as id in the body).
Cybooks-Event-TypeThe event type.
Cybooks-Delivery-IdThis delivery; every retry of it keeps the id, a manual replay gets a new one.
Cybooks-Delivery-AttemptThe attempt number, starting at 1.
Cybooks-Api-VersionThe subscription's pinned API version.
Cybooks-SignatureThe signature described below.

Verifying the signature

Cybooks-Signature: t=1700000000,v1=74edc608579d3c4222ae14e910b76a882c2b9245a39d3c40a75152d97cad8a1b

t is the Unix time the request was signed. Each v1 is the hex
HMAC-SHA256 of t + "." + raw request body, keyed with the whole secret
string (including the whsec_ prefix). While a rotated secret is still in its
grace period the header carries two v1 values, one per secret; accept the
request when any of them matches.

Test vector: the secret whsec_example, the timestamp
1700000000 and the body {"id":"evt_1","object":"event"} produce exactly the
header shown above.

To verify:

  1. Read the raw request body before any JSON parsing — re-encoding changes
    the bytes.
  2. Split the header on , and take t and every v1.
  3. Reject the request when t is more than 5 minutes (300 seconds) from
    your clock. This is the replay window.
  4. Compute the expected HMAC and compare it with each v1 using a
    constant-time comparison.

PHP

<?php

function cybooks_verify_signature(
    string $payload,
    string $header,
    string $secret,
    int $toleranceSeconds = 300,
    ?int $now = null,
): bool {
    $timestamp = null;
    $signatures = [];

    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't' && ctype_digit($value)) {
            $timestamp = (int) $value;
        } elseif ($key === 'v1' && $value !== '') {
            $signatures[] = $value;
        }
    }

    if ($timestamp === null || $signatures === []) {
        return false;
    }

    if (abs(($now ?? time()) - $timestamp) > $toleranceSeconds) {
        return false;
    }

    $expected = hash_hmac('sha256', $timestamp.'.'.$payload, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }

    return false;
}

// $payload = file_get_contents('php://input');
// $valid = cybooks_verify_signature($payload, $_SERVER['HTTP_CYBOOKS_SIGNATURE'] ?? '', $secret);

Node.js

const crypto = require('crypto')

function verifyCybooksSignature(rawBody, header, secret, toleranceSeconds = 300) {
  let timestamp = null
  const signatures = []
  for (const part of header.split(',')) {
    const [key, value] = part.trim().split('=', 2)
    if (key === 't' && /^\d+$/.test(value)) timestamp = Number(value)
    else if (key === 'v1' && value) signatures.push(value)
  }
  if (timestamp === null || signatures.length === 0) return false
  if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > toleranceSeconds) return false

  const expected = Buffer.from(
    crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex'),
  )
  return signatures.some((signature) => {
    const candidate = Buffer.from(signature)
    return candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected)
  })
}

Python

import hashlib
import hmac
import time


def verify_cybooks_signature(raw_body: bytes, header: str, secret: str, tolerance_seconds: int = 300) -> bool:
    timestamp = None
    signatures = []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t" and value.isascii() and value.isdigit():
            timestamp = int(value)
        elif key == "v1" and value:
            signatures.append(value)
    if timestamp is None or not signatures:
        return False
    if abs(int(time.time()) - timestamp) > tolerance_seconds:
        return False

    signed = f"{timestamp}.".encode() + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, signature) for signature in signatures)

Responding and deduplicating

  • Answer with any 2xx status within 10 seconds (connect plus read). Anything
    else — including a 3xx redirect — counts as a failure.
  • Delivery is at least once: the same event can arrive more than once.
    Deduplicate on Cybooks-Event-Id (the body's id); a manual replay keeps
    the event id and gets a new Cybooks-Delivery-Id.
  • Deliveries are not guaranteed to arrive in sequence order. Order by
    sequence or re-fetch the resource when order matters.

Testing and rotating

POST /v1/webhook-subscriptions/{id}/test sends one signed
webhook_subscription.tested event right away (also while the subscription is
paused) and returns what your endpoint answered: delivered,
response_status, latency_ms, error_code and a short diagnostic excerpt.
Test events are not stored and do not count against the subscription's
health. You can send five per minute per subscription, and ten per minute
across all of your company's subscriptions; deleting and recreating a
subscription does not reset the company count. Over either limit the request
returns 429 with a Retry-After header.

POST /v1/webhook-subscriptions/{id}/rotate-secret returns a new secret. The
old one keeps signing alongside it for expire_previous_in_seconds (default
86400, at most 86400; 0 retires it immediately), so you can roll your
verifier without dropping events.

Retries

An event is queued for every matching subscription in the same database
transaction that records the change, so a change that is saved always gets
its webhook, and one that is rolled back never sends one.

Each delivery gets up to 8 attempts: the first straight away, then after
60 seconds, 5 minutes, 30 minutes, 2 hours, 4 hours, 8 hours and 9 hours — a
little under 24 hours in all. Every retry waits up to 10 % longer than listed,
never less, so receivers coming back online are not hit all at once. Every
attempt is signed again with a fresh t, so an old signature never goes
stale in your verifier; the body bytes are identical on every attempt of a
delivery. When the eighth attempt fails the delivery is exhausted and is not
retried again.

Delivery records

GET /v1/webhook-deliveries lists deliveries newest first, cursor-paginated,
with the filters filter[subscription_id], filter[event_type],
filter[status] and filter[since] (an ISO 8601 time). A delivery carries
its event_id, event_type, sequence, the api_version it is rendered
under, its status (pending, delivering, succeeded, exhausted or
cancelled), attempt_count, next_attempt_at, a short log of every attempt
and the last response: last_response_status, last_error_code and
last_response_diagnostics.

The error codes are timeout, connection_failed, tls_error,
dns_resolution_failed, destination_blocked (the host now resolves to a
non-public address), redirect_not_followed and http_error, plus
render_failed and attempt_failed when the attempt failed on Cybooks' side
before anything was sent (these follow the same retry schedule but do not
count against your endpoint's health). The diagnostics
hold only the status, the latency, your response's Content-Type and
X-Request-Id, and the first 1 KB of a text or JSON response body. Cybooks
never stores or returns the signature, the secret or any other header.

Replaying a delivery

POST /v1/webhook-deliveries/{id}/replay (with an Idempotency-Key) answers
202 Accepted with a new delivery of the same event: the same event
id, a new Cybooks-Delivery-Id, and the full retry schedule. A replay is
rendered under the subscription's current pinned api_version, not the
version the event first went out under. A replay is refused with 409 webhook_subscription_paused while the subscription is paused (resume it
first), with 404 once the subscription is deleted, and with 409 event_expired once the event is past its retention window.

Automatic pause

If deliveries to a subscription fail on three separate UTC calendar days
with no successful delivery in between (any success resets the count), Cybooks pauses it:
status becomes paused with pause_reason: "delivery_failures", every
delivery still waiting is cancelled, and the people with the Manage
integrations
permission — and whoever created the subscription — get a
notification in Cybooks. The subscription's health shows the count and when
the failures started.

Events that happen while a subscription is paused are not queued. After
fixing your endpoint, resume it with PATCH {"status": "active"} and catch up
from the change feed: call GET /v1/changes from the last sequence you
processed. A manual pause (PATCH {"status": "paused"}) behaves the same way,
and deleting a subscription cancels its waiting deliveries.

Retention and recovery

Delivery records are kept for 30 days, and change-feed rows for 90
days
(never while a delivery still needs them). Pruning runs daily. The
change feed is the recovery path for anything a webhook did not deliver:
page through GET /v1/changes from the sequence of the last event you
handled. A change-feed item's snapshot is reduced to id, type and
version unless the token also holds the scope of an endpoint that reads that
resource type: its show endpoint (for example invoices:read for an invoice),
or its list or status endpoint when it has no show endpoint. A resource type
that no endpoint reads, such as reconciliation_match, is always reduced. A /changes cursor that points below what retention has already
removed is rejected with 422 on cursor; restart from a fresh sync (no
cursor) and re-read the resources you need.


Did this page help you?