subscriptions
npx skills add https://github.com/crystallizeapi/ai --skill subscriptionsCrystallize 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 themCore createProduct / updateProduct variant prices per plan period and price variantCore igniteDiscoApi so the storefront can read the plan cards from DiscoveryCore createCustomer Core contracts need a customer; the Shop endpoint does notCore 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 renewAtCrystallize renews the contract at renewAt: dates move one period on, renew webhook firesCore usage(startDate, endDate) the meter for the period that just endedyou charge your payment provider; Crystallize takes no moneyCore 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 hereStates
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:
activateAtis exclusive ofrenewAtandactiveUntil(ActivateAtMustBeExclusiveError; the Shop endpoint only says “Unexpected error”). Send either a future start, or a running contract’s dates.- Send
renewAtandactiveUntiltogether.createSubscriptionContractfills a missingactiveUntilfromrenewAt, butupdateSubscriptionContract { status }and the Shopcreatedo not: there,renewAtalone readscancelled.
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.periodNameis required on Core, so carry the period’s name alongside its id.- A phase needs only
priceandcurrency:periodandunitdefault to the plan period’s. - A Core contract needs an existing customer (
CustomerNotFoundError) and an existing SKU (SkuNotFoundError). Create the customer withcreateCustomerfirst; it is not an upsert, and answersCustomerIdentifierAlreadyExistsErroron a returning customer. paymenthere 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-datesignedAt(accepted) and the orders (registerOrder { createdAt }), and keep your own history inmeta. - In TypeScript,
createSubscriptionContractManager([[js-api-client]]) wraps create, update and the lifecycle calls. ItscreateTemplateBasedOnVariant(variant, planIdentifier, periodId, priceVariantIdentifier)buildsitem,subscriptionPlan,initialandrecurringfrom a variant read with its plans; addcustomerIdentifierandstatus.createTemplateBasedOnVariantIdentityfetches the variant itself, but from Cataloguevariants, 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.
activateAtcannot be combined with the other two (ActivateAtMustBeExclusiveError). A contract that starts later is created withactivateAtalone, and the platform activates it within minutes of that moment:activateAtclears,renewAtandactiveUntilbecome now plus one recurring period, and theactivatewebhook fires. Aninitialphase does not shorten that:status.phasereads 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 clearsactivateAt, so it also activates early.renewAtandactiveUntiltravel together. For a trial, both are the trial’s end. For a running period, both are the end of the paid period. Becauseupdate { status }replaces the whole status, sending{ renewAt }alone clearsactiveUntiland the contract readscancelled.- A contract with an
initialphase stays on it until the first renewal, so “is this a trial?” isstatus.phaseequal to the initial phase. Leaveinitialout and it starts onrecurringat 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
renewAtcomes due it renews the contract, so arenewSubscriptionContracton top moves it a second period. Call it only to renew ahead ofrenewAt. - Renew adds a period to the previous
activeUntil, not to now (to now only if there is none), andrenewAtlands on the same date. Renewing a long-expired contract revives it on its old dates, and the platform then keeps renewing it untilrenewAtis back in the future. - Pause freezes nothing. The dates keep their values, and a paused contract that has a
renewAtkeeps being renewed: it stayspausedwhile the dates and therenewandrenewalDuewebhooks roll on, so checkstatus.statebefore you charge. Only one with norenewAtruns out, andresumethen yieldscancelled. To give back the paid time, record what was left at the pause (meta.pauseRemainingMs) and on resume setrenewAt/activeUntilto now plus that. Note thatupdateSubscriptionContract { status }also un-pauses, so a resume is:resume(toleratingSubscriptionContractIsNotPausedError), then the date update. - Undo a cancel with
updateSubscriptionContract { status: { renewAt: activeUntil, activeUntil } }, notrenewSubscriptionContract— renew reactivates too, but silently moves the customer a whole period on without an invoice. - A contract cancels once. A second
cancelSubscriptionContractanswersSubscriptionContractAlreadyCancelledError, sodeactivate: trueafterdeactivate: falsefails 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.
UpdateSubscriptionContractInputhas nosubscriptionPlan, so monthly ↔ yearly is cancel plus a new contract. A tier change isupdate { item, recurring }, with no proration: a contract on its trial shows it at the first renewal, one already onrecurringshows it instatus.phaseat 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 withdeleteOrder.
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:
createneeds no Core customer: it creates one fromcustomer { identifier, email, firstName, lastName }. Ids areUUID!. Prices are{ gross, net }per phase instead of Core’s singleprice, and the currency comes fromcontext.price.currency(eurif omitted).planis{ identifier, periodId }— noperiodName.periodandunithave no default here: send them.createchecks the SKU, plan, period and metered variables against the published Catalogue incontext.language(enif 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-contractfine, butcreateanswers only “Unexpected error”. The same call with a token scoped tosubscription-contractandsubscription-contract:adminworks. Cache one token per route family on the server. - Select only
idfromcreate. Selectingstatus { … }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 checkmetafor your own key first. - The contract you read back has no
itemand noplan. The ShopSubscriptionContracttype has neither field (introspected 2026-11-12), so write the SKU, the plan identifier and the period intometaatcreateif the account page shows them.recurring.productVariantsis served. signedAtoncreateback-dates, which suits “subscriber since” history.- The lifecycle behaves as above (
pause,resume,renew,cancel,deactivate,changeDates), with three differences:resumeafter a cancel is silently ignored,renewon a paused contract makes itactive(on Core it stayspaused), and the only way to change what is billed isupdateRecurringPhase(phase: { price, period, unit, productVariants, meteredVariables }), which replaces the whole phase — there is no item update.changeDatestakes only the dates to change, unlike Core’supdate { status }. status.phaseisnulluntil a Core change syncs back.status.stateis stored at each write, not derived, so it does not flip when a date passes: on a “my subscription” page compareactiveUntilwith now.subscriptionContracts(customerIdentifier:)right aftercreatecan 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:
grossandnetboth become Core’s singleprice, andcustomerandcontextare dropped. A Shop edit other thanpause,resume,renew,cancelanddeactivatereplaces the Core copy,metaincluded, which loses_shopApiId; the next Core change, a scheduled renewal included, then reaches the Shop store under the Core id, andsubscriptionContractsfails on that element. subscriptionContractTemplateis a stub. It reads nothing: it echoes your arguments with arecurringof 1 month at 0, noinitial, andcurrency: "eur". Build the create input yourself from Discovery plus the plan.- There is no delete here.
deleteSubscriptionContracton 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._shopApiIdonce 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.subscriptionPlansreads back on Core, merged with the plan: names and period lengths from the plan, prices from the variant, inperiods { id name initial { period unit price priceVariants meteredVariables { tiers } } recurring { … } }.- A tier’s own
priceis not the price most reads show. It is required by the input, but Core, PIM and Discovery take the tier price frompriceVariants:price: 99withdefault: 0.1reads 0.1, and an emptypriceVariantsreadsnull. Catalogue’s tierpricefield 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
nokout and onlydefaultis stored; Discovery then answersnokPrice: null. A period omitted from the variant is stored asinitial: null, recurring: nulland Discovery drops it. - Meters are addressed two ways. On a variant’s tiers, by metered-variable
id. On contracts and when tracking usage, byidentifier. Mixing them up givesMeteredVariableNotFoundError.
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 } } } } } } } } }}periodcomes back as a string ("1"),priceVariantsas a hash ({ default: { price, currency }, nok: { … } }), andmeteredVariablesas[]when there are none.- Do not trust
initial. It repeatsrecurring’s period, unit and prices (only itsmeteredVariablesare its own): on a tenant whose Monthly period is “14 days free, then 1 month at 7.99”, Discovery answeredinitial { period: "1", unit: "month", defaultPrice: 7.99 }. Its presence is reliable, since it isnullon 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. hasSubscriptionPlansis the cheap filter for “is this a plan variant”.- The Catalogue API’s
variantscan come back empty for products whose variants were created through Core, whiledefaultVariantandproductVariants(skus:, language:)still answer, with the correct plans, including the trial. If a plan card looks empty, readdefaultVariant, 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 answersMeteredVariableNotFoundError. - The
idempotencyKeyis the retry guard. A reused key answersIdempotencyKeyExistsErrorand 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
pausedandcancelledcontracts too. If that should not be allowed, checkstatus.statein 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 pausedusage(periodStart, now) the meter for the period that just endedprice the tiers yourself graduated: (usage − threshold) × the tier's price, per tiercharge your payment provider; Crystallize takes no moneyregisterOrder 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: falselets the new period run out. updateSubscriptionContract { meta }replaces the whole list, so send every key back withperiodStartandtier. 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, andsubscriptionContractsfails on that element.- To charge before the period starts, bill from the day-ahead
renewalDueinstead (compare itsrenewAtwith now): charge, then callrenewSubscriptionContractyourself, which movesrenewAton so the platform finds nothing due.renewfires for that call too, so take billing off therenewwebhook, or it charges the period a second time. If the charge fails,cancelSubscriptionContract { deactivate: false }clearsrenewAtand 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
renewAtyou last billed inmetaand sweep the contracts for any that have moved past it. There is norenewAtfilter, 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.startandendareDate, notDateTime, and here the metered variable is referenced byid— the opposite of tracking.- Put the overage on its own line (
type: service) so the total adds up. The meters insidesubscription.meteredVariablesare 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’smeta, with therenewAtthe contract has after renewing, and look for it withorders(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
priceinsidesubscription.meteredVariablesis not added to the total. Price the usage yourself (it is tracked on the Core copy, see contracts) and add it as its owntype: serviceline, with atotalthat includes it. - The date, if you back-date. Shop
createignoredcreatedAton one tenant and honoured it on another; keep the intended date inmeta(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, sorenewalDue,activationDueanddeactivatedneed$subscriptionContractId, not$id. The query runs on the PIM API unlessgraphqlQueryTarget: nextsends it to Core. renewalDueandrenewfire for paused contracts too. A contract created less than a week beforerenewAtmisses the week-aheadrenewalDue. Handle all of them idempotently.- Lifecycle calls on the Shop endpoint fire these too, once they have reached the Core copy.
createWebhookaccepts anyconcern/eventstring —nope/nopeis accepted — so a typo creates a webhook that never fires, without an error.
Crystallize AI