Skip to the page

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, a membership policy enforces plan seat limits 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 wallets

Balance constraints and idempotency keys prevent overdrafts and duplicate charges.

Enforced seat limits

A membership deny policy enforces seat caps across invites and SSO joins.

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.

dbschema/default.gel
module default {  # Set to 'service' in endpoint serviceGlobals for service keys. User sessions cannot set globals.  global role: str;   type BillingPlan {    # Existing BillingPlan fields from SaasDoc, plus:    stripe_price: str {      constraint exclusive;    };  }   type Organization {    # Existing Organization fields, plus:    stripe_customer: str {      constraint exclusive;    };     access policy billing_can_read_and_update      allow select, update      using (global role ?= 'service');  }   type Membership {    # Existing Membership fields and policies, plus:    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);    # Members can only record negative credit spends.    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 system of record for payment methods and invoices, while your schema stores the active plan, Stripe customer ID and credit balance enforced by your access policies.

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.

Terminal
# Issue a scoped key for the billing routes and save the printed secret as NAPALM_KEYnapalm keys create acme-app --label billing --days 90 # Verify that the key reaches only billing types before deployingnapalm 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#

Creating a Stripe Checkout Session requires your Stripe secret key, so checkout runs as an action. The gatekeeper query checks that the caller is an organization Owner before invoking your handler. Any other caller receives 403 nothing_found, and your handler never runs.

dbschema/queries/startCheckout.edgeql
# Returns the organization only to an Owner so non-owners never invoke the checkout 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.ts
// 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) {      // Gatekeeper query verified that the caller is an Owner of this organization.      const [organization] = call.rows as Checkout[]      const session = await stripe.checkout.sessions.create({        mode: 'subscription',        line_items: [{ price: organization.price, quantity: 1 }],        // Attach the organization UUID so subscription webhooks map back to this tenant.        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,  },)

Register the action with napalm actions add acme-app startCheckout https://app.example.com/actions/startCheckout. Your frontend calls POST /query/startCheckout with the organization ID and plan slug, then redirects the browser to the returned url. Opening the Stripe customer portal follows the same pattern with stripe.billingPortal.sessions.create.

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.

Stripe webhook delivery

Stripe sends subscription and top-up events directly to your webhook endpoint.

Signature verification

Your route verifies the Stripe HMAC signature over raw bytes before parsing.

Scoped billing key

The billing key updates plans and wallets without reading customer documents.

Deploy recordSubscription and mount a webhook route that verifies Stripe’s signature and updates the organization’s plan with the billing key.

dbschema/queries/recordSubscription.edgeql
# Runs under the billing service key and falls back to the starter plan when unpaid.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.ts
// 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!// Authenticate with the scoped billing service key.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 {    // Verify the Stripe webhook signature over the raw request body.    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 })   // Webhooks can arrive late or out of order, so fetch current subscription state from Stripe.  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,      },    }),  })  // Return 500 on database failure so Stripe retries the event.  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 a single deny policy on Membership. Once an organization reaches plan.seat_limit, PostgreSQL rejects new memberships across both email invites and company SSO joins. Because deny overrides every allow policy, individual queries never need a manual seat check.

Client feedback
Inserts past the cap fail with an access policy error. Display count(.members) alongside plan.seat_limit on your invite screen so admins see remaining capacity up front.
Concurrent joins
Each statement evaluates policies against its transaction snapshot, so two invitees accepting at the exact same instant can claim the final seat simultaneously. If strict post-commit accounting matters, reconcile active seat counts in Stripe afterward.
Per-seat metered billing
This schema enforces a fixed tier cap. To bill per active seat instead, queue a background job inside your membership insert and delete queries that updates the Stripe subscription quantity from count(.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.

dbschema/queries/spendCredits.edgeql
# Atomically records the ledger entry and deducts credits in one statement.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 }
Concurrent spends
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.
Retried requests
A retry carrying the same $key hits the exclusive constraint on idempotency_key and aborts, so a request that timed out after succeeding is never charged twice.
Negative spend amounts
Passing a negative spend amount would increase the balance, which members_can_spend rejects 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.

dbschema/queries/addCredits.edgeql
# Runs under the billing service key keyed by payment ID so duplicate webhooks credit once.with  amount := <int64>$amount,  # Create the organization's wallet on first top-up or increment the existing balance.  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#

  1. Start a checkout as a non-owner member

    POST /query/startCheckout returns 403 nothing_found. For the owner, the query returns a Stripe URL.

  2. Pay with a test card

    Complete checkout using a Stripe test card. When the webhook commits, the organization’s plan updates immediately in any open live query, and replaying the webhook event from Stripe’s dashboard leaves state unchanged.

  3. Check the billing key’s reach

    napalm keys reach counts organizations, wallets and ledger entries, and nothing else.

  4. Overspend the credit balance

    The call fails with “Not enough credits”, and the ledger has no entry for the failed spend.

Type a word or two to search every docs page.