Watch
1
0
Fork
You've already forked packages
0
packages/stripe/stripe.weft
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

316 lines
9.7 KiB
Text

// `@weft/stripe`: the client, its errors and the calls every resource module is built on.
import { fetch } from "std/http"
import { parse } from "std/json"
import { floor, min } from "std/math"
import { random, uuid } from "std/random"
import { sleep } from "std/time"
import { encodeComponent, encodeForm } from "./lib/form"
/// The Stripe API version this package's types are written against.
export let API_VERSION = "2026-10-28.endive"
/// A configured client. Make one with `client`; it holds no connection and can be shared freely.
export type Client = {
apiKey: string,
apiVersion: string,
baseUrl: string,
maxRetries: float,
timeout: float,
stripeAccount: string?,
}
/// Options for `client`. `maxRetries` (2) is how often a request that failed in a way that is safe to repeat is sent again;
/// `timeout` (80,000) is in milliseconds; `stripeAccount` makes every call on behalf of a connected account.
export type ClientOptions = {
apiVersion?: string,
baseUrl?: string,
maxRetries?: float,
timeout?: float,
stripeAccount?: string,
}
/// Options for one call. `idempotencyKey` makes a retried `POST` safe to repeat (one is generated when left out);
/// `stripeAccount` makes this call on behalf of a connected account; `expand` lists the fields to expand.
export type RequestOptions = {
idempotencyKey?: string,
stripeAccount?: string,
expand?: string[],
timeout?: float,
maxRetries?: float,
}
/// A client for an API key. Keep the key on the server: read it from the environment.
///
/// ```weft
/// import { client } from "@weft/stripe"
/// import { env } from "std/process"
///
/// let stripe = client(env("STRIPE_SECRET_KEY")!)
/// ```
export fn client(apiKey: string, options: ClientOptions = {}): Client {
return {
apiKey,
apiVersion: options.apiVersion ?? API_VERSION,
baseUrl: options.baseUrl ?? "https://api.stripe.com",
maxRetries: options.maxRetries ?? 2,
timeout: options.timeout ?? 80000,
stripeAccount: options.stripeAccount,
}
}
/// What Stripe said about a request it refused.
export type Failure = {
message: string,
status: float,
type: string,
code: string?,
decline_code: string?,
param: string?,
doc_url: string?,
charge: string?,
payment_intent: string?,
request_id: string?,
}
/// Why a call failed. `CardError` is the customer's card being declined; `ConnectionFailed` means Stripe was never
/// reached, so the outcome of a `POST` is unknown; `BadResponse` means Stripe answered with something this package can't
/// read.
export type StripeError =
| CardError { failure: Failure }
| InvalidRequest { failure: Failure }
| AuthenticationFailed { failure: Failure }
| PermissionDenied { failure: Failure }
| RateLimited { failure: Failure }
| IdempotencyConflict { failure: Failure }
| ApiFailure { failure: Failure }
| ConnectionFailed { message: string }
| BadResponse { message: string, request_id: string? }
/// A sentence saying what went wrong, for logs.
export fn errorMessage(error: StripeError): string {
return match error {
CardError { failure } | InvalidRequest { failure } | AuthenticationFailed {
failure,
} | PermissionDenied { failure } | RateLimited { failure } | IdempotencyConflict {
failure,
} | ApiFailure { failure } => failure.message,
ConnectionFailed { message } | BadResponse { message } => message,
}
}
/// One page of a list.
export type Page<T> = { data: T[], has_more: boolean, url?: string }
/// One page of a search. `next_page` is what to pass as `page` for the next one.
export type SearchPage<T> = {
data: T[],
has_more: boolean,
next_page?: string,
total_count?: float,
}
/// What deleting an object answers.
export type Deleted = { id: string, deleted: boolean }
/// A postal address.
export type Address = {
city?: string,
country?: string,
line1?: string,
line2?: string,
postal_code?: string,
state?: string,
}
/// The id of an expandable field: the field itself when it wasn't expanded, its `id` when it was.
///
/// ```weft
/// let customerId = idOf(session.customer)
/// ```
export fn idOf(field: json): string? {
if field is string {
return field
}
let id = field.id
return id is string ? id : null
}
/// A value from an object's `metadata`.
export fn metadata(field: json, key: string): string? {
let value = field[key]
return value is string ? value : null
}
fn text(value: json): string? {
return value is string ? value : null
}
/// The error for an answer that isn't a success.
export fn failureFrom(status: int, body: json, requestId: string?): StripeError {
let e = body.error
let kind = text(e.type) ?? ""
let failure: Failure = {
message: text(e.message) ?? `Stripe answered ${status}`,
status,
type: kind,
code: text(e.code),
decline_code: text(e.decline_code),
param: text(e.param),
doc_url: text(e.doc_url),
charge: text(e.charge),
payment_intent: idOf(e.payment_intent),
request_id: requestId,
}
if kind == "card_error" || status == 402 {
return CardError { failure }
}
if kind == "idempotency_error" {
return IdempotencyConflict { failure }
}
return match status {
400 | 404 => InvalidRequest { failure },
401 => AuthenticationFailed { failure },
403 => PermissionDenied { failure },
429 => RateLimited { failure },
_ => ApiFailure { failure },
}
}
/// Stripe's own advice on repeating a request wins; otherwise conflicts and server errors are repeated.
fn shouldRetry(status: float, advice: string?): boolean {
if advice == "false" {
return false
}
return advice == "true" || status == 409 || status >= 500
}
/// How long to wait before attempt `attempt + 1`: exponential with jitter, or what `Retry-After` asks for up to a minute.
fn retryDelay(attempt: int, retryAfter: string?): float {
let asked = retryAfter != null ? (try parse(retryAfter) else null) : null
if asked is float && asked >= 0 && asked <= 60 {
return asked * 1000
}
let base = min(500 * 2 ** attempt, 8000)
return floor(base * (0.75 + random() * 0.25))
}
/// An id made safe for a path.
export fn segment(id: string): string {
return encodeComponent(id)
}
/// Sends one request and decodes the answer: what every function in this package calls. Use it for the parts of Stripe's
/// API this package doesn't model.
///
/// ```weft
/// let balance = try await request(stripe, "GET", "/v1/balance", null, {}, j => try j as Balance)
/// ```
export async fn request<T>(
c: Client,
method: "GET" | "POST" | "DELETE",
path: string,
params: json,
options: RequestOptions,
escaping decode: (value: json) => T ! CastError,
): T ! StripeError {
let mut fields = params
let expand = options.expand
if expand != null && expand.length > 0 {
if fields == null {
fields = try parse("{}") else null
}
fields["expand"] = expand
}
let form = encodeForm(fields)
let write = method == "POST"
let url = !write && form != "" ? `${c.baseUrl}${path}?${form}` : `${c.baseUrl}${path}`
let retries = options.maxRetries ?? c.maxRetries
let mut headers: [string, string][] = [
["authorization", `Bearer ${c.apiKey}`],
["stripe-version", c.apiVersion],
["user-agent", "weft-stripe/0.1.0"],
["accept", "application/json"],
]
if write {
headers.push(["content-type", "application/x-www-form-urlencoded"])
// One key for every attempt, so a request Stripe did receive isn't carried out twice.
let key = options.idempotencyKey ?? (retries > 0 ? uuid() : null)
if key != null {
headers.push(["idempotency-key", key])
}
}
let account = options.stripeAccount ?? c.stripeAccount
if account != null {
headers.push(["stripe-account", account])
}
let timeout = options.timeout ?? c.timeout
let mut attempt = 0
while true {
let res, sent = try await fetch(url, { method, headers, body: write ? form : null, timeout })
if sent != null {
if attempt < retries {
await sleep(retryDelay(attempt, null))
attempt += 1
continue
}
fail ConnectionFailed { message: `could not reach Stripe: ${sent.message}` }
}
let requestId = res.headers.get("request-id")
let body, read = try await res.text()
if read != null {
if attempt < retries {
await sleep(retryDelay(attempt, null))
attempt += 1
continue
}
fail ConnectionFailed { message: `the answer from Stripe broke off: ${read.message}` }
}
let parsed = try parse(body) else null
if res.status >= 200 && res.status < 300 {
let value, wrong = try decode(parsed)
if wrong != null {
fail BadResponse {
message: `unexpected answer from ${path}: ${wrong.path} isn't ${wrong.expected}`,
request_id: requestId,
}
}
return value
}
if attempt < retries && shouldRetry(res.status, res.headers.get("stripe-should-retry")) {
await sleep(retryDelay(attempt, res.headers.get("retry-after")))
attempt += 1
continue
}
fail failureFrom(res.status.truncToInt(), parsed, requestId)
}
}
/// Every item of a list, following its pages up to `max` items.
export async fn collect<T>(
c: Client,
path: string,
params: json,
options: RequestOptions,
escaping decode: (value: json) => Page<T> ! CastError,
escaping id: (item: T) => string,
max: int,
): T[] ! StripeError {
let mut items: T[] = []
let mut after: string? = null
while items.length < max {
let mut fields = params
if after != null {
if fields == null {
fields = try parse("{}") else null
}
fields["starting_after"] = after
}
let page = try await request(c, "GET", path, fields, options, decode)
items.push(...page.data)
if !page.has_more || page.data.length == 0 {
break
}
after = id(page.data[page.data.length - 1])
}
return items.slice(0, max)
}