Functional Weave
Code in Rust

payments.stripe-checkout@1.1.0

README.md

3,841 bytes · view raw

# payments.stripe-checkout

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.

From a Next.js route handler:

```ts
// 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.

A one-off payment can also take lines with no Price made in the dashboard
first: put them in `customItems`, each a name, an amount and a currency.
They follow `items` on the checkout, and `items` may be empty when they
hold every line:

```ts
items: [{ price: "price_1PzMug", quantity: 2 }],
customItems: [{ name: "Gift wrap", amount: 350, currency: "gbp", quantity: 1 }], // £3.50
```

`amount` is in the currency's minor unit (pence, cents), as Stripe takes it;
each line is sent as `price_data` with the name as `product_data[name]`. A
subscription takes Price ids only, since a recurring price is made in
Stripe, and refuses `customItems`.

`createCheckoutSession` checks the request first (a mode, at least one line,
`price_...` ids in `items`, a name, a whole amount and a three-letter currency
in each of `customItems`, quantities 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.