Getting Started · End-to-End Quickstart (Zero NPM Install)

React & Next.js Client Hook

Add prepaid credits, a Shadow DOM balance pill & paywall modal, and crash-proof server holds to any Next.js or React app in 5 minutes — with zero npm packages to install.

How CreditKit Works: Signed-In User Binding, Sandbox Keys & 2-Phase Holds
  • Signed-in users + 1-line Identity HMAC: CreditKit binds wallets (and your 50 cr starter trial quota) to your app's authenticated userId. Render <script async src=".../v1/creditkit.js" /> with data-user-id={user?.id || ''} and data-identity-signature={user ? credits.signUser(user.id) : ''} so cross-device wallet sync is spoof-proof and updates automatically on router.refresh() or sign-out.
  • Sandbox first (pk_test_... / sk_test_...): New projects start in Test Mode so you can run instant fake checkouts locally before connecting Stripe. Swap to pk_live_... / sk_live_... once Stripe Express is connected.
  • Why <script async> instead of next/script: Next.js's <Script strategy="afterInteractive"> renders null after initial mount and does not update DOM attributes during SPA login/logout. Native <script async ... /> reconciles data-user-id live and triggers creditkit.js's MutationObserver.
  • Placement keys: New projects pre-register 'default', 'run_action', and 'export_batch' (10 cr each). Configure costs anytime in Pricing & Gates.

1. Add Your Sandbox Keys to .env.local

Copy your pk_test_... and sk_test_... keys from Console → Developers:

.env.local
# Sandbox keys (instant zero-Stripe test checkouts). Swap to pk_live_ / sk_live_ in prod:
NEXT_PUBLIC_CREDITKIT_KEY=pk_test_YOUR_PUBLIC_KEY
CREDITKIT_SECRET_KEY=sk_test_YOUR_SECRET_KEY

2. Create Server Helper lib/creditkit.ts

Single zero-dependency TypeScript helper for Identity HMAC signing, 2-phase crash-proof holds, webhook verification, and mobile sheet URLs:

lib/creditkit.ts
import crypto from 'node:crypto';

export interface GateActionResult<T> {
  allowed: boolean;
  mode?: 'normal' | 'standard' | 'slow_tier';
  data?: T;
  remaining?: number;
  deducted?: number;
  holdId?: string | null;
  refundedOnCrash?: boolean;
  status?: number;
  configError?: boolean;
  error?: string;
}

function readHeader(req: any, name: string): string | undefined {
  const h = req?.headers;
  if (!h) return undefined;
  if (typeof h.get === 'function') return h.get(name) || undefined;
  const raw = h[name] ?? h[name.toLowerCase()];
  return Array.isArray(raw) ? raw[0] : raw || undefined;
}

/** Verifies X-CreditKit-Signature (t=<sec>,v1=<hmac_hex>) against the exact raw HTTP body string */
export function verifyCreditKitWebhook(
  rawBody: string,
  signatureHeader: string | null | undefined,
  secretKey: string,
  toleranceSeconds = 300
): boolean {
  const sig = String(signatureHeader || '').trim();
  const secret = String(secretKey || '').trim();
  if (!sig || !secret) return false;

  const parts: Record<string, string> = {};
  for (const segment of sig.split(',')) {
    const eqIdx = segment.indexOf('=');
    if (eqIdx > 0) parts[segment.slice(0, eqIdx).trim()] = segment.slice(eqIdx + 1).trim();
  }

  const ts = Number(parts.t);
  const v1 = parts.v1;
  if (!Number.isFinite(ts) || !v1) return false;
  if (toleranceSeconds > 0 && Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSeconds) {
    return false;
  }

  let effectiveSecret = secret;
  try {
    const parsed = JSON.parse(rawBody);
    if (parsed && typeof parsed.livemode === 'boolean') {
      if (parsed.livemode === false && effectiveSecret.startsWith('sk_live_')) {
        effectiveSecret = effectiveSecret.replace(/^sk_live_/, 'sk_test_');
      } else if (parsed.livemode === true && effectiveSecret.startsWith('sk_test_')) {
        effectiveSecret = effectiveSecret.replace(/^sk_test_/, 'sk_live_');
      }
    }
  } catch {}

  const expected = crypto.createHmac('sha256', effectiveSecret).update(`${parts.t}.${rawBody}`).digest('hex');
  if (v1.length !== expected.length) return false;
  return crypto.timingSafeEqual(Buffer.from(v1, 'utf8'), Buffer.from(expected, 'utf8'));
}

function alignPublicKeyWithSecret(pubKey: string, apiKey: string): string {
  const cleanPub = String(pubKey || '').trim();
  if (!cleanPub || cleanPub.startsWith('sk_')) return cleanPub;
  if (apiKey.startsWith('sk_test_') && cleanPub.startsWith('pk_live_')) {
    return cleanPub.replace(/^pk_live_/, 'pk_test_');
  }
  if (apiKey.startsWith('sk_live_') && cleanPub.startsWith('pk_test_')) {
    return cleanPub.replace(/^pk_test_/, 'pk_live_');
  }
  return cleanPub;
}

export class CreditKitClient {
  private baseUrl: string;
  private apiKey: string;
  private explicitProjectKey: string;
  private projectKey: string;

  constructor(config: {
    baseUrl?: string;
    apiKey?: string;
    secretKey?: string;
    projectKey?: string;
    publicKey?: string;
  }) {
    this.baseUrl = (config.baseUrl || 'https://creditkit.dev').replace(/\/$/, '');
    this.apiKey = (config.apiKey || config.secretKey || '').trim();
    this.explicitProjectKey = alignPublicKeyWithSecret(
      (config.projectKey || config.publicKey || '').trim(),
      this.apiKey
    );
    this.projectKey = this.explicitProjectKey || this.apiKey;
  }

  /** Computes the spoof-proof HMAC stamp for data-identity-signature / mobile ?sig= */
  signUser(userIdOrEmail: string): string {
    if (!this.apiKey || !this.apiKey.startsWith('sk_')) {
      throw new Error(
        'CreditKitClient.signUser() requires CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...)'
      );
    }
    return crypto
      .createHmac('sha256', this.apiKey)
      .update(String(userIdOrEmail || '').trim().toLowerCase())
      .digest('hex');
  }

  /** Verifies an outbound CreditKit webhook (X-CreditKit-Signature) against the raw HTTP body */
  verifyWebhookSignature(
    rawBody: string,
    signatureHeader: string | null | undefined,
    options?: { secretKey?: string; toleranceSeconds?: number }
  ): boolean {
    return verifyCreditKitWebhook(
      rawBody,
      signatureHeader,
      (options?.secretKey || this.apiKey).trim(),
      options?.toleranceSeconds ?? 300
    );
  }

  /** Builds a signed hosted mobile top-up sheet URL (/p/pk_...?user_id=...&sig=...) */
  getMobileTopUpUrl(
    returnUrl = 'myapp://credits-unlocked',
    options?: {
      publicKey?: string;
      visitorToken?: string;
      userId?: string;
      email?: string;
      identitySignature?: string;
    }
  ): string {
    const pubKey =
      options?.publicKey?.trim() ||
      (!this.projectKey.startsWith('sk_') ? this.projectKey : '');
    if (!pubKey || pubKey.startsWith('sk_')) {
      throw new Error(
        'CreditKitClient.getMobileTopUpUrl() requires a publicKey (pk_test_... or pk_live_...)'
      );
    }
    const qs = new URLSearchParams({ return_url: returnUrl });
    if (options?.visitorToken) qs.set('token', options.visitorToken);
    if (options?.userId) qs.set('user_id', options.userId);
    if (options?.email) qs.set('email', options.email);
    const signingSecret =
      pubKey.startsWith('pk_test_') && this.apiKey.startsWith('sk_live_')
        ? this.apiKey.replace(/^sk_live_/, 'sk_test_')
        : pubKey.startsWith('pk_live_') && this.apiKey.startsWith('sk_test_')
        ? this.apiKey.replace(/^sk_test_/, 'sk_live_')
        : this.apiKey;
    const sig =
      options?.identitySignature ||
      (signingSecret.startsWith('sk_') && (options?.userId || options?.email)
        ? crypto
            .createHmac('sha256', signingSecret)
            .update(String((options.userId || options.email)!).trim().toLowerCase())
            .digest('hex')
        : '');
    if (sig) qs.set('sig', sig);
    return `${this.baseUrl}/p/${encodeURIComponent(pubKey)}?${qs.toString()}`;
  }

  async getStatus(params?: { visitorToken?: string; fingerprint?: string }) {
    const headers: Record<string, string> = {};
    if (this.apiKey.startsWith('sk_')) headers.Authorization = `Bearer ${this.apiKey}`;
    if (params?.visitorToken) headers['X-CreditKit-Token'] = params.visitorToken;
    if (params?.fingerprint) headers['X-CreditKit-Fingerprint'] = params.fingerprint;
    const qs = new URLSearchParams();
    if (this.explicitProjectKey && !this.explicitProjectKey.startsWith('sk_')) {
      qs.set('projectKey', this.explicitProjectKey);
    } else if (!this.apiKey.startsWith('sk_') && this.projectKey) {
      qs.set('projectKey', this.projectKey);
    }
    const querySuffix = qs.toString() ? `?${qs.toString()}` : '';
    const res = await fetch(`${this.baseUrl}/api/v1/status${querySuffix}`, { headers });
    return res.json().catch(() => ({ ok: false, status: res.status }));
  }

  async identify(params: {
    userId?: string;
    email?: string;
    visitorToken?: string;
    identitySignature?: string;
  }) {
    const isSecret = this.apiKey.startsWith('sk_');
    const effectivePubKey = this.explicitProjectKey || (!isSecret ? this.apiKey : '');
    const sig =
      params.identitySignature ||
      (isSecret && (params.userId || params.email)
        ? this.signUser((params.userId || params.email)!)
        : '');
    const res = await fetch(`${this.baseUrl}/api/v1/identify`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(isSecret ? { Authorization: `Bearer ${this.apiKey}` } : {}),
        ...(!isSecret && this.apiKey ? { 'X-CreditKit-Key': this.apiKey } : {}),
        ...(params.visitorToken ? { 'X-CreditKit-Token': params.visitorToken } : {}),
        ...(sig ? { 'X-CreditKit-Identity-Signature': sig } : {}),
      },
      body: JSON.stringify({
        ...(effectivePubKey && !effectivePubKey.startsWith('sk_') ? { projectKey: effectivePubKey } : {}),
        userId: params.userId,
        email: params.email,
        visitorToken: params.visitorToken,
        ...(sig ? { identitySignature: sig } : {}),
      }),
    });
    return res.json().catch(() => ({
      ok: false,
      merged: false,
      walletId: '',
      visitorToken: params.visitorToken || '',
      email: params.email || null,
      transferredLotsCount: 0,
      balance: 0,
    }));
  }

  async consume(options: {
    placementKey: string;
    visitorToken?: string;
    walletId?: string;
    userId?: string;
    email?: string;
    amount?: number;
    units?: number;
    idempotencyKey?: string;
  }) {
    if (!this.apiKey && !this.explicitProjectKey) {
      return {
        ok: false,
        allowed: false,
        configError: true,
        status: 401,
        error: 'MISSING_SECRET_KEY: Set CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...) in .env.local',
      };
    }
    const isPublishableKey = this.apiKey.startsWith('pk_');
    if (isPublishableKey && (options.userId || options.email || options.walletId)) {
      return {
        ok: false,
        allowed: false,
        configError: true,
        status: 401,
        error: 'INVALID_SECRET_KEY: Server-side userId/email/walletId operations require CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...), not a publishable key (pk_...).',
      };
    }
    const effectivePubKey = this.explicitProjectKey || (isPublishableKey ? this.apiKey : '');
    const res = await fetch(`${this.baseUrl}/api/v1/consume`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(this.apiKey && !isPublishableKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
        ...(options.visitorToken ? { 'X-CreditKit-Token': options.visitorToken } : {}),
        ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),
      },
      body: JSON.stringify({
        ...(effectivePubKey ? { projectKey: effectivePubKey } : {}),
        placementKey: options.placementKey,
        walletId: options.walletId,
        userId: options.userId,
        email: options.email,
        amount: options.amount,
        units: options.units ?? 1,
        idempotencyKey: options.idempotencyKey,
      }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok && res.status !== 402) {
      return { ...data, ok: false, allowed: false, status: res.status, configError: true };
    }
    return { ...data, status: res.status };
  }

  async withCrashProofHold<T>(
    options: {
      placementKey: string;
      req?: { headers?: any };
      visitorToken?: string;
      walletId?: string;
      userId?: string;
      email?: string;
      amount?: number;
      units?: number;
      idempotencyKey?: string;
    },
    fn: (hold: {
      holdId: string;
      deducted: number;
      remaining: number;
      mode?: 'normal' | 'standard' | 'slow_tier';
    }) => Promise<T>
  ): Promise<GateActionResult<T>> {
    if (!this.apiKey && !this.explicitProjectKey) {
      return {
        allowed: false,
        configError: true,
        status: 401,
        remaining: 0,
        error: 'MISSING_SECRET_KEY: Set CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...) in .env.local',
      };
    }
    const isPublishableKey = this.apiKey.startsWith('pk_');
    if (isPublishableKey && (options.userId || options.email || options.walletId)) {
      return {
        allowed: false,
        configError: true,
        status: 401,
        remaining: 0,
        error: 'INVALID_SECRET_KEY: Server-side userId/email/walletId operations require CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...), not a publishable key (pk_...).',
      };
    }
    const token = options.visitorToken || readHeader(options.req, 'x-creditkit-token');
    const fp = readHeader(options.req, 'x-creditkit-fingerprint');
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      ...(this.apiKey && !isPublishableKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
      ...(token ? { 'X-CreditKit-Token': token } : {}),
      ...(fp ? { 'X-CreditKit-Fingerprint': fp } : {}),
      ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),
    };

    const effectivePubKey = this.explicitProjectKey || (isPublishableKey ? this.apiKey : '');
    const res = await fetch(`${this.baseUrl}/api/v1/holds`, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        ...(effectivePubKey ? { projectKey: effectivePubKey } : {}),
        placementKey: options.placementKey,
        walletId: options.walletId,
        userId: options.userId,
        email: options.email,
        amount: options.amount,
        units: options.units ?? 1,
        idempotencyKey: options.idempotencyKey,
      }),
    });
    const reserve = await res.json().catch(() => ({}));
    if (!res.ok || !reserve.allowed) {
      const configError = res.status !== 402 && !res.ok;
      return {
        allowed: false,
        status: res.status,
        configError: configError || undefined,
        remaining: reserve.remaining ?? 0,
        error: configError
          ? reserve.error || reserve.code || `CREDITKIT_HTTP_${res.status}`
          : reserve.code || 'INSUFFICIENT_CREDITS',
      };
    }

    const holdId: string = reserve.holdId;
    const holdVisitorToken = token || reserve.visitorToken;
    if (holdVisitorToken) headers['X-CreditKit-Token'] = holdVisitorToken;
    try {
      const data = await fn({
        holdId,
        deducted: reserve.deducted,
        remaining: reserve.remaining,
        mode: reserve.mode,
      });
      if (holdId) {
        await fetch(`${this.baseUrl}/api/v1/holds`, {
          method: 'PUT',
          headers,
          body: JSON.stringify({ holdId, action: 'settle' }),
        });
      }
      return {
        allowed: true,
        mode: reserve.mode,
        data,
        deducted: reserve.deducted,
        remaining: reserve.remaining,
        holdId,
      };
    } catch (err: any) {
      if (holdId) {
        await fetch(`${this.baseUrl}/api/v1/holds`, {
          method: 'PUT',
          headers,
          body: JSON.stringify({
            holdId,
            action: 'refund',
            reason: err?.message || 'upstream_5xx_exception',
          }),
        });
      }
      return {
        allowed: false,
        refundedOnCrash: true,
        holdId,
        error: err?.message || 'UPSTREAM_EXECUTION_FAILED',
      };
    }
  }

  async grantCredits(params: {
    amount: number;
    walletId?: string;
    userId?: string;
    email?: string;
    visitorToken?: string;
    projectKey?: string;
    publicKey?: string;
    reason?: string;
  }) {
    if (!this.apiKey) {
      return {
        ok: false,
        configError: true,
        status: 401,
        error: 'MISSING_SECRET_KEY: Set CREDITKIT_SECRET_KEY (sk_test_... or sk_live_...) in .env.local',
      };
    }
    const explicitKey = alignPublicKeyWithSecret(
      params.projectKey || params.publicKey || this.explicitProjectKey,
      this.apiKey
    );
    const res = await fetch(`${this.baseUrl}/api/v1/growth`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${this.apiKey}`,
        ...(params.visitorToken ? { 'X-CreditKit-Token': params.visitorToken } : {}),
      },
      body: JSON.stringify({
        action: 'manual_grant',
        ...(explicitKey && !explicitKey.startsWith('sk_') ? { projectKey: explicitKey } : {}),
        targetWalletId: params.walletId,
        userId: params.userId,
        email: params.email,
        visitorToken: params.visitorToken,
        creditsAmount: params.amount,
        reason: params.reason || 'server_grant',
      }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      return {
        ...data,
        ok: false,
        configError: true,
        status: res.status,
        error: data.error || `CREDITKIT_HTTP_${res.status}`,
      };
    }
    return { ...data, status: res.status };
  }
}

3. Load the Shadow DOM Widget in app/layout.tsx

app/layout.tsx (Server Component)
import { CreditKitClient } from '@/lib/creditkit';

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

// Replace with your own auth helper (Clerk currentUser(), Supabase, Better Auth, NextAuth)
async function getCurrentUser(): Promise<{ id: string; email?: string } | null> {
  return { id: 'usr_demo_123', email: 'dev@example.com' };
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const user = await getCurrentUser();

  return (
    <html lang="en">
      <body>
        {/* Optional inline navbar balance pill slot: <div data-creditkit-pill></div> */}
        {children}
        <script
          async
          src="https://creditkit.dev/v1/creditkit.js"
          data-project-key={process.env.NEXT_PUBLIC_CREDITKIT_KEY}
          data-user-id={user?.id || ''}
          data-user-email={user?.email || ''}
          data-identity-signature={user ? credits.signUser(user.id) : ''}
        />
      </body>
    </html>
  );
}

4. Gate Your Metered Route in app/api/generate/route.ts

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

const credits = new CreditKitClient({
  apiKey: process.env.CREDITKIT_SECRET_KEY!,
});

// Replace with your own auth session lookup
async function getSession(_req: NextRequest): Promise<{ user: { id: string; email?: string } } | null> {
  return { user: { id: 'usr_demo_123', email: 'dev@example.com' } };
}

export async function POST(req: NextRequest) {
  const session = await getSession(req);
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const hold = await credits.withCrashProofHold(
    {
      req, // Forwards x-creditkit-token header from browser
      userId: session.user.id,
      email: session.user.email,
      placementKey: 'run_action', // Costs 10 credits by default
      units: 1,
    },
    async ({ remaining }) => {
      // Run your OpenAI / Anthropic / Replicate / API job here.
      // Throwing any error automatically refunds the exact reserved credits!
      return { outputUrl: 'https://cdn.example.com/result.png', remaining };
    }
  );

  if (!hold.allowed) {
    return NextResponse.json(hold, {
      status: hold.configError ? 500 : hold.refundedOnCrash ? 502 : 402,
    });
  }

  return NextResponse.json(hold.data);
}

5. Copy hooks/useCreditKit.ts & Trigger Paywall on HTTP 402

Exposes reactive balance, openTopUp, openWallet, and logout. If your auth state lives purely on the client (e.g. Clerk useUser() or Supabase SPA auth), pass useCreditKit({ userId, identitySignature }) to auto-sync login and logout transitions:

hooks/useCreditKit.ts
'use client';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';

const CreditKitCtx = createContext<ReturnType<typeof useStandaloneCreditKit> | null>(null);

function useStandaloneCreditKit(identity?: {
  userId?: string | null;
  email?: string | null;
  identitySignature?: string | null;
}) {
  const [projectKey, setProjectKey] = useState<string>('');
  const [walletId, setWalletId] = useState<string | null>(null);
  const [balance, setBalance] = useState<number>(0);
  const [freeBalance, setFreeBalance] = useState<number>(0);
  const [paidBalance, setPaidBalance] = useState<number>(0);
  const [tokenMultiplier, setTokenMultiplier] = useState<number>(1);
  const [subscription, setSubscription] = useState<any>(null);
  const [visitorToken, setVisitorToken] = useState<string>('');
  const [ready, setReady] = useState<boolean>(false);
  const prevIdentRef = useRef<string>('');

  const syncFromWindow = useCallback(() => {
    const ck = (window as any).CreditKit;
    if (!ck) return;
    const p = ck.getProject?.();
    if (p?.publicKey) setProjectKey(p.publicKey);
    const w = ck.getWallet?.();
    if (w && typeof w.totalAvailable === 'number') {
      setWalletId(w.walletId || null);
      setBalance(w.totalAvailable);
      setFreeBalance(w.freeRemaining ?? w.freeBalance ?? 0);
      setPaidBalance(w.paidRemaining ?? w.paidBalance ?? 0);
      setTokenMultiplier(
        Math.max(1, Math.round(Number(w.effectiveDesign?.tokenDisplayMultiplier || 1)))
      );
      setSubscription(w.subscription || null);
      setReady(true);
    }
    setVisitorToken(ck.getToken?.() || '');
  }, []);

  useEffect(() => {
    syncFromWindow();
    const events = ['creditkit:synced', 'creditkit:consumed', 'creditkit:purchased'];
    events.forEach((ev) => window.addEventListener(ev, syncFromWindow));
    return () => events.forEach((ev) => window.removeEventListener(ev, syncFromWindow));
  }, [syncFromWindow]);

  useEffect(() => {
    if (!identity) return;
    const uid = (identity.userId || '').trim();
    const em = (identity.email || '').trim();
    const sig = (identity.identitySignature || '').trim();
    const nextKey = uid || em ? `${uid}|${em}|${sig}` : '';
    if (nextKey === prevIdentRef.current) return;
    const hadPrev = Boolean(prevIdentRef.current);
    prevIdentRef.current = nextKey;

    const applyIdentity = () => {
      const ck = (window as any).CreditKit;
      if (!ck) return false;
      if (nextKey) {
        ck.identify?.({
          ...(uid ? { userId: uid } : {}),
          ...(em ? { email: em } : {}),
          ...(sig ? { identitySignature: sig } : {}),
        });
      } else if (hadPrev) {
        ck.logout?.();
      }
      return true;
    };
    if (!applyIdentity()) {
      window.addEventListener('creditkit:synced', applyIdentity, { once: true });
      return () => window.removeEventListener('creditkit:synced', applyIdentity);
    }
  }, [identity?.userId, identity?.email, identity?.identitySignature]);

  return {
    projectKey,
    ready,
    loading: !ready,
    walletId,
    balance,
    freeBalance,
    paidBalance,
    tokenMultiplier,
    unitLabel: (tokenMultiplier > 1 ? 'tokens' : 'credits') as 'credits' | 'tokens',
    subscription,
    visitorToken,
    openTopUp: (placementKey?: string) => {
      if ((window as any).CreditKit?.openTopUp) {
        (window as any).CreditKit.openTopUp(placementKey);
      } else {
        console.warn('[CreditKit] openTopUp() called before creditkit.js mounted.');
      }
    },
    openWallet: (e?: any) => {
      if ((window as any).CreditKit?.toggleWalletDrawer) {
        (window as any).CreditKit.toggleWalletDrawer(e?.currentTarget ?? e ?? null);
      } else {
        console.warn('[CreditKit] openWallet() called before creditkit.js mounted.');
      }
    },
    refresh: async () => {
      await (window as any).CreditKit?.refresh?.();
      syncFromWindow();
    },
    identify: async (user: { userId?: string; email?: string; identitySignature?: string }) => {
      await (window as any).CreditKit?.identify?.(user);
      syncFromWindow();
    },
    logout: async () => {
      await (window as any).CreditKit?.logout?.();
      syncFromWindow();
    },
    gate: async <T = any>(
      placementKey: string,
      optsOrFn?:
        | { units?: number; idempotencyKey?: string }
        | ((ctx: { holdId?: string | null; remaining: number; mode?: 'normal' | 'standard' | 'slow_tier' }) => Promise<T>),
      maybeFn?: (ctx: { holdId?: string | null; remaining: number; mode?: 'normal' | 'standard' | 'slow_tier' }) => Promise<T>
    ) => {
      if (typeof window === 'undefined' || !(window as any).CreditKit?.gate) {
        return { allowed: false, configError: true, error: 'CREDITKIT_NOT_MOUNTED' };
      }
      try {
        const res = await (window as any).CreditKit.gate(placementKey, optsOrFn, maybeFn);
        syncFromWindow();
        return {
          allowed: Boolean(res?.allowed),
          mode: res?.mode,
          data: (res?.data ?? res?.result) as T | undefined,
          remainingBalance: res?.remainingBalance ?? res?.remaining,
          configError: res?.configError,
          status: res?.status,
          error: res?.error,
        };
      } catch {
        syncFromWindow();
        return { allowed: false, refundedOnCrash: true };
      }
    },
  };
}

export function CreditKitProvider({
  projectKey,
  publicKey,
  baseUrl = 'https://creditkit.dev',
  userId,
  email,
  identitySignature,
  children,
}: {
  projectKey?: string;
  publicKey?: string;
  baseUrl?: string;
  userId?: string;
  email?: string;
  identitySignature?: string;
  children: React.ReactNode;
}) {
  const pk = projectKey || publicKey || '';
  useEffect(() => {
    if (!pk || typeof window === 'undefined') return;
    const host = baseUrl.replace(/\/$/, '');
    let el = document.querySelector<HTMLScriptElement>('script[data-creditkit-sdk="1"], script[src*="/v1/creditkit.js"]');
    if (!el) {
      el = document.createElement('script');
      el.src = `${host}/v1/creditkit.js`;
      el.async = true;
      el.setAttribute('data-creditkit-sdk', '1');
      document.head.appendChild(el);
    }
    el.setAttribute('data-project-key', pk);
    if (host) el.setAttribute('data-api-base', host);
    if (userId) el.setAttribute('data-user-id', userId);
    else el.removeAttribute('data-user-id');
    if (email) el.setAttribute('data-user-email', email);
    else el.removeAttribute('data-user-email');
    if (identitySignature) el.setAttribute('data-identity-signature', identitySignature);
    else el.removeAttribute('data-identity-signature');
  }, [pk, baseUrl, userId, email, identitySignature]);

  const value = useStandaloneCreditKit({ userId, email, identitySignature });
  return React.createElement(CreditKitCtx.Provider, { value }, children);
}

export function useCreditKit(identity?: {
  userId?: string | null;
  email?: string | null;
  identitySignature?: string | null;
}) {
  const ctx = useContext(CreditKitCtx);
  const standalone = useStandaloneCreditKit(ctx ? undefined : identity);
  return ctx || standalone;
}

export function CreditBalancePill({ className = '' }: { className?: string }) {
  const { balance, tokenMultiplier, unitLabel, loading, openWallet, openTopUp } = useCreditKit();
  const scaled = Math.max(0, balance * Math.max(1, tokenMultiplier));
  const label = scaled === 1 ? (unitLabel === 'tokens' ? 'token' : 'credit') : unitLabel;
  return React.createElement(
    'div',
    {
      'data-creditkit-wallet-trigger': '1',
      className: `inline-flex items-center gap-2.5 pl-3 pr-1.5 py-1 rounded-full border border-white/10 bg-zinc-900 text-zinc-100 text-xs ${className}`,
    },
    React.createElement(
      'button',
      {
        type: 'button',
        onClick: (e: React.MouseEvent<HTMLButtonElement>) =>
          openWallet(e.currentTarget.parentElement || e.currentTarget),
        className: 'font-medium cursor-pointer',
      },
      loading ? '...' : `${scaled.toLocaleString()} ${label}`
    ),
    React.createElement(
      'button',
      {
        type: 'button',
        onClick: () => openTopUp(),
        className: 'px-2.5 py-0.5 rounded-full bg-zinc-100 text-zinc-950 font-medium cursor-pointer',
      },
      'Top up'
    )
  );
}
components/GenerateButton.tsx
'use client';
import { useCreditKit } from '@/hooks/useCreditKit';

export function GenerateButton() {
  const { balance, tokenMultiplier, unitLabel, ready, visitorToken, openTopUp, openWallet, refresh } =
    useCreditKit();
  const displayBalance = Math.max(0, balance * Math.max(1, tokenMultiplier));

  async function handleGenerate() {
    const res = await fetch('/api/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-creditkit-token': visitorToken, // Links browser wallet to your server hold
      },
    });

    if (res.status === 402) {
      openTopUp('run_action'); // Opens Shadow DOM paywall modal
      return;
    }
    if (!res.ok) {
      console.error('Generation error:', await res.json().catch(() => ({})));
      return;
    }

    const data = await res.json();
    await refresh(); // Syncs live credit balance after server settlement
    console.log('Generated:', data);
  }

  return (
    <div className="flex items-center gap-3">
      <button type="button" onClick={openWallet}>
        Wallet ({ready ? `${displayBalance.toLocaleString()} ${unitLabel}` : '...'})
      </button>
      <button type="button" onClick={handleGenerate}>
        Generate (-10 credits)
      </button>
    </div>
  );
}

6. Going Live 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 your production environment.
  4. Verify Server-Signed Identity HMAC: Ensure data-identity-signature={credits.signUser(user.id)} is passed on your root <script> (Live Mode rejects unsigned client userId binding).
  5. Set HTTPS Webhook Endpoint (Optional): Point Outbound Webhooks to your production HTTPS route and verify signatures with credits.verifyWebhookSignature(rawBody, sig).