# Billing

> The plan and usage page of an AI product. Handles credits running out mid-cycle, plan changes with proration and card errors.

Canonical: https://hextaui.com/blocks/billing
Last updated: 2026-10-29

## Overview

Billing is the Plan & usage section of an AI product’s settings. It drops into a SettingsShell section and covers what people come to that page for: how much they’ve used, whether it will last, what they pay, and how to change it.

The usage meter fills by model, with a lighter extension showing where the cycle will likely end at the pace of the last 7 days. When that runs past the included credits, a quiet note says when: “At this pace you’ll run out around Oct 24, 4 days before your credits reset”, with ways to turn on extra usage or see plans. Below it, a daily bar chart built on Chart covers the whole cycle: past days, today in full strength, the rest of the cycle as faint projected bars at your recent pace, and a dashed line for the even pace that would last the cycle. Hover or focus it and use the arrow keys to read any day.

Limits are a draft, like every other settings section. Drag the alert threshold or turn on extra usage and the markers move on the meters straight away, the extra usage meter slides in, and the save bar rises. A limit lower than what was already spent this cycle is refused with the amount.

Upgrades show the exact proration before anything is charged: the new plan for the days left, the unused days of the current one, and “You’ll pay $13.33 today”. Downgrades wait until the end of the period and list what goes away. Canceling is one honest confirmation with no offers, the plan stays on until the period ends, and Keep Pro undoes it until then.

The card form formats numbers as you type without moving the cursor, checks them with Luhn, detects the brand, and validates the expiry and security code. Invoices have status badges, Pay now for failed ones, and download as real PDF files.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/billing
```

## Usage

### Wire it to your API

BillingSettings shows the data you pass and calls you back for every change. Return or throw from a callback: a thrown message shows in the dialog that asked, and nothing changes until you pass new props.

```tsx
"use client"

import * as React from "react"

import { SettingsSection, SettingsShell } from "../settings/settings"
import {
  BillingSettings,
  BillingSettingsSkeleton,
  type BillingSettingsProps,
} from "@/components/blocks/billing/billing-settings"

type BillingData = Pick<
  BillingSettingsProps,
  "plans" | "subscription" | "usage" | "spendLimit" | "paymentMethod" | "invoices" | "today"
>

async function post(url: string, body: unknown = {}) {
  const response = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  })
  if (!response.ok) {
    const { message } = await response.json().catch(() => ({ message: "" }))
    throw new Error(message || "Try again in a moment.")
  }
}

export function BillingPage() {
  const [data, setData] = React.useState<BillingData | null>(null)
  const [failed, setFailed] = React.useState(false)

  const load = React.useCallback(async () => {
    setFailed(false)
    try {
      const response = await fetch("/api/billing")
      if (!response.ok) throw new Error()
      setData(await response.json())
    } catch {
      setFailed(true)
    }
  }, [])

  React.useEffect(() => {
    void load()
  }, [load])

  const then = (url: string) => async (body?: unknown) => {
    await post(url, body)
    await load()
  }

  return (
    <SettingsShell sections={[{ id: "billing", label: "Plan & usage" }]}>
      <SettingsSection
        id="billing"
        status={failed ? "error" : data ? "ready" : "loading"}
        skeleton={<BillingSettingsSkeleton />}
        onRetry={load}
      >
        {data ? (
          <BillingSettings
            {...data}
            customer={{ name: "Mia Chen", email: "mia@example.com" }}
            onChangePlan={then("/api/billing/plan")}
            onCancelPlan={then("/api/billing/cancel")}
            onResumePlan={then("/api/billing/resume")}
            onSpendLimitChange={then("/api/billing/limit")}
            onPayInvoice={(invoice) => then("/api/billing/pay")({ id: invoice.id })}
          />
        ) : null}
      </SettingsSection>
    </SettingsShell>
  )
}
```

### Card updates

onUpdatePaymentMethod gets clean digits, the expiry, the security code and the brand once the form passes its checks. Throw to show a decline in the dialog. In production, hand the details to your payment provider’s tokenization and never store them yourself.

```tsx
"use client"

import * as React from "react"

import { BillingSettings, type BillingSettingsProps } from "@/components/blocks/billing/billing-settings"

export function BillingWithStripe(props: BillingSettingsProps) {
  return (
    <BillingSettings
      {...props}
      onUpdatePaymentMethod={async (card) => {
        const response = await fetch("/api/billing/card", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(card),
        })
        if (response.status === 402) {
          throw new Error("Your bank declined this card. Try another card.")
        }
        if (!response.ok) throw new Error("We couldn’t save that card. Try again.")
      }}
    />
  )
}
```

### Your own invoice files

Invoices download as PDFs built in the browser from the invoice data. Return a Blob from onDownloadInvoice to serve your own file instead, or give an invoice an href.

```tsx
"use client"

import * as React from "react"

import { BillingSettings, type BillingSettingsProps } from "@/components/blocks/billing/billing-settings"

export function BillingWithServerInvoices(props: BillingSettingsProps) {
  return (
    <BillingSettings
      {...props}
      seller="Acme Labs, Inc."
      onDownloadInvoice={async (invoice) => {
        const response = await fetch(`/api/invoices/${invoice.id}/pdf`)
        if (!response.ok) throw new Error("That invoice isn’t ready yet.")
        return response.blob()
      }}
    />
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `BillingSettings` | The section content: plan summary, usage meters and the daily Chart, limits, plans, payment, invoices and cancel, with their dialogs. |
| `BillingSettingsSkeleton` | A loading placeholder shaped like the section. Pass it to SettingsSection’s skeleton. |
| `prorate` | The proration math behind the upgrade dialog, for your server or tests. |
| `forecastUsage` | The projection behind the meter and the run-out note. |
| `createInvoicePdf` | Builds the invoice PDF as a Blob. |

## API reference

### BillingSettings

Prices are in cents and dates are ISO days like 2026-10-28. Leave out a callback to hide its action.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `plans` | `BillingPlan[]` | – | { id, name, price, included, description?, features }. Features are full lists per plan, so a downgrade can list what’s missing. A plan with price 0 is the plan people move to when they cancel. |
| `subscription` | `BillingSubscription` | – | { planId, periodStart, periodEnd, status?, cancelAtPeriodEnd?, scheduledPlanId? }. |
| `usage` | `BillingUsage` | – | { models: { id, name, used }[], daily: { date, used }[], extraRate, unit? }. extraRate is cents per unit beyond what’s included. unit defaults to "credits". |
| `spendLimit` | `BillingSpendLimit` | – | { enabled, limit, alertAt }. limit is in cents and alertAt is a percentage. |
| `paymentMethod` | `BillingPaymentMethod \| null` | – | { brand, last4, expMonth, expYear, name? }. |
| `invoices` | `BillingInvoice[]` | `[]` | { id, number, date, description, amount, status, href?, lines?, paidWith? }. status is paid, open, failed, refunded or void. |
| `today` | `string` | `the last daily date` | The day your server considers today. Used for proration, projections and card expiry, so server and browser agree. |
| `currency` | `string` | `"USD"` | Any ISO currency code. |
| `seller` | `string` | `"Hexta"` | The name at the top of generated invoices. |
| `customer` | `{ name?, email? }` | – | Printed under Bill to on generated invoices. |
| `onChangePlan` | `(change) => void \| Promise` | – | Called with { planId, when, amountDue }. when is "now" for upgrades and "period_end" for downgrades. |
| `onCancelPlan` | `() => void \| Promise` | – | Cancel at the end of the period. |
| `onResumePlan` | `() => void \| Promise` | – | Undo a cancellation or a scheduled downgrade. |
| `onSpendLimitChange` | `(limit) => void \| errors \| Promise` | – | Save the limits. Return { limit: message } to show a field error. |
| `onUpdatePaymentMethod` | `(card) => void \| Promise` | – | Called with { number, expMonth, expYear, cvc, name, brand } once the form is valid. Throw to show a decline. |
| `onPayInvoice` | `(invoice) => void \| Promise` | – | Adds Pay now to open and failed invoices. |
| `onDownloadInvoice` | `(invoice) => Blob \| void \| Promise` | – | Return a Blob to download your own file, or nothing if you handled it. Without it, a PDF is built from the invoice. |

### prorate

Returns { kind, amountDue, charge, credit, daysLeft, totalDays, effectiveDate, nextBillingDate }.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `options` | `{ from, to, periodStart, periodEnd, today }` | – | Upgrades charge the price difference for the days left, rounded once. Downgrades charge nothing and start at periodEnd. Moving off a free plan charges a full month from today. |

## Keyboard

| Key | Action |
| --- | --- |
| `←` `→` | With the daily chart focused, move the tooltip to the previous or next day. |
| `Enter` | In the card form, check the details and save. |
| `⌘` `S` | Saves changed limits. Ctrl+S on Windows and Linux. |

## Accessibility

- Meters use role meter with a value text that includes the projection and the alert threshold, and the model breakdown is a real list.
- The daily chart is a figure named “Daily usage this cycle”, described by a summary with the total, the recent daily average, the busiest day and the even pace. A visually hidden table lists every day, with projected days marked as estimates.
- Plan changes, cancellations, card updates and downloads are announced politely. Failures show in the dialog that asked, as an alert, and the dialog stays open with your input.
- Card fields use the standard autocomplete tokens, so browsers and password managers can fill them. The first invalid field gets focus.
- Inputs are 16px on touch screens so iOS doesn’t zoom, and buttons grow to 44px.
- Numbers and dates are formatted in English with fixed time zones, so the server and the browser render the same text.

## Built with

The free HextaUI components Billing is made from. Each one installs on its own.

- [Alert](https://hextaui.com/docs/alert) - Inline messages for status and feedback, with a neutral surface, a colored icon and a dismiss that collapses smoothly.
- [Alert dialog](https://hextaui.com/docs/alert-dialog) - A confirmation dialog for destructive or important actions that waits for async work, and becomes a bottom sheet on phones.
- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Chart](https://hextaui.com/docs/chart) - Recharts charts with themed colors, a tooltip and legend that read labels from one config, and keyboard navigation with a visible focus ring.
- [Collapsible](https://hextaui.com/docs/collapsible) - A panel that shows and hides with height motion you can reverse mid-way, without jumping the layout.
- [Dialog](https://hextaui.com/docs/dialog) - A window over the page for forms and focused tasks, with a pinned header and footer, nesting, and a swipeable bottom sheet on phones.
- [Field](https://hextaui.com/docs/field) - Labels, descriptions and errors wired to their control, with validation states and layouts for forms.
- [Input](https://hextaui.com/docs/input) - A text input with three sizes, invalid and read-only states, native validation styling and a 16px touch font so phones never zoom in.
- [Input group](https://hextaui.com/docs/input-group) - An input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- [Skeleton](https://hextaui.com/docs/skeleton) - Placeholders that wait 150ms before showing, take the exact size of the content they wrap, and fade it in without moving anything.
- [Slider](https://hextaui.com/docs/slider) - Pick a value or a range by dragging, tapping the track or using the keys, with jumps that glide and an optional value bubble.
- [Switch](https://hextaui.com/docs/switch) - An on/off toggle you can tap, press or drag, with a thumb that stretches under your finger and an optional pending state for saves.
- [Table](https://hextaui.com/docs/table) - A responsive table with a surface style, wrapping or compact cells, sticky headers, pinned columns and scroll hints.

## Code

4 files, added to components/blocks/billing.
