payments.stripe-checkout
Start a Stripe Checkout session and verify Stripe's signed webhooks, with a local stand-in for development.
Integration · does I/O It talks to stripe or local, reads 3 secrets 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 (not the latest) · published 2026-10-09 by charlie · Anterra
Pinned by 32 contract tests on recorded exchanges, offline, run in TypeScript · per provider: stripe 20, local 9.createCheckoutSession 12 · verifyWebhook 12 · signWebhook 8
What it does
Take a payment, or start a subscription, with Stripe Checkout: create a session, send the buyer to its URL, and act on the webhook Stripe sends when they have paid. `PAYMENTS_PROVIDER` picks the provider:
- **stripe** calls Stripe's API with `STRIPE_SECRET_KEY` and checks webhooks with the endpoint's signing secret, `STRIPE_WEBHOOK_SECRET`. - **local** needs no Stripe account: the session is a `cs_local_...` id and a URL to a page in your own app (`LOCAL_CHECKOUT_URL`, by default `http://localhost:3000/dev/checkout`) that plays Stripe's part. Its webhooks are signed exactly as Stripe signs them, with `LOCAL_WEBHOOK_SECRET`, so the handler you test locally is the one that runs in production.
The functions
A group: 3 functions that work together, each in its own file, each pinned by its own tests. A project can install only the ones it calls.
TypeScript only. This capability has no Python implementation, so it is shown in TypeScript. A Python project cannot use it: fune build stops and names where it was required. Your choice of Python is kept for every other page.
- createCheckoutSession async fn createCheckoutSession(request: CheckoutRequest) -> CheckoutSession
- verifyWebhook (payload: string, signatureHeader: string, toleranceSeconds: int = 300) -> WebhookEvent
- signWebhook (payload: string) -> string
The types it declares, generated into your project
export type CheckoutMode = "payment" | "subscription";
/** One line of the checkout. */
export interface CheckoutItem {
/** a Price id, price_... */
readonly price: string;
/** 1 or more */
readonly quantity: number;
}
/** A checkout to start. */
export interface CheckoutRequest {
/** payment for one-off, subscription for recurring prices */
readonly mode: CheckoutMode;
/** at least one */
readonly items: readonly CheckoutItem[];
/** where Stripe sends the buyer after paying; may hold {CHECKOUT_SESSION_ID} */
readonly successUrl: string;
/** where the buyer goes back to without paying */
readonly cancelUrl: string;
/** fills in the buyer's email */
readonly customerEmail?: string;
/** your id for the buyer or order, echoed in the webhook */
readonly clientReferenceId?: string;
/** your keys and values, echoed in the webhook */
readonly metadata?: Readonly<Record<string, string>>;
/** sent as Idempotency-Key, so a retried request makes one session */
readonly idempotencyKey?: string;
}
/** A started checkout. */
export interface CheckoutSession {
/** stripe or local */
readonly provider: string;
/** cs_test_..., cs_live_... or cs_local_... */
readonly id: string;
/** where to redirect the buyer */
readonly url: string;
}
/** A webhook whose signature and time were checked. */
export interface WebhookEvent {
/** evt_... */
readonly id: string;
/** such as checkout.session.completed */
readonly type: string;
/** when the event happened, in Unix seconds */
readonly created: number;
/** false for test-mode and local events */
readonly livemode: boolean;
/** the event's data.object: the session, invoice or subscription it is about */
readonly object: unknown;
}
Once installed, your code imports each one from the group's module.
createCheckoutSession throws on bad input 12 tests
async function createCheckoutSession(request: CheckoutRequest): Promise<CheckoutSession>
| request | CheckoutRequest | what is being bought, and where the buyer comes back to |
| returns | CheckoutSession | the session's id, and the URL to send the buyer to |
For example
createCheckoutSession(mode payment, items ×2, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart, customer email ada@example.com, client referen…)→ provider stripe, id cs_test_a1B2c3, url https://checkout.stripe.com/c/pay/cs_test_a1B2c3#fidkdWxOYHwnPyd1blpxYHZxWjA0 stripe: a one-off payment with email, reference, metadata and an idempotency keycreateCheckoutSession(mode subscription, items ×1, success url https://app.example/billing/done, cancel url https://app.example/billing)→ provider stripe, id cs_test_sub9, url https://checkout.stripe.com/c/pay/cs_test_sub9 stripe: a subscription, nothing optionalcreateCheckoutSession(mode payment, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart)→ provider local, id cs_local_a1b2c3d4e5f60718293a4b5c, url http://localhost:5173/dev/checkout?session=cs_local_a1b2c3d4e5f60718293a4b5c&success_url=https%3A%2F%2Fshop.example%2Ftha… local: a session on the machine, its id in the success URL
import { createCheckoutSession } from "#fune/payments.stripe-checkout@^1";
import { chooseProvider } from "./funeio.ts";
import type { CheckoutRequest, CheckoutSession } from "./payments_stripe_checkout_types.ts";
import { stripeCheckout } from "./payments_stripe_checkout_adapter_stripe.ts";
import { localCheckout } from "./payments_stripe_checkout_adapter_local.ts";
const PROVIDERS = ["stripe", "local"];
/**
* Start a checkout through the provider PAYMENTS_PROVIDER names. The request
* is checked first, so a malformed one never reaches Stripe.
*/
export async function createCheckoutSession(request: CheckoutRequest): Promise<CheckoutSession> {
if (!request || (request.mode !== "payment" && request.mode !== "subscription")) {
throw new Error('mode is "payment" or "subscription"');
}
if (!Array.isArray(request.items) || request.items.length === 0) throw new Error("a checkout needs at least one item");
request.items.forEach((item, i) => {
if (typeof item.price !== "string" || !/^price_[A-Za-z0-9]+$/.test(item.price)) {
throw new Error(`items[${i}].price ${JSON.stringify(item.price)} is not a Price id (price_...)`);
}
if (!Number.isInteger(item.quantity) || item.quantity < 1) throw new Error(`items[${i}].quantity is a whole number, 1 or more`);
});
for (const [name, url] of [["successUrl", request.successUrl], ["cancelUrl", request.cancelUrl]]) {
if (typeof url !== "string" || !/^https?:\/\/[^\s]+$/.test(url)) throw new Error(`${name} is an absolute http(s) URL`);
}
const provider = chooseProvider("PAYMENTS_PROVIDER", PROVIDERS);
return provider === "stripe" ? stripeCheckout(request) : localCheckout(request);
}verifyWebhook throws on bad input 12 tests
export function verifyWebhook(payload: string, signatureHeader: string, toleranceSeconds: number = 300): WebhookEvent
| payload | string | the request body exactly as received, before any JSON parsing |
| signatureHeader | string | the Stripe-Signature header |
| toleranceSeconds | int | how far the signed time may be from now, against replays |
| returns | WebhookEvent | the event, once its signature and time are proven |
For example
verifyWebhook({"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi…)→ id evt_1PzFake0001, type checkout.session.completed, created 1,772,366,395, livemode false, object … stripe: a signed checkout.session.completedverifyWebhook({"id":"evt_local_0002","object":"event","type":"customer.subscription.created","created":1772366400,"livemode":false,"data":{"object":{"id":"sub_local_1","status":"active"}}}, t=1…)→ id evt_local_0002, type customer.subscription.created, created 1,772,366,400, livemode false, object … local: signed the same way, with the local secretverifyWebhook({"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi…)→ id evt_1PzFake0001, type checkout.session.completed, created 1,772,366,395, livemode false, object … stripe: two v1 signatures while the secret is rolled, the second matching
import { verifyWebhook } from "#fune/payments.stripe-checkout@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { io } from "./funeio.ts";
import type { WebhookEvent } from "./payments_stripe_checkout_types.ts";
import { constantTimeEqual } from "./crypto_constant_time_equal.ts"; ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
import { hexDecode } from "./encoding_hex.ts"; ← from encoding.hex ^1.0.0 · built alongside by fune
import { webhookSecret, webhookSignature } from "./payments_stripe_checkout_sign_webhook.ts"; ← signWebhook, another function of this group · built into the same file, even by a slim install
/**
* Prove a webhook came from the provider: one of the header's v1 signatures
* is the HMAC of "<t>.<payload>" under the webhook secret (compared in
* constant time), and t is within toleranceSeconds of now. Only then is the
* payload parsed and the event returned.
*/
export function verifyWebhook(payload: string, signatureHeader: string, toleranceSeconds: number = 300): WebhookEvent {
if (!Number.isInteger(toleranceSeconds) || toleranceSeconds < 1) throw new Error("toleranceSeconds is a whole number of seconds, 1 or more");
if (typeof payload !== "string") throw new Error("payload is the request body as text, before any JSON parsing");
let timestamp: number | null = null;
const signatures: string[] = [];
for (const part of String(signatureHeader ?? "").split(",")) {
const at = part.indexOf("=");
if (at < 0) continue;
const key = part.slice(0, at).trim();
const value = part.slice(at + 1).trim();
if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
else if (key === "v1") signatures.push(value);
}
if (timestamp === null) throw new Error("the Stripe-Signature header has no timestamp (t=)");
if (!signatures.length) throw new Error("the Stripe-Signature header has no v1 signature");
const expected = webhookSignature(webhookSecret(), timestamp, payload);
const matches = signatures.some((s) => /^[0-9a-f]{64}$/.test(s) && constantTimeEqual(hexDecode(s), expected));
if (!matches) throw new Error("no v1 signature matches: the payload was changed, or signed with another secret");
const age = Math.abs(Math.floor(io().now() / 1000) - timestamp);
if (age > toleranceSeconds) {
throw new Error(`the webhook was signed ${age} seconds from now, more than the ${toleranceSeconds} allowed: a replay, or a clock out of step`);
}
let event: { id?: unknown; type?: unknown; created?: unknown; livemode?: unknown; data?: { object?: unknown } };
try {
event = JSON.parse(payload);
} catch {
throw new Error("the payload is signed but is not JSON, so not a Stripe event");
}
if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new Error("the payload is signed but is not a Stripe event (no id or type)");
return {
id: event.id,
type: event.type,
created: typeof event.created === "number" ? event.created : 0,
livemode: event.livemode === true,
object: event.data?.object ?? null,
};
}signWebhook throws on bad input 8 tests
export function signWebhook(payload: string): string
| payload | string | an event's JSON, as it will be sent |
| returns | string | a Stripe-Signature header for it, signed now with the provider's webhook secret |
For example
signWebhook({"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi…)→ t=1767225600,v1=32a09722e6bc81c9beb45a97053a722dcbf489865c9bf1ca6e77abfe092b9ad4 stripe: signs at the default clocksignWebhook({"id":"evt_local_0002","object":"event","type":"customer.subscription.created","created":1772366400,"livemode":false,"data":{"object":{"id":"sub_local_1","status":"active"}}})→ t=1772366400,v1=ce66ae7d98c9d0887d953688691a0f6c995f9bc146a7879ae20cb547180ebae3 local: signs with the local secretsignWebhook({"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi…)→ t=1772366400,v1=945f08dc95c6b6ddeca6c21c6f6ea1a80911d4fe7a4f39ec32a2861123d50db8 stripe: the time is whole seconds, rounded down
import { signWebhook } from "#fune/payments.stripe-checkout@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { chooseProvider, io } from "./funeio.ts";
import { hmacSha256 } from "./crypto_hmac_sha256.ts"; ← from crypto.hmac-sha256 ^1.0.0 · built alongside by fune
import { hexEncode } from "./encoding_hex.ts"; ← from encoding.hex ^1.0.0 · built alongside by fune
import { utf8Encode } from "./encoding_utf8.ts"; ← from encoding.utf8 ^1.0.0 · built alongside by fune
import { stripeWebhookSecret } from "./payments_stripe_checkout_adapter_stripe.ts";
import { localWebhookSecret } from "./payments_stripe_checkout_adapter_local.ts";
const PROVIDERS = ["stripe", "local"];
/** The chosen provider's webhook signing secret. */
export function webhookSecret(): string {
return chooseProvider("PAYMENTS_PROVIDER", PROVIDERS) === "stripe" ? stripeWebhookSecret() : localWebhookSecret();
}
/** Stripe's v1 signature: hex HMAC-SHA256 of "<t>.<payload>" under the secret, as bytes. */
export function webhookSignature(secret: string, timestamp: number, payload: string): readonly number[] {
return hmacSha256(utf8Encode(secret), utf8Encode(`${timestamp}.${payload}`));
}
/**
* A Stripe-Signature header for a payload, signed now: what Stripe sends,
* and what the local provider's webhooks carry, so the handler that checks
* them with verifyWebhook is the same in both.
*/
export function signWebhook(payload: string): string {
if (typeof payload !== "string") throw new Error("payload is the event's JSON, as text");
const secret = webhookSecret();
const t = Math.floor(io().now() / 1000);
return `t=${t},v1=${hexEncode(webhookSignature(secret, t, payload))}`;
}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): Checkout Sessions, and webhooks signed with the endpoint's secret |
| local | A stand-in for development without a Stripe account: a local checkout URL, webhooks signed as Stripe signs them |
| Variable | Kind | Needed | Read by | What it is |
|---|---|---|---|---|
| PAYMENTS_PROVIDER | config · picks the provider | required | every provider | which provider takes payments: stripe or local |
| STRIPE_SECRET_KEY | secret | required | stripe only | a secret key from dashboard.stripe.com/apikeys: sk_test_... while testing |
| STRIPE_WEBHOOK_SECRET | secret | required | stripe only | the webhook endpoint's signing secret, whsec_... |
| LOCAL_CHECKOUT_URL | config | optional (default "http://localhost:3000/dev/checkout") | local only | the page in your app that plays Stripe's checkout |
| LOCAL_WEBHOOK_SECRET | secret | required | local only | any long random text; your webhook handler verifies with it as it would with Stripe's |
Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 4 dependencies, 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-checkout
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add payments.stripe-checkout --only createCheckoutSession
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-checkout-1.0.0-typescript.fune, or fetch it from a terminal with fune pull payments.stripe-checkout@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-checkout-1.0.0.fune, 46,089 bytes, sha256 e2f115f50fb008fb05a8ec439825b82f3a8bf1bbe32a18534b4abd46f2b0c8ab.
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-checkout.createCheckoutSession
// fune: before payments.stripe-checkout.verifyWebhook
// fune: before payments.stripe-checkout.signWebhook
after — your function gets the result and the arguments, and returns the final result.
// fune: after payments.stripe-checkout.createCheckoutSession
// fune: after payments.stripe-checkout.verifyWebhook
// fune: after payments.stripe-checkout.signWebhook
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 crypto.constant-time-equal in payments.stripe-checkout
// fune: replace crypto.hmac-sha256 in payments.stripe-checkout
// fune: replace encoding.hex in payments.stripe-checkout
// fune: replace encoding.utf8 in payments.stripe-checkout
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show payments.stripe-checkout --steps.
// fune: step payments.stripe-checkout.<fn> 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 20, local 9. The exact JSON is contracts.json.
createCheckoutSession 12 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| stripe stripe: a one-off payment with email, reference, metadata and an idempotency key | mode payment, items ×2, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart, customer email ada@example.com, client referen… | → | provider stripe, id cs_test_a1B2c3, url https://checkout.stripe.com/c/pay/cs_test_a1B2c3#fidkdWxOYHwnPyd1blpxYHZxWjA0 |
| stripe stripe: a subscription, nothing optional | mode subscription, items ×1, success url https://app.example/billing/done, cancel url https://app.example/billing | → | provider stripe, id cs_test_sub9, url https://checkout.stripe.com/c/pay/cs_test_sub9 |
| stripe stripe: an unknown price is thrown with Stripe's code, message and parameter | mode payment, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | error: stripe refused the checkout session (400 resource_missing, param line_items[0][price]): No such price: 'price_x' |
| stripe stripe: a refused key names the variable | mode payment, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | error: stripe refused STRIPE_SECRET_KEY (401): Invalid API Key provided |
| stripe stripe: no secret key set | mode payment, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | error: STRIPE_SECRET_KEY is not set |
| local local: a session on the machine, its id in the success URL | mode payment, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | provider local, id cs_local_a1b2c3d4e5f60718293a4b5c, url http://localhost:5173/dev/checkout?session=cs_local_a1b2c3d4e5f60718293a4b5c&success_url=https%3A%2F%2Fshop.example%2Ftha… |
| local local: the default checkout page | mode subscription, items ×1, success url https://app.example/done, cancel url https://app.example/billing | → | provider local, id cs_local_000102030405060708090a0b, url http://localhost:3000/dev/checkout?session=cs_local_000102030405060708090a0b&success_url=https%3A%2F%2Fapp.example%2Fdone… |
| stripe no items is refused before anything is sent | mode payment, items , success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | error: a checkout needs at least one item |
| local a quantity of 0 | mode payment, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | error: items[0].quantity is a whole number, 1 or more |
| stripe a relative success URL | mode payment, items ×1, success url /thanks, cancel url https://shop.example/cart | → | error: successUrl is an absolute http(s) URL |
Show the other 2 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| stripe an unknown mode | mode setup, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | error: mode is "payment" or "subscription" |
| no provider chosen | mode payment, items ×1, success url https://shop.example/thanks?session={CHECKOUT_SESSION_ID}, cancel url https://shop.example/cart | → | error: PAYMENTS_PROVIDER is not set; set it to one of stripe, local |
verifyWebhook 12 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| stripe stripe: a signed checkout.session.completed | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | id evt_1PzFake0001, type checkout.session.completed, created 1,772,366,395, livemode false, object … |
| local local: signed the same way, with the local secret | {"id":"evt_local_0002","object":"event","type":"customer.subscription.created","created":1772366400,"livemode":false,"data":{"object":{"id":"sub_local_1","status":"active"}}}, t=1… | → | id evt_local_0002, type customer.subscription.created, created 1,772,366,400, livemode false, object … |
| stripe stripe: two v1 signatures while the secret is rolled, the second matching | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | id evt_1PzFake0001, type checkout.session.completed, created 1,772,366,395, livemode false, object … |
| stripe stripe: a changed payload fails | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: no v1 signature matches |
| local local: signed with another secret | {"id":"evt_local_0002","object":"event","type":"customer.subscription.created","created":1772366400,"livemode":false,"data":{"object":{"id":"sub_local_1","status":"active"}}}, t=1… | → | error: no v1 signature matches |
| stripe stripe: an old signature is a replay | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: signed 600 seconds from now, more than the 300 allowed |
| stripe stripe: a wider tolerance lets it through | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | id evt_1PzFake0001, type checkout.session.completed, created 1,772,366,395, livemode false, object … |
| stripe a header without v1 | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: the Stripe-Signature header has no v1 signature |
| stripe a header without t | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: the Stripe-Signature header has no timestamp |
| local signed, but not JSON | not json, t=1772366400,v1=46fdb387bc2ef316054dacb9c6f4d5ff026c2b527818f46f9a5eed5042e6c70f | → | error: the payload is signed but is not JSON |
Show the other 2 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| stripe no webhook secret set | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: STRIPE_WEBHOOK_SECRET is not set |
| stripe a tolerance of 0 | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: toleranceSeconds is a whole number of seconds, 1 or more |
signWebhook 8 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| stripe stripe: signs at the default clock | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | t=1767225600,v1=32a09722e6bc81c9beb45a97053a722dcbf489865c9bf1ca6e77abfe092b9ad4 |
| local local: signs with the local secret | {"id":"evt_local_0002","object":"event","type":"customer.subscription.created","created":1772366400,"livemode":false,"data":{"object":{"id":"sub_local_1","status":"active"}}} | → | t=1772366400,v1=ce66ae7d98c9d0887d953688691a0f6c995f9bc146a7879ae20cb547180ebae3 |
| stripe stripe: the time is whole seconds, rounded down | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | t=1772366400,v1=945f08dc95c6b6ddeca6c21c6f6ea1a80911d4fe7a4f39ec32a2861123d50db8 |
| local an empty payload is still signed | → | t=1772366400,v1=eab97be9a0971b85b33ee11fc1b7f87997b426369b073d9fc5eded8859f182a9 | |
| stripe non-ASCII text is signed as UTF-8 | {"id":"evt_1","type":"note","data":{"object":{"text":"café ☕ — £5"}}} | → | t=1772366400,v1=435ac2e071cc7a794b9bbf02ac8a94dff0ac5360471526bb6dc22a4f3aee84e6 |
| local no local secret set | {"id":"evt_local_0002","object":"event","type":"customer.subscription.created","created":1772366400,"livemode":false,"data":{"object":{"id":"sub_local_1","status":"active"}}} | → | error: LOCAL_WEBHOOK_SECRET is not set |
| no provider chosen | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: PAYMENTS_PROVIDER is not set |
| an unknown provider | {"id":"evt_1PzFake0001","object":"event","type":"checkout.session.completed","created":1772366395,"livemode":false,"data":{"object":{"id":"cs_test_a1B2c3","object":"checkout.sessi… | → | error: PAYMENTS_PROVIDER is "paypal"; set it to one of stripe, local |
Verification
Verified by the operator, not the sandbox 32 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/checkout/route.ts
import { createCheckoutSession } from "#fune/payments.stripe-checkout@^1";
export async function POST() {
const session = await createCheckoutSession({
mode: "payment",
items: [{ price: "price_1PzTshirt", quantity: 1 }],
successUrl: "https://shop.example/thanks?session={CHECKOUT_SESSION_ID}",
cancelUrl: "https://shop.example/cart",
clientReferenceId: "order_42",
idempotencyKey: "order_42",
});
return Response.redirect(session.url, 303);
}
// app/api/stripe/webhook/route.ts
import { verifyWebhook } from "#fune/payments.stripe-checkout@^1";
export async function POST(req: Request) {
const event = verifyWebhook(await req.text(), req.headers.get("stripe-signature") ?? "");
if (event.type === "checkout.session.completed") { /* fulfil the order */ }
return new Response("ok");
}`verifyWebhook` takes the body as text, exactly as it arrived: parse it first and re-serialise it, and the signature no longer matches. It accepts any of the header's `v1` signatures (Stripe sends two while you roll the secret), compares in constant time, and refuses a signature more than `toleranceSeconds` (300) from now, which stops replays. Only then is the payload parsed. `signWebhook` makes the header for a payload, for the local provider's stand-in page and for your own tests of the handler.
`createCheckoutSession` checks the request first (a mode, at least one `price_...` item with a quantity of 1 or more, absolute URLs), then posts it form-encoded as Stripe's API takes it. Stripe's error object is thrown in words: `stripe refused the checkout session (400 resource_missing, param line_items[0][price]): No such price: 'price_x'`. Pass `idempotencyKey` so a retried request does not make a second session.
Out of scope: prices, products, customers and refunds (make them in the Stripe dashboard or with Stripe's own SDK), payment intents without Checkout, and Connect.
The contract tests replay the request and response shapes from Stripe's API reference (Checkout Sessions, errors) with test-mode keys, and the webhook signature scheme from Stripe's "verify signatures manually" guide; the expected signatures were computed independently with Node's crypto. Make one real test-mode checkout, with the Stripe CLI forwarding webhooks, before going live.