The dev provider is an offline stand-in for a real payment provider. It serves a
hosted checkout page and a billing portal from your own app, keeps provider-side
state in a key/value store, and delivers signed Standard Webhooks events through
your real webhook route, so handleWebhook, the state machine and reconcile
run exactly as they do in production. Nothing is charged and no account or key
is needed.
It is for development and tests only: the factory throws unless the Worker's
env names a development environment (see below), and it lives in its own
subpath, so it is in a bundle only when you import it.
Prop
Type
Configure
The pages are unauthenticated and have no CSRF protection, so never route them outside development. A portal link is a random session id minted by
createPortalSession; it is the only credential. A checkout stuck in paying (the worker died during delivery) is reset by creating a new checkout.
Provider-side state must live outside the provider instance. The shard builds
one instance for createCheckout and your HTTP route builds another for the
hosted pages, and an in-memory map would give each its own copy, so the hosted
page would 404. Bind a KV namespace (wrangler dev persists it) and keep the
signing secret in .dev.vars. The pages rely on the local KV that wrangler dev simulates, which is consistent and has no per-key write rate
limit; a remote KV namespace is not supported.
// wrangler.jsonc
{
"kv_namespaces": [{ "binding": "LUNORA_DEV_PAYMENT_STATE", "id": "dev-payment-state" }],
}# .dev.vars (lunora dev generates the secret on first run)
LUNORA_DEV_PAYMENT_SECRET=replace-with-openssl-rand-hex-32Build the provider in one place and use it from the shard and from the route.
It builds only in development, by the rule mail capture uses: at least one of
CF_ENV, ENVIRONMENT, NODE_ENV and WORKER_ENV is set, and every one that
is set names development. lunora dev and the Vite and Rspack plugins set
WORKER_ENV=development, so no extra variable is needed. Choose the adapter with
the same rule, isDevelopmentEnvironment, so a deployed Worker never reaches it
and a development one never builds the real provider by accident.
import type { DevPaymentState } from "@lunora/payment/dev";
import { createDevPaymentProvider, isDevelopmentEnvironment } from "@lunora/payment/dev";
import { createStripeAdapter } from "@lunora/payment/stripe";
/** The bindings the dev provider reads. The generated `CloudflareBindings` types every value `unknown`, so name them here. */
interface DevPaymentEnv {
APP_BASE_URL: string;
LUNORA_DEV_PAYMENT_SECRET: string;
LUNORA_DEV_PAYMENT_STATE: DevPaymentState;
}
export const devPayment = (env: DevPaymentEnv) =>
createDevPaymentProvider({
baseUrl: env.APP_BASE_URL,
env,
prices: { price_lifetime: { currency: "USD", minorUnits: 4900n } },
state: env.LUNORA_DEV_PAYMENT_STATE,
webhookSecret: env.LUNORA_DEV_PAYMENT_SECRET,
});
// In the worker entry: createShardDO({ payment: (env) => ({ adapter: isDevelopmentEnvironment(env) ? devPayment(env).adapter : createStripeAdapter({ ... }) }) })| Option | Type | Notes |
|---|---|---|
env | object | The Worker's env. Must name a development environment, or construction throws CONFIG_INVALID. |
baseUrl | string | Public origin (APP_BASE_URL) the checkout and portal URLs are built on. |
webhookSecret | string | Signing secret for simulated webhooks. An empty value throws. |
state | DevPaymentState | { get(key), put(key, value) }; a KV namespace satisfies it. Required. |
prices | Record<string, Money> | Amounts for one-time checkouts by priceId; a missing price fails createCheckout with CONFIG_INVALID. |
basePath | string | Where the pages are served. Default /payment/dev. |
now | () => number | Injectable clock (ms) for tests. |
Serve the pages
handle(request, deliver) answers the pages under basePath and returns
undefined for any other path, so the route falls through to the rest of your
app. deliver is the app's real webhook path: it forwards the signed body and
headers to ctx.runAction(processWebhook, …) and reports { applied, status } (and reason, when your route passes it on). An answer of status 400 or
above is shown as an error and leaves provider-side state as it was. Any other answer is committed, as a real provider's state moves whether or not
the app applied the event, and applied: false is shown as a warning on the page.
The headers it needs (webhook-id, webhook-timestamp, webhook-signature) are
already in the webhook route's SIGNATURE_HEADERS allowlist.
import { env as workerEnv } from "cloudflare:workers";
// The Worker's bindings, narrowed to what the dev provider reads (`DevPaymentEnv` above).
const env = workerEnv as unknown as DevPaymentEnv;
const servePages = httpAction(async (ctx, request) => {
const response = await devPayment(env).handle(request, async (body, headers) => ctx.runAction(processWebhook, { body, headers }));
return response ?? new Response("Not found", { status: 404 });
});
app.get("/payment/dev/*", servePages);
app.post("/payment/dev/*", servePages);- Checkout (
/payment/dev/checkout/<id>): Pay (a subscription becomesactive; a one-time payment is captured at the configured price), Fail the payment, Cancel (back tocancelUrl). After a delivered event it redirects tosuccessUrl. A captured one-time payment offers Refund. - Portal (
/payment/dev/portal/<sessionId>): for each subscription, Cancel now, Cancel at period end, Resume, Mark past due, Recover, Pause, and a Change plan / seats form.
When your webhook route answers an error, the page shows it instead of redirecting.
Simulate an event in a test
emit(event) applies a simulated provider event to the provider-side state and
returns a signed delivery to hand to handleWebhook:
import { createDevPaymentProvider, createMemoryDevPaymentState } from "@lunora/payment/dev";
const dev = createDevPaymentProvider({
baseUrl: "https://app.test",
env: { WORKER_ENV: "test" },
state: createMemoryDevPaymentState(),
webhookSecret: "test-secret",
});
const payment = createPayment({ adapter: dev.adapter, authorize: () => true, store: new MemoryPaymentStore() });
const { body, headers } = await dev.emit({
data: { priceId: "price_pro", referenceId: "user_1", subscriptionId: "dev_sub_1" },
type: "subscription.active",
});
await payment.handleWebhook(new Request("https://app.test/payment/webhook", { body, headers, method: "POST" }));createMemoryDevPaymentState() is for tests: one process, one provider
instance. It cannot back a running app, for the reason above.
To check that reconcile repairs drift, change provider-side state without an
event (for example dev.adapter.cancelSubscription(id)) and run reconcile
against the dev adapter.
Events carry a time, and the facade drops one older than the last it applied to a subscription. After an API call that changes a subscription (cancel,
resume, update) the facade stamps the row about a minute before the call. Use the real clock, or an injected now that only moves forward and is at
least the facade's Date.now(): a frozen clock in the past makes later portal events read as stale. Events of one subscription are ordered by the time
stored on its record, so two provider instances sharing state, or two events in the same millisecond, are still ordered.