# Billing system (PRO)

import { Callout } from "fumadocs-ui/components/callout";
import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
import { Step, Steps } from "fumadocs-ui/components/steps";
import { Badge } from "@pycolors/ui";
import {
  CreditCard,
  Database,
  Download,
  FileText,
  KeyRound,
  LockKeyhole,
  RefreshCcw,
  ShieldCheck,
} from "lucide-react";

import { PreferAvoid } from "@/components/docs/prefer-avoid";
import { DocsDecisionGrid } from "@/components/docs/docs-decision-grid";
import { DocsFeatureGrid } from "@/components/docs/docs-feature-grid";
import { DocsLinks } from "@/components/docs/docs-links";
import { DocsUpgradeCTA } from "@/components/docs/docs-upgrade-cta";

<div className="flex flex-wrap items-center gap-2">
  <Badge variant="outline">
    Starter Pro
  </Badge>

  <Badge>
    Billing
  </Badge>
</div>

## Billing that turns your product into a business

Starter Free gives you **pricing surfaces and billing UX**.

Starter Pro gives you **real Stripe billing foundations**:

* Stripe Checkout
* billing portal
* customer mapping
* subscription lifecycle
* webhook synchronization
* invoice-ready flows
* plan-aware access

This is not just a pricing page.

It is the layer that makes your SaaS capable of generating real revenue.

<DocsUpgradeCTA title="Revenue starts when billing is real." description="Starter Pro helps you move from pricing UI to a production-oriented billing system that can actually charge customers." productSlug="starter-pro" buyLabel="Get Starter Pro" secondaryHref="/docs/starter-pro/getting-started" secondaryLabel="Setup guide" />

<Callout title="Core idea">
  Billing is not UI. Billing is payment state, customer ownership, webhook truth, and product access.
</Callout>

### What this solves

Most teams underestimate what “add Stripe” means.

A real SaaS billing layer needs:

* checkout session creation
* customer-to-user mapping
* subscription state handling
* webhook verification
* invoice tracking
* billing portal access
* plan-aware product behavior
* failed payment handling
* cancellation behavior

Starter Pro gives you a structured foundation for that layer so billing can become a product system, not a fragile afterthought.

### Included foundations

<DocsFeatureGrid
  columns={2}
  tone="platform"
  items={[
  {
    title: 'Stripe Checkout',
    description:
      'Server-created checkout sessions, upgrade entry points, and a clean path from pricing intent to payment.',
    icon: CreditCard,
  },
  {
    title: 'Webhook synchronization',
    description:
      'Stripe events synchronized into your app state so subscriptions, invoices, and access stay aligned.',
    icon: RefreshCcw,
  },
  {
    title: 'Invoices and subscriptions',
    description:
      'Invoice-ready tracking, subscription lifecycle handling, status surfaces, and billing history foundations.',
    icon: FileText,
  },
  {
    title: 'Plan-aware access',
    description:
      'Billing-aware product logic so access can reflect plan, status, subscription, and customer state.',
    icon: ShieldCheck,
  },
]}
/>

## Billing lifecycle

<Steps>
  <Step>
    ### User starts upgrade

    The user clicks an upgrade CTA from pricing, billing, or a gated feature.

    ```txt title="entry-points.txt"
    /pricing
    /billing
    /protected-feature
    ```
  </Step>

  <Step>
    ### Backend creates Checkout session

    The browser should not create Stripe sessions directly.
    Your backend creates the Checkout session using server-side Stripe keys.

    ```ts title="server/billing/create-checkout-session.ts"
    const session = await stripe.checkout.sessions.create({
      customer: stripeCustomerId,
      mode: "subscription",
      line_items: [{ price: priceId, quantity: 1 }],
      success_url: `${appUrl}/billing?success=true`,
      cancel_url: `${appUrl}/pricing?canceled=true`,
    });
    ```
  </Step>

  <Step>
    ### Stripe confirms payment

    Stripe handles payment, subscription creation, and customer billing operations.

    The UI should not assume success only because a redirect happened.
  </Step>

  <Step>
    ### Webhook updates app state

    Webhooks are the synchronization layer.
    They verify what actually happened in Stripe and update your database.

    ```txt title="webhook-events.txt"
    checkout.session.completed
    customer.subscription.created
    customer.subscription.updated
    customer.subscription.deleted
    invoice.payment_succeeded
    invoice.payment_failed
    ```
  </Step>

  <Step>
    ### App reflects billing state

    Product access, billing page, invoice history, and plan-aware UI should read from synchronized backend state.
  </Step>
</Steps>

<Callout title="Production rule">
  Redirects are UX. Webhooks are truth.
</Callout>

### Billing flows

<DocsDecisionGrid
  columns={2}
  items={[
  {
    eyebrow: 'Checkout',
    title: 'Checkout starts revenue',
    icon: CreditCard,
    description:
      'Checkout creates the initial payment or subscription flow between your product and Stripe.',
    items: [
      'upgrade CTA triggers backend session creation',
      'Stripe Checkout handles payment',
      'success and cancel URLs return users to the app',
      'webhook confirms the actual state',
    ],
  },
  {
    eyebrow: 'Portal',
    title: 'Portal manages existing customers',
    icon: KeyRound,
    description:
      'The billing portal handles customer self-service flows without rebuilding billing management UI.',
    items: [
      'payment method updates',
      'invoice access',
      'subscription management',
      'cancellation flows',
      'plan changes',
    ],
  },
  {
    eyebrow: 'Webhooks',
    title: 'Webhooks synchronize truth',
    icon: RefreshCcw,
    description:
      'Webhooks keep your application aligned with Stripe billing events and subscription state.',
    items: [
      'verified Stripe event handling',
      'subscription status updates',
      'invoice state updates',
      'idempotent event handling patterns',
    ],
  },
  {
    eyebrow: 'Access',
    title: 'Plan-aware product access',
    icon: ShieldCheck,
    description:
      'Billing becomes product infrastructure when subscription state controls feature access.',
    items: [
      'feature gates by plan',
      'subscription status checks',
      'past due and canceled handling',
      'billing-aware dashboard surfaces',
    ],
  },
]}
/>

## Starter Free vs Starter Pro

| Capability             | Starter Free | Starter Pro         |
| ---------------------- | ------------ | ------------------- |
| Pricing page           | Included     | Included            |
| Billing UI             | Mocked       | Real-backed         |
| Stripe Checkout        | Not included | Included            |
| Billing portal         | UI only      | Included            |
| Customer mapping       | Not included | Included foundation |
| Subscription lifecycle | Mocked       | Real sync           |
| Webhooks               | Not included | Included foundation |
| Invoice tracking       | Mocked       | Invoice-ready       |
| Plan-aware access      | Conceptual   | Included foundation |
| Revenue readiness      | Demo only    | Production-oriented |

<Callout title="Simple distinction">
  Starter Free simulates monetization.
  Starter Pro gives you the billing layer required to charge customers.
</Callout>

## Architecture

### Data model responsibilities

Billing needs enough structure to represent customer and subscription state inside your app.

Typical responsibilities include:

| Area         | Purpose                                             |
| ------------ | --------------------------------------------------- |
| Customer     | Maps app users or organizations to Stripe customers |
| Product      | Represents sellable SaaS products                   |
| Price        | Represents Stripe prices and commercial plans       |
| Subscription | Tracks current subscription state                   |
| Invoice      | Stores invoice references and payment status        |
| WebhookEvent | Tracks processed Stripe events for reliability      |

<Callout type="info" title="Why this matters">
  Stripe is the payment source.
  Your app still needs synchronized billing state to protect access and render product UI correctly.
</Callout>

### Plan gating

Billing becomes valuable when it controls product behavior.

Starter Pro gives you the foundation to build logic such as:

* free vs paid access
* plan-based feature flags
* subscription status checks
* billing-aware settings
* upgrade prompts
* cancellation behavior
* failed payment messaging

```ts title="plan-access.ts"
export function canAccessProFeature(subscriptionStatus: string) {
  return subscriptionStatus === "active" || subscriptionStatus === "trialing";
}
```

Keep plan logic clear, centralized, and server-verifiable.

### Security rules

Use these rules when adapting the billing layer.

<PreferAvoid
  prefer={[
  'create Stripe sessions on the server',
  'verify webhook signatures',
  'use webhooks as the billing source of truth',
  'store synchronized subscription state',
  'check access server-side for sensitive features',
]}
  avoid={[
  'calling Stripe secret APIs from the browser',
  'unlocking access only from redirect success',
  'skipping webhook verification',
  'scattering plan checks across the UI',
  'using vague billing error messages',
]}
/>

## Decision guide

<DocsDecisionGrid
  columns={2}
  items={[
  {
    eyebrow: 'Starter Pro',
    title: 'Use Starter Pro when billing becomes real',
    href: '/docs/starter-pro/getting-started',
    icon: CreditCard,
    tone: 'pro',
    description:
      'Use Starter Pro when charging users becomes part of your launch plan and billing can no longer stay mocked.',
    items: [
      'you want to charge users',
      'Stripe Checkout must work',
      'subscription status controls access',
      'invoice history matters',
      'webhooks need to sync state',
      'billing is blocking launch confidence',
    ],
    cta: 'Start setup →',
  },
  {
    eyebrow: 'Starter Free',
    title: 'Stay on Free while validating pricing UX',
    icon: FileText,
    description:
      'Stay on Starter Free while your monetization flow is still a product surface and not a real payment system.',
    items: [
      'you are validating pricing UX',
      'billing is still mocked',
      'you do not accept payments yet',
      'your product is not ready to monetize',
    ],
  },
]}
/>

<Callout title="Upgrade when billing becomes real">
  Starter Free helps you shape monetization.
  Starter Pro gives you the billing layer required to charge customers.
</Callout>

### Implementation checklist

Before treating billing as launch-ready, validate:

* checkout session creation
* checkout success flow
* checkout cancel flow
* customer mapping
* billing portal session creation
* webhook signature verification
* subscription created event
* subscription updated event
* subscription canceled event
* invoice payment succeeded event
* invoice payment failed event
* plan-aware access logic
* billing page state
* user-facing billing error copy

<Callout type="info" title="Validation principle">
  Do not trust billing until you validate the full lifecycle:
  checkout, webhook, database sync, and product access.
</Callout>

## Common questions

<Accordions type="single">
  <Accordion title="Is this only a pricing page?">
    No. Starter Pro billing is about the revenue layer: Checkout, portal, webhooks, subscription state, invoices, and plan-aware access.
  </Accordion>

  <Accordion title="Can I start with one-time payments instead of subscriptions?">
    Yes, but the billing model should still keep a clear customer, payment, and access boundary. Keep the product decision separate from the Stripe integration pattern.
  </Accordion>

  <Accordion title="Should the frontend decide if a user has access?">
    No. The UI can reflect access state, but sensitive access checks should be server-verifiable and based on synchronized billing state.
  </Accordion>

  <Accordion title="Why are webhooks required?">
    Redirects are not enough. Webhooks tell your application what actually happened inside Stripe after payment, renewal, cancellation, or failure.
  </Accordion>
</Accordions>

<DocsUpgradeCTA title="Move from pricing UI to real revenue infrastructure." description="Starter Pro helps you wire Checkout, Portal, webhooks, subscription state, and plan-aware access from a stronger baseline." productSlug="starter-pro" buyLabel="Get Starter Pro" secondaryHref="/pricing" secondaryLabel="View pricing" />

## Next steps

<DocsLinks
  variant="grid"
  items={[
  {
    title: 'Backend foundations',
    href: '/docs/starter-pro/backend',
    description:
      'Understand how billing state connects to your data layer and server-side logic.',
    icon: Database,
  },
  {
    title: 'Secure delivery',
    href: '/docs/starter-pro/delivery',
    description:
      'Learn how paid access can unlock protected downloads and post-purchase delivery.',
    icon: Download,
  },
  {
    title: 'Authentication system',
    href: '/docs/starter-pro/auth',
    description:
      'Review how users, sessions, and customer ownership connect to billing.',
    icon: LockKeyhole,
  },
  {
    title: 'Production checklist',
    href: '/docs/starter-pro/production-checklist',
    description:
      'Validate authentication, billing, backend, and delivery before launch.',
    icon: ShieldCheck,
  },
]}
/>