# Billing Concept

import { Callout } from "fumadocs-ui/components/callout";
import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
import { Step, Steps } from "fumadocs-ui/components/steps";
import { Tabs, Tab } from "fumadocs-ui/components/tabs";
import {
  Badge,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@pycolors/ui";
import {
  ArrowRight,
  ArrowUpRight,
  CheckCircle,
  CreditCard,
  FileText,
  LoaderCircle,
  RefreshCw,
  Rocket,
  ShieldCheck,
  WalletCards,
  Webhook,
  XCircle,
} from "lucide-react";
import { PreferAvoid } from '@/components/docs/prefer-avoid';
import { DocsLinks } from "@/components/docs/docs-links";
import { DocsFeatureGrid } from "@/components/docs/docs-feature-grid";
import { DocsConceptTabs } from "@/components/docs/docs-concept-tabs";

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

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

## Overview

Billing is one of the most important SaaS workflows, but also one of the easiest to wire incorrectly.

Starter Free gives you the **complete billing UX surface** while keeping the implementation intentionally mocked.

You get the product-facing structure:

* current plan
* renewal date
* seats
* payment method
* invoice history
* billing portal entry point

But you do not get the billing engine yet.

<Callout title="Core idea">
  Starter Free models the billing experience. Starter Pro wires the billing business layer.
</Callout>

## Billing philosophy

Starter Free ships the **billing surface**, not the billing engine.

| Included                   | Not included                     |
| -------------------------- | -------------------------------- |
| Plan display               | Stripe Checkout                  |
| Renewal information        | Stripe webhooks                  |
| Seats concept              | subscription lifecycle sync      |
| Invoice history UI         | real Stripe invoices             |
| Billing portal entry point | customer portal session creation |
| Payment method surface     | backend billing contracts        |

This separation lets you validate monetization UX before committing to full Stripe architecture.

<Callout type="info" title="Why this matters">
  Billing is not just a page. It is a revenue workflow. The UI can be mocked early, but the production implementation must be wired carefully.
</Callout>

### What you’ll understand

<DocsFeatureGrid
  columns={3}
  tone="platform"
  items={[
  {
    title: 'Billing surface',
    description:
      'Understand the mocked plan, seats, payment method, and billing entry points.',
    icon: CreditCard,
  },
  {
    title: 'Invoice model',
    description:
      'See how invoice history is represented before replacing it with real Stripe data.',
    icon: FileText,
  },
  {
    title: 'Stripe boundary',
    description:
      'Know where Checkout, Portal, webhooks, and subscription sync connect later.',
    icon: ShieldCheck,
  },
]}
/>

### Mental model

> Billing UI is stable.
> Billing implementation evolves behind it.

| Layer    | Responsibility                                        |
| -------- | ----------------------------------------------------- |
| UI       | Plan, invoices, payment method, seats, portal actions |
| Backend  | Creates checkout and portal sessions                  |
| Stripe   | Payments, subscriptions, invoices, customer state     |
| Webhooks | Source of truth for lifecycle changes                 |
| Database | Stores synchronized billing state for the app         |

<Callout title="Production rule">
  Never treat the billing page as the source of truth. Stripe events and your backend state must drive production billing.
</Callout>

### Steps

<Steps>
  <Step>
    ### Understand the billing route

    The billing surface lives here:

    ```txt title="route"
    app/(app)/billing/page.tsx
    ```

    It simulates:

    * current plan
    * seats
    * renewal date
    * subscription status
    * payment method
    * invoice history
    * billing portal action

    This route is designed to feel like a real SaaS billing area before backend wiring exists.
  </Step>

  <Step>
    ### Review the mocked subscription model

    Starter Free uses a mocked subscription object.

    ```tsx title="app/(app)/billing/page.tsx"
    const plan = {
      name: "Pro",
      priceLabel: "€29 / month",
      seats: 10,
      renewalIso: "2026-03-01",
      status: "active",
    };
    ```

    Later, this should be replaced by your backend subscription state.

    ```tsx title="app/(app)/billing/page.tsx"
    const plan = await getCurrentSubscription(user.id);
    ```

    The UI should not need a rewrite when the source changes.
  </Step>

  <Step>
    ### Replace invoices with Stripe-backed data

    Invoice history starts as mock data.

    ```tsx title="app/(app)/billing/page.tsx"
    const MOCK_INVOICES = [
      {
        number: "INV-0001",
        amountCents: 2900,
        status: "paid",
      },
    ];
    ```

    Later, invoices should come from Stripe or from a synchronized invoice table in your database.

    ```ts title="server/billing/invoices.ts"
    export async function listInvoices(customerId: string) {
      return stripe.invoices.list({
        customer: customerId,
        limit: 10,
      });
    }
    ```
  </Step>

  <Step>
    ### Wire the billing portal later

    The frontend should call your backend, not Stripe directly.

    ```txt title="endpoint"
    POST /api/billing/portal
    ```

    Your backend creates the portal session:

    ```ts title="app/api/billing/portal/route.ts"
    const session = await stripe.billingPortal.sessions.create({
      customer: stripeCustomerId,
      return_url: "https://yourapp.com/billing",
    });
    ```

    Then the frontend redirects:

    ```ts title="app/billing/page.tsx"
    window.location.href = session.url;
    ```

    <Callout type="info" title="Security boundary">
      Stripe secret keys must stay on the server. The browser should only receive a session URL created by your backend.
    </Callout>
  </Step>
</Steps>

## Stripe lifecycle

A production billing system usually follows this flow:

```txt title="stripe-lifecycle.txt"
User selects a plan
  ↓
Stripe Checkout opens
  ↓
Payment or subscription is created
  ↓
Stripe sends webhook event
  ↓
Backend verifies event
  ↓
Database subscription state updates
  ↓
App reads updated billing state
```

<DocsConceptTabs
  items={[
  {
    value: 'Checkout',
    title: 'Checkout starts revenue',
    icon: CreditCard,
    description: (
      <>
        <p>
          Checkout creates the initial payment or subscription flow between your product and Stripe.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Checkout session</Badge>
          <Badge variant="outline">Subscription creation</Badge>
          <Badge variant="outline">Backend endpoint</Badge>
          <Badge variant="outline">Payment initiation</Badge>
        </div>
      </>
    ),
  },
  {
    value: 'Webhook',
    title: 'Webhooks synchronize truth',
    icon: Webhook,
    description: (
      <>
        <p>
          Webhooks keep your application aligned with Stripe billing events and subscription state.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Payment success</Badge>
          <Badge variant="outline">Renewals</Badge>
          <Badge variant="outline">Subscription changes</Badge>
          <Badge variant="outline">Cancellation events</Badge>
        </div>
      </>
    ),
  },
  {
    value: 'Portal',
    title: 'Portal manages customers',
    icon: WalletCards,
    description: (
      <>
        <p>
          The billing portal handles customer self-service flows without rebuilding billing management UI.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Payment methods</Badge>
          <Badge variant="outline">Invoices</Badge>
          <Badge variant="outline">Plan changes</Badge>
          <Badge variant="outline">Cancellation flows</Badge>
        </div>
      </>
    ),
  },
]}
/>

## Decision guide

Starter Free is enough when:

* you are validating pricing UX
* you need a credible billing page in a demo
* you want to show plan, invoice, and payment surfaces
* you are not accepting real payments yet

Starter Pro becomes the faster path when:

* real payments are required
* Stripe Checkout must work
* webhooks must update your app
* invoices must reflect real customer history
* subscription status controls product access
* auth and billing need to work together

<Callout title="Ready to turn billing into revenue?">
  Starter Free validates UX.
  Starter Pro lets you **charge customers for real**.

  → <a href="/pricing" className="font-medium underline underline-offset-4">Upgrade to Starter Pro</a>
</Callout>

<PreferAvoid
  prefer={[
  'keep billing UI separate from Stripe implementation',
  'create Checkout and Portal sessions on the server',
  'use webhooks as the lifecycle source of truth',
  'store synchronized billing state in your app database',
  'make billing copy clear, specific, and trustworthy',
]}
  avoid={[
  'calling Stripe secret APIs from the browser',
  'treating UI state as billing truth',
  'skipping webhook verification',
  'unlocking paid features before backend confirmation',
  'hiding payment failures behind vague error messages',
]}
/>

## UX copywriting

Billing pages are high-trust surfaces. Copy should reduce doubt and make money-related actions explicit.

Use clear labels:

* “Manage billing”
* “View invoices”
* “Update payment method”
* “Change plan”
* “Cancel subscription”

Avoid vague labels:

* “Continue”
* “Submit”
* “Open”
* “Confirm”

<Callout title="Conversion principle">
  Billing copy should make the next action obvious. Users should never wonder whether they are starting checkout, opening a portal, changing a plan, or cancelling access.
</Callout>

### Common questions

<Accordions type="single">
  <Accordion title="Why is billing mocked in Starter Free?">
    Because billing architecture depends on real customer state, Stripe products, webhook handling, and backend contracts. Starter Free focuses on validating the billing surface before wiring the engine.
  </Accordion>

  <Accordion title="Can I connect Stripe myself?">
    Yes. Keep Stripe secret logic on the server, create Checkout and Portal sessions through backend endpoints, and use webhooks to update your app state.
  </Accordion>

  <Accordion title="Should the billing page call Stripe directly?">
    No. The billing page should call your backend. Your backend should communicate with Stripe and return safe session URLs or synchronized billing data.
  </Accordion>
</Accordions>

## Next steps

<DocsLinks
  variant="grid"
  items={[
  {
    title: 'Deployment',
    href: '/docs/starter/deployment',
    description:
      'Deploy the starter and understand what stays mocked before production wiring.',
    icon: Rocket,
  },
  {
    title: 'Upgrade to Starter Pro',
    href: '/docs/starter/upgrade',
    description:
      'Move from mocked billing UX to production-shaped auth, billing, backend, and delivery foundations.',
    icon: ArrowUpRight,
    badge: 'Pro',
    tone: 'primary',
  },
  {
    title: 'Starter Pro billing',
    href: '/docs/starter-pro/billing',
    description:
      'Review the production billing foundation when you are ready to wire the business layer.',
    icon: CreditCard,
  },
  {
    title: 'Async actions pattern',
    href: '/docs/patterns/async-actions',
    description:
      'Design payment, portal, retry, and feedback actions with production-ready UX.',
    icon: LoaderCircle,
  },
]}
/>

<Callout title="Upgrade when billing becomes real">
  Starter Free gives you the billing surface.
  Starter Pro gives you the production-ready business layer: auth, Stripe, backend structure, and secure delivery.

  <a href="/docs/starter-pro" className=" no-underline  hover:underline">
    Upgrade to Starter Pro →
  </a>
</Callout>