Functional Weave
Code in Rust

payments.stripe-checkout@1.1.0

adapters/typescript/local.ts

1,458 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { io, requireEnv } from "./funeio.ts";
import type { CheckoutRequest, CheckoutSession } from "./payments_stripe_checkout_types.ts";
import { hexEncode } from "./encoding_hex.ts";  ← from encoding.hex ^1.0.0 · built alongside by fune

const DEFAULT_CHECKOUT_URL = "http://localhost:3000/dev/checkout";

// RFC 3986 percent-encoding for a query value.
function queryValue(s: string): string {
  return encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
}

/** The local provider's webhook secret: any long random text the app shares with itself. */
export function localWebhookSecret(): string {
  return requireEnv("LOCAL_WEBHOOK_SECRET");
}

/**
 * A checkout that never leaves the machine: a cs_local_ id and a URL to the
 * app's own stand-in page, which plays Stripe's part (and can post a webhook
 * signed with signWebhook to the app's handler). {CHECKOUT_SESSION_ID} in
 * successUrl is filled in, as Stripe fills it in on the way back.
 */
export async function localCheckout(request: CheckoutRequest): Promise<CheckoutSession> {
  const base = io().env("LOCAL_CHECKOUT_URL") ?? DEFAULT_CHECKOUT_URL;
  const id = `cs_local_${hexEncode(io().randomBytes(12))}`;
  const query = [`session=${queryValue(id)}`, `success_url=${queryValue(request.successUrl.split("{CHECKOUT_SESSION_ID}").join(id))}`, `cancel_url=${queryValue(request.cancelUrl)}`].join("&");
  return { provider: "local", id, url: `${base}${base.includes("?") ? "&" : "?"}${query}` };
}