// `node packages/stripe/scripts/integration.mjs` runs this: every call against stripe-mock (Stripe's OpenAPI spec checks each request, and // its fixtures check each response type), then retries, headers and paging against a small server in this program. import { header, json as jsonResponse, serve, status, text } from "std/http" import type { Request } from "std/http" import { log } from "std/log" import { env, exit } from "std/process" import { client, errorMessage, idOf, request } from "@weft/stripe" import type { Client, StripeError } from "@weft/stripe" import * as billing from "@weft/stripe/billing" import * as checkout from "@weft/stripe/checkout" import * as customers from "@weft/stripe/customers" import * as paymentIntents from "@weft/stripe/payment_intents" import * as prices from "@weft/stripe/prices" import * as products from "@weft/stripe/products" import * as refunds from "@weft/stripe/refunds" import * as subscriptions from "@weft/stripe/subscriptions" let mut passed = 0 let mut failed = 0 fn check(name: string, ok: boolean, detail: string = "") { if ok { passed += 1 } else { failed += 1 log(`FAIL ${name} ${detail}`) } } fn failure(name: string, e: StripeError) { failed += 1 log(`FAIL ${name}: ${errorMessage(e)}`) } let mock = client( "sk_test_123", { baseUrl: env("STRIPE_MOCK_URL") ?? "http://127.0.0.1:12111", maxRetries: 0 }, ) // ---- every call, against Stripe's OpenAPI spec ---- async fn runMock() { let customer, e1 = try await customers.create( mock, { email: "ana@example.com", name: "Ana", address: { city: "Ljubljana", country: "SI" }, metadata: Map([["site", "a1"]]), preferred_locales: ["sl"], }, ) if e1 != null { return failure("customers.create", e1) } check("customers.create", customer.id != "") let got, e2 = try await customers.retrieve(mock, customer.id) if e2 != null { return failure("customers.retrieve", e2) } check("customers.retrieve", got.id != "") let up, e3 = try await customers.update( mock, customer.id, { name: "Ana N." }, { idempotencyKey: "k1" }, ) check("customers.update", e3 == null) let page, e4 = try await customers.list(mock, { limit: 3, email: "ana@example.com" }) check("customers.list", e4 == null) let all, e5 = try await customers.listAll(mock, { limit: 3 }) check("customers.listAll", e5 == null) let found, e6 = try await customers.search(mock, "email:\"ana@example.com\"") check("customers.search", e6 == null) let gone, e7 = try await customers.remove(mock, customer.id) check("customers.remove", e7 == null && gone.deleted) let product, e8 = try await products.create( mock, { name: "Ticket", active: true, metadata: Map([["a", "b"]]) }, ) if e8 != null { return failure("products.create", e8) } check("products.create", product.id != "") check("products.retrieve", (try await products.retrieve(mock, product.id) else null) != null) check( "products.update", (try await products.update(mock, product.id, { description: "x" }) else null) != null, ) check( "products.list", (try await products.list(mock, { active: true, limit: 2 }) else null) != null, ) check("products.listAll", (try await products.listAll(mock) else null) != null) check("products.remove", (try await products.remove(mock, product.id) else null) != null) let price, e9 = try await prices.create( mock, { currency: "eur", unit_amount: 1999, product: product.id, recurring: { interval: "month", interval_count: 1 }, lookup_key: "base-monthly", }, ) if e9 != null { return failure("prices.create", e9) } check("prices.create", price.id != "") check("prices.retrieve", (try await prices.retrieve(mock, price.id) else null) != null) check( "prices.update", (try await prices.update(mock, price.id, { nickname: "Base", active: true }) else null) != null, ) let keyed, e10 = try await prices.list( mock, { lookup_keys: ["base-monthly"], active: true, limit: 1 }, ) check("prices.list by lookup key", e10 == null) check( "prices.listAll", (try await prices.listAll(mock, { product: product.id }) else null) != null, ) let intent, e11 = try await paymentIntents.create( mock, { amount: 1999, currency: "eur", automatic_payment_methods: { enabled: true }, metadata: Map([["sale", "s1"]]), application_fee_amount: 100, transfer_data: { destination: "acct_1" }, }, { idempotencyKey: "sale-s1", stripeAccount: "acct_1" }, ) if e11 != null { return failure("paymentIntents.create", e11) } check("paymentIntents.create", intent.id != "" && intent.amount > 0) check( "paymentIntents.retrieve", (try await paymentIntents.retrieve(mock, intent.id) else null) != null, ) check( "paymentIntents.update", (try await paymentIntents.update(mock, intent.id, { description: "x" }) else null) != null, ) check( "paymentIntents.confirm", (try await paymentIntents.confirm(mock, intent.id) else null) != null, ) check( "paymentIntents.capture", (try await paymentIntents.capture(mock, intent.id) else null) != null, ) check( "paymentIntents.cancel", (try await paymentIntents.cancel(mock, intent.id) else null) != null, ) check( "paymentIntents.list", (try await paymentIntents.list(mock, { limit: 2 }) else null) != null, ) check("paymentIntents.listAll", (try await paymentIntents.listAll(mock) else null) != null) check( "paymentIntents.search", (try await paymentIntents.search(mock, "status:\"succeeded\"") else null) != null, ) let sub, e12 = try await subscriptions.create( mock, { customer: "cus_1", items: [{ price: price.id, quantity: 2 }], metadata: Map([["siteId", "a1"]]), trial_period_days: 14, }, ) if e12 != null { return failure("subscriptions.create", e12) } check("subscriptions.create", sub.id != "" && idOf(sub.customer) != null) let item = sub.items.data.at(0) check("a subscription's items carry their price", item != null && item.price != null) check( "subscriptions.retrieve", (try await subscriptions.retrieve(mock, sub.id, { expand: ["customer"] }) else null) != null, ) check( "subscriptions.update", (try await subscriptions.update( mock, sub.id, { cancel_at_period_end: true, items: [{ id: "si_1", deleted: true }, { price: price.id, quantity: 1 }], proration_behavior: "none", }, ) else null) != null, ) check("subscriptions.cancel", (try await subscriptions.cancel(mock, sub.id) else null) != null) check( "subscriptions.list", (try await subscriptions.list(mock, { status: "all", limit: 2 }) else null) != null, ) check( "subscriptions.listAll", (try await subscriptions.listAll(mock, { customer: "cus_1" }) else null) != null, ) check( "subscriptions.search", (try await subscriptions.search(mock, "status:\"active\"") else null) != null, ) let session, e13 = try await checkout.create( mock, { mode: "payment", success_url: "https://example.com/thanks?s={CHECKOUT_SESSION_ID}", cancel_url: "https://example.com/cart", customer_email: "ana@example.com", client_reference_id: "sale-1", locale: "sl", metadata: Map([["saleId", "s1"]]), line_items: [ { quantity: 1, price_data: { currency: "eur", unit_amount: 1999, product_data: { name: "Vstopnica" } }, }, ], payment_intent_data: { application_fee_amount: 100, description: "Ticket", metadata: Map([["saleId", "s1"]]), }, }, { idempotencyKey: "vidni-sale-s1", stripeAccount: "acct_1" }, ) if e13 != null { return failure("checkout.create", e13) } check("checkout.create", session.id != "") let sub2, e14 = try await checkout.create( mock, { mode: "subscription", success_url: "https://example.com/ok", line_items: [{ price: price.id, quantity: 1 }], allow_promotion_codes: true, subscription_data: { metadata: Map([["siteId", "a1"]]), trial_period_days: 7, }, }, ) check("checkout.create for a subscription", e14 == null) check( "checkout.retrieve", (try await checkout.retrieve( mock, session.id, { expand: ["subscription", "payment_intent"] }, ) else null) != null, ) check("checkout.expire", (try await checkout.expire(mock, session.id) else null) != null) check("checkout.list", (try await checkout.list(mock, { limit: 2 }) else null) != null) check("checkout.listAll", (try await checkout.listAll(mock) else null) != null) check("checkout.lineItems", (try await checkout.lineItems(mock, session.id) else null) != null) let refund, e15 = try await refunds.create( mock, { payment_intent: intent.id, amount: 100, reason: "requested_by_customer" }, ) if e15 != null { return failure("refunds.create", e15) } check("refunds.create", refund.id != "") check("refunds.retrieve", (try await refunds.retrieve(mock, refund.id) else null) != null) check( "refunds.list", (try await refunds.list(mock, { payment_intent: intent.id }) else null) != null, ) check("refunds.listAll", (try await refunds.listAll(mock) else null) != null) // That stripe-mock really checks requests: a field Stripe doesn't have is refused. let unknown: json = { not_a_field: "x" } let _, e18 = try await customers.create(mock, { extra: unknown }) check( "stripe-mock refuses a field Stripe doesn't have", kindOf(e18) == "InvalidRequest", kindOf(e18), ) let portal, e16 = try await billing.createPortalSession( mock, { customer: "cus_1", return_url: "https://example.com" }, ) check("billing.createPortalSession", e16 == null) check( "billing.retrieveCoupon", (try await billing.retrieveCoupon(mock, "co_1") else null) != null, ) check( "billing.retrievePromotionCode", (try await billing.retrievePromotionCode(mock, "promo_1") else null) != null, ) let components: json = { payments: { enabled: true } } let account, e17 = try await billing.createAccountSession(mock, { account: "acct_1", components }) check("billing.createAccountSession", e17 == null) } // ---- what stripe-mock can't show: a server that misbehaves on request ---- let mut seen: Request[] = [] let mut script: string[] = [] async fn handle(req: Request) { seen.push(req) let step = script.shift() ?? "ok" return match step { "500" => status(500, "{\"error\":{\"type\":\"api_error\",\"message\":\"boom\"}}"), "500-no-retry" => header( status(500, "{\"error\":{\"type\":\"api_error\",\"message\":\"no retry\"}}"), "stripe-should-retry", "false", ), "429" => jsonResponse(rateLimit(), { status: 429 }), "402" => header(jsonResponse(declined(), { status: 402 }), "request-id", "req_declined"), "garbage" => text("this is not json"), "wrong-shape" => jsonResponse(wrongShape()), "page1" => jsonResponse(pageOf(["cus_1", "cus_2"], true)), "page2" => jsonResponse(pageOf(["cus_3"], false)), _ => jsonResponse(okCustomer()), } } fn rateLimit(): json { return { error: { type: "invalid_request_error", message: "slow down" } } } fn declined(): json { return { error: { type: "card_error", code: "card_declined", decline_code: "insufficient_funds", message: "Your card was declined.", }, } } fn wrongShape(): json { return { id: 42 } } fn okCustomer(): json { return { id: "cus_ok", object: "customer" } } fn pageOf(ids: string[], more: boolean): json { let data: json[] = ids.map(id => { let item: json = { id } return item }) return { object: "list", data, has_more: more } } fn kindOf(e: StripeError?): string { return e == null ? "none" : e.kind } async fn runScripted(c: Client) { // A server error is repeated, with the same idempotency key, and then succeeds. script = ["500", "ok"] seen = [] let first, e1 = try await customers.create(c, { email: "a@b.c" }) check("a 500 is retried", e1 == null && seen.length == 2, kindOf(e1)) let keys = seen.map(r => r.headers.get("idempotency-key") ?? "") check("every attempt carries one idempotency key", keys[0] != "" && keys[0] == keys[1]) // An explicit key is what is sent. script = ["ok"] seen = [] let _, e2 = try await customers.create( c, { email: "a@b.c" }, { idempotencyKey: "my-key", stripeAccount: "acct_9" }, ) check( "idempotency key and connected account", e2 == null && seen[0].headers.get("idempotency-key") == "my-key" && seen[0].headers.get("stripe-account") == "acct_9", ) check( "the API key and version are sent", seen[0].headers.get("authorization") == "Bearer sk_test_scripted" && (seen[0].headers.get("stripe-version") ?? "") != "", ) check( "a POST is form encoded", seen[0].headers.get("content-type") == "application/x-www-form-urlencoded" && seen[0].text() == "email=a%40b.c", ) // Reads have no key, and carry their parameters in the query. script = ["ok"] seen = [] let _, e3 = try await customers.retrieve(c, "cus/1", { expand: ["default_source"] }) check( "a GET has no idempotency key", e3 == null && seen[0].headers.get("idempotency-key") == null, ) check( "expand goes in the query, the id is escaped", seen[0].url.includes("/v1/customers/cus%2F1?expand[0]=default_source"), seen[0].url, ) // Stripe saying not to retry is obeyed. script = ["500-no-retry", "ok"] seen = [] let _, e4 = try await customers.create(c, { email: "a@b.c" }) check("stripe-should-retry: false", kindOf(e4) == "ApiFailure" && seen.length == 1, kindOf(e4)) // Retries run out. script = ["500", "500", "500", "ok"] seen = [] let _, e5 = try await customers.create(c, { email: "a@b.c" }) check("retries are limited", kindOf(e5) == "ApiFailure" && seen.length == 3, `${seen.length}`) // A 429 is an error the caller decides about, unless Stripe asks for a retry. script = ["429", "ok"] seen = [] let _, e6 = try await customers.create(c, { email: "a@b.c" }) check("a 429 is a typed error", kindOf(e6) == "RateLimited" && seen.length == 1, kindOf(e6)) // A declined card. script = ["402"] seen = [] let _, e7 = try await customers.create(c, { email: "a@b.c" }) match e7 { CardError { failure: f } => check( "a declined card", f.decline_code == "insufficient_funds" && f.request_id == "req_declined", ), _ => check("a declined card", false, kindOf(e7)), } // What can't be read is an error, not a crash. script = ["wrong-shape"] let _, e8 = try await customers.retrieve(c, "cus_1") check("an unexpected shape", kindOf(e8) == "BadResponse", kindOf(e8)) script = ["garbage"] let _, e9 = try await customers.retrieve(c, "cus_1") check("an answer that isn't JSON", kindOf(e9) == "BadResponse", kindOf(e9)) // Every page is followed. script = ["page1", "page2"] seen = [] let all, e10 = try await customers.listAll(c, { limit: 2 }) check( "listAll follows the pages", e10 == null && all.map(x => x.id).join(",") == "cus_1,cus_2,cus_3", kindOf(e10), ) check( "listAll asks for the page after the last item", seen.length == 2 && seen[1].url.includes("starting_after=cus_2"), ) // And stops at the limit it was given. script = ["page1", "page2"] seen = [] let some, e11 = try await customers.listAll(c, {}, {}, 2) check("listAll stops at max", e11 == null && some.length == 2 && seen.length == 1) // Nothing listening. let dead = client( "sk_test_scripted", { baseUrl: "http://127.0.0.1:9", maxRetries: 1, timeout: 2000 }, ) let _, e12 = try await customers.retrieve(dead, "cus_1") check("no connection", kindOf(e12) == "ConnectionFailed", kindOf(e12)) } await runMock() let server = try await serve({ port: 0, host: "127.0.0.1" }, handle) await runScripted( client("sk_test_scripted", { baseUrl: `http://127.0.0.1:${server.port}`, maxRetries: 2 }), ) await server.close() log(`${passed} passed, ${failed} failed`) if failed > 0 { exit(1) }