Náhled: Capydra brzy otevírá. Objednávat zatím nelze.

Capydra
Help Cart
Deal of the week

Webhooks

Tento průvodce je napsán v angličtině.

We call your HTTPS endpoint when something happens, so you do not have to poll. Up to 3 endpoints per account.

curl -s -X POST "https://capydra.com/api/v1/webhooks" \
  -H "Authorization: Bearer $CAPYDRA_KEY" -H "Content-Type: application/json" \
  -d '{"url":"https://example.org/capydra/webhook","events":["order.complete","order.status","product.update"]}'

The answer holds the endpoint's secret (whsec_...) once. Events:

  • order.status: any status change of an order made with an API key.
  • order.complete: the order is delivered; fetch its keys.
  • product.update: products whose offers changed (price, stock, status), up to 100 ids per call, every 15 minutes.

A payload never carries a key, buyer data or an amount of money. Fetch the details with your key.

Signature

Every call has three headers (the Standard Webhooks format): webhook-id, webhook-timestamp (Unix seconds) and webhook-signature (v1, plus the base64 HMAC-SHA256 of id.timestamp.body, keyed with the base64-decoded part of your secret after whsec_). After a secret rotation two signatures are sent, space separated. No secret is ever sent in a header.

  1. Use the raw body, before JSON parsing.
  2. Drop calls whose timestamp is more than 5 minutes off.
  3. Compare in constant time.
  4. Drop ids you have seen: a call can come twice, and calls can come out of order.
  5. Answer any 2xx within 10 seconds; do the work afterwards.

curl and openssl

# Check one saved webhook call by hand. body.json holds the raw body exactly as it arrived;
# WEBHOOK_ID and WEBHOOK_TS are the webhook-id and webhook-timestamp headers; WHSEC is your secret.
key_hex=$(printf '%s' "${WHSEC#whsec_}" | base64 -d | xxd -p -c 256)
expected=$(printf '%s.%s.' "$WEBHOOK_ID" "$WEBHOOK_TS" | cat - body.json \
  | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$key_hex" -binary | base64)
echo "v1,$expected"   # must equal one of the space-separated values of webhook-signature

# Ask for a test call to your endpoint:
curl -s -X POST "https://capydra.com/api/v1/webhooks/<endpoint id>/test" \
  -H "Authorization: Bearer $CAPYDRA_KEY"

Node.js

import crypto from 'node:crypto';

// rawBody: the request body as a string, before any JSON parsing. headers: lower-case names.
export function verifyWebhook(rawBody, headers, secret, toleranceSeconds = 300) {
  const id = headers['webhook-id'];
  const ts = Number(headers['webhook-timestamp']);
  const sigs = String(headers['webhook-signature'] || '').split(' ');
  if (!id || !Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) > toleranceSeconds) return false;
  const key = Buffer.from(String(secret).replace(/^whsec_/, ''), 'base64');
  const expected = crypto.createHmac('sha256', key).update(id + '.' + ts + '.' + rawBody).digest();
  return sigs.some((s) => {
    const [version, value] = s.split(',');
    if (version !== 'v1' || !value) return false;
    const got = Buffer.from(value, 'base64');
    return got.length === expected.length && crypto.timingSafeEqual(got, expected);
  });
}

Python

import base64, hashlib, hmac, time

def verify_webhook(raw_body: bytes, headers, secret: str, tolerance: int = 300) -> bool:
    msg_id = headers.get("webhook-id", "")
    ts = headers.get("webhook-timestamp", "")
    sigs = headers.get("webhook-signature", "").split(" ")
    if not msg_id or not ts.isdigit() or abs(time.time() - int(ts)) > tolerance:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = msg_id.encode() + b"." + ts.encode() + b"." + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    return any(s.startswith("v1,") and hmac.compare_digest(s[3:], expected) for s in sigs)

PHP

<?php
function verify_webhook(string $rawBody, array $headers, string $secret, int $tolerance = 300): bool {
    $id = $headers['webhook-id'] ?? '';
    $ts = $headers['webhook-timestamp'] ?? '';
    $sigs = explode(' ', $headers['webhook-signature'] ?? '');
    if ($id === '' || !ctype_digit($ts) || abs(time() - (int) $ts) > $tolerance) {
        return false;
    }
    $raw = str_starts_with($secret, 'whsec_') ? substr($secret, strlen('whsec_')) : $secret;
    $expected = base64_encode(hash_hmac('sha256', $id . '.' . $ts . '.' . $rawBody, base64_decode($raw), true));
    foreach ($sigs as $s) {
        if (str_starts_with($s, 'v1,') && hash_equals($expected, substr($s, strlen('v1,')))) {
            return true;
        }
    }
    return false;
}

Retries

A call that does not get a 2xx is retried after 5 minutes, 30 minutes, 2, 5, 10 and 24 hours (7 tries in about 41 hours). After 20 failed calls in a row the endpoint is switched off; switch it on again with POST /api/v1/webhooks/{id}/enable. The delivery log is at GET /api/v1/webhooks/deliveries, a manual retry at POST /api/v1/webhooks/deliveries/{id}/retry.