Files
CatoandClaude 0474c3a887 paykit 0.7.0: prepaid credit, top-ups, auto top-up and per-key limits (#31)
Pay as you go beside the subscriptions, the way OpenRouter charges:

- ./credits: append-only CreditLedger with idempotency keys and an
  in-memory ledger; balance, FIFO lots and debt; charge refused with 402
  below the app's floor or over a spending key's daily/weekly/monthly
  limit; hold then settle or release; top-up quotes with a fee per rail
  in integer arithmetic; refund eligibility (window, fee kept, rails that
  never refund); expiry of old lots; auto top-up decision with backoff
  and a failure cap; credit events applied idempotently; top-ups through
  any PaymentProvider (OrangeCat: sats, never refundable).
- ./stripe: stripeCredits — top-up Checkout Session (saves the method
  off-session when auto top-up is on), off-session PaymentIntent with an
  Idempotency-Key, refunds, and webhook mapping for
  checkout.session.completed, payment_intent.succeeded/payment_failed
  and charge.refunded. The pass provider ignores top-up sessions.
- ./react: CreditBalance, TopUp, AutoTopUp, CreditActivity; PickerTier
  gains optional rates for a pay-as-you-go tier.

No price, fee or threshold is built in; all are the app's config.


Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-03 13:07:29 +01:00
..

paykit

Let a website get paid. The website does not hold the money.

pnpm add @bitbaum/paykit

Part of bitbaum. The same behavior ships in OrangeCat today.

Why this exists

A shop, a clinic, or a fundraiser should be able to take a payment without building a wallet, a balance, or a support desk for missing coins. You store where the money should land. The payer uses their own app.

Use

import { classifyPaste, shownRail } from '@bitbaum/paykit';

classifyPaste('bitcoin:bc1q…'); // 'onchain'
classifyPaste('you@coinos.io'); // 'lightning'
classifyPaste('nostr+walletconnect://…'); // 'nwc'

// A code to show. Twint, Monero, anything else. Their app pays it.
shownRail('Twint', qrPayload);

classifyPaste reads the shape of a Bitcoin receive string after stripping the bitcoin: wrapper a wallet copies. It does not check the checksum. A host that moves money still validates before it saves.

A settled rail (Lightning address, Bitcoin address, xpub, wallet-connect) is one the host can ask for a payment. A shown rail is only displayed. paykit does not store keys and never holds money; prepaid credit (below) is a ledger in the app's own database, and the money behind it went through the payment provider to the seller.

Sell a pass

Bitcoin has no recurring charge, so what an app sells is a pass: one payment, a number of days. Paying again before it runs out adds the days to the end.

import { applySettlement, isActive, type Plan } from '@bitbaum/paykit/checkout';
import { orangeCatProvider } from '@bitbaum/paykit/orangecat';

const month: Plan = { id: 'month', days: 30, price: { amount: 21000, currency: 'SAT' }, providerRef: productId };
const provider = orangeCatProvider({ webhookSecret: process.env.ORANGECAT_WEBHOOK_SECRET });

// 1. Something the buyer can pay. Store it: it is the only link back to the buyer.
const checkout = await provider.createCheckout({ plan: month, reference: user.id });
//    checkout.invoice is the QR code, checkout.payUrl opens a wallet.

// 2. The provider says it settled (webhook), or the app asks (poll). Both end here.
const verdict = provider.verifyWebhook(rawBody, request.headers);
if (verdict.ok && verdict.event) await applySettlement({ event: verdict.event, plans: [month], store });
const { state } = await provider.status(checkout);

// 3. Gate on the pass.
isActive(entitlement);

PaymentProvider is three calls (createCheckout, status, verifyWebhook) and names no provider. applySettlement grants once per payment however often it is reported, and takes what was bought, by whom and for how much from the checkout the app stored, not from the event. The app supplies the store; settleOnce must be one transaction.

Bitcoin through an OrangeCat account

The seller publishes a product on OrangeCat and connects a wallet there. The provider asks OrangeCat for an invoice that pays it, so the money goes from the buyer's wallet to the seller's.

  • With apiKey (an ock_… integration key, scopes payments.write and payments.read) it starts the payment with POST /api/v1/payments and reads it with GET /api/v1/payments/{id}. OrangeCat records the key's owner as the buyer and refuses an owner paying their own entity, so a key minted by the account that is paid cannot start a customer's payment. When OrangeCat answers exactly that, the provider falls back to the account-less call.

  • Without a key it uses the account-less POST /api/v1/payments/public and reads the payment with the status token it returns.

  • entityType says what is being paid (product by default, project for an app's own OrangeCat project). provider.payee(id) reads that entity from OrangeCat: its name and its page (https://orangecat.ch/projects/<id>). Its payable is true when the entity shows an address of its own and null otherwise, never false: the owner's connected wallet is not on the public record, so only createCheckout knows.

  • The id of what is paid is the app's configuration, never a constant in this package or in a component. Each app keeps its own OrangeCat project id in its config and passes it as the plan's providerRef:

    // In the app's config layer, from its environment.
    const projectId = process.env.ORANGECAT_PAY_ENTITY_ID; // Heidi's, Loki's and Solon's each differ
    const provider = orangeCatProvider({ entityType: 'project', webhookSecret: process.env.ORANGECAT_WEBHOOK_SECRET });
    const month: Plan = { id: 'month', days: 30, price: { amount: sats, currency: 'SAT' }, providerRef: projectId };
    
  • The plan is priced in whole SAT. The caller states the amount; applySettlement checks what arrived.

  • A payment.settled webhook names only the payment, never the buyer. Without the stored checkout a settlement cannot be matched.

  • The webhook is authenticated with X-OrangeCat-Signature (t=<unix>,v1=<HMAC-SHA-256 of "${t}.${rawBody}">, five minutes' tolerance). Pass the body exactly as received.

  • @bitbaum/paykit/orangecat uses node:crypto and belongs on the server. @bitbaum/paykit/checkout and the root entry run anywhere.

Cards, TWINT and wallets through a Stripe account

The seller has a Stripe account. The provider asks Stripe for a Checkout Session, a payment page Stripe hosts, and sends the buyer there. No card number reaches the app.

import { stripeProvider } from '@bitbaum/paykit/stripe';

const month: Plan = { id: 'month', days: 30, price: { amount: 1200, currency: 'CHF' }, providerRef: 'pass-30' };
const provider = stripeProvider({
  secretKey: process.env.STRIPE_SECRET_KEY,
  webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
  successUrl: 'https://app.example/pass/checkout/{CHECKOUT_SESSION_ID}',
  cancelUrl: 'https://app.example/pass',
});

const checkout = await provider.createCheckout({ plan: month, reference: user.id });
// checkout.payUrl is Stripe's page; there is no checkout.invoice to draw.
  • Which ways to pay are offered is the seller's Stripe Dashboard, not this code. No payment_method_types is sent, so Stripe shows every method the account has switched on that fits the currency. TWINT needs a price in CHF and is limited to 5000.00 CHF a payment.
  • It is one payment (mode=payment). A renewing subscription is stripeBilling, below; the one-time provider ignores a subscription's checkout, so both can share one webhook endpoint.
  • plan.price.amount is in the currency's smallest unit (1200 is CHF 12.00). A providerRef that is a Stripe Price id (price_…) charges that price instead; applySettlement still checks what arrived against the stored amount.
  • reference is sent as client_reference_id so a payment can be found in the Dashboard. sendReference: false sends nothing about the buyer; settling does not need it.
  • Stripe replaces {CHECKOUT_SESSION_ID} in successUrl and cancelUrl with the session's id, which is the checkout's id.
  • Point a Stripe webhook endpoint at the app for checkout.session.completed and checkout.session.async_payment_succeeded. It is authenticated with Stripe-Signature (t=<unix>,v1=<HMAC-SHA-256 of "${t}.${rawBody}">, five minutes' tolerance, several v1 while a secret is rolled). A session that finished but is not paid yet settles nothing; the second event follows when the money is there.
  • No Stripe SDK is used. @bitbaum/paykit/stripe uses node:crypto and belongs on the server.

An app can offer more than one provider at once: each stored checkout says which provider made it, and each provider gets its own webhook path.

Sell a subscription

A price charged every month or every year until the buyer cancels, through the same Stripe account. Bitcoin has no recurring charge, so a product that takes Bitcoin keeps selling a pass beside it.

import { applySubscriptionEvent, subscriptionAccessUntil, subscriptionStanding } from '@bitbaum/paykit/checkout';
import { subscriptionPricing } from '@bitbaum/paykit/plans';
import { stripeBilling } from '@bitbaum/paykit/stripe';

const monthly = { id: 'plus-month', interval: 'month', price: { amount: 1200, currency: 'CHF' }, intro: { amount: { amount: 600, currency: 'CHF' }, months: 3 } };
const billing = stripeBilling({ secretKey, webhookSecret, successUrl, cancelUrl, sendReference: false });

const checkout = await billing.createSubscriptionCheckout({ plan: monthly, reference: user.id });
// Store it; send the buyer to checkout.payUrl.

const verdict = billing.verifyWebhook(rawBody, request.headers);
// verdict.event: checkout_completed | invoice_paid | payment_failed | subscription_updated | subscription_ended
record = applySubscriptionEvent(record, verdict.event);
subscriptionAccessUntil(record); // access runs to the paid period's end
subscriptionStanding(record);    // renews on / ends on / payment failed / ended

const { url } = await billing.createPortalSession({ customerId: record.customerId, returnUrl });
  • The checkout is a hosted session in mode=subscription with an inline recurring price (price_data[recurring][interval]), so nothing is set up in the Dashboard first. Ways to pay are the Dashboard's, as for a pass; Stripe lists TWINT as supporting recurring payments and Billing, through a mandate the buyer approves in the TWINT app.
  • An intro price ("first 3 months at CHF 6") is a coupon with duration=repeating, created once under an id derived from the offer (paykit-intro-chf-600-3m) and found again after that.
  • Point the webhook endpoint at checkout.session.completed, invoice.paid, invoice.payment_failed, customer.subscription.created, customer.subscription.updated and customer.subscription.deleted (STRIPE_SUBSCRIPTION_EVENTS). Both the current API shape (period end on subscription items, invoice.parent.subscription_details) and the pre-2025-03-31 one are read.
  • applySubscriptionEvent is pure and safe with repeated and out-of-order events: the paid period end only moves later, an older state change cannot undo a newer one, and an ended subscription keeps the period it paid for. Idempotency by event id is the app's (event.eventId).
  • The portal (createPortalSession) is where the buyer cancels or changes the card; what it allows is set in the Dashboard's customer portal settings. cancelSubscription stops one at once, for the app's own reasons (an account being deleted).
  • subscriptionPricing({ month, year, intro }) computes the year per month and the saving in whole percent, rounded down, so a page never prints a saving the prices do not give.

Sell prepaid credit

Pay as you go: the person buys a balance, each use is taken off it, and the balance is topped up by hand or automatically when it falls below a threshold they chose. It is the way OpenRouter charges (prepaid credit, manual or automatic top-up, a purchase fee, refunds of unused credit within a window with the fee kept, crypto never refunded, unused credit that may expire) and limits (per-key spending limits that reset, a 402 on a negative balance even for free models). Every price, fee, floor, threshold and window is the app's configuration; paykit names no amount.

import { applyCreditEvent, autoTopUpDue, creditBook, recordAutoTopUp, topUpQuote } from '@bitbaum/paykit/credits';
import { stripeCredits } from '@bitbaum/paykit/stripe';

const book = creditBook({
  ledger,                                   // the app's CreditLedger (one append-only table)
  currency: 'CHF',
  floor: 0,                                 // uses are refused below this (default 0)
  keyLimit: (key) => limits.get(key),       // { limit, reset: 'daily' | 'weekly' | 'monthly' | null }
  refunds: { windowHours: env.REFUND_HOURS, neverRefund: ['bitcoin'] },
  expiry: { afterDays: env.CREDIT_EXPIRY_DAYS },
});

// A use whose price is known now:
const result = await book.charge({ account, cost, key, idempotencyKey: requestId, meta: { model } });
if (!result.ok) return new Response(result.reason, { status: result.status }); // 402

// A use whose price is known only after it (a streamed answer):
const hold = await book.hold({ account, estimate, key, idempotencyKey: requestId });
// …the call runs…
await book.settle({ account, hold: requestId, actual });   // takes the actual cost, releases the rest

// Buying credit:
const quote = topUpQuote({ amount: 2000, currency: 'CHF', rail: 'card', fees: env.FEES });
const stripe = stripeCredits({ secretKey, webhookSecret, successUrl, cancelUrl });
const checkout = await stripe.createTopUpCheckout({ account, quote, saveForAutoTopUp: true });

// The webhook (the same endpoint as passes and subscriptions):
const verdict = stripe.verifyWebhook(rawBody, request.headers);
if (verdict.ok && verdict.event) await applyCreditEvent(book, verdict.event, { ledger });

// After a charge, or on a timer:
const due = autoTopUpDue({ balance: result.available, threshold, amount, ...state });
if (due.due) await stripe.chargeSaved({ account, quote: topUpQuote({ amount: due.amount, … }), customerId, paymentMethodId, idempotencyKey });
  • Money is an integer in the smallest unit of the credit currency, always. A fee percent is read to a hundredth of a percent and applied in integers, rounded up unless the rule says nearest or down; min, max and a fixed part are optional, and each way of paying (fees[rail]) has its own rule. mode: 'included' takes the fee out of the amount instead of adding it.
  • The ledger is append-only: top_up, charge, refund, expire, adjust, and hold/release for reserving. Every entry has an idempotency key, unique across the ledger; a top-up's key is ${provider}:${paymentId}, so a checkout's completion and its PaymentIntent's success credit once. CreditLedger.transact must serialise per account (a row lock), so two uses at once cannot both spend the last franc. memoryLedger() is the reference implementation for tests.
  • Use is taken from the oldest purchase first, so expiry (book.expire, safe on a timer) and refund eligibility (book.refundable) are about what is really left of that purchase. A refund gives back unused credit only and keeps the fee; a rail in neverRefund, and every top-up through OrangeCat, is never refundable. stripe.refundTopUp asks Stripe for it; charge.refunded books it from Stripe's cumulative amount_refunded, so a repeated report removes nothing twice.
  • A settle takes the actual cost even when it is more than the estimate: the use happened. The balance may then be below the floor, and the next use is refused until a top-up. A hold that never settles stops reserving at its expiry (holdMinutes, default 60).
  • Automatic top-up saves the method with setup_future_usage=off_session on the first checkout (and customer_creation=always when the app has no customer yet), then charges it with an off-session, confirmed PaymentIntent sent with an Idempotency-Key. A decline answers { state: 'failed', code }; autoTopUpDue backs off after a failure (60 minutes, doubling, at most a day) and stops after three in a row until the person fixes their method; all three are options.
  • Point the webhook endpoint at STRIPE_CREDIT_EVENTS too: checkout.session.completed, payment_intent.succeeded, payment_intent.payment_failed, charge.refunded. Top-up sessions carry metadata[paykit_kind]=credit_top_up; the pass provider and stripeBilling ignore them. With sendReference: false no account id is sent to Stripe and applyCreditEvent's account option finds it from what the app stored.
  • Bitcoin: providerTopUp({ provider: orangeCatProvider(…), account, quote, price: { amount, currency: 'SAT' }, providerRef }) starts the invoice; the app converts the quote's total to sats at its own rate and stores the returned pending. On settlement, topUpFromSettlement(event, pending) is the credit event, checked against the sats asked for.

The plan screens (React)

import { PlanPicker, PlanReview } from '@bitbaum/paykit/react';
import '@bitbaum/paykit/styles.css';
  • PlanPicker: a segmented switch of tiers, the chosen tier's benefits, period cards (monthly and yearly, an intro line, the saving), one primary button and the fine print. A tier without periods shows one price line: a free tier, "your own key" (the product's AI paid by the person's own provider key, at no charge from the product), or "contact us".
  • PlanReview: the step before the payment page. A summary card, expandable notes, the signed-in account, required terms as checkboxes that keep the button off until ticked (and say how many are left), optional opt-ins, and an overlap warning that replaces the buy button with "manage the plan you have".
  • The app passes words, prices, benefits, links and callbacks. Colours, radius and fonts are --pk-* variables that fall back to --sk-* and then to the system's light or dark colours; map them to your tokens once. Targets are at least 44 px and nothing overflows at 320 px.
  • A "pay as you go" tier is a tier without periods with rates (what each use costs, written by the app) and ratesLabel; tiers without rates draw as before.
  • The credit screens: CreditBalance (the balance, what is reserved, a word when it is low or below zero, and the button to add to it), TopUp (amount choices and an optional typed amount, the way to pay, the credit, fee and total computed by topUpQuote from each rail's fee rule before paying, an opt-in to save the method for automatic top-up), AutoTopUp (on or off, below which balance, how much, the rule in a sentence with the fee included, the saved method, the last attempt's status) and CreditActivity (newest first, signed amounts, filterable by kind and by key, a describe line per entry such as the model). Amounts are Money written with formatMoney; every word is a prop.
  • react is an optional peer dependency: only @bitbaum/paykit/react needs it.

Licence

MIT