- Developers selling a download, licence key, access or a service from a Cloudflare Worker with one-off payments.
- Teams whose AI agent wrote a Stripe webhook and who want it checked for signature, idempotency and amount problems.
- Agencies who set up the same payment and delivery flow for several clients.
Stripe on Workers Kit
Adds Stripe Checkout, a signature-checked webhook and idempotent order fulfilment to a Cloudflare Worker with no Stripe SDK, then tests the webhook path with a bundled script.
- Node 18 or newer for the verify script. The template's tests need a current Node and install pinned versions of Wrangler, Vitest and TypeScript.
- A Cloudflare account with Workers and D1. Receipt emails use Cloudflare Email Sending on a domain you have verified; without it the Worker still delivers.
- A Stripe account. Everything is built and tested in test mode first.
- The Stripe CLI for the local end-to-end test.
Every file, and a preview of the main ones.
The tree lists everything in the zip. The previews show the first part of each main file, so you can judge the real code before you buy.
Preview the files
Everything in the zip (27 files)
- stripe-checkout-workers/
- LICENSE
- README.md
- SKILL.md preview
- references/
- go-live.md
- webhook-events.md
- scripts/
- verify-stripe.mjs preview
- template/
- .gitignore
- package.json
- tsconfig.json
- vitest.config.ts
- worker-configuration.d.ts
- wrangler.jsonc
- migrations/
- 0001_init.sql
- src/
- crypto.ts
- email.ts
- env.ts
- fulfil.ts
- index.ts
- pages.ts
- stripe.ts preview
- test/
- checkout.test.ts
- env.d.ts
- helpers.ts
- setup.ts
- success.test.ts
- webhook.test.ts
- test/
- verify.test.mjs
stripe-checkout-workers/SKILL.mdLines 1 to 70 of 230---
name: stripe-checkout-workers
description: Add one-off Stripe payments to a Cloudflare Worker with no Stripe SDK. Creates a Checkout session, verifies the webhook signature with the raw body, fulfils each paid order exactly once (idempotent, retry-safe, amount-checked), delivers something automatically, and proves it with unit tests, the Stripe CLI and the bundled verify-stripe.mjs script. Use when asked to take payments, add Stripe Checkout, handle Stripe webhooks, sell a product or deliver after payment on Cloudflare Workers.
license: Commercial. See LICENSE in this folder.
metadata:
version: "1.0.0"
author: Red Center Studio
---
# Stripe one-off payments on a Cloudflare Worker
You are adding a payment flow that takes one-off payments with Stripe Checkout and delivers something automatically after the money arrives. Work through the nine phases below, in order. Do not skip Phase 9: the job is done when the verify script passes and the test-mode run in Phase 7 worked, not when the files exist.
Paths in this file are relative to this skill's folder. The verify script needs Node 18 or newer and has no dependencies. The Worker template targets Cloudflare Workers with D1 and the Email Sending binding, and is written in TypeScript.
## Ground rules
1. **Test mode only until Phase 8.** Every key, secret, endpoint and payment in Phases 1 to 7 is Stripe test mode. Never create, read or use a live-mode key, and never run a `stripe` CLI command that touches live mode. Phase 8 is a checklist the user works through.
2. **Never handle secrets in chat or in files.** Do not ask the user to paste a key into the conversation. Tell them to run `npx wrangler secret put STRIPE_SECRET_KEY` and `npx wrangler secret put STRIPE_WEBHOOK_SECRET` themselves, and to put test values in `.dev.vars` (gitignored) for local work. Do not print, log or echo a secret. If you must use one in a shell, read it from an environment variable.
3. **The webhook is the only thing that fulfils.** The success page, a redirect, a query string or a browser call never grants access, sends the product or marks an order paid. The success page may look the session up on Stripe's servers to show a message, nothing more.
4. **The price lives in one place.** `PRICE_CENTS` in `wrangler.jsonc` (smallest currency unit, for example cents). The checkout code reads it, the amount check reads it, and the page copy that shows a price is generated from or checked against the same value. Never accept a price from the request.
5. **Answer Stripe honestly.** 2xx means "handled or nothing to do". 400 means "bad signature or unreadable". 5xx means "try again later". Never answer 2xx for something that failed and can still succeed.
6. **Fulfilment must be safe to run twice.** Stripe can send an event more than once and can send several different events for one payment. Every side effect goes through `ctx.once(step, fn)` or an equivalent record.
7. **Do not invent Stripe facts.** API version names, CLI flags, dashboard menu names, permission names and test card numbers change. When you are not sure, read Stripe's documentation at https://docs.stripe.com (webhooks, Checkout, API keys, CLI) and say what you checked. If you cannot check, say so in the report.
8. **Change the source, not generated files.** `worker-configuration.d.ts` is generated by `npm run types` after any change to `wrangler.jsonc`. Do not hand-edit it.
9. **Ask before anything that costs money or goes public.** Deploying, creating a Dashboard webhook endpoint, creating Cloudflare resources and every Phase 8 step need the user's yes. Do not run `wrangler deploy` on your own initiative.
10. **No false claims.** Do not promise the user "PCI compliance", tax handling, refunds or fraud protection. Say what the code does and what it does not (see "What this does not cover").
## Phase 1: Decide the product, the price and what is delivered
Ask the user these questions once, in one message, and write the answers down before you touch code:
1. What is sold, in one line (this becomes `PRODUCT_NAME` and `PRODUCT_DESCRIPTION`, shown on Stripe's checkout page)?
2. The price and currency (becomes `PRICE_CENTS` and `CURRENCY`). One product at one price. If they sell several products, this template needs one more step (see Phase 3, "More than one product").
3. What does the buyer get after paying? Pick one:
- an email receipt only (the default `deliver()` does this);
- an email with a link, a licence key or a download;
- access granted in a database, a repository or another API;
- something started on your side (a job, an account, a file).
4. Where do alerts go when an order needs a person (`OWNER_EMAIL`), what is the buyer-facing sender (`MAIL_FROM`, on a domain verified for Email Sending) and the support address (`SUPPORT_EMAIL`)?
5. Where does the buyer land after paying? Default: this Worker's own `/success` and `/cancel` pages. If their own website should show the result, note the origin for `ALLOWED_ORIGIN`.
6. Is this a new Worker, or an existing Worker project that needs payments added?
Do not move on until you have the product name, price, currency and delivery choice. If the buyer needs something that is not a one-off payment (recurring billing, marketplace payouts, tax calculation), stop and say so: see "What this does not cover".
Done when: you can state the product, price, currency, delivery and alert address back to the user in two lines.
## Phase 2: Copy the template
1. New Worker: copy `template/` to the project (for example `cp -r template ./payments`, or the project root if empty). Existing Worker: copy these files in and merge, never overwrite the user's own files without asking: `src/stripe.ts`, `src/fulfil.ts`, `src/crypto.ts`, `src/email.ts`, `src/pages.ts`, `src/env.ts`, the three routes from `src/index.ts`, `migrations/0001_init.sql` (renumber it after the project's own migrations), the bindings and vars in `wrangler.jsonc`, and `test/`.
2. Run, in the project folder: `npm install`, then `npm run types`, then `npm run check`. The template's own tests (about 40) and the type check must pass before you change anything. If they do not, fix the environment first (Node version, install errors), not the code.
3. Keep the pinned versions in `package.json` unless there is a reason to upgrade. If you upgrade, rerun `npm run check`.
4. Edit the `vars` in `wrangler.jsonc` (both the top level and the `test` environment) with the Phase 1 answers: `PRODUCT_TAG` (a short lowercase id for this product), `PRODUCT_NAME`, `PRODUCT_DESCRIPTION`, `PRICE_CENTS`, `CURRENCY`, `MAIL_FROM`, `SUPPORT_EMAIL`, `OWNER_EMAIL`, `SITE_ORIGIN`. Keep `SALES_OPEN` at `"true"` in the test environment and set it to `"false"` for the live environment until Phase 8.
5. Set `STRIPE_API_VERSION` to the API version of the user's Stripe account. Look in Stripe's documentation for where the account version is shown, or ask the user. Do not copy the example value without checking it. An empty value omits the header and uses the account default.
6. Run `npm run types` again, then `npm run check`.
Done when: `npm run check` passes with the user's values in `wrangler.jsonc`.
## Phase 3: The checkout endpoint
`POST /api/checkout` starts a Checkout session and returns `{ "url": "https://checkout.stripe.com/..." }`. The code is `createCheckoutSession` in `src/stripe.ts`. Read it and confirm these properties; do not weaken them:
- It calls Stripe's REST API directly with `fetch`, form-encoded, with `Authorization: Bearer <secret key>` and a `Stripe-Version` header taken from `STRIPE_API_VERSION`.
- `mode=payment`, one line item, `unit_amount` from `PRICE_CENTS`, currency from `CURRENCY`. Nothing in the request body can change the price.
- `metadata[product]` (and the same on `payment_intent_data`) carries `PRODUCT_TAG`, so a webhook shared with other products ignores payments that are not yours.
- `success_url` is `<SITE_ORIGIN>/success?session_id={CHECKOUT_SESSION_ID}` and `cancel_url` is `<SITE_ORIGIN>/cancel`. Stripe replaces `{CHECKOUT_SESSION_ID}`. Confirm in Phase 7 that the address you land on contains a real `cs_test_` id.
- The endpoint refuses to start payments while `SALES_OPEN` is not `"true"`, rate limits per IP (and fails open if the limiter itself breaks), and refuses browser requests from origins other than `SITE_ORIGIN` and `ALLOWED_ORIGIN`.
- It never writes an order. An order exists only after a verified, paid webhook.
Wire the buyer's button to it. A minimal front-end snippet:
Preview ends at line 70. The file continues for 160 more lines in the kit.
stripe-checkout-workers/scripts/verify-stripe.mjsLines 1 to 63 of 576#!/usr/bin/env node
// verify-stripe.mjs: checks a Cloudflare Worker that takes one-off Stripe payments.
// No dependencies. Needs Node 18 or newer.
//
// node verify-stripe.mjs --dir ./my-worker
// node verify-stripe.mjs --url http://localhost:8787/api/stripe/webhook --secret-env STRIPE_WEBHOOK_SECRET
//
// Options:
// --dir <path> Static checks on the project's source, config and .gitignore.
// --url <webhook-url> Live test of a running webhook endpoint (wrangler dev or a test deployment).
// --secret-env <NAME> Name of the environment variable that holds the test-mode signing secret for that
// endpoint. Default STRIPE_WEBHOOK_SECRET. The secret is never taken from the command line
// and never printed.
// --product-tag <tag> The value your Worker expects in session metadata.product. Without it the fake session
// is tagged with nothing, so a Worker that filters by product answers "other product".
// --i-know-this-is-test-mode
// Allow --url to point at a host that is not localhost. Use only with a test-mode secret.
// --strict Treat warnings as failures.
// --json Print the results as JSON instead of text.
//
// Exit code 0 when nothing failed, 1 when at least one check failed, 2 when the arguments are wrong.
import { createHmac, randomBytes } from "node:crypto";
import { readdir, readFile, stat } from "node:fs/promises";
import { dirname, join, relative, resolve, sep } from "node:path";
import { pathToFileURL } from "node:url";
const SKIP_DIRS = new Set(["node_modules", ".git", ".wrangler", "dist", "build", "coverage", ".next", ".turbo", ".svelte-kit", ".output"]);
const SKIP_FILES = new Set(["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "worker-configuration.d.ts"]);
const TEXT_EXT = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".json", ".jsonc", ".toml", ".sql", ".md", ".txt", ".yml", ".yaml", ".html", ".example", ".sh"]);
const CODE_EXT = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
const LOCAL_SECRET_FILE = /^\.(dev\.vars|env)(\.(?!example$)[\w.-]+)?$/; // .dev.vars, .env, .env.local, not the .example copies
// ---------- reading the project ----------
const extOf = (name) => {
const i = name.lastIndexOf(".");
return i < 0 ? "" : name.slice(i).toLowerCase();
};
const isTestPath = (rel) => /(^|\/)(test|tests|__tests__|fixtures)\//.test(rel) || /\.(test|spec)\.[cm]?[jt]sx?$/.test(rel);
async function walk(dir, root, out) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
const abs = join(dir, e.name);
if (e.isDirectory()) {
if (!SKIP_DIRS.has(e.name)) await walk(abs, root, out);
} else if (e.isFile() && !SKIP_FILES.has(e.name)) {
const ext = extOf(e.name);
const local = LOCAL_SECRET_FILE.test(e.name);
if (!TEXT_EXT.has(ext) && !e.name.startsWith(".dev.vars") && !e.name.startsWith(".env")) continue;
const info = await stat(abs);
if (info.size > 2_000_000) continue;
const rel = relative(root, abs).split(sep).join("/");
out.push({ rel, abs, ext, local, test: isTestPath(rel), text: await readFile(abs, "utf8") });
}
}
}
Preview ends at line 63. The file continues for 513 more lines in the kit.
stripe-checkout-workers/template/src/stripe.tsLines 1 to 72 of 127// Stripe: verify webhook signatures, start Checkout sessions, look sessions up. Raw REST calls, no SDK.
import { hmacVerifyHex } from "./crypto";
import { type AppEnv, type Deps, priceCents } from "./env";
/** How far the signature timestamp may be from now. Stripe's own libraries default to 5 minutes. */
export const SIGNATURE_TOLERANCE_SECONDS = 300;
/**
* Checks the Stripe-Signature header. Check Stripe's webhook signature documentation if this ever stops matching.
* The scheme: the header looks like t=<unix seconds>,v1=<hex HMAC-SHA256>, and the HMAC is computed over
* "<t>.<raw body>" with the endpoint's signing secret. Rules this code follows:
* - The payload must be the exact raw body string. Parse JSON only after this passes.
* - Several v1 values can appear while a secret is being rolled; any match passes.
* - Unknown entries (v0 on test events, or debug metadata such as secret= and payload=) are ignored. They are not
* signed and must never be used to authenticate anything.
* - Old timestamps are refused, which stops a captured request from being replayed later.
*/
export async function verifyStripeSignature(
payload: string,
header: string | null,
secret: string,
nowMs: number,
toleranceSeconds = SIGNATURE_TOLERANCE_SECONDS,
): Promise<boolean> {
if (!header || !secret) return false;
let timestamp = "";
const signatures: string[] = [];
for (const part of header.split(",")) {
const i = part.indexOf("=");
if (i < 0) continue;
const k = part.slice(0, i).trim();
const v = part.slice(i + 1).trim();
if (k === "t") timestamp = v;
else if (k === "v1") signatures.push(v);
}
const t = Number(timestamp);
if (!/^\d+$/.test(timestamp) || !Number.isFinite(t) || signatures.length === 0) return false;
if (Math.abs(nowMs / 1000 - t) > toleranceSeconds) return false;
for (const sig of signatures) {
if (await hmacVerifyHex(secret, `${timestamp}.${payload}`, sig)) return true;
}
return false;
}
/** The parts of a Checkout Session this Worker uses. */
export interface CheckoutSession {
id: string;
object: "checkout.session";
payment_status: "paid" | "unpaid" | "no_payment_required";
status?: string;
amount_total: number | null;
currency: string | null;
payment_intent?: string | { id?: string } | null;
metadata?: Record<string, string> | null;
customer_details?: { email?: string | null; name?: string | null } | null;
livemode?: boolean;
}
export interface StripeEvent {
id: string;
type: string;
livemode?: boolean;
data: { object: unknown };
}
function stripeHeaders(env: AppEnv): Record<string, string> {
if (!env.STRIPE_SECRET_KEY) throw new Error("STRIPE_SECRET_KEY is not set");
const headers: Record<string, string> = { Authorization: `Bearer ${env.STRIPE_SECRET_KEY}` };
// Pin the API version your code was written and tested against. Set STRIPE_API_VERSION to your account's version.
if (env.STRIPE_API_VERSION) headers["Stripe-Version"] = env.STRIPE_API_VERSION;
return headers;
}
Preview ends at line 72. The file continues for 55 more lines in the kit.
Nine phases, in order.
The agent follows SKILL.md from the first phase to the last. It is not done until verify-stripe.mjs passes.
- Decide the product, the price and what is delivered. Asks what you sell, the price and what the buyer gets, once, and writes the answers down before touching code.
- Copy the template. Copies the tested Worker template, sets the product and price variables, and runs the template's own tests before changing anything.
- The checkout endpoint. Confirms the Checkout endpoint: price only from config, product tag in metadata, closed until sales open, rate limited and origin checked.
- The webhook and its signature. Reads the raw body once, checks the Stripe signature with a timestamp tolerance and a constant-time compare, and answers 400 on failure.
- Idempotent fulfilment. One order per payment however many events arrive: event ids and session ids are unique keys, deliveries take a lease, and every side effect runs once.
- The success page that never fulfils. Keeps the success page read-only: it asks Stripe for the session status and never creates an order or sends email.
- Test mode, end to end, with the Stripe CLI. Runs a real test-mode payment end to end with the Stripe CLI, including a repeated event and a bad signature.
- Go live checklist. Walks you through the go-live checklist: live restricted key, a new webhook secret, live sender domain and one real refunded purchase. You do these steps.
- Verify and finish. Runs the template tests and the verify script until both pass, then reports what changed and what is left.
What it does not cover.
- Subscriptions and recurring billing
- Stripe Connect and marketplace payouts
- Calculating or collecting tax
- Carts, shipping and several products in one order
- Automated refunds and disputes
Unzip it where your agent looks for skills.
Claude Code, this project
mkdir -p .claude/skills && unzip stripe-workers-kit-v1.0.0.zip -d .claude/skills/Cursor
mkdir -p .cursor/skills && unzip stripe-workers-kit-v1.0.0.zip -d .cursor/skills/Antigravity
mkdir -p .agent/skills && unzip stripe-workers-kit-v1.0.0.zip -d .agent/skills/Then ask in plain words, for example: "Use the stripe-checkout-workers skill on this project."
Stripe on Workers Kit
$19 USD
- Price
- $19 USD, paid once through Stripe. No subscription.
- Licence
- One purchase covers one person or one company. Use the kit on as many projects as you like, your own and your clients'. What you build with it is yours. You may not resell, share or publish the kit itself, or hand a client the kit's folder to reuse.
- Delivery
- Pay once through Stripe Checkout. You land on a download page with your zip, and the same download link is emailed to you. It works for 30 days and up to 10 downloads.
- Version
- Version 1.0.0, updated 20 November 2026.
- Updates
- Each kit has a version number. Updates within version 1 are free: email Hello@redcenterstudio.com with your order id and you get a new download link.
- Refunds
- If a kit has a major problem we cannot fix, you can ask for a refund. Your rights under Australian Consumer Law apply in full. Email Hello@redcenterstudio.com. See the terms for the kits and your rights under Australian Consumer Law.
Stripe on Workers Kit questions
Does it use the Stripe SDK?
No. The Worker calls Stripe's REST API with fetch and checks the webhook signature with Web Crypto, so there is no SDK to bundle or keep in step with the Workers runtime.
Does it handle subscriptions?
No. It covers one-off payments through Stripe's hosted Checkout page. Subscriptions, Connect, tax calculation, carts and automated refunds are out of scope, and the kit says so to the agent as well.
Will the agent ask for my Stripe keys?
No. The skill tells the agent never to ask for a key in the chat. You set secrets yourself with wrangler secret put and keep test values in .dev.vars, which is gitignored. Every step before the go-live checklist uses test mode only.
What does verify-stripe.mjs check?
On your source: the raw body is read before parsing, the signature is checked with a tolerance and a constant-time compare, the paid status, amount and currency are checked, the success route does not fulfil, orders have a unique key, and no secrets are in tracked files. Against a running Worker it sends unsigned, badly signed and stale requests, an unpaid session and the same event twice.
Other Agent Skill kits.
GEO Skill Kit
Free
Audits a website for AI search readiness, fixes robots.txt rules, structured data, canonical and Open Graph tags and llms.txt, then proves the result with a zero-dependency check script.
Remote MCP Server Kit
$39 USD
Builds a production remote MCP server on Cloudflare Workers with OAuth sign-in, tool design rules, rate limits and tests, then checks it against the MCP spec and the connector directory requirements with a bundled script.
Workers Launch Check Kit
$15 USD
Reviews a Cloudflare Workers project before launch: secrets, security headers, rate limits, error handling, observability and wrangler config, fixes what fails and re-runs the bundled checker until it passes.