# Selling Plans to Your Customers

A Perspect site can run a complete SaaS business for its own customers: a pricing page, subscriptions with trials, add-ons and plan changes, features that each plan unlocks, team accounts with seats and invitations, usage-based pricing, and prepaid credit. Payments go through Stripe on your site's own Stripe account, connected to Perspect with Stripe Connect. Perspect keeps the subscriptions in step with Stripe, so your app asks Perspect, not Stripe, what a customer may do.

This guide uses the TypeScript SDK (`perspectapi-ts-sdk`). There are two sides:

- **`client.billing`** is your team's side: the catalog, settings, and acting on any customer or account. It needs an API key. Reads need `products.read`, `settings.read` or `users.read`, and writes the matching `.update` permission (catalog, settings, and customers' billing respectively).
- **`client.customerBilling`** is a signed-in customer's own side, for your app's pages. It needs the customer's session (`client.setAuth(jwt)`), and a customer only ever sees their own billing and the accounts they belong to.

## 1. Connect Stripe

Connect your site's Stripe account in the site's payment settings. Until a site has a connected account, every billing call that needs Stripe answers `409 stripe_not_connected`; nothing is ever billed on Perspect's own account.

Your site's payment mode (test or live) decides which Stripe mode is used. A plan's product must be synced to Stripe before you price it, and a price is created in each mode the product is synced to, so sync products in both modes and you can build the catalog in test mode and go live without rebuilding it. Selling a price that has no Stripe price in the current mode is refused with `409 price_not_synced`.

You do not set up Stripe webhooks. Stripe sends events to Perspect, which updates subscriptions, grants credit from paid credit packs, and emails customers.

## 2. Build the catalog

A plan is an ordinary Perspect product given a subscription role:

- `plan`: what a customer subscribes to. One plan per subscription.
- `addon`: an extra a customer adds to a plan's subscription (more storage, an extra seat pack).
- `credit_pack`: prepaid credit bought once.

```typescript
import { PerspectApiV2Client } from 'perspectapi-ts-sdk';

const client = new PerspectApiV2Client({
  baseUrl: 'https://api.perspect.com',
  apiKey: process.env.PERSPECT_API_KEY,
});

await client.billing.setProductRole('my-site', 'prod_12', { subscription_role: 'plan' });

// A monthly price with a 14-day trial.
const pro = await client.billing.createPrice('my-site', 'prod_12', {
  currency: 'usd',
  unit_amount: 2900,
  recurring: { interval: 'month' },
  trial_period_days: 14,
});

// The yearly price of the same plan.
await client.billing.createPrice('my-site', 'prod_12', {
  currency: 'usd',
  unit_amount: 29000,
  recurring: { interval: 'year' },
});
```

Prices are created in Stripe on your connected account. A price's amount never changes: to change what a plan costs, archive the old price (`updatePrice(..., { active: false })`) and create a new one. Existing subscribers stay on the price they bought until they change plan.

Prices can also be tiered (`billing_scheme: 'tiered'`, `tiers_mode: 'graduated'` or `'volume'`), metered (see section 7), or limited in quantity (`min_quantity`, `max_quantity`). A trial can require a payment method up front or not (`trial_requires_payment_method`), and can cancel, pause or invoice when it ends (`trial_end_behavior`).

## 3. Say what each plan unlocks

Features are the things your app checks. A feature is either `boolean` (on or off) or a `limit` (a number, such as projects or seats).

```typescript
await client.billing.createFeature('my-site', { key: 'export', name: 'Export to CSV' });
await client.billing.createFeature('my-site', {
  key: 'projects',
  name: 'Projects',
  value_type: 'limit',
});

await client.billing.setPlanFeatures('my-site', 'prod_12', [
  { key: 'export' },
  { key: 'projects', limit: 50 },
]);
```

`setPlanFeatures` replaces the plan's whole list. A limit marked `per_unit: true` is multiplied by the subscription's quantity, which is how per-seat plans work (section 6). `unlimited: true` removes the limit.

### The free plan

Name one plan as the free plan, and everyone without a subscription has its features:

```typescript
await client.billing.updateSettings('my-site', { default_plan_id: 'prod_3' });
```

### Grants

A grant gives one customer or account a feature outside their plan: a pilot, a goodwill extra, an enterprise deal. It adds to what their plans give and can expire.

```typescript
await client.billing.createGrant('my-site', {
  feature: 'projects',
  account_id: 'acct_...',
  limit: 100,
  reason: 'Enterprise pilot',
  expires_at: '2027-01-31T00:00:00Z',
});
```

## 4. A pricing page and checkout

On your site, list the published plans and send the customer to Stripe Checkout:

```typescript
client.setAuth(customerJwt);

const plans = await client.customerBilling.listPlans('my-site');
// Each plan: name, description, prices, features, is_default_plan.

const session = await client.customerBilling.createCheckout('my-site', {
  price_id: pro.id,
  addons: [{ price_id: 'prc_40', quantity: 1 }],
  success_url: 'https://my-site.com/billing?checkout=done',
  cancel_url: 'https://my-site.com/pricing',
});
// Redirect the customer to session.url.
```

`listPlans` shows only published products. A customer gets a plan's trial once, on their first subscription (turn this off with `subscription_settings.checkout.one_trial_per_customer`). Pass `trial: false` to skip the trial. Promotion codes can be allowed at checkout with `subscription_settings.checkout.allow_promotion_codes`.

## 5. Check what a customer may do

Ask for the customer's entitlements and gate on them:

```typescript
const ent = await client.customerBilling.getEntitlements('my-site');

const canExport = ent.features['export'].enabled;
const projects = ent.features['projects'];
const atLimit = !projects.unlimited && myProjectCount >= (projects.limit ?? 0);
```

Every feature of the site is in `features`, each with `enabled`, `limit` and `unlimited`, so a feature the customer does not have reads as not enabled rather than missing. `sources` lists the subscriptions (or the free plan) the features come from.

A customer's own entitlements include what their active team accounts give them, and limits from several sources add up. To ask about one account alone, pass `{ account_id }`. Your back end can read the same thing with `client.billing.getUserEntitlements` or `getAccountEntitlements`.

A customer keeps their plan while a trial runs and, if a payment fails, for the grace period you set (`subscription_settings.dunning`: `past_due_access: 'keep'` with `grace_period_days`, or `'revoke'` to remove access at once).

## 6. Change plans, add-ons and the billing portal

```typescript
// What an upgrade costs today, before making it.
const preview = await client.customerBilling.previewPlanChange('my-site', 'sub_...', {
  price_id: 'prc_business_monthly',
});

// Upgrade now (prorated), or downgrade at the end of the period.
await client.customerBilling.changePlan('my-site', 'sub_...', {
  price_id: 'prc_starter_monthly',
  timing: 'period_end',
});

// Add, resize and remove add-ons.
await client.customerBilling.addSubscriptionItem('my-site', 'sub_...', { price_id: 'prc_40' });
await client.customerBilling.updateSubscriptionItem('my-site', 'sub_...', 'si_...', { quantity: 3 });
await client.customerBilling.removeSubscriptionItem('my-site', 'sub_...', 'si_...');

// Stripe's portal: payment methods, invoices, cancellation.
const portal = await client.customerBilling.createPortalSession('my-site', {
  return_url: 'https://my-site.com/billing',
});
```

A scheduled downgrade shows on the subscription as `scheduled_change`, and `cancelScheduledChange` undoes it. Each change takes `proration_behavior` (`create_prorations` by default, `always_invoice` or `none`).

## 7. Team accounts and seats

Customers can create team accounts, invite people, and subscribe as the team. A customer who creates an account is its owner. Roles are `owner`, `admin` and `member`: owners and admins manage billing and members, members use what the account pays for, and only an owner deletes the account.

```typescript
const account = await client.customerBilling.createAccount('my-site', { name: 'Acme' });

// Subscribe the account rather than the customer.
await client.customerBilling.createCheckout('my-site', {
  price_id: 'prc_team_monthly',
  quantity: 5, // seats
  account_id: account.id,
  success_url: 'https://my-site.com/team?checkout=done',
  cancel_url: 'https://my-site.com/pricing',
});

const invite = await client.customerBilling.inviteToAccount('my-site', account.id, {
  email: 'sam@acme.com',
  role: 'member',
});
```

### Seats

To limit seats, create a `limit` feature, give per-seat plans that feature with `per_unit: true`, and name it as the seat feature:

```typescript
await client.billing.createFeature('my-site', { key: 'seats', name: 'Seats', value_type: 'limit' });
await client.billing.setPlanFeatures('my-site', 'prod_team', [{ key: 'seats', limit: 1, per_unit: true }]);
await client.billing.updateSettings('my-site', {
  subscription_settings: { seats: { feature_key: 'seats' } },
});
```

An account then has as many seats as its entitlement to that feature: a quantity-5 subscription gives 5, and seat add-ons, grants and the free plan add to it. Members and open invitations take seats, and an invitation beyond the limit is refused with `409 seat_limit_reached`. `getAccount` reports `seats: { used, limit }`.

### Invitations

Set the page on your site that accepts invitations, and Perspect emails each invitation with a link to it carrying `?token=`:

```typescript
await client.billing.updateSettings('my-site', {
  subscription_settings: { invitations: { accept_url: 'https://my-site.com/join' } },
});
```

Only your team sets this page; customers who invite cannot choose where the email links. Without it, nothing is emailed, and you deliver `invite.token` (returned once, when the invitation is created) yourself.

On the accept page, once the invited person is signed in:

```typescript
await client.customerBilling.acceptInvitation('my-site', tokenFromUrl);
```

The person's email must match the invitation's and be verified (`invitation_email_mismatch`, `email_not_verified`).

Your team can also create accounts for a customer, add members directly, change roles, and suspend an account (`client.billing.createAccount`, `addAccountMember`, `updateAccount(..., { status: 'suspended' })`). A suspended account no longer counts toward its members' entitlements, and takes no new members or invitations.

## 8. Usage-based pricing

Create a meter for each thing you charge by use, then a metered price on it:

```typescript
const meter = await client.billing.createMeter('my-site', {
  event_name: 'api_calls',
  display_name: 'API calls',
  aggregation: 'sum',
});

await client.billing.createPrice('my-site', 'prod_12', {
  currency: 'usd',
  billing_scheme: 'tiered',
  tiers_mode: 'graduated',
  tiers: [
    { up_to: 10000, unit_amount: 0 },
    { up_to: null, unit_amount: 1 },
  ],
  recurring: { interval: 'month', usage_type: 'metered', meter_id: meter.id },
});
```

Report usage from your back end as it happens, for a customer or an account (exactly one):

```typescript
await client.billing.recordUsage('my-site', {
  meter: 'api_calls',
  account_id: 'acct_...',
  value: 1,
  identifier: requestId, // your own id for this event
});
```

Recording is idempotent by `identifier`: sending the same one again answers with the stored event and `duplicate: true`, so retry freely. Usage is sent to Stripe as a Billing Meter event. A report is answered once it is stored, even if Stripe did not take it (`provider_status: 'failed'`). Perspect resends it every few minutes at first, backing off, for up to a day after its first send, which is as long as Stripe recognizes a repeat. If it gives up (or Stripe refuses the report as invalid), the report keeps `provider_status: 'failed'` with `next_attempt_at: null`, and your site's webhooks get `usage.report_failed`. List those with `client.billing.listUsage('my-site', { provider_status: 'failed' })`. Usage recorded before a customer has a Stripe customer is kept (`provider_status: 'skipped'`) and sent when they first check out, if it is within Stripe's 35-day window. A `timestamp` must be within the past 35 days.

Show customers their usage with `client.customerBilling.getUsage('my-site', { meter: 'api_calls' })` (the last 30 days by default, or pass `start` and `end`).

## 9. Credit

### Credit packs

A credit pack is a product with the `credit_pack` role, a one-time price, and the credit each unit grants:

```typescript
await client.billing.setProductRole('my-site', 'prod_20', {
  subscription_role: 'credit_pack',
  credit_grant_cents: 5000,
});
await client.billing.createPrice('my-site', 'prod_20', { currency: 'usd', unit_amount: 4500 });

// A customer buys it.
const pack = await client.customerBilling.createCreditPackCheckout('my-site', {
  price_id: 'prc_...',
  success_url: 'https://my-site.com/billing?credit=added',
  cancel_url: 'https://my-site.com/billing',
});
```

When the payment completes, the credit is added to the customer's (or account's) Stripe balance, and Stripe takes it off their next invoices, including usage charges. A credit pack is not a store order: it sends no order emails or order webhooks.

### Adjusting an account's credit

Your team can add or take away an account's credit, for goodwill or a refund:

```typescript
await client.billing.adjustAccountCredits('my-site', 'acct_...', {
  amount_cents: 2500,
  currency: 'usd',
  description: 'Sorry about the outage',
  idempotency_key: 'outage-2026-11-18-acct_123',
});

const credit = await client.billing.getAccountCredits('my-site', 'acct_...');
// credit.balance_cents and credit.ledger
```

Reusing an idempotency key with a different amount is refused (`409 idempotency_key_reused`).

## 10. Webhooks and emails

Your site's outgoing webhooks receive `subscription.created`, `subscription.updated`, `subscription.canceled`, `subscription.trial_will_end`, `subscription.payment_failed` and `subscription.payment_action_required`. Each carries the subscription, including its `account_id` when it bills an account. They also receive `usage.report_failed` when Perspect stops trying to send a usage report to Stripe (section 8).

Perspect also emails the customer three days before a trial ends, when a payment fails, and when a payment needs them to confirm it. Each email can be turned off:

```typescript
await client.billing.updateSettings('my-site', {
  subscription_settings: {
    notices: { trial_will_end: true, payment_failed: true, payment_action_required: false },
  },
});
```

`updateSettings` merges what you send into the current settings, so send only what changes.

## Errors

Billing calls answer with the usual v2 error shape, thrown by the SDK as `PerspectV2Error` with `status` and `code`. The ones you are most likely to handle:

| Code | Status | Meaning |
|------|--------|---------|
| `stripe_not_connected` | 409 | The site has no connected Stripe account. |
| `price_not_synced` | 409 | The price has no Stripe price in the site's current mode. |
| `seat_limit_reached` | 409 | The account has no free seat for another member or invitation. |
| `invitation_email_mismatch` | 403 | The signed-in customer is not the person invited. |
| `email_not_verified` | 403 | The customer must verify their email before joining. |
| `idempotency_key_reused` | 409 | The key was used before with a different amount. |
| `subject_required` | 400 | Give `site_user_id` or `account_id` (for usage, exactly one). |
| `not_an_account_member` | 400 | A team checkout's `site_user_id` is not a member of the account. |

An account or subscription a customer cannot see answers 404, the same as one that does not exist.
