Guides · App patterns
Billing & payments
Put organizations on paid plans with Stripe, enforce seat counts and sell credits that cannot be overdrawn.
- In the schema
ext::auth::Identity
What you’ll build#
You will attach Stripe subscriptions and prepaid credits to the organizations from Multi-tenant B2B SaaS. An owner starts a checkout through a query-gated action, signed Stripe webhooks keep each organization’s active plan current, plan seat limits are enforced on membership inserts and prepaid credit wallets never drop below zero.
Two server endpoints connect your project to Stripe: an action handler invoked as the paying owner and an inbound webhook route using a scoped billing service key that reaches only organizations, wallets and ledger entries. Start with the SaaS schema pushed and a Stripe account holding a price ID per paid plan.
Atomic credit wallet & ledger
CreditWallet pairs constraint min_value(0) with an exclusive LedgerEntry.idempotency_key in one statement so concurrent spends never overdraw or double-charge.
Schema-enforced seat limits
A deny insert policy on Membership compares count(.org.members) against .org.plan.seat_limit inside PostgreSQL across every invite and SSO join.
Store plans in the schema#
The SaaS schema already links each organization to a plan. Extending that schema adds Stripe identifiers, seat enforcement and an atomic credit wallet.
module default { # 'service' for a service key, set in the endpoint's serviceGlobals. A session can't set it. global role: str; type BillingPlan { # … as before, and: stripe_price: str { constraint exclusive; }; } type Organization { # … as before, and: stripe_customer: str { constraint exclusive; }; access policy billing_can_read_and_update allow select, update using (global role ?= 'service'); } type Membership { # … as before, and: access policy seats_are_limited deny insert using (count(.org.members) >= .org.plan.seat_limit); } type CreditWallet { required org: Organization { readonly := true; constraint exclusive; on target delete delete source; }; required balance: int64 { default := 0; constraint min_value(0) { errmessage := 'Not enough credits'; }; }; access policy members_can_read_and_spend allow select, update using ((global caller in .org.members.identity) ?? false); access policy billing_has_full_access allow all using (global role ?= 'service'); } type LedgerEntry { required wallet: CreditWallet { readonly := true; on target delete delete source; }; required delta: int64; required reason: str; required idempotency_key: str { constraint exclusive; }; required made: datetime { readonly := true; default := datetime_of_statement(); }; access policy members_can_read allow select using ((global caller in .wallet.org.members.identity) ?? false); # A member's entry can only take credits away. access policy members_can_spend allow insert using (.delta < 0 and ((global caller in .wallet.org.members.identity) ?? false)); access policy billing_has_full_access allow all using (global role ?= 'service'); }}Stripe stays the record of payments while your schema holds the billing facts your access rules enforce, covering the active plan, the Stripe customer id and the credit balance.
Grant the billing service a role#
Because a service key is not a person, global caller is empty and no member policy admits the key. Configure { "default::role": "service" } inside serviceGlobals in your project’s endpoint settings in the console or via the Control API. User sessions cannot set globals, so no signed-in person can claim the service role.
# A key for the billing routes alone. It's shown once: store it as NAPALM_KEY.napalm keys create acme-app --label billing --days 90 # What it can reach, before anything depends on itnapalm keys reach acme-app <key-id>Policies checking global role grant the billing key access only to organizations, wallets and ledger entries, so the key cannot read customer documents or add members.
Start a checkout as the owner#
Starting a checkout needs your Stripe secret, so checkout is an action. A deployed query checks the caller, and a handler starts the checkout. The query returns a row only to an owner of the organization. Anyone else gets 403 nothing_found, and your handler is never called.
# Only an owner gets a row back, so only an owner's call reaches the handler.with plan := assert_single((select BillingPlan filter .slug = <str>$plan))select Organization { id, name, stripe_customer, seats := count(.members), price := plan.stripe_price,}filter .id = <uuid>$org and exists (select .members filter .identity ?= global caller and .role = Role.Owner)// src/app/actions/[action]/route.tsimport Stripe from 'stripe'import { handleCalls } from 'napalm-client' const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!) type Checkout = { id: string; name: string; stripe_customer: string | null; seats: number; price: string } export const POST = handleCalls( { async startCheckout(call) { // The query ran as the caller and found this row, so they own the organization. const [organization] = call.rows as Checkout[] const session = await stripe.checkout.sessions.create({ mode: 'subscription', line_items: [{ price: organization.price, quantity: 1 }], // Rides on the subscription, so every later event says whose it is. subscription_data: { metadata: { org: organization.id } }, ...(organization.stripe_customer ? { customer: organization.stripe_customer } : {}), success_url: 'https://app.example.com/billing?paid=1', cancel_url: 'https://app.example.com/billing', }) return { url: session.url } }, }, { address: process.env.NAPALM_URL!, handlers: 'https://app.example.com/actions', secret: process.env.NAPALM_ACTION_SECRET, },)Attach the handler with napalm actions add acme-app startCheckout https:/. The app calls POST / with the organization and the plan, and sends the person to the returned url. A page to manage or cancel the subscription follows the same pattern with stripe.billingPortal.sessions.create in the handler.
Record Stripe events#
A checkout redirect URL is not proof of payment because users close tabs and cards fail on renewal. Only Stripe’s signed webhook proves payment state. One route verifies Stripe’s signature and updates the organization’s plan using the billing key.
External Stripe event source
Stripe delivers subscription and credit-payment events directly to your inbound webhook route.
Raw-body HMAC verification
Your route verifies stripe-signature over the raw request bytes before reading or trusting the payload.
Scoped billing service key
An ndb_… service key runs recordSubscription and idempotent addCredits queries reaching only billing tables.
# Run by the billing service's key. An organization with no paid price goes back to the starter plan.update Organizationfilter .id = <uuid>$orgset { stripe_customer := <str>$customer, plan := assert_single( (select BillingPlan filter .stripe_price ?= <optional str>$price) ?? (select BillingPlan filter .slug = 'starter') ),}// src/app/stripe/route.tsimport Stripe from 'stripe'import { NapalmClient } from 'napalm-client' const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)const address = process.env.NAPALM_URL!// A service key: this route is Stripe speaking, not a person.const napalm = new NapalmClient(address, { token: process.env.NAPALM_KEY }) const SUBSCRIPTION_EVENTS = new Set([ 'customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted',]) export async function POST(request: Request) { let event: Stripe.Event try { // Checked against the raw body, before anything reads it. event = await stripe.webhooks.constructEventAsync( await request.text(), request.headers.get('stripe-signature') ?? '', process.env.STRIPE_WEBHOOK_SECRET!, ) } catch { return new Response(null, { status: 400 }) } if (!SUBSCRIPTION_EVENTS.has(event.type)) return new Response(null, { status: 204 }) // Events can arrive late or twice. Ask Stripe how the subscription stands now, and write that. const told = event.data.object as Stripe.Subscription const subscription = await stripe.subscriptions.retrieve(told.id) const isPaid = subscription.status === 'active' || subscription.status === 'trialing' const answer = await napalm.fetch(`${address}/query/recordSubscription`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ variables: { org: subscription.metadata.org, customer: typeof subscription.customer === 'string' ? subscription.customer : subscription.customer.id, price: isPaid ? subscription.items.data[0].price.id : null, }, }), }) // Anything but success, and Stripe sends the event again later. return new Response(null, { status: answer.ok ? 204 : 500 })}- Late and repeated events
- Stripe may deliver an event twice or out of order. Rather than trust an event’s contents, the route fetches the current subscription from Stripe and writes that state, so any delivery order reaches the same result.
- Lapsed plans
- A cancelled or unpaid subscription has no paid price, and the query moves the organization back to
starter. The seat limit and every other plan value your rules read change at that commit. - Live plan updates
- A page showing the plan through a live query updates the moment the webhook’s write commits. No reload is needed after checkout.
Enforce seat limits#
seats_are_limited is one deny rule on memberships. At the plan’s seat limit, nobody can join the organization by invite or through the company’s sign-in. A deny wins over every allow, so no query has to check.
- What the app sees
- A join past the limit is refused with an access policy error. Read
count(.members)andplan.seat_limitbeside the invite form to warn admins before the organization reaches the limit. - Two joins at once
- A rule reads a snapshot of the rows, so two people accepting in the same instant can both get the last seat. If the overrun matters, recount afterward and bill for the extra seat.
- Billing by the seat
- This page sells a plan with a limit. To charge for each member, set the subscription’s quantity from
count(.members)in a job queued by the queries that add and remove members.
Prevent overdrawn credits#
Two simultaneous requests must never spend the final prepaid credit twice. Pairing a non-negative balance constraint with an exclusive ledger idempotency key inside one atomic statement prevents double-spending without application locks.
# Takes credits and writes the ledger entry, or does neither.with amount := <int64>$amount, wallet := assert_single((select CreditWallet filter .org.id = <uuid>$org)), entry := ( insert LedgerEntry { wallet := wallet, delta := -amount, reason := <str>$reason, idempotency_key := <str>$key, } ), spent := (update wallet set { balance := .balance - amount }),select { entry := entry.id, remaining := spent.balance }- Two spends at once
- Both spends update the same wallet row, so PostgreSQL serializes the row lock automatically. If the second spend would drop the balance below zero, the constraint aborts the entire second statement including the ledger entry.
- A request sent twice
- A retry carrying the same
$keyhits the exclusive constraint onidempotency_keyand aborts, so a request that timed out after succeeding is never charged twice. - A negative amount
- Passing a negative spend amount would increase the balance, which
members_can_spendrejects because member entries require.delta < 0.
Only the billing key adds credits. The same webhook route runs addCredits when a credit payment succeeds, keyed by the Stripe payment id so duplicate webhook deliveries credit the wallet once.
# Run by the billing service's key, with the payment's id as the key: a payment told twice adds once.with amount := <int64>$amount, # The organization's wallet, made with this amount the first time and added to after. wallet := ( insert CreditWallet { org := (select Organization filter .id = <uuid>$org), balance := amount, } unless conflict on .org else (update CreditWallet set { balance := .balance + amount }) ), entry := ( insert LedgerEntry { wallet := wallet, delta := amount, reason := <str>$reason, idempotency_key := <str>$key, } ),select { entry := entry.id, balance := wallet.balance }Handle refunds#
A refund is also an action. The gatekeeper query returns the paid order only when the caller has permission to refund it, and the handler calls Stripe and records the result as the caller. Actions & background jobs builds a refund action with an idempotency key that prevents duplicate refunds on retry.
Check billing#
Start a checkout as a non-owner member
POST /returnsquery/ startCheckout 403 nothing_found. For the owner, the query returns a Stripe URL.Pay with a test card
Use Stripe’s test mode. The organization’s plan changes when the webhook arrives, and a page watching the plan updates automatically. Send the same event again from Stripe’s dashboard, and nothing changes.
Check the billing key’s reach
napalm keys reachcounts organizations, wallets and ledger entries, and nothing else.Overspend the credit balance
The call fails with “Not enough credits”, and the ledger has no entry for the failed spend.