Where this code goes, and what it assumes
Where this code goes, and what it assumes
Examples on this page are fragments. They render inside the provider you mounted
in the Quickstart:If something below does not work, one of these is usually missing. Each links
straight to the step that sets it up.
- Component registered —
app.use(creem)inconvex/convex.config.ts - Secrets set —
CREEM_API_KEYandCREEM_WEBHOOK_SECRETin Convex env - Billing API exported —
convex/billing.tscallingcreem.api({ resolve }) - Webhook registered —
creem.registerRoutes(http)inconvex/http.ts - Products created — one Creem product per plan and billing cycle
- Products synced —
npx convex run billing:syncBillingProducts - Styles imported —
@creem_io/convex/stylesafter the Tailwind import - Catalog defined —
billingCatalogmapping plan IDs to product IDs - Provider mounted —
<CreemConvexProvider>around your billing UI
Custom auth and RBAC
Billing and identity are separate domains that meet in one place: theresolve
callback. Your auth layer answers who is calling and what may they act on.
This component answers what that billing entity owns and may change. resolve
is the handover between the two.
On the billing side, the generated API enforces its own boundary: every
generated function except the public products.list and products.get, which
read no entity, derives the entity from resolve, scopes customer data to that entity, and verifies
explicitly selected subscriptions before reading or changing them. The only
entity a browser can name is the optional entityId of uiModel and
checkouts.create, which <Subscription.Root entityId> sends: your resolver
authorizes it, and the call fails when the resolver returns another entity.
Every other generated function acts on the entity your resolver returns by
default.
On the identity side, sessions, roles, and org membership stay with whatever auth
you already use. Convex Auth, Clerk, WorkOS, or your own tables all work the
same way here, because the component only ever sees the result.
Quick start
creem.api({ resolve }) generates ready-to-export Convex functions. Each one,
except the public products.list and products.get, calls your resolve
callback to authenticate and determine the entityId. For
team billing, verify membership and the required billing role before returning
an organization ID, since that check belongs to the identity domain. This is
what the Quickstart uses.
Full control
Call the resource namespaces (creem.subscriptions.*, creem.checkouts.*,
creem.customers.*, creem.orders.*, creem.products.*) inside your own Convex
functions and handle auth, entity resolution, and permission checks there. The
library exports shared arg validators matching exactly what the widgets send,
so your custom functions stay drop-in compatible:
subscriptionUpdateArgs carries a kind discriminator for the three mutually exclusive update targets. The exported SubscriptionUpdateArgs type is a true discriminated union:
"immediate" on a paid switch, or two targets at once, does not compile.
Convex requires top-level args to be a flat object, which means the wire validator itself is permissive. The generated mutation calls parseSubscriptionUpdateArgs to re-check the same rules for calls arriving over the wire. Use it in your own wrappers too:
convex/billing.ts
convex/billing.ts
permissions so non-admins see disabled buttons instead of server errors. The server check above is what actually enforces the rule.
Credit grants and spending are deliberately not part of ConnectedBillingApi.
Expose an app-specific backend action for a business operation such as
generateImage, and let that action call creem.credits.creditForEntity or
creem.credits.debitForEntity with server-controlled amounts, references, and
idempotency keys.
Resolver plan overrides
The resolver may return two optional overrides, for apps that own their plan assignment rather than letting the component own it:
Omit both and the component reads the active plan from its own app-plan
assignment rows.
Billing a named entity
A widget can bill an entity other than the caller’s default one, for example an organization the user administers without having switched to it:<Subscription.Root entityId={organizationId} />. The generated uiModel and
checkouts.create take that entityId and pass it to your resolver as its
second argument. The resolver gets a context with only runQuery, so it reads
the caller and checks the entity in an internal query of yours:
convex/billing.ts
entityId (one written before this option, which
ignores request), the call fails instead of reading or billing the default
entity.
A Subscription.Root with entityId is purchase-only: it starts new
checkouts for the named entity, and that’s all. Plan changes, cancellation,
resume and unit updates act on the caller’s default entity, so it offers none
of them and shows no scheduled-change banner. Billing widgets nested inside it
aren’t supported: Product.Root, BillingEmail, Credits.Root,
BillingPortal, BillingHistory, PaymentRecoveryButton,
ScheduledChangeBanner and a Subscription.Root without entityId render
nothing there and make no call, and log one
console warning each. Its own parts (the cards, the choice, Subscription.Item
and its slots) keep working. Under a root without entityId, the nested
widgets work as before.
When entityId changes while an action is under way, nothing reaches another
entity than the one the action started for:
- an open dialog closes, so there is nothing left to confirm;
- a plan switch or app-plan activation whose
onBeforePlanChangeoronBeforePlanActivationresolves after the change stops without a message, because the root no longer allows it; - any other billing call of the root, for example a checkout whose
onBeforeCheckoutawaited a sign-in, is refused when it would be sent, and the root shows “The billing entity changed, so nothing was sent”. A SvelteScheduledChangeBannerinside a default root logs the same refusal to the console instead, as it does with its other failures.
expectedEntityId, the entity the widget showed, and the generated
function refuses it with the same message when it would bill another one. That
also covers what the client can’t see, such as the resolver’s default moving
while a guard waits. See
Reference → expectedEntityId.
checkoutCreateArgs stays without entityId, so a custom wrapper declared with
it alone rejects a call that names an entity, and spreading its arguments into
creem.checkouts.create never takes the entity from the browser.
A custom uiModel or checkouts.create that serves
<Subscription.Root entityId> declares the entity itself: args: uiModelArgs for the model and
args: { ...checkoutCreateArgs, ...entityRequestArgs } for the checkout. Take
entityId out of the arguments, authorize it, and pass the entity you
authorized to creem.getBillingModel or creem.checkouts.create. A wrapper
with args: {} or args: checkoutCreateArgs rejects the calls of a root that
names an entity.
Webhook event middleware
registerRoutes accepts an events map for app-specific logic. Your handlers run after the component’s built-in processing, which upserts customers, subscriptions, and orders.
The ctx is a Convex action context. It has no ctx.db, so reach your own tables through ctx.runQuery and ctx.runMutation, and use ctx.runAction for third-party calls:
checkout.completed, subscription.active, subscription.paid, subscription.canceled, subscription.scheduled_cancel, subscription.past_due, subscription.expired, subscription.trialing, subscription.paused, subscription.unpaid, subscription.update, refund.created, dispute.created. Dispute events are available to custom handlers only (no built-in sync).
Checkout gates and auto-resume
onBeforeCheckout fires before the widget calls checkouts.create, at either the provider or the widget level. Return false to abort. Use it for auth gates, terms acceptance, confirmation dialogs, or analytics:
pendingCheckout.save(intent), the widget notices when the Convex query re-fires with an authenticated user and re-triggers checkout itself. This works for modal auth such as Clerk or an Auth0 popup, and for redirect auth such as OAuth, with no manual resume code. An intent from a root that names an entity carries its entityId and resumes only in a Subscription.Root for the same entity; an intent without entityId, including one saved by an earlier version, belongs to the default entity, and only that one resumes in Product.Root.
Auto-resume is skipped when the user already has an active subscription or owns the product, so a sign-in cannot produce a duplicate purchase.
Sibling guards for the other flows: onBeforePlanChange (paid switches and unit updates) and onBeforePlanActivation (app-owned plans like trials).
Internationalization
Seti18n once on the provider. Every connected widget inherits it, covering
cards, dialogs, billing history, portal buttons, recovery banners, credits, and
accessibility labels:
Custom billing UI model
uiModel returns everything the widgets need. To add app-specific fields, write your own query on top of creem.getBillingModel():
entityId is handled gracefully, so public pricing pages get the catalog without auth.