Skip to content

subscriptions

Terminal window
npx skills add https://github.com/crystallizeapi/ai --skill subscriptions

Crystallize Subscriptions

A subscription plan describes what can be sold repeatedly — its periods (monthly, yearly), an optional introductory period, and any metered variables. A variant carries the plan’s prices. A subscription contract is one customer’s agreement: the plan and period they chose, the prices they agreed, the dates it runs on, and the meter readings.

The contract is the whole model. It is not a state machine that bills for you.

Reviewed on 2026-10-30 against the API implementation, on top of two builds that ran the whole lifecycle: Screen Universe (memberships with a 14-day trial and metered downloads) and Lab Universe (B2B standing orders). Claims that come only from those builds are marked.

Two things to know before you write any code

1. Crystallize moves the dates; it never bills. There is no billing engine behind a contract: nothing is charged and no order appears, at renewAt or ever. What does run by itself is the calendar. Within minutes of renewAt the platform renews every contract that has one: renewAt and activeUntil move one recurring period on, a trial moves to its recurring phase, and the renew webhook fires, whether or not anyone paid and even if the contract is paused. A contract with activateAt is activated the same way. A contract with no renewAt runs out and reads cancelled once activeUntil passes. Billing is your job, hung on those events: price the period, charge, write an order. Calling renewSubscriptionContract on top moves the contract a second period; keep it for renewing ahead of renewAt. Plan for that before you model anything.

2. Contracts live in two stores that sync loosely. Core and the Shop API /subscription-contract endpoint both hold contracts, and they are not one store with two doors:

Core API Shop API /subscription-contract
Meant for back office, seeding, batch, renewals a storefront acting for the signed-in customer
Ids 24-character hex id UUID!
Usage tracking trackSubscriptionContractUsage, usage(startDate, endDate) not available — Core only
Needs a customer first yes (CustomerNotFoundError) no, it creates one from customer { … }
Status labelled stable labelled EXPERIMENTAL

A Shop contract is copied to Core about 7 seconds later with a new Core id and the Shop UUID in meta._shopApiId. After that the two copies follow each other, asynchronously: Shop pause, resume, renew, cancel and deactivate are replayed on the Core copy, any other Shop edit overwrites it, and every Core change, scheduled renewals included, overwrites the Shop copy. Those overwrites lose data — see contracts. In the other direction a Core contract is copied into the Shop store with its 24-character Core id as id — which is not a UUID, so subscriptionContracts(customerIdentifier:) then fails on that element and the contract cannot be addressed through the Shop API at all.

So pick one store per tenant and stay in it. Both builds landed on that rule the hard way:

  • Core for everything when the lifecycle is driven server-side — seeding, billing jobs, usage, back-dated history, and account pages rendered by your own server. This is what Screen Universe does. Core is rate limited and is not meant for storefront traffic, so put it behind your own server actions or API routes — never in a browser call, and never once per page view.
  • Shop API for everything when the storefront itself creates and changes contracts for the customer in front of it, as Lab Universe and a third build do for standing orders. Then never create contracts for those customers in Core. Metering still needs the Core copy; see contracts.

Either way the calls run on the server — a server action, an API route, a webhook receiver. The Shop token and the Core token pair never reach the browser. The [[query]] and [[mutation]] skills defer to this choice; [[storefront]] has the API contract around it.

Renewal orders follow the store. On a Core-store tenant, write them with Core registerOrder. On a Shop-store tenant, write them with the Shop API: read orderIntent(id, format: shop) and pass its order to /order create, so the order sits in the same store as the storefront’s order history. Shop createFromSubscriptionContract is in the schema but failed on every contract on two tenants. See usage-and-renewals.

The pipeline

PIM subscriptionPlan.create periods and metered variables — the ids are generated, keep them
Core createProduct / updateProduct variant prices per plan period and price variant
Core igniteDiscoApi so the storefront can read the plan cards from Discovery
Core createCustomer Core contracts need a customer; the Shop endpoint does not
Core createSubscriptionContract the agreement: item, phases, dates, meta (Shop store: Shop create)
Core registerOrder the receipt for the first period (Shop store: Shop /order create)
Core trackSubscriptionContractUsage every metered event, with an idempotency key
… then, every period, per contract ………………………………………………………………………
Crystallize renewalDue webhook a week and a day before renewAt
Crystallize renews the contract at renewAt: dates move one period on, renew webhook fires
Core usage(startDate, endDate) the meter for the period that just ended
you charge your payment provider; Crystallize takes no money
Core registerOrder the invoice: plan line + overage line, priced by you
(Shop store: orderIntent(format: shop) → /order create)
Core updateSubscriptionContract meta.periodStart, so the next meter window starts here

States

SubscriptionContractState is active, paused, pendingActivation, pendingDeactivation or cancelled, and it is derived from the dates, not set directly:

Dates State
activateAt in the future pendingActivation
now before activeUntil, renewAt set active
activeUntil in the future, no renewAt pendingDeactivation
no activeUntil, or it has passed cancelled
paused explicitly (wins over the dates) paused

Two rules follow, and both bite:

  • activateAt is exclusive of renewAt and activeUntil (ActivateAtMustBeExclusiveError; the Shop endpoint only says “Unexpected error”). Send either a future start, or a running contract’s dates.
  • Send renewAt and activeUntil together. createSubscriptionContract fills a missing activeUntil from renewAt, but updateSubscriptionContract { status } and the Shop create do not: there, renewAt alone reads cancelled.

Failure modes

Symptom Cause Fix
Nothing is charged and no order appears at renewAt There is no billing engine Bill from the renew webhook — see usage-and-renewals
renewAt moved two periods A job called renewSubscriptionContract after the platform renewed Never renew what is already due; only bill it
A paused customer gets charged renew and renewalDue fire for paused contracts too Check status.state before charging
A brand-new contract reads cancelled activeUntil missing (Shop: also when only renewAt was sent) Send both; for a trial set both to the trial’s end
subscriptionContracts errors on one element, the rest is data A contract reached the Shop store under its Core id Use one store; read with partial results in the meantime
A Shop pause/renew is not on the Core copy yet The copies sync asynchronously Don’t read one store to confirm a write to the other
Usage tracked but the invoice has no overage Nothing prices usage for you Read usage(…), price the tiers yourself, add an overage line
A trial shows the full price on the plan card Discovery’s initial repeats recurring Read the trial from the plan (PIM, server-side), Catalogue or your own config
MeteredVariableNotFoundError when tracking The metered variable’s id was sent Track by identifier
Variant prices or contracts stop resolving after a plan edit subscriptionPlan.update without ids mints new period ids Always pass the existing ids back
A resumed contract lost the time it spent paused Pause freezes nothing; renewals kept rolling the dates On resume, set renewAt/activeUntil to now plus what was left
A state filter misses contracts that ran out The filter reads the state stored at the last write Compare the dates yourself
InvalidActiveUntilDateError while seeding history Core refuses dates in the past (InvalidRenewAtDateError too) Back-date signedAt and the orders instead
Shop create answers “Unexpected error”, the token reads fine One token with every scope lacks subscription-contract access Mint a token for this route family alone: subscription-contract (+ :admin)
Shop create says “Unexpected error” but the contract exists status { … } was selected in the create response Select only id; read the status later. A blind retry makes a duplicate
createFromSubscriptionContract always “Unexpected error” Not working on the tenants tried orderIntent(id, format: shop) → /order create, or Core registerOrder on Core store
The Shop contract read back has no product or plan SubscriptionContract on the Shop API has no item or plan field Write the SKU, plan and period into the contract’s meta at create

References

  • references/plans-and-pricing.md — plans and periods in the PIM API, variant subscription prices, metered variables, and what Discovery and Catalogue serve.
  • references/contracts.md — creating contracts, the date rules, the whole lifecycle with what each call actually changes, and the Shop endpoint’s differences.
  • references/usage-and-renewals.md — metered usage, period windows, scheduled renewals, renewal orders, orderIntent, webhooks, and how to bill on top of them.

Related: [[pricing]] for price variants and markets, [[mutation]] and [[query]] for the APIs themselves, [[js-api-client]] for the TypeScript helpers, [[bookable-resources]] for the other “sold over time” model — booking holds a calendar, a subscription repeats a charge.


Reference Details

Contracts: creating them, and what each lifecycle call really does

A contract holds the customer, the plan and period they chose, the phases (an optional initial, a required recurring), the dates, and your meta. Everything below is the Core API unless it says otherwise; the Shop endpoint’s differences are at the end.

Create

mutation Create($input: CreateSubscriptionContractInput!) {
createSubscriptionContract(input: $input) {
__typename
... on SubscriptionContractAggregate {
id
status {
state
renewAt
activeUntil
}
}
... on BasicError {
errorName
message
}
}
}
{
"input": {
"customerIdentifier": "ada@example.com",
"subscriptionPlan": { "identifier": "membership", "periodId": "<period id>", "periodName": "Monthly" },
"item": { "sku": "plan-premium", "name": "Membership Premium", "quantity": 1 },
"initial": { "currency": "EUR", "price": 0, "period": 14, "unit": "day" },
"recurring": {
"currency": "EUR",
"price": 19.99,
"period": 1,
"unit": "month",
"meteredVariables": [
{
"identifier": "downloads",
"tierType": "graduated",
"tiers": [
{ "threshold": 0, "price": 0, "currency": "EUR" },
{ "threshold": 10, "price": 0.61, "currency": "EUR" }
]
}
]
},
"status": { "renewAt": "2026-10-12T00:00:00Z", "activeUntil": "2026-10-12T00:00:00Z" },
"payment": { "provider": "custom", "custom": { "properties": [{ "property": "method", "value": "card" }] } },
"meta": [
{ "key": "tier", "value": "premium" },
{ "key": "periodStart", "value": "2026-09-28T00:00:00Z" }
]
}
}
  • subscriptionPlan.periodName is required on Core, so carry the period’s name alongside its id.
  • A phase needs only price and currency: period and unit default to the plan period’s.
  • A Core contract needs an existing customer (CustomerNotFoundError) and an existing SKU (SkuNotFoundError). Create the customer with createCustomer first; it is not an upsert, and answers CustomerIdentifierAlreadyExistsError on a returning customer.
  • payment here records how it will be paid; it does not take money.
  • Core refuses dates in the past (InvalidActiveUntilDateError, InvalidRenewAtDateError). To seed a subscriber “since 2025”, back-date signedAt (accepted) and the orders (registerOrder { createdAt }), and keep your own history in meta.
  • In TypeScript, createSubscriptionContractManager ([[js-api-client]]) wraps create, update and the lifecycle calls. Its createTemplateBasedOnVariant(variant, planIdentifier, periodId, priceVariantIdentifier) builds item, subscriptionPlan, initial and recurring from a variant read with its plans; add customerIdentifier and status. createTemplateBasedOnVariantIdentity fetches the variant itself, but from Catalogue variants, which can be empty — see plans-and-pricing.

The date rules, which decide the state

SubscriptionContractStatusInput is only activateAt, renewAt and activeUntil — there is no state field. See the table in SKILL.md.

  • activateAt cannot be combined with the other two (ActivateAtMustBeExclusiveError). A contract that starts later is created with activateAt alone, and the platform activates it within minutes of that moment: activateAt clears, renewAt and activeUntil become now plus one recurring period, and the activate webhook fires. An initial phase does not shorten that: status.phase reads the trial while the dates read the recurring length, so correct them from the webhook if the trial is shorter. updateSubscriptionContract { status: { renewAt, activeUntil } } replaces the whole status and clears activateAt, so it also activates early.
  • renewAt and activeUntil travel together. For a trial, both are the trial’s end. For a running period, both are the end of the paid period. Because update { status } replaces the whole status, sending { renewAt } alone clears activeUntil and the contract reads cancelled.
  • A contract with an initial phase stays on it until the first renewal, so “is this a trial?” is status.phase equal to the initial phase. Leave initial out and it starts on recurring at once — which is what you want for an add-on, or for seeding an existing subscriber.

One contract, several products

item is the single headline product, but recurring.productVariants takes a list of { sku, name, quantity, imageUrl, meta }, and the phase’s price is what the whole basket costs per period. A standing order of six consumables is therefore one contract with six lines, not six contracts — pause, resume and renewal then act on all of them at once. (Lab Universe.)

The lifecycle

Recorded step by step on a trial contract (renewAt = activeUntil = T+14d):

Call State after What moved
createSubscriptionContract active phase = the 14-day trial
pauseSubscriptionContract paused nothing else — the dates keep their values
pause again error SubscriptionContractIsAlreadyPausedError
resumeSubscriptionContract active dates unchanged
updateSubscriptionContract { item, recurring } active item and recurring phase now; status.phase only at the next renew
renewSubscriptionContract active activeUntil = old activeUntil + one period; renewAt too
cancelSubscriptionContract { deactivate: false } pendingDeactivation renewAt → null, activeUntil kept (runs to the paid end)
renewSubscriptionContract after that active back from the dead, renewAt = activeUntil + one period
cancelSubscriptionContract { deactivate: true } cancelled renewAt and activeUntil → null

Consequences worth designing around:

  • The platform runs the same renew for you. When renewAt comes due it renews the contract, so a renewSubscriptionContract on top moves it a second period. Call it only to renew ahead of renewAt.
  • Renew adds a period to the previous activeUntil, not to now (to now only if there is none), and renewAt lands on the same date. Renewing a long-expired contract revives it on its old dates, and the platform then keeps renewing it until renewAt is back in the future.
  • Pause freezes nothing. The dates keep their values, and a paused contract that has a renewAt keeps being renewed: it stays paused while the dates and the renew and renewalDue webhooks roll on, so check status.state before you charge. Only one with no renewAt runs out, and resume then yields cancelled. To give back the paid time, record what was left at the pause (meta.pauseRemainingMs) and on resume set renewAt/activeUntil to now plus that. Note that updateSubscriptionContract { status } also un-pauses, so a resume is: resume (tolerating SubscriptionContractIsNotPausedError), then the date update.
  • Undo a cancel with updateSubscriptionContract { status: { renewAt: activeUntil, activeUntil } }, not renewSubscriptionContract — renew reactivates too, but silently moves the customer a whole period on without an invoice.
  • A contract cancels once. A second cancelSubscriptionContract answers SubscriptionContractAlreadyCancelledError, so deactivate: true after deactivate: false fails unless the contract was reactivated in between. To end it at once, updateSubscriptionContract { status: {} } clears the dates.
  • updateSubscriptionContract { meta } replaces the whole list. Keys you leave out are deleted; always send all of it.
  • Plan and period cannot change. UpdateSubscriptionContractInput has no subscriptionPlan, so monthly ↔ yearly is cancel plus a new contract. A tier change is update { item, recurring }, with no proration: a contract on its trial shows it at the first renewal, one already on recurring shows it in status.phase at once. Keep the tier in force and the coming one apart (meta.tier, meta.nextTier) and swap them when you bill the renewal.
  • deleteCustomer(identifier, deleteSubscriptionContracts: true) removes a customer and their contracts in one call; orders go separately with deleteOrder.

Reading contracts

subscriptionContracts(filter: { customerIdentifier, state, sku, subscriptionPlanIdentifier, signedAt, activateAt }) is a connection (edges { node { … } }), sortable by createdAt; the two date filters take { min, max }, and there is none on renewAt. One contract is subscriptionContract(id:). Useful fields: status { state activateAt renewAt activeUntil phase }, item, initial, recurring { price currency period unit meteredVariables { tiers } productVariants }, subscriptionPlan { identifier periodId periodName }, meta, and usage(startDate:, endDate:).

status.phase is the phase in force — the trial before the first renewal, the recurring phase after it.

The state filter is not the state you read back. status.state in a result is derived from the dates at read time, while the filter matches the state stored at the last write. A contract that ran out with no write since reads cancelled but still matches state: pendingDeactivation.

The Shop API endpoint

/subscription-contract (scope subscription-contract) is the storefront-facing store, and it is labelled EXPERIMENTAL. What differs:

  • create needs no Core customer: it creates one from customer { identifier, email, firstName, lastName }. Ids are UUID!. Prices are { gross, net } per phase instead of Core’s single price, and the currency comes from context.price.currency (eur if omitted). plan is { identifier, periodId } — no periodName. period and unit have no default here: send them.
  • create checks the SKU, plan, period and metered variables against the published Catalogue in context.language (en if omitted). A draft-only product fails, with no more than “Unexpected error”.
  • Mint a token for this route family alone. A token requested with every Shop scope reads /subscription-contract fine, but create answers only “Unexpected error”. The same call with a token scoped to subscription-contract and subscription-contract:admin works. Cache one token per route family on the server.
  • Select only id from create. Selecting status { … } in the response fails the request with “Unexpected error”, although the contract is created. A retry then makes a duplicate, so read the status in a second query, and make retries check meta for your own key first.
  • The contract you read back has no item and no plan. The Shop SubscriptionContract type has neither field (introspected 2026-11-12), so write the SKU, the plan identifier and the period into meta at create if the account page shows them. recurring.productVariants is served.
  • signedAt on create back-dates, which suits “subscriber since” history.
  • The lifecycle behaves as above (pause, resume, renew, cancel, deactivate, changeDates), with three differences: resume after a cancel is silently ignored, renew on a paused contract makes it active (on Core it stays paused), and the only way to change what is billed is updateRecurringPhase(phase: { price, period, unit, productVariants, meteredVariables }), which replaces the whole phase — there is no item update. changeDates takes only the dates to change, unlike Core’s update { status }.
  • status.phase is null until a Core change syncs back. status.state is stored at each write, not derived, so it does not flip when a date passes: on a “my subscription” page compare activeUntil with now.
  • subscriptionContracts(customerIdentifier:) right after create can answer []; the contract shows up seconds later. Don’t list to confirm a write.
  • Each sync overwrites. A Core change replaces the Shop contract with Core’s view: gross and net both become Core’s single price, and customer and context are dropped. A Shop edit other than pause, resume, renew, cancel and deactivate replaces the Core copy, meta included, which loses _shopApiId; the next Core change, a scheduled renewal included, then reaches the Shop store under the Core id, and subscriptionContracts fails on that element.
  • subscriptionContractTemplate is a stub. It reads nothing: it echoes your arguments with a recurring of 1 month at 0, no initial, and currency: "eur". Build the create input yourself from Discovery plus the plan.
  • There is no delete here. deleteSubscriptionContract on the Core copy removes the Shop contract too; otherwise cancelled test contracts stay in the list.
  • Usage is Core-only and needs the Core id, which the Shop API does not expose. A Shop-store tenant can only meter on the Core copy: find it on Core by meta._shopApiId once it has appeared, and keep the id. If metering matters, keep the whole thing in Core.

Plans, periods and subscription pricing

A plan is the template. It says which periods can be bought (Monthly, Yearly), whether there is an introductory period, and which meters exist. Prices are not on the plan — they are on the variant, per plan period and per price variant.

Plans live in the legacy PIM API

There is no plan surface on the Core API. Create and edit plans in the App’s settings or on https://pim.crystallize.com/graphql, which takes the tenant id, not the identifier:

mutation CreatePlan($input: CreateSubscriptionPlanInput!) {
subscriptionPlan {
create(input: $input) {
identifier
periods {
id
name
initial {
period
unit
}
recurring {
period
unit
}
}
meteredVariables {
id
identifier
}
}
}
}
{
"input": {
"tenantId": "<tenant id>",
"identifier": "membership",
"name": "Membership",
"periods": [
{
"name": "Monthly",
"initial": { "period": 14, "unit": "day" },
"recurring": { "period": 1, "unit": "month" }
},
{
"name": "Yearly",
"initial": { "period": 14, "unit": "day" },
"recurring": { "period": 1, "unit": "year" }
}
],
"meteredVariables": [{ "identifier": "downloads", "name": "Offline downloads", "unit": "download" }]
}
}

The ids are generated, and everything downstream points at them. Period ids and metered-variable ids come back from create as 24-character hex ids. Variant prices reference a period id; contracts reference a period id and a metered-variable identifier. Store them in your seed or config.

update mints new ids for anything you send without one. update(identifier, tenantId, input: { periods: [{ id, … }], meteredVariables: [{ id, … }] }) keeps them; the same lists without ids replace them, and every variant price and contract pointing at the old ids is orphaned: updateSubscriptionContract on those contracts answers SubscriptionPlanPeriodNotFoundError, and a metered variable dropped from the list is also stripped from every variant. A name-only update (input: { name }) leaves periods and meters alone. delete(identifier, tenantId) succeeds even while variants still reference the plan; contract updates and usage tracking then answer SubscriptionPlanNotFoundError.

Prices go on the variant (written on Core)

createProduct, updateProduct and updateProductVariant take subscriptionPlans per variant:

{
"identifier": "membership",
"periods": [
{
"id": "<period id>",
"initial": { "priceVariants": [{ "identifier": "default", "price": 0 }] },
"recurring": {
"priceVariants": [
{ "identifier": "default", "price": 7.99 },
{ "identifier": "nok", "price": 89 }
],
"meteredVariables": [
{
"id": "<metered variable id>",
"tierType": "graduated",
"tiers": [
{ "threshold": 0, "price": 0, "priceVariants": [{ "identifier": "default", "price": 0 }] },
{
"threshold": 10,
"price": 0.5,
"priceVariants": [{ "identifier": "default", "price": 0.5 }]
}
]
}
]
}
}
]
}

Four things worth knowing:

  • ProductVariant.subscriptionPlans reads back on Core, merged with the plan: names and period lengths from the plan, prices from the variant, in periods { id name initial { period unit price priceVariants meteredVariables { tiers } } recurring { … } }.
  • A tier’s own price is not the price most reads show. It is required by the input, but Core, PIM and Discovery take the tier price from priceVariants: price: 99 with default: 0.1 reads 0.1, and an empty priceVariants reads null. Catalogue’s tier price field does answer the tier’s own value, so set it to the default price and every read agrees.
  • Price variants are optional per period. Leave nok out and only default is stored; Discovery then answers nokPrice: null. A period omitted from the variant is stored as initial: null, recurring: null and Discovery drops it.
  • Meters are addressed two ways. On a variant’s tiers, by metered-variable id. On contracts and when tracking usage, by identifier. Mixing them up gives MeteredVariableNotFoundError.

What the storefront can read

Discovery serves the plan cards, and this is the query that works (verified on a live tenant):

{
browse {
plan(language: en) {
hits {
variants {
sku
hasSubscriptionPlans
subscriptionPlans {
identifier
name
periods {
id
name
recurring {
period
unit
defaultPrice
priceVariants
meteredVariables {
identifier
tierType
tiers {
threshold
defaultPrice
}
}
}
}
}
}
}
}
}
}
  • period comes back as a string ("1"), priceVariants as a hash ({ default: { price, currency }, nok: { … } }), and meteredVariables as [] when there are none.
  • Do not trust initial. It repeats recurring’s period, unit and prices (only its meteredVariables are its own): on a tenant whose Monthly period is “14 days free, then 1 month at 7.99”, Discovery answered initial { period: "1", unit: "month", defaultPrice: 7.99 }. Its presence is reliable, since it is null on a period with no initial phase, but take the introductory period from the plan (PIM, server-side), Catalogue or your own config, and price the trial yourself.
  • hasSubscriptionPlans is the cheap filter for “is this a plan variant”.
  • The Catalogue API’s variants can come back empty for products whose variants were created through Core, while defaultVariant and productVariants(skus:, language:) still answer, with the correct plans, including the trial. If a plan card looks empty, read defaultVariant, or use Discovery.

Remember that a plan variant is an ordinary variant: markets, price variants, VAT and volume tiers behave as they do everywhere else — see [[pricing]].

Metered usage and renewals

Two jobs Crystallize does not do for you: pricing what a customer used, and charging them for the next period. The platform keeps the calendar and gives you a meter, webhooks and an order writer; the charge and the arithmetic are yours.

Tracking usage

mutation Track($id: ID!, $input: TrackSubscriptionContractUsageInput!) {
trackSubscriptionContractUsage(subscriptionContractId: $id, input: $input) {
__typename
... on SubscriptionContractUsage {
id
createdAt
}
... on BasicError {
errorName
message
}
}
}
{
"meteredVariableIdentifier": "downloads",
"quantity": 1,
"idempotencyKey": "<contract>:<title>:<profile>:2026-09-28",
"description": "Offline download"
}
  • By identifier, never by id. The metered variable’s id answers MeteredVariableNotFoundError.
  • The idempotencyKey is the retry guard. A reused key answers IdempotencyKeyExistsError and records nothing, which makes it safe to call from a route that may run twice. Keys are unique across the tenant, so build the key from what makes the event unique — contract, thing, day.
  • Fractional quantities are accepted (0.5).
  • Usage is Core-only and needs the Core contract id. A Shop UUID gives InvalidIdError, and usage tracked on the Core copy of a Shop contract is invisible to the Shop API.
  • Usage can be tracked against paused and cancelled contracts too. If that should not be allowed, check status.state in your own route first.

Reading the meter

usage(startDate:, endDate:) on the contract returns the sum per metered variable in that window ([{ meteredVariableIdentifier: "downloads", quantity: 12.5 }]), and [] when there is nothing. It is a window over the tracking time — there is no notion of “the current period”, and usage cannot be back-dated.

So keep the period’s start yourself, in meta.periodStart: set it at sign-up and again each time you bill, and read the meter as usage(periodStart, now). If you renew early — a demo button, a manual run — the next period starts at the moment of renewal, otherwise events between the real renewAt and your early run fall outside every window.

Renewals

The platform renews; you bill. Every few minutes it picks up each contract whose renewAt is due and runs the same operation as renewSubscriptionContract: renewAt and activeUntil move one recurring period on and status.phase leaves the trial. It looks at neither payment nor status.state, so paused contracts renew too, and it can run a few minutes ahead of renewAt. Only clearing renewAt stops it, which is what cancelSubscriptionContract does.

So do not poll for renewAt <= now: the platform has already moved it, and renewing again skips a whole period. Hang billing on the renew webhook and, for each contract:

read the contract stop here if status.state is paused
usage(periodStart, now) the meter for the period that just ended
price the tiers yourself graduated: (usage − threshold) × the tier's price, per tier
charge your payment provider; Crystallize takes no money
registerOrder the invoice: plan line + an overage line so the total adds up
(Shop store: orderIntent(format: shop) → /order create, below)
update meta.periodStart (and tier) that same now, and nextTier → tier if it changed
  • A failed charge does not undo the renewal. The dates have already moved, so decide what it means: cancelSubscriptionContract { deactivate: true } ends the contract now, deactivate: false lets the new period run out.
  • updateSubscriptionContract { meta } replaces the whole list, so send every key back with periodStart and tier. On the Core copy of a contract born in the Shop store that includes _shopApiId: without it, the next Core change reaches the Shop store under the Core id, and subscriptionContracts fails on that element.
  • To charge before the period starts, bill from the day-ahead renewalDue instead (compare its renewAt with now): charge, then call renewSubscriptionContract yourself, which moves renewAt on so the platform finds nothing due. renew fires for that call too, so take billing off the renew webhook, or it charges the period a second time. If the charge fails, cancelSubscriptionContract { deactivate: false } clears renewAt and the contract simply runs out. The usage of the ending period is not complete yet at that point, so this suits flat plans.
  • For a safety net against a missed webhook, keep the renewAt you last billed in meta and sweep the contracts for any that have moved past it. There is no renewAt filter, so page through them.

On a Core-store tenant, registerOrder writes the invoice. The shape that worked:

{
"customer": { "identifier": "ada@example.com" },
"cart": [
{
"name": "Membership Premium",
"sku": "plan-premium",
"quantity": 1,
"type": "subscription",
"subscriptionContractId": "<core contract id>",
"price": { "currency": "NOK", "gross": 211.25, "net": 169 },
"subscription": {
"name": "Monthly",
"period": 1,
"unit": "month",
"start": "2026-10-10",
"end": "2026-11-10",
"meteredVariables": [{ "id": "<metered variable id>", "usage": 13.5, "price": 21.88 }]
}
}
],
"total": { "currency": "NOK", "gross": 238.6, "net": 190.88 },
"type": "recurring"
}
  • subscription.start and end are Date, not DateTime, and here the metered variable is referenced by id — the opposite of tracking.
  • Put the overage on its own line (type: service) so the total adds up. The meters inside subscription.meteredVariables are a record, not a charge: nothing in Crystallize prices them.
  • pipelines: [{ pipelineId, stageId }] drops the order straight into a stage (Trial, Active). The ids come from the PIM API, so resolve them in your seed rather than at runtime.
  • Make it idempotent: put renewalOf = <contract>:<renewAt> in the order’s meta, with the renewAt the contract has after renewing, and look for it with orders(filter: { subscriptionContractId, meta: [{ key, value }] }) before writing.

What orderIntent gives you

orderIntent(id, format: shop | core | coreWithOrderV2 | legacy) on the Shop API returns a draft of the next order — type: recurring, the price of status.phase (the recurring phase while that is null), and subscription { start: renewAt, end: renewAt + period, meteredVariables: [{ identifier, price, usage }] }. It is a preview, not a charge. usage is always 0 and price is the first tier’s, whatever was tracked in Core, and format only labels the result: the shape is the same. Treat it as a template to render, not as a source of truth for money.

Renewal orders per store

Write the renewal order in the store that holds the contracts, so the account page lists it where it lists the rest of the customer’s orders (see “pick one store” in the main skill).

Contracts in Renewal order Evidence
Core Core registerOrder, as above Screen Universe, every period
Shop API orderIntent(id, format: shop) { order }, then /order create with it Standing-order renewals

createFromSubscriptionContract on the Shop /order endpoint does not work: it is in the schema, and every call failed with “Unexpected error” on two tenants — trial, renewed, cancelled and basic contracts, with and without an initial phase, with productVariants, before and after an ignite. Use orderIntent instead: its order has type: recurring, the customer, the context and the lines with subscriptionContractId and the period’s subscription { start end period unit }. Pass it to create with what it lacks, in the same write: pipelines (ids), payments, paymentStatus, and meta with your idempotency key (renewalOf = <contract>:<renewAt>).

Two things to add yourself, because a Shop create does not:

  • The metered charge. The metered price inside subscription.meteredVariables is not added to the total. Price the usage yourself (it is tracked on the Core copy, see contracts) and add it as its own type: service line, with a total that includes it.
  • The date, if you back-date. Shop create ignored createdAt on one tenant and honoured it on another; keep the intended date in meta (orderedAt) as well.

Guard the webhook handler with the Shop API’s /lock endpoint (acquire(key, ttl), release(key), scope lock), keyed on the contract and its renewAt, so two deliveries of one renew do not write two orders. Never use the order listing for that check: orders(customerIdentifier:) lags seconds to minutes behind create. In Screen Universe, Shop renewal orders kept coreId: null and never reached Core, which is fine on a Shop-store tenant and one more reason not to mix stores.

Webhooks

The concern is subscriptionContracts, and its events are create, update, delete and:

Event Fires Payload
renewalDue a week and again a day before renewAt (once a day, by UTC date) subscriptionContractId, renewAt, tenantId
renew on every renewal, scheduled or called id, tenantId
activationDue a week and again a day before activateAt subscriptionContractId, activateAt, tenantId
activate when the platform activates a contract id, tenantId
pause on pauseSubscriptionContract id, tenantId
resume on resumeSubscriptionContract id, tenantId
cancel on every cancelSubscriptionContract id, tenantId
deactivate on cancelSubscriptionContract { deactivate: true }, after cancel id, tenantId
deactivated minutes before activeUntil on a contract with no renewAt subscriptionContractId, tenantId
  • The id does not always have the same name. Those fields are also the variables of the webhook’s graphqlQuery, so renewalDue, activationDue and deactivated need $subscriptionContractId, not $id. The query runs on the PIM API unless graphqlQueryTarget: next sends it to Core.
  • renewalDue and renew fire for paused contracts too. A contract created less than a week before renewAt misses the week-ahead renewalDue. Handle all of them idempotently.
  • Lifecycle calls on the Shop endpoint fire these too, once they have reached the Core copy.
  • createWebhook accepts any concern/event string — nope/nope is accepted — so a typo creates a webhook that never fires, without an error.


Crystallize AI