API & Webhooks · REST Reference

Core REST API & Idempotency

Call CreditKit's HTTP endpoints directly from Python, Go, Rust, Ruby, PHP, or Node.js backends using Authorization: Bearer sk_....

Endpoints Overview

EndpointPurpose
GET /api/v1/statusResolves visitor wallet, lazy quota refills, A/B variant, and FIFO lots.
POST /api/v1/identifyBinds an anonymous wallet to userId / email, merges lots across devices, or runs action: 'logout'.
POST /api/v1/consumeDeducts credits in strict FIFO expiration order or returns 402.
POST / PUT /api/v1/holdsCreates a 2-phase hold (POST) or settles/refunds exact lots on 5xx crash (PUT).
POST /api/v1/checkoutCreates a Stripe Checkout session or fulfills Test Mode sandbox credits.
POST /api/v1/growthPromo redemption (redeem_promo; free-credit drops never expire) and server CRM grants (manual_grant).

1. Wallet Status & Identity Sync (/status & /identify)

GET /api/v1/status & POST /api/v1/identify
// A) Read wallet balance & active FIFO credit lots
// GET https://creditkit.dev/api/v1/status?projectKey=pk_test_...
// Headers: { "X-CreditKit-Token": "<visitorToken>" }
// -> 200 { ok: true, wallet: { walletId, userId, email, visitorToken, totalAvailable, freeRemaining, paidRemaining, lots } }

// B) Bind signed-in userId & merge lots across devices
const identRes = await fetch('https://creditkit.dev/api/v1/identify', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.CREDITKIT_SECRET_KEY}`, // sk_test_... or sk_live_...
  },
  body: JSON.stringify({
    userId: 'usr_clerk_9921',
    email: 'founder@acme.ai',
    visitorToken, // Optional browser session token to merge
  }),
});
// -> 200 { ok: true, walletId, visitorToken, merged: false, transferredLotsCount: 0, balance: 50 }

2. Direct Consume & Idempotency (POST /api/v1/consume)

Pass Idempotency-Key on POST /api/v1/consume or POST /api/v1/holds to safely retry network timeouts without double-charging:

POST /api/v1/consume
const res = await fetch('https://creditkit.dev/api/v1/consume', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.CREDITKIT_SECRET_KEY}`,
    'Idempotency-Key': `req_${jobId}_attempt_1`,
  },
  body: JSON.stringify({
    placementKey: 'run_action',
    userId: 'usr_clerk_9921',
    units: 1,
  }),
});
// 200 OK: { ok: true, allowed: true, deducted: 10, remaining: 40, walletId: "wal_..." }
// 402 Payment Required: { ok: false, allowed: false, code: "INSUFFICIENT_CREDITS", remaining: 0 }
// Rate limit: 180 req/min per IP (returns HTTP 429 with Retry-After header if exceeded)

3. Two-Phase Crash-Proof Holds (POST & PUT /api/v1/holds)

POST & PUT /api/v1/holds
// 1. Reserve credits (returns HTTP 200 { ok: true, allowed: true, holdId, deducted, remaining } or HTTP 402)
const reserveRes = await fetch('https://creditkit.dev/api/v1/holds', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.CREDITKIT_SECRET_KEY}`,
  },
  body: JSON.stringify({
    placementKey: 'run_action',
    userId: 'usr_clerk_9921',
    units: 1,
  }),
});
const { allowed, holdId, remaining } = await reserveRes.json();

// 2. Settle after upstream success — OR pass action: 'refund' on 5xx crash
// (Both PUT /api/v1/holds and POST /api/v1/holds accept { holdId, action: 'settle' | 'refund' | 'commit' | 'release' })
await fetch('https://creditkit.dev/api/v1/holds', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.CREDITKIT_SECRET_KEY}`,
  },
  body: JSON.stringify({
    holdId,
    action: 'settle', // or 'refund' with optional reason: 'upstream_502'
  }),
});

4. Checkout Sessions, Promo Redemption & Server Grants (/checkout & /growth)

POST /api/v1/checkout & POST /api/v1/growth
// A) Create a Stripe Checkout session (or instant sandbox grant when using pk_test_ / sk_test_)
const checkoutRes = await fetch('https://creditkit.dev/api/v1/checkout', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.CREDITKIT_SECRET_KEY}`,
  },
  body: JSON.stringify({
    userId: 'usr_clerk_9921',
    tierId: 'tier_standard',
    promoCode: 'LAUNCH20', // Optional % off code
    returnUrl: 'https://yourapp.com/billing',
  }),
});
// -> { ok: true, mode: "stripe_redirect", checkoutUrl: "https://checkout.stripe.com/..." }

// B) Server-side credit grant (Apple IAP sync, onboarding bonus, or support comp)
await fetch('https://creditkit.dev/api/v1/growth', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.CREDITKIT_SECRET_KEY}`,
  },
  body: JSON.stringify({
    action: 'manual_grant', // or 'manual_deduct'
    userId: 'usr_clerk_9921',
    creditsAmount: 250,
    reason: 'onboarding_referral_bonus',
  }),
});
// -> { ok: true, creditsAdded: 250, targetWalletId: "wal_..." }

5. Python (FastAPI) & Go (net/http) + Identity HMAC Formula

When rendering <script data-user-id="..." data-identity-signature="..."> from Python, Go, Ruby, or Rails, compute HMAC-SHA256(secretKey, userId.strip().lower()) in hex (use sk_test_... with pk_test_... and sk_live_... with pk_live_...):

Python (FastAPI + httpx 2-Phase Hold & Identity HMAC)
import hashlib, hmac, os, httpx
from fastapi import FastAPI, HTTPException

SECRET_KEY = os.environ["CREDITKIT_SECRET_KEY"]  # sk_test_... or sk_live_...

def sign_creditkit_user(user_id: str) -> str:
    msg = user_id.strip().lower().encode("utf-8")
    return hmac.new(SECRET_KEY.encode("utf-8"), msg, hashlib.sha256).hexdigest()

async def run_metered_job(user_id: str, job_id: str):
    headers = {"Authorization": f"Bearer {SECRET_KEY}"}
    async with httpx.AsyncClient(base_url="https://creditkit.dev", timeout=10.0) as client:
        hold_res = await client.post(
            "/api/v1/holds",
            headers={**headers, "Idempotency-Key": f"job_{job_id}"},
            json={"placementKey": "run_action", "userId": user_id, "units": 1},
        )
        if hold_res.status_code == 402:
            raise HTTPException(status_code=402, detail=hold_res.json())
        hold_res.raise_for_status()
        hold_id = hold_res.json().get("holdId")
        try:
            result = {"ok": True}  # Run your LLM / GPU / API workload here
            if hold_id:
                await client.put("/api/v1/holds", headers=headers, json={"holdId": hold_id, "action": "settle"})
            return result
        except Exception as exc:
            if hold_id:
                await client.put("/api/v1/holds", headers=headers, json={"holdId": hold_id, "action": "refund", "reason": str(exc)})
            raise
Go (net/http Identity HMAC & Direct Consume)
func signCreditKitUser(userID, secretKey string) string {
    mac := hmac.New(sha256.New, []byte(strings.TrimSpace(secretKey)))
    mac.Write([]byte(strings.ToLower(strings.TrimSpace(userID))))
    return hex.EncodeToString(mac.Sum(nil))
}

body := strings.NewReader(`{"placementKey":"run_action","userId":"usr_9921","units":1}`)
req, _ := http.NewRequest("POST", "https://creditkit.dev/api/v1/consume", body)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+os.Getenv("CREDITKIT_SECRET_KEY"))
req.Header.Set("Idempotency-Key", "job_"+jobID)

resp, err := http.DefaultClient.Do(req)
if err != nil {
    return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusPaymentRequired { // 402 -> insufficient credits
    w.WriteHeader(http.StatusPaymentRequired)
    io.Copy(w, resp.Body)
    return nil
}
if resp.StatusCode >= 400 { // 401/403/429/500 -> config or rate-limit error
    return fmt.Errorf("creditkit consume error: HTTP %d", resp.StatusCode)
}