Books by finzkoDevelopers

Webhooks

We POST signed JSON to your endpoint whenever subscribed events fire. Verify the signature, reject stale deliveries, return 2xx. Signature scheme is Stripe-style t=<unix_ts>,v1=<hex_hmac> so existing Stripe / GitHub verification code is mostly portable.

Register an endpoint

Go to Console → Webhooks, click Add endpoint, paste a URL, pick the event types you want, save. You'll get a per-endpoint signing secret — shown once at creation.

Or via API (scope AIBooks.webhooks.CREATE). The full set of endpoints (list, update, delete, test ping, event types) is on the Webhooks API reference.

POST /api/public/v1/webhooks
{
  "url":         "https://your-app.example.com/webhooks/aibooks",
  "events":      ["INVOICE_CREATED", "PAYMENT_RECEIVED", "BILL_PAID"],
  "description": "Accounting sync"      // optional
}

# Response → grab "secret" (only shown here once)
{
  "code": 0,
  "message": "Webhook created. Save the secret — it is shown once.",
  "webhook": {
    "id":               "6f1c0d7e-…",
    "url":              "https://your-app.example.com/webhooks/aibooks",
    "events":           ["INVOICE_CREATED", "PAYMENT_RECEIVED", "BILL_PAID"],
    "is_active":        true,
    "description":      "Accounting sync",
    "last_status":      null,
    "last_delivery_at": null,
    "secret":           "whsec_…"     ← store securely
  }
}

The URL must be https:// and must resolve to a public address. Private, loopback and link-local targets are refused with 400 validation.invalid_value, and the check is repeated at send time. Redirects are not followed.

Delivery shape

POST https://your-app.example.com/webhooks/aibooks
Content-Type:           application/json
X-AIBooks-Event:        INVOICE_CREATED
X-AIBooks-Delivery-Id:  d3a8d2c9-4f5b-…
X-AIBooks-Signature:    t=1715492700,v1=8c4f1a9b…

{
  "event":      "INVOICE_CREATED",
  "occurredAt": "2026-05-12T08:30:00.123456Z",
  "data": {
    "id":        "d41f2a9e-…",
    "number":    "INV-2026-0042",
    "contactId": "c0b7e5a2-…",
    "total":     23600.0,
    "status":    "DRAFT"
  }
}

There is no separate timestamp header. The timestamp is the t value inside X-AIBooks-Signature. The body carries only event, occurredAt and data: no delivery id and no organization id (the delivery id is in the header).

data is a short summary of the record, usually its id, a number or name, and a total or status. The keys differ by event (some are camelCase, some snake_case), so treat it as a pointer and fetch the full record by id from the API.

Verify the signature (canonical)

The signed payload is t.body — the timestamp string, a literal dot, then the raw request body bytes (NOT the parsed JSON — byte equality matters). Compute HMAC-SHA256 with your endpoint secret and compare constant-time against the v1 value.

Node.js

import crypto from "crypto";

function verifyAIBooksSignature(
  rawBody: Buffer,           // express.raw() or req body BEFORE JSON.parse
  signatureHeader: string,   // X-AIBooks-Signature
  secret: string,            // whsec_…
): boolean {
  const parts = Object.fromEntries(
    signatureHeader.split(",").map(kv => kv.split("=")),
  );
  const ts = parts.t;
  const sig = parts.v1;
  if (!ts || !sig) return false;

  // 5-minute replay window
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;

  const payload = Buffer.concat([Buffer.from(`${ts}.`), rawBody]);
  const expected = crypto.createHmac("sha256", secret)
    .update(payload)
    .digest("hex");

  // Constant-time compare. Lengths must match for timingSafeEqual.
  if (expected.length !== sig.length) return false;
  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig));
}

Python

import hmac, hashlib, time

def verify_aibooks_signature(
    raw_body: bytes,
    signature_header: str,
    secret: str,
) -> bool:
    parts = dict(kv.split("=", 1) for kv in signature_header.split(",") if "=" in kv)
    ts, sig = parts.get("t"), parts.get("v1")
    if not ts or not sig:
        return False

    # 5-minute replay window
    if abs(time.time() - int(ts)) > 300:
        return False

    payload = f"{ts}.".encode() + raw_body
    expected = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)

Go

func VerifyAIBooksSignature(rawBody []byte, header, secret string) bool {
    parts := strings.Split(header, ",")
    kv := map[string]string{}
    for _, p := range parts {
        if i := strings.Index(p, "="); i > 0 {
            kv[p[:i]] = p[i+1:]
        }
    }
    ts, sig := kv["t"], kv["v1"]
    if ts == "" || sig == "" { return false }

    t, err := strconv.ParseInt(ts, 10, 64)
    if err != nil || math.Abs(float64(time.Now().Unix()-t)) > 300 { return false }

    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write([]byte(ts + "."))
    mac.Write(rawBody)
    expected := hex.EncodeToString(mac.Sum(nil))
    return hmac.Equal([]byte(expected), []byte(sig))
}

Common signature mistakes

  • Parsing the JSON first. Compute HMAC on the raw bytes you received — any whitespace / key-order change breaks the signature. Use express.raw() / req.body.read() / equivalent before any JSON middleware runs.
  • Signing the wrong payload. It's timestamp.body(timestamp string + literal dot + body), NOT just the body. We do this to bind the signature to the timestamp — preventing “replay with new timestamp” attacks.
  • Non-constant-time compare. === / strcmp leak timing info that a remote attacker can exploit to forge signatures bit-by-bit. Always use timingSafeEqual / hmac.compare_digest / hmac.Equal.
  • Skipping the timestamp check. Even with a valid signature, accept only deliveries within 5 minutes of now, or a captured payload can be replayed at any future point. Retries keep their original timestamp (see Retries + the 2xx contract below), so dedupe on X-AIBooks-Delivery-Id if you want them accepted.

Idempotent receiver pattern

We retry failed deliveries. The same X-AIBooks-Delivery-Id is reused across retries — store it and reject duplicates on your end:

// On every incoming webhook:
const deliveryId = req.header("X-AIBooks-Delivery-Id");
const seen = await redis.set(`wh:${deliveryId}`, "1", "NX", "EX", 86400);
if (!seen) {
  return res.status(200).end();  // already processed; 2xx so we don't retry
}
// ... handle the event ...

Retries + the 2xx contract

Return any 2xx status within 8 seconds to acknowledge. Anything else (3xx, 4xx, 5xx, timeout, connection error) counts as a failed attempt. A delivery gets 6 attempts: the first is sent inline when the event fires, and the next five are picked up by a retry worker that runs every 5 minutes. The wait after each failed attempt is:

After failed attemptWait before the next one
11 minute
25 minutes
330 minutes
42 hours
512 hours
6none: the delivery is marked FAILED

The waits are fixed, with no jitter, and because the worker runs every 5 minutes a retry can arrive up to about 5 minutes after its due time. A delivery that has failed all 6 attempts can be replayed from the delivery log.

Retries carry the original signature. The X-AIBooks-Signature header is computed once, when the event fires, and the same header and body are re-sent on every retry. The t value is therefore not refreshed. If your receiver rejects signatures older than 5 minutes (as the examples above do), it will reject every retry. To accept retries, verify the HMAC but skip the age check for deliveries you can match to a stored X-AIBooks-Delivery-Id, or widen the window.

Tip:if you can't process the event synchronously, enqueue + return 200 immediately. A handler that takes longer than 8 seconds is treated as failed and retried, leading to duplicate work.

Event types

These 13 events are the complete list the API accepts today. Any other name is rejected with 400 validation.invalid_value when you register or update an endpoint. GET /webhooks/event_types returns the same list. More events are planned; they will be added to this list when they ship.

  • INVOICE_CREATED, INVOICE_UPDATED (fires when an invoice is approved), INVOICE_PAID, INVOICE_VOIDED
  • BILL_CREATED, BILL_PAID
  • PAYMENT_RECEIVED (INCOMING payment), PAYMENT_MADE (OUTGOING payment)
  • CONTACT_CREATED, CONTACT_UPDATED
  • ITEM_CREATED, ITEM_UPDATED
  • JOURNAL_POSTED

An endpoint with an empty events list receives nothing. Delivery is per endpoint: every active endpoint of the organization that lists the event gets its own delivery.

Testing locally

Use ngrok or cloudflared tunnel to expose your local handler, register the public URL as a webhook endpoint, trigger the event from the FinzBooks UI, or send a signed test ping with POST /webhooks/{id}/test (see the Webhooks API reference). The Console → Webhooks delivery log shows every attempt with the request/response payloads.