CatoandClaude 9e63512686 feat(plans): PlansScreen, own-key sheet, test-only Stripe guard (0.5.0) (#20)
* feat(plans): PlansScreen, three-screen checkout, own-key sheet, Stripe test-only guard (0.5.0)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(plans): one 'Pay X to Y' checkout screen with a method list and a Bitcoin scan view

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-03 01:56:38 +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 does not keep a balance.

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), never a subscription.
  • 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.

Plans screen and your own API key

@bitbaum/paykit/plans/react is the pricing page, from config: up to three cards (Free, a paid plan, Organisations), a yearly toggle that starts on with a saving worked out from your two prices (and none shown when yearly is not cheaper), one button per card, the paid card first on a phone, a "Models" row, and three trust lines (prices in CHF; hosted in the EU, Germany, Hetzner; Bitcoin passes do not renew automatically). definePlans refuses the word "unlimited" and token counts anywhere in the copy.

import { definePlans } from '@bitbaum/paykit/plans';
import { PlansScreen, CheckoutSheet, OwnKeySheet } from '@bitbaum/paykit/plans/react';

export const plans = definePlans({
  salesEnabled: process.env.SALES_ENABLED === '1', // false: the paid button reads "Coming soon, get notified"
  free: { name: 'Free', allowance: 'A small daily amount', features: ['Core lessons'], models: 'Free model' },
  paid: {
    name: 'Plus',
    monthlyChf: 9,
    yearlyChf: 90,
    allowance: 'CHF 4 of AI use every month',
    features: ['Spoken answers'],
    models: 'Standard model',
    providerRefs: { bitcoin: orangeCatProductId },
  },
  org: { name: 'Organisations', features: ['Seats'], models: 'Standard model', contactHref: 'mailto:hello@example.org' },
});

<PlansScreen
  config={plans}
  currentPlan={me.plan}            // 'free' hides the own-key link: own keys are for paid plans
  onChoose={({ plan, period }) => openCheckout(period)}
  onNotify={(email) => saveNotifyEmail(email)} // while salesEnabled is false
  onOpenOwnKey={() => setSheet('key')}
/>;

Checkout is at most three screens: the plans; CheckoutSheet, one "Pay CHF 90 to Heidi" screen; and either the provider's own pay page (card, TWINT) or, for Bitcoin, the "Scan QR code" view inside the same sheet. Server side, startPlanCheckout({ config, providers, method, period, reference, chfToSats }) returns the checkout to send the buyer to: Bitcoin through your OrangeCat provider (priced in whole SAT by the chfToSats you supply), card and TWINT through Stripe.

 Pay CHF 90 to Heidi                      Scan with your Bitcoin wallet
 Plus, yearly                             ┌──────────────┐
 (•) Bitcoin via OrangeCat                │   QR code    │   About 120,000 sats
     One payment. It does not renew…      └──────────────┘
 ( ) Card          Visa, Mastercard…      lnbc1…  (the code, to copy)
 ( ) TWINT         Pay with the TWINT app [ Copy payment code ]   <- the one button
 About 120,000 sats                       Back
 [ Pay CHF 90 ]   <- the one button
 Scan QR code  ·  Back

Each screen has exactly one filled button. The method list is native radio inputs in a fieldset (arrow keys, visible focus ring, 44px rows), the sheet is at most 420px wide and fills a 390px phone. The CHF amount and recipient are always in the heading; sats appear only while Bitcoin is picked (sats is your own rate, like chfToSats). Extra methods appear only when you pass extraMethods (they reach onPay with their own id). The UI never says "Lightning".

import { QRCodeSVG } from 'qrcode.react'; // your app's own QR library: paykit ships none

<CheckoutSheet
  recipient="Heidi" amountChf={90} sats={120000} summary="Plus, yearly"
  methods={availableMethods(providers)}
  onPay={(method) => startOnServer(method)}              // answers the page to pay on
  onShowQr={() => startBitcoinOnServer()}                // answers checkout.invoice; turns on "Scan QR code"
  renderQr={(value) => <QRCodeSVG value={value} size={216} marginSize={4} />}
  testMode
/>

Without renderQr the scan view still shows the code with its copy button. Screenshots are not included: the layout above is the checked structure, asserted in test/vitest/plans.test.tsx; it has not been viewed in a real browser.

Stripe is test mode only and behind a flag. stripeTestOnlyProvider(config, env) returns null unless STRIPE_TEST_ONLY=1, and throws StripeLiveKeyRefusedError for any key that is not sk_test_ / rk_test_. Pass its result as providers.card; CheckoutSheet shows a "test mode, no real payment" line with testMode.

OwnKeySheet is the "Use your own API key" sheet: a provider and a password field, a call to your server (onSave), and only the last four characters shown back. Store the key with @bitbaum/ai-kit/key-vault (AES-256-GCM); calls on it skip the allowance. Words in all three components are labels props, colours are CSS variables (--pk-accent, --pk-border, --pk-muted).

Licence

MIT

S
Description
No description provided
Readme MIT
257 KiB
0 Stars 2 Watchers 0 Forks
Languages
TypeScript 76.2%
JavaScript 23.8%