# CreditKit — Complete Technical Reference for LLMs & Coding Agents > Canonical URL: https://creditkit.dev > Concise Index: https://creditkit.dev/llms.txt CreditKit is a drop-in prepaid credit wallet, atomic PostgreSQL FIFO credit ledger, two-phase crash-proof hold engine, and Shadow-DOM Stripe Connect paywall SDK for web and mobile applications. --- ## 1. Architectural Overview & Core Guarantees 1. **Strict FIFO Expiration Ledger:** Every credit grant (daily/monthly free quota, non-expiring promo credit drop, recurring subscription allowance, or non-expiring one-time pack) is stored as an immutable PostgreSQL lot. Deductions lock rows atomically and burn soonest-expiring lots first (`ORDER BY expires_at ASC NULLS LAST`), preserving permanent paid packs and promo grants until expiring subscription or free reset credits are exhausted. 2. **Two-Phase Crash-Proof Holds:** Before running an expensive AI model, API call, or compute job, CreditKit reserves the exact credits (`POST /api/v1/holds`). On HTTP 200, the hold settles (`action: "settle"`). On an upstream 5xx error or timeout, the hold releases (`action: "refund"`) and restores the exact original lots with their original expiration timestamps. 3. **Works With Your Own Stripe Account:** Developers connect their existing Stripe account via Stripe Connect Express. One-time credit packs, monthly/annual rollover subscriptions, mid-cycle proration upgrades, dunning, and proportional partial refund clawbacks run directly against the developer's Stripe account. 4. **Zero-UI-Build Drop-In Surfaces:** Includes an isolated Shadow DOM balance pill (floating corner or inline navbar `
`), top-up paywall modal, exit-intent recovery modal, user wallet & receipt drawer, and hosted mobile Apple Pay / Stripe Link checkout sheet (`/p/[publicKey]`). 5. **Spoof-Proof Authenticated User Binding:** Starter quotas (`50 cr` default) and paid wallets bind directly to the developer's signed-in `userId` (`requireAuth: true` by default). Rendering ` ``` Programmatic APIs on `window.CreditKit`: - `window.CreditKit.getToken()` — Returns active `visitorToken` to send in `x-creditkit-token` headers - `window.CreditKit.openTopUp(placementKey?)` — Opens Shadow DOM paywall modal (e.g., on HTTP `402`) - `window.CreditKit.refresh()` — Syncs balance pill & wallet drawer after server deductions - `window.CreditKit.toggleWalletDrawer(anchorEl?)` — Opens/closes user wallet & receipt drawer - `window.CreditKit.getWallet()` — Reads `{ walletId, userId, email, totalAvailable, freeRemaining, paidRemaining }` - `window.CreditKit.identify({ userId, email, identitySignature })` — Unlocks signed-in starter credits & syncs paid/promo lots across devices - `window.CreditKit.logout()` — Clears local session token & cached identity on user sign-out - `window.CreditKit.gate(placementKey, { units }, async ({ holdId, remaining }) => { ... })` — Client UI gate --- ## 8. Mobile Hosted Checkout Sheet (Expo, React Native & Swift) Docs URL: https://creditkit.dev/docs/expo Every project exposes a hosted Stripe Checkout (Card, Apple Pay & Link) sheet at `/p/[publicKey]` that deep-links back into native apps (`?credits_added=500&balance=550`) and unifies wallet balances across Web and Mobile. Generate a signed URL on your backend with `credits.getMobileTopUpUrl(returnUrl, { userId })`: ```ts import * as WebBrowser from 'expo-web-browser'; const { sheetUrl } = await fetch('https://api.yourapp.com/api/credits/mobile-sheet', { method: 'POST', headers: { Authorization: `Bearer ${authToken}` }, }).then((r) => r.json()); const result = await WebBrowser.openAuthSessionAsync(sheetUrl, 'myapp://credits-unlocked'); ``` > **App Store Storefront Compliance:** External Stripe web links (`0%` Apple fee) are permitted on the **US iOS App Store** (`Storefront === 'USA'`). Apps distributed outside the US must check native `Storefront` in-app before opening the hosted sheet and fall back to StoreKit / RevenueCat IAP internationally (calling `credits.grantCredits({ userId, amount, reason })` from their server IAP webhook to credit the same wallet). --- ## 9. Complete REST API Reference (`/api/v1/*`) REST Docs: https://creditkit.dev/docs/api 1. **`GET /api/v1/status?projectKey=pk_...`** - Headers: `X-CreditKit-Token: ` (optional) - Response `200`: `{ ok: true, wallet: { walletId, userId, email, visitorToken, totalAvailable, freeRemaining, paidRemaining, lots }, project }` 2. **`POST /api/v1/identify`** - Headers: `Authorization: Bearer sk_...` OR `X-CreditKit-Identity-Signature: ` (`= HMAC-SHA256(secretKey.trim(), (userId || email).trim().toLowerCase())` hex; use `sk_test_...` with `pk_test_...` and `sk_live_...` with `pk_live_...`) - Body (bind user): `{ projectKey: "pk_...", userId: "usr_123", email: "u@app.com", visitorToken }` → `{ ok: true, walletId, visitorToken, merged, transferredLotsCount, balance }` - Body (sign out): `{ projectKey: "pk_...", visitorToken, action: "logout" }` → `{ ok: true, loggedOut: true, walletId, visitorToken, balance: 0 }` 3. **`POST /api/v1/consume`** - Headers: `Authorization: Bearer sk_...`, `Idempotency-Key: ` - Body: `{ placementKey: "run_action", userId: "usr_123", visitorToken, units: 1 }` - Response `200`: `{ ok: true, allowed: true, deducted: 10, remaining: 40, walletId }` (or `402` `{ ok: false, allowed: false, code: "INSUFFICIENT_CREDITS", remaining }`) 4. **`POST /api/v1/holds` & `PUT /api/v1/holds`** - `POST` Reserve Body: `{ placementKey: "run_action", userId: "usr_123", units: 1 }` → `200` `{ ok: true, allowed: true, holdId: "hold_...", deducted: 10, remaining: 40, walletId, visitorToken }` (or `402`) - `PUT` (or `POST`) Settle/Refund Body: `{ holdId: "hold_...", action: "settle" | "refund" | "commit" | "release", reason?: "upstream_502" }` → `200` `{ ok: true, holdId, status: "settled", settledCredits, refundedUnused }` or `{ ok: true, holdId, status: "refunded", restoredCredits, restoredLots }` 5. **`POST /api/v1/checkout`** - Body: `{ projectKey: "pk_...", tierId: "tier_standard", visitorToken, promoCode?: "LAUNCH20", returnUrl?: "https://app.com/billing", instantSandbox?: true }` - Response `200`: `{ ok: true, mode: "stripe_redirect" | "sandbox_fulfilled", checkoutUrl?, creditsAdded?, wallet? }` 6. **`POST /api/v1/growth`** - Promo redemption (client or server): `{ projectKey: "pk_...", visitorToken, action: "redeem_promo", code: "PRODUCTHUNT" }` → `200` `{ ok: true, promoType: "free_credits", code: "PRODUCTHUNT", creditsAdded: 25, expiryDays: null, wallet }` (free-credit promo grants never expire) or `{ ok: true, promoType: "percent_off", discountPct: 20, code }` - Server admin grant/deduct (`Authorization: Bearer sk_...`): `{ action: "manual_grant" | "manual_deduct", userId: "usr_123", creditsAmount: 100, reason: "apple_iap_sync" }` → `200` `{ ok: true, creditsAdded: 100, targetWalletId }` --- ## 10. Going Live Cutover Checklist (`pk_test_` → `pk_live_`) 1. **Connect Stripe Express:** Complete 1-click onboarding in **Console → Developers** so live customer top-ups route directly to your Stripe account. 2. **Lock Authorized Production Domains:** Flip **Test mode → Live** in the Console header and enter your HTTPS production domain (e.g. `https://yourapp.com`). 3. **Swap Environment Keys:** Update `NEXT_PUBLIC_CREDITKIT_KEY` to `pk_live_...` and `CREDITKIT_SECRET_KEY` to `sk_live_...` in production. 4. **Verify Server-Signed Identity HMAC:** Ensure `data-identity-signature={credits.signUser(user.id)}` is passed on your root `