Functional Weave
Code in Rust

payments.stripe-checkout@1.1.0

adapters/typescript/stripe.ts

3,306 bytes · the TypeScript implementation · view raw

import { io, requireEnv } from "./funeio.ts";
import type { CheckoutRequest, CheckoutSession } from "./payments_stripe_checkout_types.ts";

const SESSIONS = "https://api.stripe.com/v1/checkout/sessions";

// RFC 3986 percent-encoding, as a form body takes it.
function formPart(name: string, value: string): string {
  const enc = (s: string) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
  return `${enc(name)}=${enc(value)}`;
}

/** Stripe's webhook signing secret for this endpoint. */
export function stripeWebhookSecret(): string {
  return requireEnv("STRIPE_WEBHOOK_SECRET");
}

/**
 * POST /v1/checkout/sessions, form-encoded as Stripe's API takes it. Stripe's
 * error object is thrown in words: its code, message and the parameter at fault.
 */
export async function stripeCheckout(request: CheckoutRequest): Promise<CheckoutSession> {
  const key = requireEnv("STRIPE_SECRET_KEY");
  const form = [formPart("mode", request.mode)];
  request.items.forEach((item, i) => {
    form.push(formPart(`line_items[${i}][price]`, item.price), formPart(`line_items[${i}][quantity]`, String(item.quantity)));
  });
  (request.customItems ?? []).forEach((item, j) => {
    const i = request.items.length + j;
    form.push(
      formPart(`line_items[${i}][price_data][currency]`, item.currency.toLowerCase()),
      formPart(`line_items[${i}][price_data][unit_amount]`, String(item.amount)),
      formPart(`line_items[${i}][price_data][product_data][name]`, item.name),
      formPart(`line_items[${i}][quantity]`, String(item.quantity)),
    );
  });
  form.push(formPart("success_url", request.successUrl), formPart("cancel_url", request.cancelUrl));
  if (request.customerEmail) form.push(formPart("customer_email", request.customerEmail));
  if (request.clientReferenceId) form.push(formPart("client_reference_id", request.clientReferenceId));
  for (const [k, v] of Object.entries(request.metadata ?? {})) form.push(formPart(`metadata[${k}]`, v));
  const headers: Record<string, string> = { authorization: `Bearer ${key}`, "content-type": "application/x-www-form-urlencoded" };
  if (request.idempotencyKey) headers["idempotency-key"] = request.idempotencyKey;
  const res = await io().http({ method: "POST", url: SESSIONS, headers, body: form.join("&") });
  let parsed: { id?: unknown; url?: unknown; error?: { type?: string; code?: string; message?: string; param?: string } } = {};
  try {
    parsed = JSON.parse(res.body);
  } catch {
    parsed = {};
  }
  const err = parsed.error;
  if (res.status === 401) throw new Error(`stripe refused STRIPE_SECRET_KEY (401): ${err?.message ?? "invalid API key"}`);
  if (res.status === 429) throw new Error("stripe is rate limiting this key (429); retry with the same idempotencyKey");
  if (res.status < 200 || res.status > 299) {
    const what = [err?.code ?? err?.type, err?.param ? `param ${err.param}` : null].filter(Boolean).join(", ");
    throw new Error(`stripe refused the checkout session (${res.status}${what ? ` ${what}` : ""}): ${err?.message ?? res.body}`);
  }
  if (typeof parsed.id !== "string" || typeof parsed.url !== "string") throw new Error(`stripe answered ${res.status} without a session id and url`);
  return { provider: "stripe", id: parsed.id, url: parsed.url };
}