// signed event delivery — payload schema, HMAC verification, retry backoff

Webhooks

Three things to wire before going live: the event payload shape, the HMAC-SHA256 signature, and the retry schedule when your endpoint is down.

base url https://agentkit-2.polsia.app

// event payload schema

Every webhook delivery — live events, retries, and webhook.test pings — uses the same envelope. The event field names the topic, wallet_id the wallet it belongs to, and data an event-specific payload.

Envelope (always present)

{
  "event":        "<event-name>",
  "wallet_id":    <integer>,
  "data":         "<event-specific object>",
  "delivered_at": "<iso-8601 timestamp>"
}

wallet.spent payload

Fired after a successful charge on your wallet. idempotency_key is the same key the originating charge carried, so a replay against your endpoint maps 1:1 to the ledger row.

{
  "event": "wallet.spent",
  "wallet_id": 12,
  "data": {
    "tx_id": 4891,
    "agent_id": "my-agent-001",
    "amount": 420,
    "currency": "USD",
    "merchant": "openai",
    "idempotency_key": "pay-quickstart-01",
    "spent_at": "2026-08-22T12:00:00.000Z",
    "test": false
  },
  "delivered_at": "2026-08-22T12:00:00.123Z"
}

webhook.test payload

Synthetic envelope sent by POST /api/v1/webhooks/:id/test. Useful keys (tx_id: 0, amount: 0, test: true) make it safe to run against staging. merchant is the literal string "webhook.test".

{
  "event": "webhook.test",
  "wallet_id": 12,
  "data": {
    "tx_id": 0,
    "agent_id": "my-agent-001",
    "amount": 0,
    "currency": "USD",
    "merchant": "webhook.test",
    "idempotency_key": "webhook.test.<ms-timestamp>",
    "spent_at": "2026-08-22T12:00:00.000Z",
    "test": true
  },
  "delivered_at": "2026-08-22T12:00:00.123Z"
}

// verifying the signature

Every delivery ships with three headers: X-AgentKit-Signature (hex HMAC-SHA256 of the body), X-AgentKit-Webhook-Id (sender id), and Content-Type: application/json. Sign over the raw, unparsed request body — re-stringifying parsed JSON produces a different digest.

Your signing_secret is a 64-hex-char string issued once when you register the endpoint. Store it the moment you see it; it is not retrievable later.

01

Node.js — verify with timingSafeEqual

Read the raw body via express.raw() (or your framework's equivalent). Verify before parsing. crypto.timingSafeEqual runs in constant time so a leaked signature comparison surface can't time-attack the secret.

const crypto = require('crypto');

function verifyAgentKitSignature(rawBody, headerSig, secret) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)               // raw, unparsed Buffer or string
    .digest('hex');
  if (expected.length !== headerSig.length) return false;
  return crypto.timingSafeEqual(
    Buffer.from(expected),                  // local digest
    Buffer.from(headerSig)                  // X-AgentKit-Signature header
  );
}

// In your Express handler, mount BEFORE express.json():
app.post('/hook', express.raw({ type: 'application/json' }), (req, res) => {
  const sig  = req.headers['x-agentkit-signature'];
  const body = req.body;                  // Buffer — do not JSON.parse before hashing
  if (!verifyAgentKitSignature(body, sig, SIGNING_SECRET)) {
    return res.status(401).end();
  }
  const { event, data } = JSON.parse(body.toString('utf8'));
  res.status(200).end();
});
02

Python — verify with hmac.compare_digest

Read request.body raw (do not pass it through json.loads first). Django, Flask, and FastAPI all expose the original bytes.

import hmac, hashlib

def verify_agentkit_signature(raw_body: bytes, header_sig: str, secret: str) -> bool:
    expected = hmac.new(
        secret.encode('utf-8'),
        raw_body,                 # raw bytes — not json.dumps(parsed)
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(expected, header_sig)

# Django view example
def hook(request):
    sig      = request.headers['X-AgentKit-Signature']
    raw_body = request.body                  # raw bytes — do not parse before hashing
    if not verify_agentkit_signature(raw_body, sig, SIGNING_SECRET):
        return HttpResponse(status=401)
    payload = json.loads(raw_body)
    return HttpResponse(status=200)
03

cURL — header format reference

There is no command-line verifier; use Node or Python. The literal header shape is shown here so you can log or replay against your own endpoint.

curl -X POST https://your-app.example.com/hook \n
  -H "Content-Type: application/json" \n
  -H "X-AgentKit-Webhook-Id: 42" \n
  -H "X-AgentKit-Signature: <64-char hex HMAC-SHA256>" \n
  --data-binary '@payload.json'

// retry & dead-letter semantics

If your endpoint stalls or returns a non-2xx status, the dispatcher retries on a fixed schedule — then either queues another retry or marks the delivery dead-letter. Track every subscription in one wallet-wide feed, or inspect one subscription with the legacy per-subscription route.

Wallet-wide delivery feed

Use GET /api/v1/webhooks/deliveries as the primary status feed. Results are scoped to the wallet behind your API key and use keyset pagination with limit (1–100, default 20) and cursor.

{
  "deliveries": [{
    "webhook_id": 42,
    "delivery_id": "...",
    "event": "wallet.spent",
    "status": "delivered",
    "attempt_number": 1,
    "http_status": 200,
    "next_retry_at": null,
    "created_at": "<iso-8601 timestamp>"
  }],
  "next_cursor": "...",
  "limit": 20
}
→ Follow next_cursor for the next page
curl "https://agentkit-2.polsia.app/api/v1/webhooks/deliveries?limit=20&cursor=<next_cursor>" \n
  -H "X-API-Key: ak_live_xxxxxxxx"

Backoff schedule

Four hops with the wall-clock delay calculated from the prior attempt's timestamp. Max attempts default = 5 (so up to 4 retries after the initial attempt).

hop 1  →  1  min     (60000 ms)
hop 2  →  5  min     (300000 ms)
hop 3  →  30 min     (1800000 ms)
hop 4  →  2  hour    (7200000 ms)

# Override via env vars (jobs/webhook-retry.js):
#   WEBHOOK_RETRY_BACKOFF_MS    "[60000,300000,1800000,7200000]"
#   WEBHOOK_RETRY_MAX_ATTEMPTS  5

Terminal statuses

Each attempt resolves to one of three terminal states. The first wins — a 2xx reply flips the delivery to delivered regardless of how many retries were previously queued.

"delivered"       // any attempt returned 2xx
"scheduled_retry" // failed attempt; next_retry_at set
"dead"           // retries exhausted (attempt_number >= max_attempts)
→ Per-subscription feed
curl https://agentkit-2.polsia.app/api/v1/webhooks/<id>/deliveries \n
  -H "X-API-Key: ak_live_xxxxxxxx"

// Verify it now

The webhook.test payload above is exactly what this one-liner delivers. Hit it with your endpoint running and your verifier will see the matching signature for free.

curl -X POST https://agentkit-2.polsia.app/api/v1/webhooks/<id>/test \n
  -H "X-API-Key: ak_live_xxxxxxxx"