Watch
1
0
Fork
You've already forked packages
0

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
This commit is contained in:
Weft packages 2026-11-19 20:43:26 +00:00
commit 306b143104
72 changed files with 10915 additions and 0 deletions

148
stripe/README.md Normal file
View file

@ -0,0 +1,148 @@
# @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`.
```sh
weft add weft/stripe
```
```weft
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:
```weft
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`:
```weft
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`):
```weft
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:
```weft
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.
```weft
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:
```weft
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](https://github.com/stripe/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.

126
stripe/billing.weft Normal file
View file

@ -0,0 +1,126 @@
// The customer portal, discounts and embedded Connect components.
import { request, segment } from "./stripe"
import type { Client, RequestOptions, StripeError } from "./stripe"
/// A session of the customer portal: send the customer to its `url`.
export type PortalSession = {
id: string,
url: string,
customer?: string,
return_url?: string,
created?: float,
}
/// A new portal session.
export type PortalParams = {
customer: string,
return_url?: string,
configuration?: string,
locale?: string,
extra?: json,
}
/// A coupon.
export type Coupon = {
id: string,
name?: string,
valid?: boolean,
percent_off?: float,
amount_off?: float,
currency?: string,
duration?: string,
duration_in_months?: float,
max_redemptions?: float,
times_redeemed?: float,
redeem_by?: float,
metadata?: json,
}
/// A promotion code customers can type in. `coupon` and `customer` are expandable: `idOf` gives their ids.
export type PromotionCode = {
id: string,
code: string,
active?: boolean,
coupon?: json,
promotion?: json,
customer?: json,
expires_at?: float,
max_redemptions?: float,
times_redeemed?: float,
metadata?: json,
}
/// A session for Stripe's embedded Connect components: give its `client_secret` to the browser.
export type AccountSession = {
account: string,
client_secret: string,
expires_at?: float,
livemode?: boolean,
}
/// A new account session. `components` says which embedded components it may show.
export type AccountSessionParams = { account: string, components: json }
/// Opens the customer portal for a customer.
export async fn createPortalSession(
c: Client,
params: PortalParams,
options: RequestOptions = {},
): PortalSession ! StripeError {
return try await request(
c,
"POST",
"/v1/billing_portal/sessions",
params,
options,
j => try j as PortalSession,
)
}
/// Gets a coupon by id.
export async fn retrieveCoupon(
c: Client,
id: string,
options: RequestOptions = {},
): Coupon ! StripeError {
return try await request(
c,
"GET",
`/v1/coupons/${segment(id)}`,
null,
options,
j => try j as Coupon,
)
}
/// Gets a promotion code by id.
export async fn retrievePromotionCode(
c: Client,
id: string,
options: RequestOptions = {},
): PromotionCode ! StripeError {
return try await request(
c,
"GET",
`/v1/promotion_codes/${segment(id)}`,
null,
options,
j => try j as PromotionCode,
)
}
/// Creates a session for a connected account's embedded components.
export async fn createAccountSession(
c: Client,
params: AccountSessionParams,
options: RequestOptions = {},
): AccountSession ! StripeError {
return try await request(
c,
"POST",
"/v1/account_sessions",
params,
options,
j => try j as AccountSession,
)
}

213
stripe/checkout.weft Normal file
View file

@ -0,0 +1,213 @@
// Checkout: Stripe's hosted payment page.
import { collect, request, segment } from "./stripe"
import type { Client, Page, RequestOptions, StripeError } from "./stripe"
/// A Checkout session. `customer`, `subscription` and `payment_intent` are expandable: `idOf` gives their ids.
export type Session = {
id: string,
url?: string,
status?: string,
payment_status?: string,
mode?: string,
amount_subtotal?: float,
amount_total?: float,
currency?: string,
client_reference_id?: string,
client_secret?: string,
customer?: json,
customer_email?: string,
customer_details?: json,
invoice?: json,
line_items?: json,
locale?: string,
metadata?: json,
payment_intent?: json,
subscription?: json,
success_url?: string,
cancel_url?: string,
expires_at?: float,
total_details?: json,
created?: float,
livemode?: boolean,
}
/// What a line is sold for, when it isn't an existing price.
export type PriceData = {
currency: string,
unit_amount?: float,
unit_amount_decimal?: string,
product?: string,
product_data?: {
name: string,
description?: string,
images?: string[],
metadata?: Map<string, string>,
},
recurring?: { interval: string, interval_count?: float },
tax_behavior?: string,
}
/// One line of what is being bought: an existing `price`, or `price_data`.
export type LineItem = { price?: string, price_data?: PriceData, quantity?: float, extra?: json }
/// A new Checkout session. `extra` holds any field this type doesn't list.
export type SessionParams = {
mode: "payment" | "subscription" | "setup",
success_url?: string,
cancel_url?: string,
return_url?: string,
ui_mode?: string,
line_items?: LineItem[],
customer?: string,
customer_email?: string,
customer_creation?: string,
client_reference_id?: string,
locale?: string,
metadata?: Map<string, string>,
expires_at?: float,
allow_promotion_codes?: boolean,
discounts?: { coupon?: string, promotion_code?: string }[],
payment_method_types?: string[],
billing_address_collection?: string,
automatic_tax?: { enabled: boolean },
payment_intent_data?: {
application_fee_amount?: float,
description?: string,
metadata?: Map<string, string>,
capture_method?: string,
receipt_email?: string,
transfer_data?: { destination: string, amount?: float },
extra?: json,
},
subscription_data?: {
application_fee_percent?: float,
description?: string,
metadata?: Map<string, string>,
trial_end?: float,
trial_period_days?: float,
extra?: json,
},
extra?: json,
}
/// What to list.
export type SessionListParams = {
customer?: string,
payment_intent?: string,
subscription?: string,
status?: string,
limit?: float,
starting_after?: string,
ending_before?: string,
extra?: json,
}
/// A line of a finished session.
export type SessionLineItem = {
id: string,
amount_subtotal?: float,
amount_total?: float,
currency?: string,
description?: string,
price?: json,
quantity?: float,
}
/// Creates a session: send the customer to its `url`.
///
/// ```weft
/// 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}`, stripeAccount: accountId })
/// ```
export async fn create(
c: Client,
params: SessionParams,
options: RequestOptions = {},
): Session ! StripeError {
return try await request(
c,
"POST",
"/v1/checkout/sessions",
params,
options,
j => try j as Session,
)
}
/// Gets a session by id. `{ expand: ["subscription"] }` includes what it refers to.
export async fn retrieve(
c: Client,
id: string,
options: RequestOptions = {},
): Session ! StripeError {
return try await request(
c,
"GET",
`/v1/checkout/sessions/${segment(id)}`,
null,
options,
j => try j as Session,
)
}
/// Ends a session that hasn't been paid, so it can't be.
export async fn expire(c: Client, id: string, options: RequestOptions = {}): Session ! StripeError {
return try await request(
c,
"POST",
`/v1/checkout/sessions/${segment(id)}/expire`,
null,
options,
j => try j as Session,
)
}
/// One page of sessions, newest first.
export async fn list(c: Client, params: SessionListParams = {}, options: RequestOptions = {}): Page<
Session,
> ! StripeError {
return try await request(
c,
"GET",
"/v1/checkout/sessions",
params,
options,
j => try j as Page<Session>,
)
}
/// Every session matching `params`, up to `max`.
export async fn listAll(
c: Client,
params: SessionListParams = {},
options: RequestOptions = {},
max: int = 10000,
): Session[] ! StripeError {
return try await collect(
c,
"/v1/checkout/sessions",
params,
options,
j => try j as Page<Session>,
x => x.id,
max,
)
}
/// One page of what a session sold.
export async fn lineItems(c: Client, id: string, options: RequestOptions = {}): Page<
SessionLineItem,
> ! StripeError {
return try await request(
c,
"GET",
`/v1/checkout/sessions/${segment(id)}/line_items`,
null,
options,
j => try j as Page<SessionLineItem>,
)
}

150
stripe/customers.weft Normal file
View file

@ -0,0 +1,150 @@
// Customers.
import { collect, request, segment } from "./stripe"
import type {
Address,
Client,
Deleted,
Page,
RequestOptions,
SearchPage,
StripeError,
} from "./stripe"
/// A customer.
export type Customer = {
id: string,
email?: string,
name?: string,
phone?: string,
description?: string,
address?: Address,
metadata?: json,
balance?: float,
currency?: string,
delinquent?: boolean,
default_source?: json,
invoice_prefix?: string,
created?: float,
livemode?: boolean,
}
/// The fields of a customer you can set. `extra` holds any field this type doesn't list.
export type CustomerParams = {
email?: string,
name?: string,
phone?: string,
description?: string,
address?: Address,
metadata?: Map<string, string>,
payment_method?: string,
preferred_locales?: string[],
extra?: json,
}
/// What to list. `email` is matched exactly.
export type CustomerListParams = {
email?: string,
limit?: float,
starting_after?: string,
ending_before?: string,
extra?: json,
}
/// Creates a customer.
///
/// ```weft
/// let customer = try await customers.create(stripe, { email: "ana@example.com", name: "Ana" })
/// ```
export async fn create(
c: Client,
params: CustomerParams,
options: RequestOptions = {},
): Customer ! StripeError {
return try await request(c, "POST", "/v1/customers", params, options, j => try j as Customer)
}
/// Gets a customer by id.
export async fn retrieve(
c: Client,
id: string,
options: RequestOptions = {},
): Customer ! StripeError {
return try await request(
c,
"GET",
`/v1/customers/${segment(id)}`,
null,
options,
j => try j as Customer,
)
}
/// Changes the fields given.
export async fn update(
c: Client,
id: string,
params: CustomerParams,
options: RequestOptions = {},
): Customer ! StripeError {
return try await request(
c,
"POST",
`/v1/customers/${segment(id)}`,
params,
options,
j => try j as Customer,
)
}
/// Deletes a customer, and cancels their subscriptions.
export async fn remove(c: Client, id: string, options: RequestOptions = {}): Deleted ! StripeError {
return try await request(
c,
"DELETE",
`/v1/customers/${segment(id)}`,
null,
options,
j => try j as Deleted,
)
}
/// One page of customers, newest first.
export async fn list(
c: Client,
params: CustomerListParams = {},
options: RequestOptions = {},
): Page<Customer> ! StripeError {
return try await request(c, "GET", "/v1/customers", params, options, j => try j as Page<Customer>)
}
/// Every customer matching `params`, up to `max`.
export async fn listAll(
c: Client,
params: CustomerListParams = {},
options: RequestOptions = {},
max: int = 10000,
): Customer[] ! StripeError {
return try await collect(
c,
"/v1/customers",
params,
options,
j => try j as Page<Customer>,
x => x.id,
max,
)
}
/// Customers matching a search query (`email:"ana@example.com"`).
export async fn search(c: Client, query: string, options: RequestOptions = {}): SearchPage<
Customer,
> ! StripeError {
return try await request(
c,
"GET",
"/v1/customers/search",
{ query },
options,
j => try j as SearchPage<Customer>,
)
}

110
stripe/lib/form.weft Normal file
View file

@ -0,0 +1,110 @@
// Stripe's request encoding: `application/x-www-form-urlencoded` with nesting in brackets (`a[b][0]=c`). A `json` value's
// keys can't be listed in Weft, so this walks its JSON text, which keeps the fields in the order they were written.
import { parse, stringify } from "std/json"
fn isUnreserved(c: int): boolean {
return (c >= 48 && c <= 57) ||
(c >= 65 && c <= 90) ||
(c >= 97 && c <= 122) ||
c == 45 ||
c == 95 ||
c == 46 ||
c == 126
}
/// `text` percent-encoded as UTF-8, keeping only RFC 3986's unreserved characters.
export fn encodeComponent(text: string): string {
let mut out: string[] = []
for b of Bytes.fromUtf8(text).toList() {
if isUnreserved(b) {
out.push(String.fromCharCode(b))
} else {
out.push("%" + str(b, { radix: 16 }).toUpperCase().padStart(2, "0"))
}
}
return out.join("")
}
fn stringEnd(text: string, from: int): int {
let mut i = from + 1
while i < text.length {
let c = text.codeUnitAt(i) ?? 34
if c == 92 {
i += 2
} else if c == 34 {
return i + 1
} else {
i += 1
}
}
return i
}
fn pair(key: string, value: string): string {
let name = encodeComponent(key).replaceAll("%5B", "[").replaceAll("%5D", "]")
return `${name}=${encodeComponent(value)}`
}
fn child(key: string, name: string): string {
return key == "" ? name : `${key}[${name}]`
}
/// Writes the JSON value at `at` under `key`, and gives the position after it.
fn walk(text: string, at: int, key: string, mut out: string[]): int {
let c = text.codeUnitAt(at) ?? 0
if c == 123 {
let mut i = at + 1
while text.codeUnitAt(i) != 125 {
let end = stringEnd(text, i)
let name = try parse(text.slice(i, end)) else ""
let label = name is string ? name : ""
// `extra` holds fields this package doesn't model: they belong to the object it is written in.
i = walk(text, end + 1, label == "extra" ? key : child(key, label), &out)
if text.codeUnitAt(i) == 44 {
i += 1
}
}
return i + 1
}
if c == 91 {
let mut i = at + 1
let mut index = 0
while text.codeUnitAt(i) != 93 {
i = walk(text, i, `${key}[${index}]`, &out)
index += 1
if text.codeUnitAt(i) == 44 {
i += 1
}
}
return i + 1
}
if c == 34 {
let end = stringEnd(text, at)
let value = try parse(text.slice(at, end)) else ""
out.push(pair(key, value is string ? value : ""))
return end
}
let mut end = at
while end < text.length {
let u = text.codeUnitAt(end) ?? 44
if u == 44 || u == 125 || u == 93 {
break
}
end += 1
}
let literal = text.slice(at, end)
// A field left out is `null`: Stripe is sent nothing for it. To clear a field, send an empty string.
if literal != "null" {
out.push(pair(key, literal))
}
return end
}
/// `params` in Stripe's form encoding. `null` fields are left out.
export fn encodeForm(params: json): string {
let mut out: string[] = []
if params != null {
walk(stringify(params), 0, "", &out)
}
return out.join("&")
}

195
stripe/lib/sha256.weft Normal file
View file

@ -0,0 +1,195 @@
// SHA-256 and HMAC-SHA-256 (FIPS 180-4, RFC 2104), for verifying webhook signatures. Written here until `std/crypto` is
// on main: when it is, this file goes and `webhooks.weft` calls `hmac` and `timingSafeEqual` from there.
let K: i64[] = [
0x428a2f98,
0x71374491,
0xb5c0fbcf,
0xe9b5dba5,
0x3956c25b,
0x59f111f1,
0x923f82a4,
0xab1c5ed5,
0xd807aa98,
0x12835b01,
0x243185be,
0x550c7dc3,
0x72be5d74,
0x80deb1fe,
0x9bdc06a7,
0xc19bf174,
0xe49b69c1,
0xefbe4786,
0x0fc19dc6,
0x240ca1cc,
0x2de92c6f,
0x4a7484aa,
0x5cb0a9dc,
0x76f988da,
0x983e5152,
0xa831c66d,
0xb00327c8,
0xbf597fc7,
0xc6e00bf3,
0xd5a79147,
0x06ca6351,
0x14292967,
0x27b70a85,
0x2e1b2138,
0x4d2c6dfc,
0x53380d13,
0x650a7354,
0x766a0abb,
0x81c2c92e,
0x92722c85,
0xa2bfe8a1,
0xa81a664b,
0xc24b8b70,
0xc76c51a3,
0xd192e819,
0xd6990624,
0xf40e3585,
0x106aa070,
0x19a4c116,
0x1e376c08,
0x2748774c,
0x34b0bcb5,
0x391c0cb3,
0x4ed8aa4a,
0x5b9cca4f,
0x682e6ff3,
0x748f82ee,
0x78a5636f,
0x84c87814,
0x8cc70208,
0x90befffa,
0xa4506ceb,
0xbef9a3f7,
0xc67178f2,
]
/// The low 32 bits. Words are held in an `i64`, whose sums can't overflow, and masked: SHA-256's additions wrap, and an
/// `int`'s panic.
let WORD: i64 = 0xffffffff
fn shr(x: i64, n: int): i64 {
return x >>> n
}
fn rotr(x: i64, n: int): i64 {
return (shr(x, n) | (x << (32 - n))) & WORD
}
fn compress(mut h: i64[], m: int[], at: int) {
let mut w: i64[] = []
for t of 0..16 {
let i = at + t * 4
w.push(i64((m[i] << 24) | (m[i + 1] << 16) | (m[i + 2] << 8) | m[i + 3]) & WORD)
}
for t of 16..64 {
let a = w[t - 15]
let b = w[t - 2]
let s0 = rotr(a, 7) ^ rotr(a, 18) ^ shr(a, 3)
let s1 = rotr(b, 17) ^ rotr(b, 19) ^ shr(b, 10)
w.push((w[t - 16] + s0 + w[t - 7] + s1) & WORD)
}
let mut a = h[0]
let mut b = h[1]
let mut c = h[2]
let mut d = h[3]
let mut e = h[4]
let mut f = h[5]
let mut g = h[6]
let mut k = h[7]
for t of 0..64 {
let s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)
let ch = (e & f) ^ (~e & g & WORD)
let t1 = (k + s1 + ch + K[t] + w[t]) & WORD
let s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)
let maj = (a & b) ^ (a & c) ^ (b & c)
let t2 = (s0 + maj) & WORD
k = g
g = f
f = e
e = (d + t1) & WORD
d = c
c = b
b = a
a = (t1 + t2) & WORD
}
let sums = [a, b, c, d, e, f, g, k]
for i of 0..8 {
h[i] = (h[i] + sums[i]) & WORD
}
}
/// The byte of `word` that `shift` bits down.
fn byteOf(word: i64, shift: int): int {
return try int(shr(word, shift) & 255) else 0
}
/// The SHA-256 digest of `data`.
export fn sha256(data: Bytes): Bytes {
let mut m = data.toList()
let length = i64(m.length)
m.push(0x80)
while m.length % 64 != 56 {
m.push(0)
}
// The length in bits, as 64 bits big-endian.
let bits = length * 8
let high = shr(bits, 32) & WORD
let low = bits & WORD
for shift of [24, 16, 8, 0] {
m.push(byteOf(high, shift))
}
for shift of [24, 16, 8, 0] {
m.push(byteOf(low, shift))
}
let mut h: i64[] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19,
]
let mut at = 0
while at < m.length {
compress(&h, m, at)
at += 64
}
let mut out: int[] = []
for word of h {
for shift of [24, 16, 8, 0] {
out.push(byteOf(word, shift))
}
}
return Bytes.of(out)
}
/// HMAC-SHA-256 of `data` with `key`.
export fn hmacSha256(key: Bytes, data: Bytes): Bytes {
let mut block = (key.length > 64 ? sha256(key) : key).toList()
while block.length < 64 {
block.push(0)
}
let inner = Bytes.of(block.map(b => b ^ 0x36)).concat(data)
let outer = Bytes.of(block.map(b => b ^ 0x5c))
return sha256(outer.concat(sha256(inner)))
}
/// Whether two byte strings are equal, looking at every byte whatever it finds.
export fn constantTimeEqual(a: Bytes, b: Bytes): boolean {
if a.length != b.length {
return false
}
let x = a.toList()
let y = b.toList()
let mut diff = 0
for i of 0..x.length {
diff = diff | (x[i] ^ y[i])
}
return diff == 0
}

235
stripe/payment_intents.weft Normal file
View file

@ -0,0 +1,235 @@
// Payment intents: one attempt to collect a payment.
import { collect, request, segment } from "./stripe"
import type { Client, Page, RequestOptions, SearchPage, StripeError } from "./stripe"
/// A payment intent. `customer`, `payment_method` and `latest_charge` are expandable: `idOf` gives their ids.
export type PaymentIntent = {
id: string,
amount: float,
currency: string,
status: string,
amount_capturable?: float,
amount_received?: float,
application_fee_amount?: float,
capture_method?: string,
client_secret?: string,
confirmation_method?: string,
customer?: json,
description?: string,
last_payment_error?: json,
latest_charge?: json,
metadata?: json,
next_action?: json,
on_behalf_of?: json,
payment_method?: json,
payment_method_types?: string[],
receipt_email?: string,
statement_descriptor?: string,
transfer_data?: json,
transfer_group?: string,
canceled_at?: float,
cancellation_reason?: string,
created?: float,
livemode?: boolean,
}
/// A new payment intent. `amount` is in the currency's smallest unit. `extra` holds any field this type doesn't list.
export type PaymentIntentParams = {
amount: float,
currency: string,
customer?: string,
description?: string,
metadata?: Map<string, string>,
payment_method?: string,
payment_method_types?: string[],
automatic_payment_methods?: { enabled: boolean, allow_redirects?: string },
capture_method?: string,
confirm?: boolean,
return_url?: string,
receipt_email?: string,
setup_future_usage?: string,
statement_descriptor?: string,
application_fee_amount?: float,
on_behalf_of?: string,
transfer_data?: { destination: string, amount?: float },
transfer_group?: string,
extra?: json,
}
/// The fields of a payment intent that can change before it is confirmed.
export type PaymentIntentUpdateParams = {
amount?: float,
currency?: string,
customer?: string,
description?: string,
metadata?: Map<string, string>,
payment_method?: string,
receipt_email?: string,
application_fee_amount?: float,
extra?: json,
}
/// What to list.
export type PaymentIntentListParams = {
customer?: string,
limit?: float,
starting_after?: string,
ending_before?: string,
extra?: json,
}
/// Creates a payment intent.
///
/// ```weft
/// let intent = try await paymentIntents.create(stripe, {
/// amount: 1999,
/// currency: "eur",
/// automatic_payment_methods: { enabled: true },
/// }, { idempotencyKey: `order-${order.id}` })
/// ```
export async fn create(
c: Client,
params: PaymentIntentParams,
options: RequestOptions = {},
): PaymentIntent ! StripeError {
return try await request(
c,
"POST",
"/v1/payment_intents",
params,
options,
j => try j as PaymentIntent,
)
}
/// Gets a payment intent by id.
export async fn retrieve(
c: Client,
id: string,
options: RequestOptions = {},
): PaymentIntent ! StripeError {
return try await request(
c,
"GET",
`/v1/payment_intents/${segment(id)}`,
null,
options,
j => try j as PaymentIntent,
)
}
/// Changes the fields given.
export async fn update(
c: Client,
id: string,
params: PaymentIntentUpdateParams,
options: RequestOptions = {},
): PaymentIntent ! StripeError {
return try await request(
c,
"POST",
`/v1/payment_intents/${segment(id)}`,
params,
options,
j => try j as PaymentIntent,
)
}
/// Confirms that the customer intends to pay. `params` may name a `payment_method` or a `return_url`.
export async fn confirm(
c: Client,
id: string,
params: json = null,
options: RequestOptions = {},
): PaymentIntent ! StripeError {
return try await request(
c,
"POST",
`/v1/payment_intents/${segment(id)}/confirm`,
params,
options,
j => try j as PaymentIntent,
)
}
/// Captures an authorised payment, all of it unless `params` gives an `amount_to_capture`.
export async fn capture(
c: Client,
id: string,
params: json = null,
options: RequestOptions = {},
): PaymentIntent ! StripeError {
return try await request(
c,
"POST",
`/v1/payment_intents/${segment(id)}/capture`,
params,
options,
j => try j as PaymentIntent,
)
}
/// Cancels a payment intent that hasn't succeeded.
export async fn cancel(
c: Client,
id: string,
params: json = null,
options: RequestOptions = {},
): PaymentIntent ! StripeError {
return try await request(
c,
"POST",
`/v1/payment_intents/${segment(id)}/cancel`,
params,
options,
j => try j as PaymentIntent,
)
}
/// One page of payment intents, newest first.
export async fn list(
c: Client,
params: PaymentIntentListParams = {},
options: RequestOptions = {},
): Page<PaymentIntent> ! StripeError {
return try await request(
c,
"GET",
"/v1/payment_intents",
params,
options,
j => try j as Page<PaymentIntent>,
)
}
/// Every payment intent matching `params`, up to `max`.
export async fn listAll(
c: Client,
params: PaymentIntentListParams = {},
options: RequestOptions = {},
max: int = 10000,
): PaymentIntent[] ! StripeError {
return try await collect(
c,
"/v1/payment_intents",
params,
options,
j => try j as Page<PaymentIntent>,
x => x.id,
max,
)
}
/// Payment intents matching a search query (`status:"succeeded"`).
export async fn search(c: Client, query: string, options: RequestOptions = {}): SearchPage<
PaymentIntent,
> ! StripeError {
return try await request(
c,
"GET",
"/v1/payment_intents/search",
{ query },
options,
j => try j as SearchPage<PaymentIntent>,
)
}

139
stripe/prices.weft Normal file
View file

@ -0,0 +1,139 @@
// Prices: what a product costs.
import { collect, request, segment } from "./stripe"
import type { Client, Page, RequestOptions, StripeError } from "./stripe"
/// How often a recurring price is charged.
export type Recurring = {
interval: string,
interval_count?: float,
usage_type?: string,
meter?: string,
}
/// A price. `unit_amount` is in the currency's smallest unit (cents). `product` is expandable: `idOf` gives its id.
export type Price = {
id: string,
active?: boolean,
currency?: string,
unit_amount?: float,
unit_amount_decimal?: string,
billing_scheme?: string,
lookup_key?: string,
nickname?: string,
product?: json,
recurring?: Recurring,
tax_behavior?: string,
type?: string,
metadata?: json,
created?: float,
livemode?: boolean,
}
/// A new price. `extra` holds any field this type doesn't list.
export type PriceParams = {
currency: string,
unit_amount?: float,
unit_amount_decimal?: string,
product?: string,
product_data?: { name: string, active?: boolean, metadata?: Map<string, string> },
recurring?: { interval: string, interval_count?: float },
lookup_key?: string,
transfer_lookup_key?: boolean,
nickname?: string,
active?: boolean,
tax_behavior?: string,
metadata?: Map<string, string>,
extra?: json,
}
/// The fields of a price that can change after it is made.
export type PriceUpdateParams = {
active?: boolean,
lookup_key?: string,
transfer_lookup_key?: boolean,
nickname?: string,
tax_behavior?: string,
metadata?: Map<string, string>,
extra?: json,
}
/// What to list. `lookup_keys` finds prices by the stable names you gave them.
export type PriceListParams = {
active?: boolean,
currency?: string,
product?: string,
type?: string,
lookup_keys?: string[],
recurring?: { interval?: string, usage_type?: string },
limit?: float,
starting_after?: string,
ending_before?: string,
extra?: json,
}
/// Creates a price.
export async fn create(
c: Client,
params: PriceParams,
options: RequestOptions = {},
): Price ! StripeError {
return try await request(c, "POST", "/v1/prices", params, options, j => try j as Price)
}
/// Gets a price by id.
export async fn retrieve(c: Client, id: string, options: RequestOptions = {}): Price ! StripeError {
return try await request(
c,
"GET",
`/v1/prices/${segment(id)}`,
null,
options,
j => try j as Price,
)
}
/// Changes the fields given.
export async fn update(
c: Client,
id: string,
params: PriceUpdateParams,
options: RequestOptions = {},
): Price ! StripeError {
return try await request(
c,
"POST",
`/v1/prices/${segment(id)}`,
params,
options,
j => try j as Price,
)
}
/// One page of prices.
///
/// ```weft
/// let found = try await prices.list(stripe, { lookup_keys: ["base-monthly"], active: true })
/// ```
export async fn list(c: Client, params: PriceListParams = {}, options: RequestOptions = {}): Page<
Price,
> ! StripeError {
return try await request(c, "GET", "/v1/prices", params, options, j => try j as Page<Price>)
}
/// Every price matching `params`, up to `max`.
export async fn listAll(
c: Client,
params: PriceListParams = {},
options: RequestOptions = {},
max: int = 10000,
): Price[] ! StripeError {
return try await collect(
c,
"/v1/prices",
params,
options,
j => try j as Page<Price>,
x => x.id,
max,
)
}

125
stripe/products.weft Normal file
View file

@ -0,0 +1,125 @@
// Products: what you sell.
import { collect, request, segment } from "./stripe"
import type { Client, Deleted, Page, RequestOptions, StripeError } from "./stripe"
/// A product. `default_price` is expandable: `idOf` gives its id.
export type Product = {
id: string,
name?: string,
active?: boolean,
description?: string,
images?: string[],
metadata?: json,
default_price?: json,
tax_code?: json,
unit_label?: string,
url?: string,
created?: float,
updated?: float,
livemode?: boolean,
}
/// The fields of a product you can set. `extra` holds any field this type doesn't list.
export type ProductParams = {
name?: string,
id?: string,
active?: boolean,
description?: string,
images?: string[],
metadata?: Map<string, string>,
default_price?: string,
tax_code?: string,
unit_label?: string,
url?: string,
extra?: json,
}
/// What to list.
export type ProductListParams = {
active?: boolean,
ids?: string[],
url?: string,
limit?: float,
starting_after?: string,
ending_before?: string,
extra?: json,
}
/// Creates a product.
export async fn create(
c: Client,
params: ProductParams,
options: RequestOptions = {},
): Product ! StripeError {
return try await request(c, "POST", "/v1/products", params, options, j => try j as Product)
}
/// Gets a product by id.
export async fn retrieve(
c: Client,
id: string,
options: RequestOptions = {},
): Product ! StripeError {
return try await request(
c,
"GET",
`/v1/products/${segment(id)}`,
null,
options,
j => try j as Product,
)
}
/// Changes the fields given.
export async fn update(
c: Client,
id: string,
params: ProductParams,
options: RequestOptions = {},
): Product ! StripeError {
return try await request(
c,
"POST",
`/v1/products/${segment(id)}`,
params,
options,
j => try j as Product,
)
}
/// Deletes a product that has no prices.
export async fn remove(c: Client, id: string, options: RequestOptions = {}): Deleted ! StripeError {
return try await request(
c,
"DELETE",
`/v1/products/${segment(id)}`,
null,
options,
j => try j as Deleted,
)
}
/// One page of products.
export async fn list(c: Client, params: ProductListParams = {}, options: RequestOptions = {}): Page<
Product,
> ! StripeError {
return try await request(c, "GET", "/v1/products", params, options, j => try j as Page<Product>)
}
/// Every product matching `params`, up to `max`.
export async fn listAll(
c: Client,
params: ProductListParams = {},
options: RequestOptions = {},
max: int = 10000,
): Product[] ! StripeError {
return try await collect(
c,
"/v1/products",
params,
options,
j => try j as Page<Product>,
x => x.id,
max,
)
}

90
stripe/refunds.weft Normal file
View file

@ -0,0 +1,90 @@
// Refunds.
import { collect, request, segment } from "./stripe"
import type { Client, Page, RequestOptions, StripeError } from "./stripe"
/// A refund. `charge` and `payment_intent` are expandable: `idOf` gives their ids.
export type Refund = {
id: string,
amount: float,
currency: string,
status?: string,
reason?: string,
charge?: json,
payment_intent?: json,
failure_reason?: string,
receipt_number?: string,
metadata?: json,
created?: float,
}
/// A new refund of a `payment_intent` or a `charge`: all of it unless `amount` is given.
export type RefundParams = {
payment_intent?: string,
charge?: string,
amount?: float,
reason?: "duplicate" | "fraudulent" | "requested_by_customer",
metadata?: Map<string, string>,
refund_application_fee?: boolean,
reverse_transfer?: boolean,
extra?: json,
}
/// What to list.
export type RefundListParams = {
payment_intent?: string,
charge?: string,
limit?: float,
starting_after?: string,
ending_before?: string,
extra?: json,
}
/// Refunds a payment.
export async fn create(
c: Client,
params: RefundParams,
options: RequestOptions = {},
): Refund ! StripeError {
return try await request(c, "POST", "/v1/refunds", params, options, j => try j as Refund)
}
/// Gets a refund by id.
export async fn retrieve(
c: Client,
id: string,
options: RequestOptions = {},
): Refund ! StripeError {
return try await request(
c,
"GET",
`/v1/refunds/${segment(id)}`,
null,
options,
j => try j as Refund,
)
}
/// One page of refunds, newest first.
export async fn list(c: Client, params: RefundListParams = {}, options: RequestOptions = {}): Page<
Refund,
> ! StripeError {
return try await request(c, "GET", "/v1/refunds", params, options, j => try j as Page<Refund>)
}
/// Every refund matching `params`, up to `max`.
export async fn listAll(
c: Client,
params: RefundListParams = {},
options: RequestOptions = {},
max: int = 10000,
): Refund[] ! StripeError {
return try await collect(
c,
"/v1/refunds",
params,
options,
j => try j as Page<Refund>,
x => x.id,
max,
)
}

View file

@ -0,0 +1,31 @@
// Runs packages/integration/stripe against stripe-mock (https://github.com/stripe/stripe-mock), which must be on the PATH or
// named by STRIPE_MOCK. It needs no network and no Stripe account.
import { spawn, spawnSync } from "node:child_process"
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"
const root = join(dirname(fileURLToPath(import.meta.url)), "..")
const weft = process.env.WEFT_BIN ?? join(root, "../../core/target/release/weft")
const port = 12111 + (process.pid % 1000)
const mock = spawn(process.env.STRIPE_MOCK ?? "stripe-mock", ["-http-port", String(port), "-https-port", "0"], { stdio: "ignore" })
let status = 1
try {
for (let i = 0; ; i++) {
const up = await fetch(`http://127.0.0.1:${port}/v1/customers`, { headers: { authorization: "Bearer sk_test_1" } }).then(() => true, () => false)
if (up) break
if (i > 100) throw new Error("stripe-mock didn't start")
await new Promise((r) => setTimeout(r, 100))
}
spawnSync(weft, ["install"], { cwd: join(root, "../integration/stripe"), stdio: "inherit" })
const r = spawnSync(weft, ["run", "."], {
cwd: join(root, "../integration/stripe"),
encoding: "utf8",
env: { ...process.env, STRIPE_MOCK_URL: `http://127.0.0.1:${port}`, WEFT_DEADLINE_MS: "0" },
})
process.stdout.write(r.stdout)
process.stderr.write(r.stderr)
status = r.status === 0 ? 0 : 1
} finally {
mock.kill()
}
process.exit(status)

316
stripe/stripe.weft Normal file
View file

@ -0,0 +1,316 @@
// `@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)
}

215
stripe/subscriptions.weft Normal file
View file

@ -0,0 +1,215 @@
// Subscriptions: recurring payments.
import { collect, request, segment } from "./stripe"
import type { Client, Page, RequestOptions, SearchPage, StripeError } from "./stripe"
import type { Price } from "./prices"
/// One price on a subscription. On current API versions the billing period is on the item.
export type SubscriptionItem = {
id: string,
price?: Price,
quantity?: float,
metadata?: json,
current_period_start?: float,
current_period_end?: float,
created?: float,
}
/// A subscription. `customer`, `latest_invoice` and `default_payment_method` are expandable: `idOf` gives their ids.
export type Subscription = {
id: string,
status: string,
customer: json,
items: { data: SubscriptionItem[], has_more?: boolean },
metadata?: json,
currency?: string,
cancel_at?: float,
cancel_at_period_end?: boolean,
canceled_at?: float,
collection_method?: string,
default_payment_method?: json,
discounts?: json,
ended_at?: float,
latest_invoice?: json,
pending_setup_intent?: json,
start_date?: float,
trial_end?: float,
trial_start?: float,
created?: float,
livemode?: boolean,
}
/// A price on a new subscription.
export type SubscriptionItemParams = {
price?: string,
quantity?: float,
metadata?: Map<string, string>,
extra?: json,
}
/// A new subscription. `extra` holds any field this type doesn't list.
export type SubscriptionParams = {
customer: string,
items: SubscriptionItemParams[],
metadata?: Map<string, string>,
cancel_at_period_end?: boolean,
collection_method?: string,
days_until_due?: float,
default_payment_method?: string,
discounts?: { coupon?: string, promotion_code?: string }[],
payment_behavior?: string,
proration_behavior?: string,
trial_end?: float,
trial_period_days?: float,
extra?: json,
}
/// A change to one item. Give `id` to change an item, leave it out to add one, and set `deleted` to remove it.
export type SubscriptionItemUpdate = {
id?: string,
price?: string,
quantity?: float,
deleted?: boolean,
metadata?: Map<string, string>,
extra?: json,
}
/// The fields of a subscription that can change.
export type SubscriptionUpdateParams = {
items?: SubscriptionItemUpdate[],
metadata?: Map<string, string>,
cancel_at_period_end?: boolean,
default_payment_method?: string,
discounts?: { coupon?: string, promotion_code?: string, discount?: string }[],
payment_behavior?: string,
proration_behavior?: string,
trial_end?: float,
extra?: json,
}
/// What to list. `status` also takes `all`, which includes canceled subscriptions.
export type SubscriptionListParams = {
customer?: string,
price?: string,
status?: string,
limit?: float,
starting_after?: string,
ending_before?: string,
extra?: json,
}
/// Creates a subscription.
export async fn create(
c: Client,
params: SubscriptionParams,
options: RequestOptions = {},
): Subscription ! StripeError {
return try await request(
c,
"POST",
"/v1/subscriptions",
params,
options,
j => try j as Subscription,
)
}
/// Gets a subscription by id.
export async fn retrieve(
c: Client,
id: string,
options: RequestOptions = {},
): Subscription ! StripeError {
return try await request(
c,
"GET",
`/v1/subscriptions/${segment(id)}`,
null,
options,
j => try j as Subscription,
)
}
/// Changes the fields given.
export async fn update(
c: Client,
id: string,
params: SubscriptionUpdateParams,
options: RequestOptions = {},
): Subscription ! StripeError {
return try await request(
c,
"POST",
`/v1/subscriptions/${segment(id)}`,
params,
options,
j => try j as Subscription,
)
}
/// Cancels a subscription now. To cancel when the period ends, `update` with `cancel_at_period_end: true`.
export async fn cancel(
c: Client,
id: string,
options: RequestOptions = {},
): Subscription ! StripeError {
return try await request(
c,
"DELETE",
`/v1/subscriptions/${segment(id)}`,
null,
options,
j => try j as Subscription,
)
}
/// One page of subscriptions, newest first. Canceled ones are left out unless `status` asks for them.
export async fn list(
c: Client,
params: SubscriptionListParams = {},
options: RequestOptions = {},
): Page<Subscription> ! StripeError {
return try await request(
c,
"GET",
"/v1/subscriptions",
params,
options,
j => try j as Page<Subscription>,
)
}
/// Every subscription matching `params`, up to `max`.
export async fn listAll(
c: Client,
params: SubscriptionListParams = {},
options: RequestOptions = {},
max: int = 10000,
): Subscription[] ! StripeError {
return try await collect(
c,
"/v1/subscriptions",
params,
options,
j => try j as Page<Subscription>,
x => x.id,
max,
)
}
/// Subscriptions matching a search query (`status:"active" AND metadata["site"]:"a1"`). `page` is the `next_page` of the
/// page before.
export async fn search(
c: Client,
query: string,
page: string? = null,
options: RequestOptions = {},
): SearchPage<Subscription> ! StripeError {
return try await request(
c,
"GET",
"/v1/subscriptions/search",
{ query, page },
options,
j => try j as SearchPage<Subscription>,
)
}

View file

@ -0,0 +1,220 @@
// `weft test tests/stripe.test.weft`: what needs no server. packages/integration/stripe runs the rest against stripe-mock.
import { assert, assertEq } from "std/testing"
import { encodeComponent, encodeForm } from "../lib/form"
import { constantTimeEqual, hmacSha256, sha256 } from "../lib/sha256"
import { client, errorMessage, failureFrom, idOf, metadata } from "../stripe"
import { signature, verify } from "../webhooks"
import type { WebhookError } from "../webhooks"
import { parse } from "std/json"
fn hex(s: string): Bytes {
return try Bytes.fromHex(s) else Bytes.of([])
}
// ---- SHA-256 and HMAC: FIPS 180-4's and RFC 4231's own vectors ----
test "sha256 vectors" {
assertEq(
sha256(Bytes.fromUtf8("")).toHex(),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
)
assertEq(
sha256(Bytes.fromUtf8("abc")).toHex(),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
)
assertEq(
sha256(Bytes.fromUtf8("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")).toHex(),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
)
assertEq(
sha256(Bytes.fromUtf8("a".repeat(1000))).toHex(),
"41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3",
)
}
test "padding at every block boundary" {
// Lengths around 55, 56 and 64 are where the padding spills into another block.
assertEq(
sha256(Bytes.fromUtf8("a".repeat(55))).toHex(),
"9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318",
)
assertEq(
sha256(Bytes.fromUtf8("a".repeat(56))).toHex(),
"b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a",
)
assertEq(
sha256(Bytes.fromUtf8("a".repeat(64))).toHex(),
"ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb",
)
}
test "hmac vectors (RFC 4231)" {
assertEq(
hmacSha256(hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), Bytes.fromUtf8("Hi There")).toHex(),
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
)
assertEq(
hmacSha256(Bytes.fromUtf8("Jefe"), Bytes.fromUtf8("what do ya want for nothing?")).toHex(),
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
)
let longKey = Bytes.of(Array131())
assertEq(
hmacSha256(
longKey,
Bytes.fromUtf8("Test Using Larger Than Block-Size Key - Hash Key First"),
).toHex(),
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54",
)
}
fn Array131(): int[] {
let mut out: int[] = []
for i of 0..131 {
out.push(0xaa)
}
return out
}
test "constant-time comparison" {
assert(constantTimeEqual(Bytes.fromUtf8("abc"), Bytes.fromUtf8("abc")))
assert(!constantTimeEqual(Bytes.fromUtf8("abc"), Bytes.fromUtf8("abd")))
assert(!constantTimeEqual(Bytes.fromUtf8("abc"), Bytes.fromUtf8("abcd")))
}
// ---- the form encoding ----
test "form encoding nests in brackets and leaves null out" {
let params: json = {
mode: "payment",
amount: 1999,
confirm: true,
skipped: null,
metadata: Map<string, string>([["sale id", "a&b=c"]]),
line_items: [
{ quantity: 2, price_data: { currency: "eur", product_data: { name: "Vstopnica č" } } },
],
}
assertEq(
encodeForm(params),
"mode=payment&amount=1999&confirm=true&metadata[sale%20id]=a%26b%3Dc&line_items[0][quantity]=2&line_items[0][price_data][currency]=eur&line_items[0][price_data][product_data][name]=Vstopnica%20%C4%8D",
)
}
test "form encoding: strings with quotes and escapes, empty strings, extra" {
let params: json = { a: "say \"hi\"\n", cleared: "", extra: { beta: "on", nested: { x: 1 } } }
assertEq(encodeForm(params), "a=say%20%22hi%22%0A&cleared=&beta=on&nested[x]=1")
assertEq(encodeForm(null), "")
assertEq(encodeComponent("a b/č~"), "a%20b%2F%C4%8D~")
}
// ---- webhooks ----
let SECRET = "whsec_test"
let EVENT = "{\"id\":\"evt_1\",\"type\":\"checkout.session.completed\",\"created\":1700000000,\"account\":\"acct_1\",\"data\":{\"object\":{\"id\":\"cs_1\",\"metadata\":{\"saleId\":\"s1\"}}}}"
let NOW = 1700000100
test "a signed event is verified and read" {
let event = try verify(EVENT, signature(EVENT, SECRET, NOW - 10), SECRET, { now: NOW })
assertEq(event.id, "evt_1")
assertEq(event.type, "checkout.session.completed")
assertEq(event.account, "acct_1")
assertEq(metadata(event.data.object.metadata, "saleId"), "s1")
// The same from the body's bytes, as a route gets it.
let again = try verify(
Bytes.fromUtf8(EVENT),
signature(EVENT, SECRET, NOW - 10),
SECRET,
{ now: NOW },
)
assertEq(again.id, "evt_1")
}
test "a signature made by Node's crypto verifies" {
// c.createHmac("sha256", "whsec_test").update("1700000090." + EVENT).digest("hex")
let header = "t=1700000090,v1=55712e82ccc665fe735ce74716bdbb865294afa0148576756a34f43b7534a5bb"
assertEq(signature(EVENT, SECRET, 1700000090), header)
assert((try verify(EVENT, header, SECRET, { now: NOW }) else null) != null)
}
test "any of several signatures may match, as during a secret's rotation" {
let good = signature(EVENT, SECRET, NOW).split(",")[1]
let header = `t=${NOW},v1=${"0".repeat(64)},${good},v0=ignored`
assert((try verify(EVENT, header, SECRET, { now: NOW }) else null) != null)
}
test "what isn't Stripe's is refused" {
let header = signature(EVENT, SECRET, NOW)
let _, tampered = try verify(EVENT + " ", header, SECRET, { now: NOW })
assertEq(tampered, SignatureMismatch)
let _, wrongKey = try verify(EVENT, header, "whsec_other", { now: NOW })
assertEq(wrongKey, SignatureMismatch)
let _, missing = try verify(EVENT, "", SECRET, { now: NOW })
assertEq(missing, MissingSignature)
let _, malformed = try verify(EVENT, "garbage", SECRET, { now: NOW })
assertEq(malformed, MalformedSignature { header: "garbage" })
let _, noV1 = try verify(EVENT, `t=${NOW},v0=abc`, SECRET, { now: NOW })
assertEq(noV1, MalformedSignature { header: `t=${NOW},v0=abc` })
let _, badHex = try verify(EVENT, `t=${NOW},v1=zz`, SECRET, { now: NOW })
assertEq(badHex, MalformedSignature { header: `t=${NOW},v1=zz` })
}
test "an old event is refused as a replay, unless the check is off" {
let header = signature(EVENT, SECRET, NOW - 301)
let _, old = try verify(EVENT, header, SECRET, { now: NOW })
assertEq(old, TimestampOutOfTolerance { age: 301 })
assert((try verify(EVENT, header, SECRET, { now: NOW, tolerance: 0 }) else null) != null)
assert((try verify(EVENT, header, SECRET, { now: NOW, tolerance: 600 }) else null) != null)
}
test "a signed payload that isn't an event is refused" {
let payload = "{\"id\":1}"
let _, err = try verify(payload, signature(payload, SECRET, NOW), SECRET, { now: NOW })
match err {
MalformedPayload { message } => assert(message.includes("isn't")),
_ => assert(false, "a malformed payload"),
}
}
// ---- errors ----
fn body(s: string): json {
return try parse(s) else null
}
test "errors map to their types" {
let card = failureFrom(
402,
body(
"{\"error\":{\"type\":\"card_error\",\"code\":\"card_declined\",\"decline_code\":\"insufficient_funds\",\"message\":\"Declined\",\"param\":\"number\"}}",
),
"req_1",
)
match card {
CardError { failure } => {
assertEq(failure.decline_code, "insufficient_funds")
assertEq(failure.request_id, "req_1")
},
_ => assert(false, "a card error"),
}
assertEq(errorMessage(card), "Declined")
assertEq(failureFrom(401, null, null).kind, "AuthenticationFailed")
assertEq(failureFrom(403, null, null).kind, "PermissionDenied")
assertEq(failureFrom(404, null, null).kind, "InvalidRequest")
assertEq(failureFrom(400, null, null).kind, "InvalidRequest")
assertEq(failureFrom(429, null, null).kind, "RateLimited")
assertEq(failureFrom(500, null, null).kind, "ApiFailure")
assertEq(
failureFrom(400, body("{\"error\":{\"type\":\"idempotency_error\"}}"), null).kind,
"IdempotencyConflict",
)
assertEq(errorMessage(failureFrom(500, null, null)), "Stripe answered 500")
}
test "expandable fields" {
assertEq(idOf("cus_1"), "cus_1")
assertEq(idOf(body("{\"id\":\"cus_2\",\"email\":\"a@b.c\"}")), "cus_2")
assertEq(idOf(null), null)
}
test "a client's defaults" {
let c = client("sk_test")
assertEq(c.baseUrl, "https://api.stripe.com")
assertEq(c.maxRetries, 2)
assertEq(client("sk_test", { maxRetries: 0, stripeAccount: "acct_1" }).stripeAccount, "acct_1")
}

114
stripe/webhooks.weft Normal file
View file

@ -0,0 +1,114 @@
// Webhook events: checking that one really came from Stripe.
import { parse } from "std/json"
import { floor } from "std/math"
import { now } from "std/time"
import { constantTimeEqual, hmacSha256 } from "./lib/sha256"
/// An event Stripe sent. `data.object` is the object it is about: cast it with `as`, to the type of the event.
/// `account` is the connected account it happened on, for Connect endpoints.
export type Event = {
id: string,
type: string,
created: float,
livemode: boolean?,
api_version: string?,
account: string?,
pending_webhooks: float?,
data: { object: json, previous_attributes: json },
}
/// Why an event was refused. Answer any of them with a 400.
export type WebhookError =
| MissingSignature
| MalformedSignature { header: string }
| SignatureMismatch
| TimestampOutOfTolerance { age: float }
| MalformedPayload { message: string }
/// `tolerance` (300) is how old an event may be, in seconds, against replays; `0` turns the check off. `now` is the time in
/// seconds since the epoch (the clock's).
export type VerifyOptions = { tolerance?: float, now?: float }
fn bytesOf(payload: Bytes | string): Bytes {
return payload is string ? Bytes.fromUtf8(payload) : payload
}
fn signatureOver(payload: Bytes, secret: string, timestamp: float): Bytes {
return hmacSha256(Bytes.fromUtf8(secret), Bytes.fromUtf8(`${timestamp}.`).concat(payload))
}
/// Checks the `stripe-signature` header against the raw request body, and gives the event. Pass the body exactly as it
/// arrived: parsing and re-encoding it changes the bytes the signature covers.
///
/// ```weft
/// import { verify } from "@weft/stripe/webhooks"
///
/// let router = http.router().post("/stripe/webhook", async req => {
/// let event, err = try verify(req.body, req.headers.get("stripe-signature") ?? "", secret)
/// if err != null {
/// return http.status(400)
/// }
/// if event.type == "checkout.session.completed" {
/// let session = try event.data.object as Session
/// }
/// return http.json({ received: true })
/// })
/// ```
export fn verify(
payload: Bytes | string,
header: string,
secret: string,
options: VerifyOptions = {},
): Event ! WebhookError {
if header == "" {
fail MissingSignature
}
let mut timestamp: float? = null
let mut signatures: Bytes[] = []
for part of header.split(",") {
let at = part.indexOf("=")
let name = part.slice(0, at < 0 ? 0 : at).trim()
let value = part.slice(at + 1).trim()
if name == "t" {
timestamp = try float(value) else null
} else if name == "v1" {
let decoded = try Bytes.fromHex(value) else null
if decoded != null {
signatures.push(decoded)
}
}
}
if timestamp == null || signatures.length == 0 {
fail MalformedSignature { header }
}
let body = bytesOf(payload)
let expected = signatureOver(body, secret, timestamp)
// Every signature is compared, so the time taken doesn't say which one matched.
let mut matched = false
for signature of signatures {
matched = constantTimeEqual(expected, signature) || matched
}
if !matched {
fail SignatureMismatch
}
let tolerance = options.tolerance ?? 300
let current = options.now ?? floor(now().epochMs / 1000)
let age = current - timestamp
if tolerance > 0 && age > tolerance {
fail TimestampOutOfTolerance { age }
}
let parsed, bad = try parse(body.toUtf8())
if bad != null {
fail MalformedPayload { message: bad.message }
}
let event, wrong = try parsed as Event
if wrong != null {
fail MalformedPayload { message: `${wrong.path} isn't ${wrong.expected}` }
}
return event
}
/// A `stripe-signature` header for `payload`, for tests of your own webhook handler.
export fn signature(payload: Bytes | string, secret: string, timestamp: float): string {
return `t=${timestamp},v1=${signatureOver(bytesOf(payload), secret, timestamp).toHex()}`
}

11
stripe/weft.toml Normal file
View file

@ -0,0 +1,11 @@
[package]
name = "weft/stripe"
version = "0.1.0"
description = "A typed client for Stripe's API: customers, Checkout, payments, subscriptions, prices, products and webhooks"
license = "MIT OR Apache-2.0"
# A placeholder until the public repository exists (packages/README.md, Publishing for real).
repository = "https://git.weft-lang.dev/weft/packages"
hosts = ["api.stripe.com"]
exports = ["stripe", "customers", "checkout", "payment_intents", "subscriptions", "prices", "products", "refunds", "billing", "webhooks"]
main = "stripe"
include = ["*.weft", "lib", "README.md"]