Watch
1
0
Fork
You've already forked packages
0
packages/stripe/README.md
Weft packages 306b143104 packages/ at markup-kit dd1e6eb5270e
A snapshot of packages/ in the Weft repository; the official packages are published from these commits.

Markup-Kit-Commit: dd1e6eb5270e62e0c8b6c202b3d01f0da6e00ddc
2026-11-19 20:43:26 +00:00

5.8 KiB

@weft/stripe

A typed client for Stripe's API, written in Weft over std/http. It covers customers, Checkout, payment intents, subscriptions, prices, products, refunds, the customer portal and webhooks. Its only capability is http.fetch@api.stripe.com.

weft add weft/stripe
import { client } from "@weft/stripe"
import * as checkout from "@weft/stripe/checkout"
import { env } from "std/process"

let stripe = client(env("STRIPE_SECRET_KEY")!)

let session = try await checkout.create(stripe, {
  mode: "payment",
  success_url: "https://example.com/thanks?s={CHECKOUT_SESSION_ID}",
  cancel_url: "https://example.com/cart",
  line_items: [{ quantity: 1, price_data: { currency: "eur", unit_amount: 1999, product_data: { name: "Ticket" } } }],
}, { idempotencyKey: `sale-${sale.id}` })

Modules

Each resource is its own module, imported as @weft/stripe/<name>:

module functions
customers create, retrieve, update, remove, list, listAll, search
checkout create, retrieve, expire, list, listAll, lineItems
payment_intents create, retrieve, update, confirm, capture, cancel, list, listAll, search
subscriptions create, retrieve, update, cancel, list, listAll, search
prices create, retrieve, update, list, listAll
products create, retrieve, update, remove, list, listAll
refunds create, retrieve, list, listAll
billing createPortalSession, retrieveCoupon, retrievePromotionCode, createAccountSession
webhooks verify, signature

Field names are Stripe's own, so its API reference applies as written. Every parameter type has an extra field for what the type doesn't list, and request calls anything else:

import { request } from "@weft/stripe"

type Balance = { livemode: boolean }
let balance = try await request(stripe, "GET", "/v1/balance", null, {}, j => try j as Balance)

Errors are values

Every call fails with a StripeError:

let intent, err = try await paymentIntents.create(stripe, params)
if err != null {
  return match err {
    CardError { failure } => declined(failure.decline_code),
    RateLimited | ConnectionFailed => retryLater(),
    _ => report(errorMessage(err)),
  }
}
variant when
CardError the card was declined
InvalidRequest the parameters are wrong, or the object doesn't exist
AuthenticationFailed, PermissionDenied the API key is wrong or can't do this
RateLimited too many requests
IdempotencyConflict an idempotency key was reused with other parameters
ApiFailure Stripe had a problem
ConnectionFailed Stripe wasn't reached, so the outcome of a POST is unknown
BadResponse Stripe's answer isn't what the types say

Retries and idempotency

A request is repeated up to maxRetries times (2) after a network error, a conflict or a server error, with exponential backoff, as Stripe's own libraries do. It obeys Stripe's Stripe-Should-Retry and Retry-After headers. Every attempt of a POST carries one idempotency key, so a request Stripe did receive isn't carried out twice. Pass idempotencyKey to make the key your own: then a repeat after a crash is safe too.

Paging

list gives one page, and listAll follows the pages up to a limit (10,000 items unless you pass max):

let page = try await customers.list(stripe, { limit: 20, starting_after: lastId })
let everyone = try await customers.listAll(stripe, { email: "ana@example.com" })

Connect

Give stripeAccount to the client, or to one call, to act on a connected account:

let session = try await checkout.create(stripe, params, { stripeAccount: "acct_123" })

Expandable fields and metadata

An expandable field is json: an id, or the object when you asked for it with expand. idOf reads either, and as gives the object its type. metadata reads one value of an object's metadata.

let session = try await checkout.retrieve(stripe, id, { expand: ["subscription"] })
let subscriptionId = idOf(session.subscription)
let sub = try session.subscription as Subscription
let siteId = metadata(sub.metadata, "siteId")

Webhooks

verify checks the signature in constant time and refuses events older than five minutes. Give it the body exactly as it arrived:

import { verify } from "@weft/stripe/webhooks"

async fn webhook(req: Request) {
  let event, err = try verify(req.body, req.headers.get("stripe-signature") ?? "", secret)
  if err != null {
    return status(400)
  }
  if event.type == "checkout.session.completed" {
    let session = try event.data.object as Session else null
  }
  return json({ received: true })
}

signature(payload, secret, timestamp) makes the header for a test of your own handler.

What has and hasn't been tested

node packages/stripe/scripts/integration.mjs runs every function above against stripe-mock, which checks each request against Stripe's OpenAPI specification and answers from its fixtures, and runs retries, headers, paging and errors against a scripted server. weft test tests/stripe.test.weft covers the signature code with FIPS 180-4's and RFC 4231's vectors and a signature made by Node's crypto. Nothing here has run against Stripe itself: try a test-mode key before relying on it.

Limits

  • It reaches only api.stripe.com. As a dependency, a baseUrl on any other host fails with a CapabilityError. To point it at stripe-mock or a proxy, the app lists that host too: allow = ["http.fetch@api.stripe.com", "http.fetch@127.0.0.1"].
  • metadata and expandable fields are json: Weft's as can't turn a JSON object into a Map.
  • Verifying a signature takes about 0.5 ms per KB of event. It is written in Weft until std/crypto is available.