API & Webhooks · Security & Schemas

Webhook HMAC Signature Verification

Configure your endpoint in Console → Developers → Outbound Webhooks (use a public HTTPS URL, or ngrok / Cloudflare Tunnel during local testing). Every outbound event includes X-CreditKit-Signature: t=<sec>,v1=<hex>, signed with sk_test_... in Test Mode (livemode: false) and sk_live_... in Live Mode (livemode: true) — credits.verifyWebhookSignature() aligns the prefix with event.livemode automatically so Console test simulations and live deliveries both verify cleanly.

1. One-Line Verification with credits.verifyWebhookSignature()

Read the unparsed request body with await req.text() and verify with credits.verifyWebhookSignature(rawBody, sig) from lib/creditkit.ts (checks the 5-minute timestamp window and compares HMAC-SHA256 digests with crypto.timingSafeEqual):

app/api/webhooks/creditkit/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { CreditKitClient } from '@/lib/creditkit';

const credits = new CreditKitClient({
  apiKey: process.env.CREDITKIT_SECRET_KEY!, // sk_test_... locally, sk_live_... in prod
});

export async function POST(req: NextRequest) {
  const rawBody = await req.text(); // Must be the exact raw JSON body string
  const sigHeader = req.headers.get('x-creditkit-signature');

  if (!credits.verifyWebhookSignature(rawBody, sigHeader)) {
    return NextResponse.json({ error: 'Invalid or stale webhook signature' }, { status: 401 });
  }

  const event = JSON.parse(rawBody);
  console.log('Verified CreditKit event:', event.type, event.data);
  return NextResponse.json({ received: true });
}

Local development note: Outbound webhooks block private/loopback IPs (localhost, 127.0.0.1) for SSRF protection. Expose local handlers with ngrok http 3000 or cloudflared tunnel, or inspect payloads directly in the Console's built-in Webhook Simulator.

Language-Agnostic Verification (Python / FastAPI — ${t}.${rawBody})
import hashlib, hmac, json, os, time

def verify_creditkit_webhook(raw_body: str, sig_header: str, secret_key: str, tolerance: int = 300) -> bool:
    try:
        parts = dict(item.split("=", 1) for item in (sig_header or "").split(",") if "=" in item)
        ts, v1 = int(parts.get("t", "0")), parts.get("v1", "")
        if not ts or not v1 or abs(int(time.time()) - ts) > tolerance:
            return False
        event = json.loads(raw_body)
    except (ValueError, TypeError):
        return False
    key = (
        secret_key.replace("sk_live_", "sk_test_", 1)
        if event.get("livemode") is False and secret_key.startswith("sk_live_")
        else secret_key.replace("sk_test_", "sk_live_", 1)
        if event.get("livemode") is True and secret_key.startswith("sk_test_")
        else secret_key
    )
    expected = hmac.new(key.encode("utf-8"), f"{ts}.{raw_body}".encode("utf-8"), hashlib.sha256).hexdigest()
    return hmac.compare_digest(v1, expected)

2. All 7 Outbound Webhook Event Types

Event TypeTrigger & Key data Fields
credit.topup.completedPack purchase, subscription renewal, or sandbox checkout. wallet_id, user_id, email, lot_id, source_type, tier_id, credits_added, credits_delta, revenue_cents
credit.consumedEmitted when credits are deducted or reserved via hold. wallet_id, user_id, email, placement_key, source_pool, credits_deducted, credits_delta, remaining_credits, hold_id, mode
credit.hold.refunded_5xx2-phase hold refunded after upstream 5xx error or explicit hold release. wallet_id, user_id, email, hold_id, placement_key, credits_restored, credits_delta, reason
credit.gate.reachedUser hit 0 credits on consume/hold (402 block or slow_tier fallback). wallet_id, user_id, email, placement_key, required_credits, remaining_credits, ab_variant
credit.paywall.abandonedPaywall dismissed without purchasing (Builder/Studio). wallet_id, user_id, email, placement_key, exit_playbook, promo_magic_link_example
credit.subscription.payment_failedRecurring Stripe invoice failed (triggers wallet dunning banner). wallet_id, user_id, email, stripe_invoice_id, invoice_id, amount_due_cents, attempt_count
credit.charge.refundedStripe refund processed with proportional unspent lot clawback. wallet_id, user_id, email, credits_revoked, revoked_credits, refunded_cents, refund_cents, stripe_charge_id, reason

3. Example Envelope Payload

credit.topup.completed (JSON)
{
  "id": "ev_9a82b4c102ef",
  "object": "creditkit.event",
  "type": "credit.topup.completed",
  "livemode": true,
  "created": 1763219400,
  "project_id": "proj_7d82a9c4b1e02f3a81c4e910",
  "data": {
    "wallet_id": "wal_4f92c1e8b3a0",
    "user_id": "usr_clerk_9921",
    "email": "founder@acme.ai",
    "lot_id": "lot_8c31f0a2d9e4",
    "source_type": "one_time_pack",
    "tier_id": "tier_standard",
    "credits_added": 1000,
    "credits_delta": 1000,
    "revenue_cents": 1200
  }
}