Functional Weave
Code in TypeScript

payments.stripe-portal@1.0.0

README.md

2,783 bytes · view raw

# payments.stripe-portal

Let a customer manage their own billing in Stripe's hosted customer portal:
change plan, update the card, download invoices, cancel. Create a session for
the signed-in user's Stripe customer and redirect them to its URL; the portal
sends them back to `returnUrl`. `PAYMENTS_PROVIDER` picks the provider, the
same variable `payments.stripe-checkout` reads, so one setting drives both:

- **stripe** calls `POST /v1/billing_portal/sessions` with `STRIPE_SECRET_KEY`.
  What the portal offers (which plans a customer may switch to, whether they
  may cancel) is set in the dashboard's portal settings, or in a portal
  configuration (`bpc_...`) passed as `configuration`.
- **local** needs no Stripe account: the session is a `bps_local_...` id and a
  URL to a page in your own app (`LOCAL_PORTAL_URL`, by default
  `http://localhost:3000/dev/billing-portal`) with `session`, `customer`,
  `return_url` and, when asked for, `flow` and `subscription` in the query.

From a Next.js route handler:

```ts
// app/api/billing/portal/route.ts
import { createPortalSession } from "#fune/payments.stripe-portal@^1";

export async function POST() {
  const user = await currentUser();                 // yours
  const session = await createPortalSession({
    customer: user.stripeCustomerId,                // stored from checkout.session.completed
    returnUrl: "https://app.example/account",
  });
  return Response.redirect(session.url, 303);
}
```

`flow` opens one task directly instead of the portal's home page:
`payment_method_update`, `subscription_cancel` or `subscription_update` (the
last two need `subscription`, a `sub_...` id). The request is checked before
anything is sent (a `cus_...` customer, an absolute return URL, `bpc_...`,
`sub_...` and locale shapes), and Stripe's error object is thrown in words:
`stripe refused the portal session (400 resource_missing, param customer):
No such customer: 'cus_Missing'`. A portal session URL is short-lived and
single-customer: create one per click, never cache or email it.

The portal changes subscriptions in Stripe; your app learns of it from the
`customer.subscription.*` and `invoice.*` webhooks (verify them with
`payments.stripe-checkout`'s `verifyWebhook`, then fold them into your
stored state with `subscriptions.stripe-state`).

The recorded exchanges in `contracts.json` are shaped from Stripe's API
reference for the billing portal session object and its create endpoint
(docs.stripe.com/api/customer_portal/sessions/create), with fake test keys;
no call was made to Stripe. Send one real request with a test key from
staging before going live.

Out of scope: creating portal configurations, customers or subscriptions
(do that in the dashboard or with Stripe's SDK), and Connect accounts.