Vorschau: Capydra öffnet bald. Bestellen ist noch nicht möglich.

Capydra
Hilfe Warenkorb
Deal der Woche

Webhooks

Wir rufen deinen HTTPS-Endpunkt auf, wenn etwas passiert, damit du nicht ständig abfragen musst. Bis zu 3 Endpunkte je Konto.

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"]}'

Die Antwort enthält einmal das Secret des Endpunkts (whsec_...). Ereignisse:

  • order.status: jede Statusänderung einer Bestellung, die mit einem API-Schlüssel gemacht wurde.
  • order.complete: die Bestellung ist geliefert; hol ihre Keys ab.
  • product.update: Produkte, deren Angebote sich geändert haben (Preis, Bestand, Status), bis zu 100 IDs je Aufruf, alle 15 Minuten.

Ein Inhalt enthält nie einen Key, Käuferdaten oder einen Geldbetrag. Die Details holst du mit deinem Schlüssel.

Signatur

Jeder Aufruf hat drei Header (Standard-Webhooks-Format): webhook-id, webhook-timestamp (Unix-Sekunden) und webhook-signature (v1, plus der base64-HMAC-SHA256 von id.timestamp.body, Schlüssel ist der base64-decodierte Teil deines Secrets nach whsec_). Nach einer Secret-Erneuerung kommen zwei Signaturen, durch Leerzeichen getrennt. Nie steht ein Secret in einem Header.

  1. Nimm den rohen Inhalt, vor dem JSON-Parsen.
  2. Verwirf Aufrufe, deren Zeitstempel mehr als 5 Minuten abweicht.
  3. Vergleiche in konstanter Zeit.
  4. Verwirf IDs, die du schon kennst: ein Aufruf kann doppelt kommen, und die Reihenfolge ist nicht garantiert.
  5. Antworte innerhalb von 10 Sekunden mit 2xx; erledige die Arbeit danach.

curl und 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;
}

Wiederholungen

Ein Aufruf ohne 2xx wird nach 5 Minuten, 30 Minuten, 2, 5, 10 und 24 Stunden wiederholt (7 Versuche in etwa 41 Stunden). Nach 20 Fehlschlägen in Folge wird der Endpunkt abgeschaltet; einschalten mit POST /api/v1/webhooks/{id}/enable. Das Zustellprotokoll steht unter GET /api/v1/webhooks/deliveries, ein erneuter Versuch unter POST /api/v1/webhooks/deliveries/{id}/retry.