Skip to content

Payments and billing

Beignet treats payments as a provider-backed port and billing as app-owned product logic. Application workflows call ctx.ports.payments; providers adapt Stripe or another payment service. Your features/billing feature owns plans, prices, subscription records, customer state, and the app mapping from that state to product access. @beignet/core/entitlements owns the common decision shape and port for checking that access from use cases.

The port is intentionally small: hosted checkout, billing portal sessions, refunds, verified webhook events, and current checkout/subscription reads with latest invoice status. It does not model tax, metering, ledgers, or invoice management.

App-facing port

bash
bun add @beignet/core @beignet/next @beignet/provider-payments-stripe stripe

For a standard Drizzle-backed Beignet app, scaffold the billing slice:

bash
bun beignet make payments
bun beignet db generate
bun beignet db migrate
bun beignet db status

make payments creates features/billing, a billing_accounts Drizzle schema and repository, app/api/webhooks/payments/route.ts, a typed pricing module with a free/pro plan model and entitlement keys, a billing-backed entitlements port, a demo billing seed, memory payments provider wiring for local development, and BILLING_PRO_PRICE_ID env validation. On apps with the frontend shell it also emits a plan settings page at /settings/plan with typed React Query hooks and adds it to the settings navigation.

The free plan is a fully working tier: accounts without an active subscription resolve to it instead of being locked out, and FREE_PLAN_LIMITS in features/billing/pricing.ts names the quotas to enforce once usage grows. The generated app stays provider neutral; swap to the Stripe provider when you are ready to use live Stripe credentials.

Add the port to your app:

typescript
// ports/index.ts
import type { PaymentsPort } from "@beignet/core/payments";
import type { EntitlementsPort } from "@beignet/core/entitlements";

export type AppPorts = {
  entitlements: EntitlementsPort;
  payments: PaymentsPort;
  // app-owned billing repositories and other ports...
};

When providers contribute the ports at startup, list entitlements and payments as deferred keys in infra/port-wiring.ts:

typescript
export const initialPorts = definePorts<AppPorts>()({
  bound: {
    gate,
  },
  deferred: ["entitlements", "payments", "logger", "uow"],
});

Stripe provider

Wire the Stripe provider in server/providers.ts:

typescript
import { createStripePaymentsProvider } from "@beignet/provider-payments-stripe";

export const providers = [
  // other providers...
  createStripePaymentsProvider(),
] as const;

createStripePaymentsProvider(options) supplies the Stripe keys in code; options override env-derived values.

Set the provider env vars:

env
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PUBLISHABLE_KEY=pk_live_...

The provider installs ctx.ports.payments and exposes ctx.ports.stripe.client as an escape hatch for Stripe-specific operations the stable port does not model.

Stripe SDK and API versions

The payments provider and @beignet/webhooks-stripe support stripe@^22.0.0 || ^23.0.0. New CLI provider installs use stripe@^23.1.0; existing apps can keep Stripe 22 while preparing their migration.

createStripePaymentsProvider() uses the installed SDK's default API version. Stripe 22 uses the Dahlia API family (22.6.2 defaults to 2026-08-26.dahlia); Stripe 23 uses Endive (23.0.0 defaults to 2026-09-30.endive, and 23.1.0 to 2026-10-28.endive). Upgrading Beignet alone does not change an app's installed Stripe SDK or migrate its account. Review Stripe's v23 migration guide and API changelog before upgrading, including any raw SDK calls through the escape hatch.

Webhook endpoint API versions are configured separately in Stripe; installing a new SDK does not change existing event payloads. Review the endpoint version alongside the SDK and your app's event schemas. In Stripe test mode, exercise checkout, subscription/invoice refresh, billing portal, refunds, and webhook delivery before changing the production integration. See Stripe's versioning guide.

Beignet does not pin an older API version behind the SDK. Apps that own SDK configuration can pass their client to createStripePayments({ client, webhookSecret }); overriding the SDK's API version can make its TypeScript types inaccurate. Staying on Stripe 22 until the migration is ready keeps the default request version and SDK types aligned.

Cut over to Stripe

The generated billing slice starts with memory payments so local development and tests do not need Stripe credentials. Move to Stripe deliberately:

  1. Scaffold billing and create the database migration:

    bash
    bun beignet make payments
    bun beignet db generate
    bun beignet db migrate
    bun beignet db status
  2. Create the product and price in Stripe, then set BILLING_PRO_PRICE_ID to the Stripe Price ID for the paid plan your app exposes. The free plan has no price and needs no Stripe configuration.

  3. Set the Stripe provider env vars for the environment you are deploying:

    env
    STRIPE_SECRET_KEY=sk_live_...
    STRIPE_WEBHOOK_SECRET=whsec_...
    STRIPE_PUBLISHABLE_KEY=pk_live_...
    

    Keep test-mode and live-mode keys separate. The webhook secret is specific to the endpoint or local Stripe CLI session that produced it.

  4. Replace the generated memory provider in server/providers.ts:

    typescript
    import { createStripePaymentsProvider } from "@beignet/provider-payments-stripe";
    
    export const providers = [
      // other providers...
      createStripePaymentsProvider(),
    ] as const;
  5. Deploy the billing migration before accepting live webhooks. The webhook handler should never be the first code path that discovers the billing_accounts table is missing.

  6. Configure a Stripe webhook endpoint that forwards to https://<your-app>/api/webhooks/payments and subscribe to these events:

    • checkout.session.completed
    • checkout.session.async_payment_succeeded
    • checkout.session.async_payment_failed
    • customer.subscription.created
    • customer.subscription.updated
    • customer.subscription.deleted
    • invoice.paid
    • invoice.payment_succeeded
    • invoice.payment_failed
  7. Run bun beignet doctor --strict, create a checkout session, complete it in Stripe test mode, and verify that your app-owned billing state changes only after verified webhook events are handled.

Create checkout from a use case

Keep checkout creation behind an application use case. The use case decides which tenant, plan, and price are allowed; the payments port only creates the external session.

typescript
// features/billing/pricing.ts
import type {
  PaymentCheckoutLineItem,
  PaymentCheckoutMode,
} from "@beignet/core/payments";
import { env } from "@/lib/env";
import type { BillingPlan } from "./schemas";

export type BillingPlanDefinition = {
  id: BillingPlan;
  label: string;
  mode: PaymentCheckoutMode;
  lineItems: readonly PaymentCheckoutLineItem[];
  entitlements: readonly string[];
};

export const billingPlans = {
  free: {
    id: "free",
    label: "Free",
    mode: "subscription",
    lineItems: [],
    entitlements: [],
  },
  pro: {
    id: "pro",
    label: "Pro",
    mode: "subscription",
    lineItems: [{ priceId: env.BILLING_PRO_PRICE_ID, quantity: 1 }],
    entitlements: ["todos.create"],
  },
} as const satisfies Record<BillingPlan, BillingPlanDefinition>;

/**
 * Free-plan quotas. Call `requireEntitlement` only once usage reaches these
 * limits, so the free plan stays a fully working tier.
 */
export const FREE_PLAN_LIMITS = {
  todos: 100,
} as const;

export function getBillingPlan(plan: BillingPlan): BillingPlanDefinition {
  return billingPlans[plan];
}

Then use that plan definition from checkout:

typescript
// features/billing/use-cases/create-checkout-session.ts
import { requireTenant } from "@beignet/core/ports";
import { z } from "zod";
import { env } from "@/lib/env";
import { useCase } from "@/lib/use-case";
import { getBillingPlan } from "../pricing";

export const createCheckoutSessionUseCase = useCase
  .command("billing.createCheckoutSession")
  .input(
    z.object({
      plan: z.enum(["pro"]),
    }),
  )
  .run(async ({ ctx, input }) => {
    const tenant = requireTenant(ctx);
    const plan = getBillingPlan(input.plan);

    return ctx.ports.payments.createCheckoutSession({
      mode: plan.mode,
      lineItems: plan.lineItems,
      successUrl: `${env.APP_URL}/billing/success`,
      cancelUrl: `${env.APP_URL}/billing`,
      clientReferenceId: tenant.id,
      metadata: {
        tenantId: tenant.id,
        plan: input.plan,
      },
    });
  });

Expose that use case through a normal Beignet contract and route. Add idempotency metadata to the contract so browser retries reuse the same logical checkout request.

Do not use a tenant-wide provider idempotency key for checkout creation. A future legitimate checkout attempt for the same tenant and plan should create a new provider session instead of replaying an old one. If your app has a per-request idempotency key available at the use-case boundary, passing that to the payments port is reasonable.

Treat the returned checkout URL as workflow intent, not proof of payment. A success redirect is a user experience signal only; fulfillment should happen from verified provider webhooks.

Enforce product access with entitlements

Billing records are the source of subscription state. Entitlements are the server-side product access decisions derived from that state. Keep the mapping app-owned, then enforce it from use cases:

typescript
// features/todos/use-cases.ts (excerpt)
import { requireEntitlement } from "@beignet/core/entitlements";
import {
  requireTenantScope,
  tenantScopeId,
} from "@beignet/core/tenancy";
import { useCase } from "@/lib/use-case";
import { createTodoSchema, todoSchema } from "./schemas";

export const createTodoUseCase = useCase
  .command("todos.create")
  .input(createTodoSchema)
  .output(todoSchema)
  .run(async ({ ctx, input }) => {
    const scope = requireTenantScope(ctx);
    const tenantId = tenantScopeId(scope);

    await requireEntitlement(ctx, {
      entitlement: "todos.create",
      subject: { type: "tenant", id: tenantId },
    });

    return ctx.ports.todos.create(input, scope);
  });

Policies and entitlements answer different questions. Policies decide whether the current actor may perform an action on a resource. Entitlements decide whether the tenant or account has product access to that capability. Paid workflows commonly use both checks in the same use case.

Observe entitlement decisions

Use onDecision when you want paid-feature decisions to appear in devtools or logs. The observer is best-effort: it cannot change the allow/deny result, and observer errors are ignored.

typescript
// features/billing/entitlements.ts
import {
  createEntitlements,
  type EntitlementDecisionObserver,
} from "@beignet/core/entitlements";
import { createTenant } from "@beignet/core/ports";
import { createTenantScope } from "@beignet/core/tenancy";

export function createBillingEntitlements(
  billing: BillingRepository,
  options: { onDecision?: EntitlementDecisionObserver } = {},
) {
  return createEntitlements({
    async inspect(input) {
      if (input.subject.type !== "tenant") return false;
      const account = await billing.findByTenantScope(
        createTenantScope(createTenant(input.subject.id)),
      );
      return account?.status === "active";
    },
    onDecision: options.onDecision,
  });
}

In provider wiring, pass the current instrumentation or devtools port to the observer closure so the billing feature stays independent of runtime infrastructure. The built-in entitlements devtools watcher can then be enabled, disabled, searched, and filtered like payments and policies.

Billing persistence and migrations

Billing state should be app-owned and durable. Store provider customer IDs, subscription IDs, the current app subscription status, period end, cancellation intent, checkout session ID, last processed webhook event ID, and a revision number for conditional writes in a repository under features/billing/ports.ts.

For Drizzle apps, keep the billing table in infra/db/schema/billing.ts and export it from infra/db/schema/index.ts. After adding or changing billing columns, run:

bash
bun beignet db generate
bun beignet db migrate
bun beignet db status

Local development can bootstrap the billing table directly when that keeps a demo repeatable. Production apps should prefer checked-in Drizzle migrations generated from the schema.

Verify webhooks

Webhook routes are focused boundary adapters because provider signatures need the raw request body. In Next.js, use createPaymentWebhookRoute(...) so the raw-body read and signature verification stay consistent:

typescript
// app/api/webhooks/payments/route.ts
import { createPaymentWebhookRoute } from "@beignet/next";
import { handlePaymentWebhookUseCase } from "@/features/billing/use-cases";
import { getServer } from "@/server";

export const runtime = "nodejs";

export const { POST } = createPaymentWebhookRoute({
  server: getServer,
  maxBodyBytes: 1024 * 1024,
  handle: async ({ ctx, event }) => {
    await handlePaymentWebhookUseCase.run({ ctx, input: event });
    return {
      status: 200,
      body: { received: true },
    };
  },
});

The raw body limit defaults to 1 MiB. Signed requests above maxBodyBytes return 413 before payment-provider verification or fulfillment. The signature header is checked first: an unsigned request returns 400 and Beignet cancels its unread body without resolving the server, running hooks, or creating app context. Signed bodies are bounded before those lifecycle phases too. Increase the limit only when the provider's documented webhook payload limit requires a larger bound.

This is the canonical route for Beignet billing flows. It verifies through ctx.ports.payments.verifyWebhook(...) and passes your handler a normalized PaymentWebhookEvent. You do not need a defineWebhook(...) catalog for the generated billing slice.

Use @beignet/webhooks-stripe with createWebhookRoute(...) only when Stripe is a generic inbound event source outside the payments port, or when your app deliberately wants to model Stripe events through a typed generic webhook catalog.

Do not parse the body as JSON before verification, and do not put Stripe SDK calls in feature use cases. The provider owns signature verification; the feature owns what the verified event means. Webhooks should not go through the normal JSON contract route path: the route must read the raw request body once and verify the signature before running app-owned fulfillment.

Webhook operations

For local Stripe testing, forward events to the same route your deployed app uses:

bash
stripe listen --forward-to http://localhost:3000/api/webhooks/payments

Set STRIPE_WEBHOOK_SECRET to the whsec_... value printed by that command for the local app process. That secret is not interchangeable with a Dashboard endpoint secret or a live-mode endpoint secret.

Provider webhooks are at-least-once delivery and can arrive out of order. Use the provider and event ID for deduplication. Use event payloads to locate an account, then read its current checkout, subscription, and latest invoice through the payments port. A stale event is a reason to refresh state, never a reason to restore the state contained in its payload.

The generated billing slice handles checkout completion, asynchronous checkout success/failure, subscription events, and invoice events. Other verified event types are acknowledged without changing billing state.

If webhooks fail:

  • Confirm the route uses createPaymentWebhookRoute(...) and keeps export const runtime = "nodejs";.
  • Confirm the STRIPE_WEBHOOK_SECRET belongs to the exact endpoint and mode that sent the event.
  • Confirm no middleware or route code parsed the request body before signature verification.
  • Inspect payments.webhook.failed provider events in devtools or your provider logs.
  • Replay the event from the Stripe Dashboard or Stripe CLI after fixing the configuration; the idempotency key should make duplicate delivery safe.

Reconcile payment events

beignet make payments generates features/billing/reconciliation.ts. The webhook use case deduplicates each verified event and calls that helper:

typescript
// Inside handlePaymentWebhookUseCase's run callback.
const fingerprint = await createIdempotencyFingerprint({
  type: input.type,
  data: input.data,
});

return runIdempotently(ctx.ports.idempotency, {
  namespace: "webhooks.payments",
  key: input.id,
  scope: { provider: input.provider },
  fingerprint,
  ttlSec: 60 * 60 * 24 * 30,
  run: async () => ({
    received: true,
    accountUpdated: await reconcileBilling(ctx.ports, input),
  }),
});

Import the idempotency helpers from @beignet/core/idempotency and the generated reconcileBilling from ../reconciliation in features/billing/use-cases/index.ts. Setup-mode checkout events are acknowledged without reading the checkout or changing billing state. For subscription billing, the helper follows this sequence:

  1. Locate the account from the current checkout's clientReferenceId, an existing provider/customer association, or subscription metadata.
  2. Read the local account and its revision before reading provider state.
  3. Refresh the account's current checkout with getCheckoutSession({ id }). Adopt its subscription only when checkout is complete and paymentStatus is paid or no_payment_required.
  4. Read the bound subscription with getSubscription({ id }), including its current price items and latest invoice status. The generated access policy permits trials, or active subscriptions whose latest invoice is paid. Incomplete, paused, canceled, unpaid, past-due, and unknown states do not grant paid access. A zero-amount invoice marked paid qualifies.
  5. Match prices against app-owned billingPlans; unknown prices do not grant paid access. Save with compareAndSave(..., expectedRevision). On a conflict, re-read both the account and provider state before trying again.

Every billing writer advances the revision, including checkout creation. Five failed conditional writes throw so the provider can retry. Provider read failures also throw; they neither change access nor complete the event's deduplication record. Provider calls run outside database transactions. A crash after the billing write but before deduplication completes can repeat reconciliation safely.

The default policy models one current subscription per account. Only the account's most recently recorded checkout can attach a replacement subscription; old checkout events are ignored and events for old subscriptions refresh the current binding. An unfinished replacement checkout preserves the existing subscription. Subscription creation outside this checkout flow requires an app-owned association workflow; the scaffold does not guess which subscription to adopt from a customer's other subscriptions. Restrict parallel checkout flows if your product must prevent customers from paying for multiple subscriptions.

This is a conservative access policy. Invoice terms, grace periods, multiple subscriptions, and quantity-based entitlements belong in your billing feature. Customize the policy there; keep the provider responsible for returning current facts. The Stripe provider uses item-level billing periods and expands latest_invoice. See Stripe's event ordering guidance and subscription lifecycle.

If billing changes need domain events or other durable effects, put the conditional billing write and outbox append in the same Unit of Work after the provider reads. Dispatch mail, notifications, and analytics through outbox and jobs.

Existing generated apps must add the billing_accounts.revision migration, implement the repository's conditional writes, and update custom payments port implementations with both read methods. Deploy migrations before webhook code.

Refunds and portal sessions

Use the same port for customer self-service and refunds:

typescript
const portal = await ctx.ports.payments.createBillingPortalSession({
  customerId: billingAccount.providerCustomerId,
  returnUrl: `${env.APP_URL}/settings/billing`,
});

await ctx.ports.payments.createRefund({
  paymentId: payment.providerPaymentId,
  amount: 500,
  reason: "requested_by_customer",
  idempotencyKey: `refund:${payment.id}:support-credit`,
});

Keep the app's billing repository as the source of subscription state and the entitlements port as the source of product access decisions. Provider IDs are external references, not your entitlement model.

Testing

Use the memory adapter in tests:

typescript
import { createMemoryPayments } from "@beignet/core/payments";

const payments = createMemoryPayments({
  id: (prefix) => `${prefix}_test`,
});

const checkout = await payments.createCheckoutSession({
  mode: "subscription",
  lineItems: [{ priceId: "price_pro" }],
  successUrl: "https://app.example.test/success",
  cancelUrl: "https://app.example.test/cancel",
});

expect(checkout.provider).toBe("memory");
expect(payments.checkoutSessions).toHaveLength(1);

createTestPorts(...) from @beignet/core/testing also includes a memory payments port. Set authoritative state independently from queued events:

typescript
payments.setCheckoutSession({
  ...checkout,
  clientReferenceId: "tenant_123",
  customerId: "cus_123",
  subscriptionId: "sub_123",
  status: "complete",
  paymentStatus: "paid",
});
payments.setSubscription({
  id: "sub_123",
  provider: "memory",
  customerId: "cus_123",
  status: "active",
  items: [{ priceId: "price_pro" }],
  cancelAtPeriodEnd: false,
  latestInvoice: { id: "in_123", status: "paid" },
});

queueWebhookEvent(...) does not mutate current provider state. This lets tests queue an old active event while getSubscription(...) returns canceled. The generated tests cover stale events, unpaid checkout, replacement subscriptions, duplicates, concurrent writes, and retryable failures.

  • Idempotency for retry-safe checkout and webhook handling.
  • Outbox for durable post-commit billing side effects.
  • Providers for provider wiring and escape hatches.
  • Devtools for provider instrumentation watchers.

Web Fetch hosts

Use createPaymentWebhookRoute from @beignet/web for Bun or another Fetch host. Mount the returned method handlers in the host entrypoint and reuse the app's assembled server or ports. Next apps import the corresponding helper from @beignet/next. See operational HTTP handlers for mounting, context, and lifecycle behavior.