Skip to content
DocspackagesDocumentation

@lunora/payment

Provider-agnostic payments for Lunora — Stripe/Polar/Autumn/Dodo/Creem adapters, webhook sync, and a payment/subscription state machine.

Packages@lunora/payment@lunora/payment

@lunora/payment is one provider-agnostic API over Stripe, Polar, Autumn, Dodo Payments, and Creem. Webhook events are verified, normalized, and applied through an explicit payment/subscription state machine that makes duplicate and out-of-order deliveries safe by construction, and synced into a durable store that rides the request's ctx.db. Switching providers is a configuration change: the provider is a stateless translator; the store owns all state.

Outbound calls carry idempotency keys wherever the provider accepts one (no double-charge), and every mutation is authorized per-caller. Each adapter takes a loader for the provider's SDK client, called on the first provider call and reused, so the SDK stays out of the Worker's startup graph. A static import of the SDK in the entry (import Stripe from "stripe") is evaluated at startup and defeats this. The provider SDKs are optional peer dependencies, so you install (and bundle) only the providers you actually use.

pnpm add @lunora/payment stripe

Configure

Merge the store's tables into your schema with one .extend:

// lunora/schema.ts
import { paymentExtension } from "@lunora/payment";
import { defineSchema } from "@lunora/server";

export default defineSchema({
    // ... your app tables
}).extend(paymentExtension);

ctx.payments is wired by codegen onto ActionCtx whenever a lunora/ source imports @lunora/payment or reads ctx.payments. The adapter, which carries provider secrets, comes from a config.payment(env) thunk you pass to createShardDO(). The store is built per request from ctx.db, and the default authorizer ties referenceId to ctx.auth.userId.

import { createStripeAdapter } from "@lunora/payment/stripe";
import { createShardDO } from "./_generated/shard";

export const ShardDO = createShardDO({
    payment: (env) => ({
        adapter: createStripeAdapter({
            // A real `Stripe` instance satisfies the loaded client's type, so no cast. The fetch
            // HTTP client is already the default in the workerd build; passing it is explicit.
            client: async () => {
                const { default: Stripe } = await import("stripe");

                return new Stripe(env.STRIPE_SECRET_KEY, { httpClient: Stripe.createFetchHttpClient() });
            },
            webhookSecret: env.STRIPE_WEBHOOK_SECRET,
        }),
        // Override the default "caller owns the referenceId" rule for org/workspace keys. It runs per
        // request with the caller's `userId` and the request's `ctx.db`.
        // authorize: async (orgId, { db, userId }) =>
        //     (await db.findFirst("members", { where: { orgId, role: "owner", userId } })) !== null,
        entitlements: {
            plans: {
                pro: { features: ["export"], limits: { api_calls: 1000 }, priceIds: ["price_123"] },
            },
        },
        observability: (event) => console.log("[payment]", event.type, event),
    }),
});

The thunk returns PaymentsFromContextOptions:

OptionTypeNotes
adapterPaymentAdapterBuilt with createStripeAdapter / createPolarAdapter / createAutumnAdapter / createDodoPaymentsAdapter / createCreemAdapter. Required.
authorizeAuthorizeContextReference(referenceId, { db, userId }) => boolean | Promise<boolean>. Defaults to "caller owns reference".
entitlementsEntitlementsConfigPlan → features/limits map. Required for a featureId check and for listBalances on providers without native entitlements; a priceId check needs none.
observabilityPaymentObserverTelemetry sink for webhook applies, failed payments, past-due subscriptions.
singleSubscriptionPerReferencebooleanOff by default. When on, a second subscription that would grant access on one reference is refused and recorded in a state that grants nothing. The operator is alerted with subscription.duplicate and must cancel it at the provider, which still bills it. Two grants that race are ordered by a per-reference counter, so one keeps its access and the other is refused; for the moment between the loser's write and its step back, both rows read as granting.

Provider adapters

Every adapter takes a client loader and verifies inbound webhooks. Each lives at its own subpath so importing one never loads another provider's SDK:

import { createAutumnAdapter } from "@lunora/payment/autumn";
import { createCreemAdapter } from "@lunora/payment/creem";
import { createDodoPaymentsAdapter } from "@lunora/payment/dodopayments";
import { createPolarAdapter } from "@lunora/payment/polar";
import { createStripeAdapter } from "@lunora/payment/stripe";

const stripe = createStripeAdapter({ client, webhookSecret, webhookToleranceSeconds: 300 });
const polar = createPolarAdapter({ client, webhookSecret });
const autumn = createAutumnAdapter({ client, webhookSecret });
const dodo = createDodoPaymentsAdapter({ client, webhookSecret });
const creem = createCreemAdapter({ client, webhookSecret });
OptionStripePolarAutumnDodoCreemNotes
client✓✓✓✓✓Loads the provider's SDK client (e.g. a Stripe instance) on first use.
webhookSecret✓✓✓✓✓Signing secret for inbound webhook verification.
webhookToleranceSeconds✓✓✓✓Optional clock-skew tolerance (schemes that sign a timestamp).

Stripe is a payment service provider (PSP) with manual authorize/capture available. Polar, Dodo Payments, and Creem are Merchants-of-Record: merchantOfRecord is true and they own tax/invoices, so manual capture isn't part of their flow. Stripe webhooks use Stripe's signature scheme; Polar, Autumn, and Dodo Payments use Standard Webhooks (webhook-id / webhook-timestamp / webhook-signature); Creem uses a single creem-signature HMAC-SHA256 header.

Creem

Creem is a Merchant-of-Record for software with an EU-friendly global footprint. Unlike a raw PSP, it is product-based (real product ids), so it slots into the priceId interface directly like Polar/Dodo: hosted checkout sessions, first-class subscriptions (cancel at period end, pause/resume, plan upgrades), and a genuine hosted billing portal via customers.generateBillingLinks (portal is true). Refunds are issued from the Creem dashboard (no SDK endpoint), so refundPayment throws. Webhooks are verified with the creem-signature HMAC-SHA256 header.

import { createCreemAdapter } from "@lunora/payment/creem";

const creem = createCreemAdapter({
    client: async () => {
        const { Creem } = await import("creem");

        return new Creem({ apiKey: env.CREEM_API_KEY });
    },
    webhookSecret: env.CREEM_WEBHOOK_SECRET,
});

Autumn

Autumn is an open-source billing layer that runs on your own Stripe account, so it is not a Merchant-of-Record, but, like Polar, it abstracts the money movement, so manual authorize/capture/refund throw. It keys a subscription on the (customerId, planId) pair, which the adapter encodes as the composite id "<customerId>::<planId>".

Autumn owns entitlement truth: balances, credits, limits, and rollovers are computed on its side from your plan config. The adapter implements the optional checkEntitlement / getBalances hooks, so the facade delegates check and listBalances straight to Autumn's live API, and you do not need to configure entitlements for an Autumn app. Because of that, the authoritative sync path is live queries + reconcile, not webhook fan-in (the autumn-js SDK models no outbound webhook stream). Autumn's dashboard can still emit Standard Webhooks (Svix) events, so parseWebhook is provided as a best-effort convenience; reconcile remains the reliable path for subscription drift.

Load the client from autumn-js (the cast keeps the package free of a hard autumn-js dependency):

import type { AutumnClientLike } from "@lunora/payment/autumn";
import { createAutumnAdapter } from "@lunora/payment/autumn";

const autumn = createAutumnAdapter({
    client: async () => {
        const { Autumn } = await import("autumn-js");

        return new Autumn({ secretKey: env.AUTUMN_SECRET_KEY }) as unknown as AutumnClientLike;
    },
    webhookSecret: env.AUTUMN_WEBHOOK_SECRET,
});

A companion facade, createAutumnFeatures, holds the Autumn-native concepts that have no cross-provider equivalent: entities (per-seat/per-workspace sub-customers), referrals, usage-events analytics, the plan catalog, and a native checkout (prepaid feature quantities, entity scoping, reward codes, opting out of a plan's trial). It is kept separate so the provider-agnostic surface stays generic. It takes a client loader, like the adapter, and runs it on its first call. (Credit systems need no extra method: Autumn models them as features, so their balances flow through check / listBalances like any other.)

import type { AutumnFeaturesClientLike } from "@lunora/payment/autumn-features";
import { createAutumnFeatures } from "@lunora/payment/autumn-features";

const autumnFeatures = createAutumnFeatures({
    client: async () => {
        const { Autumn } = await import("autumn-js");

        return new Autumn({ secretKey: env.AUTUMN_SECRET_KEY }) as unknown as AutumnFeaturesClientLike;
    },
});

await autumnFeatures.entities.create(userId, { featureId: "seats", id: "workspace_a", name: "Workspace A" });
const usage = await autumnFeatures.events.aggregate(userId, { featureId: "api_calls", range: "30d" });
const { url } = await autumnFeatures.checkout(userId, { planId: "pro" });

Dodo Payments

Dodo Payments is a Merchant-of-Record: like Polar, it is the legal seller of record and calculates, collects, and remits tax across 190+ countries, and owns chargebacks and disputes. So merchantOfRecord is true and manual authorize/capture throw, but refunds are first-class (refunds.create). The flow is checkout-session → subscription/payment, synced from Standard Webhooks (the dodopayments SDK exposes the full, verified event catalog: payment.*, subscription.*, refund.*, …). It supports usage-based billing, so reportUsage ingests Dodo usage-events.

Load the client from dodopayments (the cast keeps the package free of a hard dodopayments dependency):

import type { DodoPaymentsClientLike } from "@lunora/payment/dodopayments";
import { createDodoPaymentsAdapter } from "@lunora/payment/dodopayments";

const dodo = createDodoPaymentsAdapter({
    client: async () => {
        const { default: DodoPayments } = await import("dodopayments");

        return new DodoPayments({ bearerToken: env.DODO_PAYMENTS_API_KEY }) as unknown as DodoPaymentsClientLike;
    },
    webhookSecret: env.DODO_PAYMENTS_WEBHOOK_KEY,
});

The ctx.payments API

Call the facade from an action. Every method authorizes the caller against the referenceId first.

MethodReturnsWhat it does
createCheckout(input)CheckoutResultStart a hosted checkout (mode: "payment" | "subscription"); returns a url.
attach(input)CheckoutResultPlan alias of createCheckout with mode defaulting to "subscription".
createPortalSession(referenceId, returnUrl){ url }Open the provider billing portal; customer derived from the store (no insecure direct object reference (IDOR)).
cancelSubscription(subscriptionId, options?)SubscriptionCancel now or atPeriodEnd; persists the result.
updateSubscription(subscriptionId, patch)SubscriptionChange the plan (priceId) or seats (quantity) of the caller's own subscription; persists the result.
resumeSubscription(subscriptionId, options?)SubscriptionUndo a period-end cancel (Creem: resume a paused subscription); persists the result.
refundPayment(input)PaymentSessionRefund the caller's own captured payment, in full or in part; persists the result.
capturePayment(input)PaymentSessionCapture the caller's own authorized payment; persists the result.
cancelPayment(sessionId, options?)PaymentSessionCancel the caller's own uncaptured payment; persists the result.
listSubscriptions(referenceId)Subscription[]Synced subscriptions for a reference.
check(input)CheckResultIs a reference allowed something now? Pass featureId or priceId.
listBalances(referenceId)FeatureBalance[]Resolve every configured feature's allowance in one call.
track(input)TrackResultRecord metered usage (exactly-once by idempotency key).
handleWebhook(request)ResponseVerify + normalize + apply a provider webhook.

refundPayment derives the provider's idempotency key from the session, the amount sent and the reason. On a provider whose refund endpoint takes that key (Stripe), a same-amount refund without a caller idempotencyKey can therefore be replayed by the provider: no money moves, the call returns the session unchanged and the observer receives a refund.replayed event. Pass a distinct idempotencyKey for an intentional second refund of the same amount. Polar and Dodo take no refund key, so there a repeated refund is a new refund, bounded only by the local over-refund guard.

The provider adapter is not reachable from ctx.payments. Every money and subscription operation goes through the facade methods above, which authorize the caller and write the store. ctx.payments.provider gives the provider's identifier and capabilities (read-only) for checks an app makes before it starts an operation, for example if (!ctx.payments.provider.capabilities.checkoutExpiry) throw new Error("this provider cannot expire a checkout");.

import { action, query, v } from "./_generated/server";

export const checkout = action.input({ priceId: v.string() }).action(async ({ ctx, args: { priceId } }): Promise<{ url: string }> => {
    const { url } = await ctx.payments.createCheckout({
        referenceId: ctx.auth.userId,
        priceId,
        mode: "subscription",
        successUrl: "https://app.test/done",
        cancelUrl: "https://app.test/cancel",
    });

    return { url };
});

createCheckout reuses a reference's stored provider customer, minting a new one only on first checkout (the customer is never caller-supplied), and attaches an outbound idempotency key automatically (override via input.idempotencyKey). A key you pass is hashed and namespaced to the authorized reference before it reaches the provider, so two tenants choosing the same key never collide. On Stripe, a replay of a completed or expired session is retried once under a derived key, so a repeat checkout gets a payable session.

Pass expiresAt (epoch ms) to stop the hosted checkout being payable after that time — for example, so a session abandoned for a later one cannot be paid as well. Stripe honours it (30 minutes to 24 hours from creation); a provider whose capabilities.checkoutExpiry is false refuses the call with PROVIDER_ERROR rather than leave the session open past your bound. The expiry is part of the derived idempotency key (Stripe refuses a replayed key whose parameters differ), so one computed from the clock makes every call a new request: pass your own idempotencyKey if a retry should get the first session back.

Entitlements: check and track

Entitlements are derived from already-synced subscription state, which is cheap and in-Worker and needs no external billing service. A plan is granted when an active (or trialing) subscription holds one of its priceIds. When several active plans cap the same limit, the most-generous value wins.

  • A product check (priceId) is allowed when the reference holds an active subscription on that price.
  • A boolean feature check (featureId, no numeric limit) returns unlimited: true when granted.
  • A metered feature check (featureId with a plan limit) subtracts usage tracked this period and returns { allowed, balance, limit, used }. "This period" is the billing period of the subscription whose plan grants that limit, so an unrelated subscription renewing never resets it.

The following actions record one call and read the remaining allowance:

export const recordApiCall = action.action(async ({ ctx }): Promise<{ recorded: boolean }> => {
    // `mode: "add"` (default) increments; `"set"` reconciles the LOCAL period total.
    // Both are a single append — a `"set"` records the absolute target as a marker
    // the period fold resets to, so concurrent or replayed `"set"` calls resolve
    // last-writer-wins instead of double-applying. Neither mode needs a lock.
    // `"set"` throws on a provider that meters usage upstream — see the callout below.
    const result = await ctx.payments.track({ referenceId: ctx.auth.userId, featureId: "api_calls" });

    return { recorded: result.recorded };
});

export const apiCallsRemaining = action.action(async ({ ctx }): Promise<{ allowed: boolean; balance?: number }> => {
    const result = await ctx.payments.check({ referenceId: ctx.auth.userId, featureId: "api_calls" });

    return { allowed: result.allowed, balance: result.balance };
});

track writes a durable, append-only usage ledger that check folds over the current billing period. When the provider advertises usage metering, the event is also forwarded to its metering API. That forward is best-effort: a reporting failure is observed, never thrown, and the local ledger check reads is always updated.

Deduping a retry is opt-in. Pass your own idempotencyKey — namespaced to the reference and feature, it makes the append exactly-once, so a retried call records once. Omit it (as the example above does) and track mints a fresh crypto.randomUUID() per call, which means "always record": the same call retried after a timeout counts twice. Derive the key from whatever identifies the unit of work — the request id, the message id, the job id.

mode: "set" is local-only, and throws where the provider meters. Provider meters are additive: they take events, not period totals, so a "set" can only be forwarded as a delta against the total just read — and a "set" that LOWERS usage has no negative delta to send. set 10 → set 5 → set 8 would forward 10 then 3, billing 13 upstream against a local period total of 8. Rather than over-bill silently, track rejects "set" with a VALIDATION_ERROR on any provider whose capabilities.usageMetering is true (Stripe, Polar, Dodo, Autumn). Use mode: "add", which is exact on both sides. "set" stays available where usage is enforced locally.

Webhooks

Signature verification needs the raw request body, so the webhook endpoint runs at the Worker edge via httpAction (no ctx.db). It forwards the raw body and signature into the shard via ctx.runAction, where ctx.payments and its store exist:

// lunora/http.ts
import { webhookResponse } from "@lunora/payment";
import { httpAction, httpRouter } from "lunorash/server";
import { processWebhook } from "./billing";

export const app = httpRouter();

app.post(
    "/payment/webhook",
    httpAction(async (ctx, request) => {
        const body = await request.text();
        // Stripe's header. Polar, Dodo Payments, Autumn, and Creem each read their own (see the provider pages).
        const signature = request.headers.get("stripe-signature") ?? "";

        // `webhookResponse`, not `Response.json(...)`: only the JSON payload crosses the
        // `runAction` boundary, so the status has to be re-applied on this side or every
        // outcome — including the deliberate 500 below — answers 200.
        return webhookResponse(await ctx.runAction(processWebhook, { body, signature }));
    }),
);

The following internal action runs in the shard and passes the request to handleWebhook:

// lunora/billing.ts
import { internalAction, v } from "./_generated/server";

export const processWebhook = internalAction
    .input({ body: v.string(), signature: v.string() })
    .action(async ({ ctx, args: { body, signature } }): Promise<{ applied: boolean; status: number }> => {
        const request = new Request("https://internal/payment/webhook", {
            body,
            headers: { "stripe-signature": signature },
            method: "POST",
        });
        const response = await ctx.payments.handleWebhook(request);
        const result = (await response.json()) as { applied?: boolean };

        return { applied: result.applied ?? false, status: response.status };
    });

handleWebhook verifies the signature, normalizes the event into a WebhookAction (e.g. subscription.active, payment.captured, payment.refunded), and applies it through the state machine. A duplicate or no-op event is acknowledged with 200, not re-applied. The inbound provider event id keys an append-only events log for idempotency and audit. A subscription event older than the last one applied to its row (a redelivery after a 5xx) is acknowledged as stale and ignored, so a late active cannot re-entitle a subscription that has since gone past_due.

There is one deliberate non-200. An orphaned event — one that patches a row whose create event has not arrived yet, which is how providers deliver out-of-order — returns 500 so the provider retries it, and the update applies once the create lands. Do not "fix" that by always answering 200: swallowing the retry is how an out-of-order delivery is lost for good. That is also why the route must return webhookResponse(result) rather than Response.json(result) — the status does not survive the runAction hop on its own. Malformed deliveries (a missing provider event id) likewise surface as a 5xx rather than a 400, so every provider retries them instead of some treating a 400 as "stop".

A money amount the store cannot hold — one beyond 2^53 minor units — is the other event that is acknowledged with 200 although nothing was written. A retry would fail the same way, so the result is unstorable, and the observer receives a webhook.applied with reason: "unstorable". The amount is not in the ledger: recover it from the provider, and alert on that observer event.

The orphan retry is bounded to exactly one. The row may never appear at all — a subscription created before the integration existed, a store reset, a completed-but-unpaid checkout whose create event never arrives — and an event retried forever makes the provider hammer the endpoint until it disables it, taking every other event down with it. So the first sighting answers 500 and the second is acknowledged 200 with reason: "unhandled". That budget is spent in wall-clock order, not on a schedule: a sender that retries immediately (svix-backed providers such as Polar and Dodo do) can burn it seconds after the first delivery, while the create event is still in flight. If the create event can lag that far behind, do not lean on the webhook retry — sweep non-terminal rows with reconcile as below.

Webhooks are eventually-but-not-guaranteed: an endpoint down past the provider's retry window can drop an event for good. reconcile re-fetches the provider's current truth for given payment/subscription ids and overwrites the store when it has drifted. Pair it with a @lunora/scheduler job that sweeps non-terminal rows.

Data it stores

paymentExtension ships the store's five tables with the package. .extend() namespaces them with the payment key, and codegen reads them from the installed package, so a new column or index reaches your app when you upgrade @lunora/payment: there is nothing to copy into your schema.

TableHolds
payment_customersone row per (provider, referenceId), carrying the provider's customer id
payment_subscriptionsone row per provider subscription: price, quantity, state, current period
payment_sessionsone row per payment: amountMinor, capturedMinor, refundedMinor, currency, state
payment_eventsthe append-only webhook log — inbound idempotency, audit, debugging
payment_referenceRevisionsone counter per reference that orders grants under singleSubscriptionPerReference
payment_usageEventsthe append-only metered-usage ledger check folds over

Money is stored as (amountMinor: number, currency: string) columns. A number holds every integer up to 2^53 exactly (about 90 trillion dollars in cents), and the store refuses to write an amount outside that range rather than round it. Every row carries a provider discriminator so multiple providers can coexist during a migration. A capture or refund is not its own table: both fold into the payment's payment_sessions row as capturedMinor / refundedMinor plus a state (refunded / partially_refunded). Products, prices, checkouts and invoices stay with the provider — the store does not mirror them.

Extension tables live on the shard. Chaining .global() on one of them is not available, so the per-table D1 opt-in an inline table had does not carry over.

Upgrading

  • Caller idempotency keys are now namespaced and hashed before they reach the provider. A retry that spans the deploy reaches the provider under a new key, so it is not deduplicated against the attempt made before it — avoid retrying a payment operation across the deploy.

API reference

These public exports are not covered by the sections above. Import them from @lunora/payment.

reconcile(input)

Type: (input: ReconcileInput) => Promise<ReconcileResult>

Re-fetches the provider's current state for the given paymentSessionIds and subscriptionIds, and overwrites any store row that has drifted. It also re-sends usage events the provider never accepted. The usage retry is skipped for an adapter that does not meter usage and for one whose forward is not idempotent (Autumn). ReconcileResult reports checked*, updated* and failed* counts for payments, subscriptions and usage.

Default: usageReportLimit is 100.

singleSubscriptionPerReference is required, and it must match the value given to createPayment. A sweep that omits it can re-grant access the policy refused. A refused subscription is recorded in a state that grants nothing (paused, or the state the row already had when that grants nothing too), under the owner it was refused for, and reported as reconcile.drift, with a subscription.duplicate event naming the subscription.

LunoraPaymentError

Type: class LunoraPaymentError extends LunoraError, with code: PaymentErrorCode

Every failure the package throws. The status is the HTTP status the code maps to:

CodeStatus
CONFIG_INVALID500
CURRENCY_MISMATCH400
FORBIDDEN403
INVALID_TRANSITION409
NOT_FOUND404
PROVIDER_ERROR502
VALIDATION_ERROR400
WEBHOOK_EVENT_ID_MISSING400
WEBHOOK_SIGNATURE_INVALID400
WEBHOOK_TIMESTAMP_INVALID400

Inside handleWebhook, a WEBHOOK_EVENT_ID_MISSING surfaces as a 5xx rather than the 400 above, so every provider retries the delivery. See Errors for the full catalog.

PAYMENT_TERMINAL_STATES and SUBSCRIPTION_TERMINAL_STATES

Type: ReadonlySet<PaymentState> and ReadonlySet<SubscriptionState>

The states the state machine treats as terminal. PAYMENT_TERMINAL_STATES holds canceled and refunded. SUBSCRIPTION_TERMINAL_STATES holds canceled. Use them to select the non-terminal rows that a reconcile sweep should check.

money(minorUnits, currency)

Type: (minorUnits: bigint | number, currency: CurrencyCode) => Money

Builds a Money value, { currency, minorUnits: bigint }, from integer minor units. The other money helpers (addMoney, subtractMoney, compareMoney, allocateMoney, formatMoney, zeroMoney, isZeroMoney, moneyFromMinor, toMoneyJSON, fromMoneyJSON) operate on the same type. Pass a Money as amount to refundPayment for a partial refund.

PaymentObserver

Type: (event: PaymentEvent) => void

The type of the observability option. PaymentEvent.type is one of webhook.applied, webhook.duplicate, subscription.duplicate, payment.failed, subscription.past_due, usage.report_failed, reconcile.drift, reconcile.completed, reconcile.error or refund.replayed.

PaymentAdapter

Type: interface PaymentAdapter

The contract every provider implements, and what a custom adapter must provide. The required members are identifier, capabilities, createCheckout, createPortalSession, getOrCreateCustomer, parseWebhook, refundPayment, capturePayment, cancelPayment, getPaymentStatus, getSubscriptionStatus, cancelSubscription, updateSubscription and resumeSubscription. The optional hooks checkEntitlement, getBalances and reportUsage let the facade delegate check, listBalances and track to the provider.

PaymentStore

Type: interface PaymentStore

The persistence port the state machine writes through. createDatabasePaymentStore implements it on ctx.db. MemoryPaymentStore implements it in memory.

verifyStandardWebhook(input) and verifyCreemSignature(input)

Type: (input) => Promise<void>

Verify a webhook signature for a custom adapter. They throw a LunoraPaymentError: CONFIG_INVALID when the secret is empty, WEBHOOK_SIGNATURE_INVALID for a missing or non-matching signature, and WEBHOOK_TIMESTAMP_INVALID for a timestamp outside the window.

Default: verifyStandardWebhook uses a toleranceSeconds of 300. verifyCreemSignature checks no timestamp, because Creem signs the body alone.

Studio

The Studio Payments panel (under Operations) shows synced customers, subscriptions, and webhook events for the app. The panel only appears once codegen detects payments in use.