payments.stripe-portal
Open Stripe's customer portal so a customer manages plan, card and invoices, with a local stand-in.
Integration · does I/O It talks to stripe or local, reads 1 secret from the environment, and is tested by contract tests on recorded exchanges, offline. Providers and environment.
TypeScript only A Python or Rust project cannot use it.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 19 contract tests on recorded exchanges, offline, run in TypeScript · per provider: stripe 13, local 5.
What it does
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.
For example
createPortalSession(customer cus_NffrFeUfNV2Hib, return url https://app.example/account, configuration bpc_1MAhNDLkdIwHu7ix, locale en-GB, idempotency key portal-u42-1)→ provider stripe, id bps_1MAhNDLkdIwHu7ixckACO1Jq, url https://billing.stripe.com/p/session/test_YWNjdF8xTTJKVGtMa2RJd0h1N2l4LF9OZmZyR3ZjS2xsZW1oQ0NUbE1Ec1NNTUxIb3VtZGt60100, retur… stripe: the portal home page for a customer, with a configuration, locale and idempotency keycreatePortalSession(customer cus_NffrFeUfNV2Hib, return url https://app.example/billing?tab=plan)→ provider stripe, id bps_1PzPlain, url https://billing.stripe.com/p/session/test_YWNjdF8xTTJKVGtMa2RJd0h1N2l4LF9OZmZyR3ZjS2xsZW1oQ0NUbE1Ec1NNTUxIb3VtZGt60100, return url https://ap… stripe: nothing optional, the exact form bodycreatePortalSession(customer cus_NffrFeUfNV2Hib, return url https://app.example/account, flow subscription_cancel, subscription sub_1MowQVLkdIwHu7ixeRlqHVzs)→ provider stripe, id bps_1PzCancel, url https://billing.stripe.com/p/session/test_YWNjdF8xTTJKVGtMa2RJd0h1N2l4LF9OZmZyR3ZjS2xsZW1oQ0NUbE1Ec1NNTUxIb3VtZGt60100, return url https://a… stripe: straight into cancelling one subscription
The function
Implemented in TypeScript only.
TypeScript only. This capability has no Rust implementation, so it is shown in TypeScript. A Rust project cannot use it: fune build stops and names where it was required. Your choice of Rust is kept for every other page.
export async function createPortalSession(request: PortalRequest): Promise<PortalSession>
| request | PortalRequest | whose portal to open, where they come back to, and optionally one flow to go straight into |
| returns | PortalSession | the session's id and the URL to send the customer to; it is short-lived, so redirect at once |
The types it declares, generated into your project
export type PortalFlow = "payment_method_update" | "subscription_cancel" | "subscription_update";
/** A portal session to open. */
export interface PortalRequest {
/** the Stripe customer, cus_... */
readonly customer: string;
/** where the portal's back link goes: an absolute http(s) URL */
readonly returnUrl: string;
/** a portal configuration, bpc_...; Stripe's default configuration when left out */
readonly configuration?: string;
/** the portal's language, such as en-GB or auto */
readonly locale?: string;
/** go straight into one flow instead of the portal's home page */
readonly flow?: PortalFlow;
/** sub_..., required for subscription_cancel and subscription_update */
readonly subscription?: string;
/** sent as Idempotency-Key, so a retried request makes one session */
readonly idempotencyKey?: string;
}
/** An opened portal session. */
export interface PortalSession {
/** stripe or local */
readonly provider: string;
/** bps_... or bps_local_... */
readonly id: string;
/** where to redirect the customer */
readonly url: string;
/** where the portal sends them back to */
readonly returnUrl: string;
}
Your code names it in one line, in the file that uses it
import { createPortalSession } from "#fune/payments.stripe-portal@^1";
import { chooseProvider } from "./funeio.ts";
import type { PortalRequest, PortalSession } from "./payments_stripe_portal_types.ts";
import { stripePortal } from "./payments_stripe_portal_adapter_stripe.ts";
import { localPortal } from "./payments_stripe_portal_adapter_local.ts";
const PROVIDERS = ["stripe", "local"];
const FLOWS = ["payment_method_update", "subscription_cancel", "subscription_update"];
/**
* Open the customer portal through the provider PAYMENTS_PROVIDER names. The
* request is checked first, so a malformed one never reaches Stripe.
*/
export async function createPortalSession(request: PortalRequest): Promise<PortalSession> {
if (!request || typeof request.customer !== "string" || !/^cus_[A-Za-z0-9]+$/.test(request.customer)) {
throw new Error(`customer ${JSON.stringify(request?.customer)} is not a Customer id (cus_...)`);
}
if (typeof request.returnUrl !== "string" || !/^https?:\/\/[^\s]+$/.test(request.returnUrl)) {
throw new Error("returnUrl is an absolute http(s) URL");
}
if (request.configuration != null && (typeof request.configuration !== "string" || !/^bpc_[A-Za-z0-9]+$/.test(request.configuration))) {
throw new Error(`configuration ${JSON.stringify(request.configuration)} is not a portal configuration id (bpc_...)`);
}
if (request.locale != null && (typeof request.locale !== "string" || !/^(auto|[a-z]{2}(-[A-Z]{2}|-[0-9]{3})?)$/.test(request.locale))) {
throw new Error(`locale ${JSON.stringify(request.locale)} is not a locale such as en, en-GB or auto`);
}
if (request.flow != null && !FLOWS.includes(request.flow)) {
throw new Error(`flow is one of ${FLOWS.join(", ")}`);
}
if (request.subscription != null && (typeof request.subscription !== "string" || !/^sub_[A-Za-z0-9]+$/.test(request.subscription))) {
throw new Error(`subscription ${JSON.stringify(request.subscription)} is not a Subscription id (sub_...)`);
}
if ((request.flow === "subscription_cancel" || request.flow === "subscription_update") && request.subscription == null) {
throw new Error(`flow ${request.flow} needs the subscription (sub_...)`);
}
const provider = chooseProvider("PAYMENTS_PROVIDER", PROVIDERS);
return provider === "stripe" ? stripePortal(request) : localPortal(request);
}Providers and environment
An integration is one interface with a provider behind it for each service it can use; each provider is an adapter file in the package. PAYMENTS_PROVIDER picks the provider at run time. Its code reaches the outside only through funeio, which fune build writes beside it. Values are never part of a package: set them in the environment.
| Provider | What it is |
|---|---|
| stripe | Stripe's API (stripe.com): Billing customer portal sessions |
| local | A stand-in for development without a Stripe account: a URL to a page in your own app that plays the portal |
| Variable | Kind | Needed | Read by | What it is |
|---|---|---|---|---|
| PAYMENTS_PROVIDER | config · picks the provider | required | every provider | which provider takes payments: stripe or local (the same variable payments.stripe-checkout reads) |
| STRIPE_SECRET_KEY | secret | required | stripe only | a secret key from dashboard.stripe.com/apikeys: sk_test_... while testing |
| LOCAL_PORTAL_URL | config | optional (default "http://localhost:3000/dev/billing-portal") | local only | the page in your app that plays Stripe's portal |
Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add payments.stripe-portal
An integration reads its settings and secrets from the environment. fune build writes every variable it reads, with what each is, to .fune/build/.env.example; fune secrets says which are set (never their values), and fune secrets --check fails a deploy step when one is missing.
fune secrets --check
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./payments.stripe-portal-1.0.0-typescript.fune, or fetch it from a terminal with fune pull payments.stripe-portal@1.0.0:typescript.
It is TypeScript only, so there is no package for Python or Rust. The full package is one file too: payments.stripe-portal-1.0.0.fune, 29,422 bytes, sha256 79a969db14efe54a068cfff7841098eb22f5a36476648f4fc644c6e859c117bb.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before payments.stripe-portal
after — your function gets the result and the arguments, and returns the final result.
// fune: after payments.stripe-portal
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
// fune: replace encoding.hex in payments.stripe-portal
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show payments.stripe-portal --steps.
// fune: step payments.stripe-portal after <n|label>
Contract tests
These are contract tests on recorded exchanges, offline: each case runs the interface through one provider with fake credentials and a fixed clock, and the funeio seam serves the HTTP exchanges or socket dialogue it recorded. A request that differs from the recording, or a recorded exchange never made, fails the case. They prove the integration speaks the protocol as recorded and handles what the service answers; they do not reach the service. Every function needs at least 8, every provider at least 2, and every function that does I/O a case through each provider. fune verify runs them in a project, and the registry ran them in its sandbox, which has no network. Cases per provider: stripe 13, local 5. The exact JSON is contracts.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| stripe stripe: the portal home page for a customer, with a configuration, locale and idempotency key | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, configuration bpc_1MAhNDLkdIwHu7ix, locale en-GB, idempotency key portal-u42-1 | → | provider stripe, id bps_1MAhNDLkdIwHu7ixckACO1Jq, url https://billing.stripe.com/p/session/test_YWNjdF8xTTJKVGtMa2RJd0h1N2l4LF9OZmZyR3ZjS2xsZW1oQ0NUbE1Ec1NNTUxIb3VtZGt60100, retur… |
| stripe stripe: nothing optional, the exact form body | customer cus_NffrFeUfNV2Hib, return url https://app.example/billing?tab=plan | → | provider stripe, id bps_1PzPlain, url https://billing.stripe.com/p/session/test_YWNjdF8xTTJKVGtMa2RJd0h1N2l4LF9OZmZyR3ZjS2xsZW1oQ0NUbE1Ec1NNTUxIb3VtZGt60100, return url https://ap… |
| stripe stripe: straight into cancelling one subscription | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, flow subscription_cancel, subscription sub_1MowQVLkdIwHu7ixeRlqHVzs | → | provider stripe, id bps_1PzCancel, url https://billing.stripe.com/p/session/test_YWNjdF8xTTJKVGtMa2RJd0h1N2l4LF9OZmZyR3ZjS2xsZW1oQ0NUbE1Ec1NNTUxIb3VtZGt60100, return url https://a… |
| stripe stripe: straight into updating the card, no subscription sent | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, flow payment_method_update | → | provider stripe, id bps_1PzCard, url https://billing.stripe.com/p/session/test_YWNjdF8xTTJKVGtMa2RJd0h1N2l4LF9OZmZyR3ZjS2xsZW1oQ0NUbE1Ec1NNTUxIb3VtZGt60100, return url https://app… |
| stripe stripe: an unknown customer is thrown with Stripe's code, message and parameter | customer cus_Missing, return url https://app.example/account | → | error: stripe refused the portal session (400 resource_missing, param customer): No such customer: 'cus_Missing' |
| stripe stripe: the portal not yet set up in test mode | customer cus_NffrFeUfNV2Hib, return url https://app.example/account | → | error: stripe refused the portal session (400 invalid_request_error): No configuration provided |
| stripe stripe: a refused key names the variable | customer cus_NffrFeUfNV2Hib, return url https://app.example/account | → | error: stripe refused STRIPE_SECRET_KEY (401): Invalid API Key provided |
| stripe stripe: rate limited says to retry with the same key | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, idempotency key portal-u42-2 | → | error: stripe is rate limiting this key (429) |
| stripe stripe: no secret key set | customer cus_NffrFeUfNV2Hib, return url https://app.example/account | → | error: STRIPE_SECRET_KEY is not set |
| local local: a session on the machine, the default portal page | customer cus_NffrFeUfNV2Hib, return url https://app.example/account | → | provider local, id bps_local_a1b2c3d4e5f60718293a4b5c, url http://localhost:3000/dev/billing-portal?session=bps_local_a1b2c3d4e5f60718293a4b5c&customer=cus_NffrFeUfNV2Hib&return_u… |
Show the other 9 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| local local: a flow and its subscription passed to the app's own page | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, flow subscription_update, subscription sub_1MowQVLkdIwHu7ixeRlqHVzs | → | provider local, id bps_local_000102030405060708090a0b, url http://localhost:5173/dev/portal?theme=dark&session=bps_local_000102030405060708090a0b&customer=cus_NffrFeUfNV2Hib&retur… |
| local local: a portal page that is not a URL is reported | customer cus_NffrFeUfNV2Hib, return url https://app.example/account | → | error: LOCAL_PORTAL_URL is not an absolute http(s) URL |
| stripe a customer that is not a cus_ id is refused before anything is sent | customer user_42, return url https://app.example/account | → | error: customer "user_42" is not a Customer id (cus_...) |
| local a relative return URL | customer cus_NffrFeUfNV2Hib, return url /account | → | error: returnUrl is an absolute http(s) URL |
| stripe a cancel flow without its subscription | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, flow subscription_cancel | → | error: flow subscription_cancel needs the subscription (sub_...) |
| stripe an unknown flow | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, flow invoice_history | → | error: flow is one of payment_method_update, subscription_cancel, subscription_update |
| stripe a configuration that is not a bpc_ id | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, configuration default | → | error: configuration "default" is not a portal configuration id (bpc_...) |
| local a malformed locale | customer cus_NffrFeUfNV2Hib, return url https://app.example/account, locale english | → | error: locale "english" is not a locale such as en, en-GB or auto |
| no provider chosen | customer cus_NffrFeUfNV2Hib, return url https://app.example/account | → | error: PAYMENTS_PROVIDER is not set; set it to one of stripe, local |
Verification
Verified by the operator, not the sandbox 19 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
From a Next.js route handler:
// 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.
Files
| Path | Bytes |
|---|---|
| README.md | 2,783 |
| adapters/typescript/local.ts | 1,466 |
| adapters/typescript/stripe.ts | 2,783 |
| contracts.json | 13,403 |
| impl/typescript.ts | 2,277 |