# Subscriptions and payments

Shipwave PDF sells its own PDF workspace and API. Stripe Checkout collects recurring payments, Billing manages renewals and payment recovery, the customer portal manages payment methods and plan changes, and Stripe creates subscription invoices. Supabase stores entitlement and usage records. Railway is a replaceable application host; it is not the account or billing database.

## Catalog

The database contains a free account and three monthly paid plans. All prices are **CAD, before applicable tax**:

- Free: 100 web operations, 100 API operations, 10 requests/minute and 1 API key. Core PDF APIs and basic native editor tools.
- Starter, CAD $9/month: 1,000 web operations, 2,000 API operations, 30 requests/minute and 3 API keys. Adds Office conversion, OCR and PDF/A; native advanced text/image/form editing and the corresponding native conversion tools.
- Pro, CAD $19/month: 5,000 web operations, 20,000 API operations, 120 requests/minute and 10 API keys. Adds AI, signing invitations and native certificate-signing access.
- Business, CAD $49/month: 25,000 web operations, 100,000 API operations, 300 requests/minute and 25 API keys. Includes the same feature groups as Pro.

AI and invitation tools additionally require their respective server provider credentials. A paid plan does not supply those credentials. A successful processing request counts as one operation, regardless of page count. Quotas reset on UTC calendar months, independently of the Stripe renewal date. Failed operations return their monthly allocation; the request still counts toward the minute limit.

Native editing runs locally and is unmetered within its subscription feature access. Server/API processing retains the monthly quotas above; a native HTTP processing batch counts as one request in the corresponding existing web/API channel. The native editor uses short signed feature leases, while HTTP execution checks entitlements on the server. See [native editor access](ACCOUNTS.md#native-editor-subscription-access) for groups, owner overrides and the signing-key/build setup.

Manage prices, availability, quotas and feature arrays directly in `shipwave_plans` through the Supabase dashboard. Manage individual exceptions in `shipwave_account_overrides`. There is no public admin interface. See [Accounts](ACCOUNTS.md) for exact fields and examples.

The existing `features` column controls the original APIs. The independent `native_features` column controls the native editor and its HTTP operation catalog. A change to native features does not alter an API feature allowance, create a new Stripe subscription or change the CAD price. `GET /api/billing/plans` exposes both `features` and `nativeFeatures`; the account's effective `limits.nativeFeatures` includes owner exceptions. Empty native features disable editor mutations while preserving independently allowed API tools.

## Initial setup

1. Apply the migrations in `supabase/migrations` to your Supabase project and configure the three server credentials shown in `.env.example`.
2. Set `APP_BASE_URL`, `STRIPE_SECRET_KEY` and `STRIPE_PUBLISHABLE_KEY`. Begin with Stripe test keys. Keep secret keys on the server.
3. Run `npm run billing:setup`. This creates or validates only Shipwave's three recurring products/prices, records their Price IDs in Supabase, and creates/updates Shipwave's customer portal configuration. It saves `STRIPE_PORTAL_CONFIGURATION_ID` in the local private `.env`. Put that ID in your deployment variables too.
4. For local development, install the official Stripe CLI and run `npm run stripe:listen` in a separate terminal. The helper saves its signing secret privately. Restart the app after the helper reports ready. An optional project-local CLI is detected under `.runtime/stripe-tools`.
5. In production, create an HTTPS Stripe webhook endpoint at `https://YOUR-APP/api/billing/webhook` and set its distinct signing secret as `STRIPE_WEBHOOK_SECRET`. A local listener secret cannot verify a production endpoint's events.
6. Run `npm start`. Sign in, open Account → Plan & billing, and choose a plan. Payment fields are hosted by Stripe.

Webhook events to enable:

```text
checkout.session.completed
checkout.session.async_payment_succeeded
checkout.session.async_payment_failed
customer.subscription.created
customer.subscription.updated
customer.subscription.deleted
customer.subscription.paused
customer.subscription.resumed
invoice.paid
invoice.payment_failed
charge.dispute.created
charge.refunded
radar.early_fraud_warning.created
```

Use Stripe API version `2026-10-28.endive`, matching the pinned server SDK. Webhook signature verification runs on the original request bytes. Failed processing returns a retryable error; Stripe retries delivery. Supabase records processed event IDs and ignores stale state updates. The application does not store card details.

## Payment truth and plan changes

Returning from Checkout does not grant paid access. Verified events retrieve the canonical subscription from Stripe, identify its customer using the server's Supabase mapping, and atomically update the subscription. Access requires an active or trialing subscription with an unexpired paid period and no billing hold. Past-due, unpaid, paused, expired and canceled subscriptions receive free limits. An account with cancellation scheduled retains its plan through the current paid period.

An `active` Stripe subscription also requires its canonical latest invoice to be `paid` before new paid access is granted. Delayed payment methods can report `active` while payment is pending or failed; the local entitlement status remains `incomplete` in that case. During a pending renewal or upgrade, a previously confirmed, unexpired paid plan and its existing period remain available without extending the period or granting the unpaid upgrade. A later paid invoice synchronizes the new plan and period. Trials remain explicitly allowed. See [Stripe's delayed payment behavior](https://docs.stripe.com/billing/subscriptions/overview#delayed-payment-confirmation).

Checkout has a shared database lease to prevent concurrent duplicate subscriptions. Customers with an existing subscription use the portal instead. The portal invoices upgrades immediately, schedules price reductions at period end and offers cancellation at period end. Payment outcomes and subscription state still determine access. Stripe handles renewals; do not add a renewal cron job or process payments yourself.

Changing a plan's amount/currency in Supabase creates a new immutable Stripe Price on the next checkout. Run `npm run billing:setup` again after changes to refresh portal choices. Existing subscribers keep their agreed Stripe Price until they change plans. Price ownership and recurrence are validated before Checkout.

Full refunds of the current invoice, disputes and early fraud warnings place an account on a billing hold for owner review. Refunds of older invoices do not reset a newer paid subscription. A risk event cannot overwrite the newer subscription's identity. Review Stripe records and clear `billing_hold`/`risk_reason` in Supabase only when the issue is resolved; an ordinary later invoice event does not silently clear a hold.

## Tax and launch state

The configured account is a **Stripe test account**. Prices use exclusive tax behavior. The business location supplied is Alberta, Canada, and the owner confirmed GST/HST registration. Automatic tax collection remains disabled until the legal business/head-office address and applicable registration details are configured in Stripe. No tax registration has been invented or submitted.

After completing that setup in Stripe, set `STRIPE_AUTOMATIC_TAX=true`. Checkout then collects a billing address/tax ID and calculates applicable tax in addition to the advertised price. If the flag is enabled before Stripe Tax settings and an active registration are ready, Checkout fails closed with setup guidance. Test and live Tax settings are separate.

Before accepting real payments, complete Stripe activation, public policies, business details and any applicable tax setup. Configure the live credentials, a live catalog/portal, and the live HTTPS webhook. Keep test and live Supabase billing data isolated, preferably in separate Supabase projects; do not point live payments at subscription rows containing test Stripe IDs.

Stripe Connect is not used by this application: Shipwave collects its own subscription revenue and does not onboard or pay third-party sellers. Add Connect only if a future marketplace actually requires seller accounts/payouts. Subscription invoices are provided through Billing and the portal; no duplicate standalone invoice is created for the same renewal.

## API

- `GET /api/billing/plans`: public catalog and readiness flags from Supabase.
- `POST /api/billing/checkout`: signed-in user only; JSON `{ "planId": "starter" }`, `pro` or `business`. Returns a hosted `url`.
- `POST /api/billing/portal`: signed-in user only; returns that user's customer portal URL.
- `GET /api/billing/invoices`: signed-in user only; returns that user's latest 24 invoices.
- `POST /api/billing/webhook`: verified Stripe delivery only. The body must remain raw.

Checkout/portal return `{"success":true,"url":"..."}`. Invoices return `{"success":true,"invoices":[...]}`; amounts use currency minor units and creation times use Unix seconds. Webhooks return `{"received":true}`, without a `success` wrapper. Public catalog flags include `testMode`, `checkoutReady` and `taxReady`; tax readiness does not mean the automatic-tax environment flag is enabled. The browser's Plan & billing tab uses exactly these APIs. [API examples](API.md#billing-api) and the machine-readable [OpenAPI specification](openapi.json) include success/error schemas, authentication and request parameters.

User API keys cannot administer billing, create keys or access another account's profile. Account management uses a verified Supabase session.

## Verification

`test/billing.test.js` uses Stripe's real signature verifier and isolated mocks for customer ownership, session-only billing, price validation, concurrent Checkout, paid-state synchronization, duplicate/out-of-order events, historical-subscription events, refunds/fraud holds, API versions and flexible cancellation. It makes no paid requests. Account/RLS/atomic quota checks run against isolated Postgres through PGlite in `test/accounts.test.js`.

Official implementation references: [hosted subscriptions](https://docs.stripe.com/billing/subscriptions/build-subscriptions), [webhooks](https://docs.stripe.com/webhooks), [customer portal](https://docs.stripe.com/customer-management), [Stripe Tax](https://docs.stripe.com/tax), and [Supabase production email](https://supabase.com/docs/guides/auth/auth-smtp).
