Skip to main content

Build a subscription contract

A subscription contract is the agreement between a customer and a merchant over a specific term for recurring purchases over a set or undefined period of time.

This guide shows you how to submit a complete desired state to subscriptionContractCreateCalculate, review Shopify's calculated result, and commit it as an active subscription contract. It includes examples for "Subscribe and save" and prepaid subscriptions.

Available in the 2026-10 release candidate

The SubscriptionContractCalculation API is available in the GraphQL Admin API 2026-10 release candidate. If your app uses the SubscriptionDraft API, refer to the legacy contract creation guide.


Note
  • Most subscriptions, pre-order and try before you buy apps need to request API access through the Partner Dashboard. We give API access to apps that are designed according to our principles for subscriptions, pre-order and TBYB apps.
  • Public apps that use subscriptions, pre-order or TBYB need to meet specific requirements to be published on the Shopify App Store.
  • Custom apps created in the Shopify admin can't use subscriptions, pre-order or TBYB because these apps can't use extensions or request access to protected scopes. If you're building a solution for a single store, then build your custom app in the Partner Dashboard.
  • Use the GraphQL Admin API version 2026-10 or later.
  • Familiarize yourself with subscription contracts.
  • Identify the customer, product variants, delivery method, and customer payment method for the contract.
  • Use an existing customer payment method that's vaulted for subscriptions or a card on file. Customers can also add a payment method in customer accounts. Subscribe to the customer_payment_methods/create webhook topic to receive new payment method events.
Note

You can create and commit a contract without a payment method by passing paymentMethod: { none: true }. To create an order for that contract, pass paymentProcessingPolicy: SKIP_PAYMENT_AND_CREATE_UNPAID_ORDER to the billing-attempt mutation. Otherwise, add a valid payment method before billing.


Anchor to How contract calculation worksHow contract calculation works

Contract creation uses an asynchronous calculate and commit flow:

  1. Submit the complete desired contract state.
  2. Poll the calculation or wait for a webhook. Shopify emits subscription_contract_calculations/succeed when a calculation succeeds and subscription_contract_calculations/fail when it fails or is voided.
  3. Review the calculated contract, projected totals, warnings, or errors.
  4. Commit a successful calculation.

The calculated result is an immutable snapshot. Committing creates an active contract. The create input doesn't accept a status. After committing, use subscriptionContractPause, subscriptionContractCancel, subscriptionContractExpire, or subscriptionContractFail to change the contract status.


Anchor to Step 1: Calculate the contractStep 1: Calculate the contract

Call subscriptionContractCreateCalculate with the complete desired state for the contract. The input includes at least one line, the customer and currency, billing and delivery policies, delivery and payment methods, and arrays for discounts and custom attributes. Set the required withMerchandiseCustomizations field to true to run Shopify Functions that customize merchandise, or false to bypass them.

Depending on your selling strategy, you might create a "Subscribe and save" or a prepaid subscription.

Anchor to Subscribe and save subscriptionsSubscribe and save subscriptions

For a subscription that's billed each delivery period, set the billing cadence and omit multiFulfillment from the delivery policy. The following example bills and delivers monthly:

POST https://{shop}.myshopify.com/admin/api/2026-10/graphql.json

GraphQL mutation

mutation CreateSubscriptionContract {
subscriptionContractCreateCalculate(
contractCreateInput: {
withMerchandiseCustomizations: true
customerId: "gid://shopify/Customer/123"
currencyCode: USD
lines: [
{
productVariantLine: {
productVariantId: "gid://shopify/ProductVariant/111"
quantity: 1
customAttributes: []
discounts: []
}
}
]
billingPolicy: {
anchors: []
cadence: { unit: MONTH, count: 1 }
}
deliveryPolicy: { anchors: [] }
deliveryMethod: {
shipping: {
address: {
firstName: "Quinn"
lastName: "Ishida"
address1: "123 Main St"
city: "Toronto"
provinceCode: "ON"
countryCode: CA
zip: "M5V 1A1"
}
deliveryPrice: {
amount: "14.99"
currencyCode: USD
}
}
}
paymentMethod: {
customerPaymentMethod: {
id: "gid://shopify/CustomerPaymentMethod/456"
}
}
discountCodes: []
manualDiscounts: []
customAttributes: []
}
) {
subscriptionContractCalculation {
... on SubscriptionContractCalculationPending {
id
}
}
userErrors {
field
message
code
}
}
}

JSON response

{
"data": {
"subscriptionContractCreateCalculate": {
"subscriptionContractCalculation": {
"id": "gid://shopify/SubscriptionContractCalculation/789"
},
"userErrors": []
}
}
}

Anchor to Prepaid subscriptionsPrepaid subscriptions

For a prepaid subscription, bill less frequently than you deliver. Use multiFulfillment to define the delivery cadence and the number of fulfillments in each billing cycle. The billing cadence must be a whole-number multiple of the delivery cadence. The following example bills every three months and delivers monthly:

POST https://{shop}.myshopify.com/admin/api/2026-10/graphql.json

GraphQL mutation

mutation CreatePrepaidSubscriptionContract {
subscriptionContractCreateCalculate(
contractCreateInput: {
withMerchandiseCustomizations: true
customerId: "gid://shopify/Customer/123"
currencyCode: USD
lines: [
{
productVariantLine: {
productVariantId: "gid://shopify/ProductVariant/111"
quantity: 1
customAttributes: []
discounts: []
}
}
]
billingPolicy: {
anchors: []
cadence: { unit: MONTH, count: 3 }
}
deliveryPolicy: {
anchors: []
multiFulfillment: {
cadence: { unit: MONTH, count: 1 }
numberOfFulfillments: 3
}
}
deliveryMethod: {
shipping: {
address: {
firstName: "Quinn"
lastName: "Ishida"
address1: "123 Main St"
city: "Toronto"
provinceCode: "ON"
countryCode: CA
zip: "M5V 1A1"
}
deliveryPrice: {
amount: "14.99"
currencyCode: USD
}
}
}
paymentMethod: {
customerPaymentMethod: {
id: "gid://shopify/CustomerPaymentMethod/456"
}
}
discountCodes: []
manualDiscounts: []
customAttributes: []
}
) {
subscriptionContractCalculation {
... on SubscriptionContractCalculationPending {
id
}
}
userErrors {
field
message
code
}
}
}

JSON response

{
"data": {
"subscriptionContractCreateCalculate": {
"subscriptionContractCalculation": {
"id": "gid://shopify/SubscriptionContractCalculation/789"
},
"userErrors": []
}
}
}

If the mutation returns a user error, then correct the input before polling. Shopify doesn't create an asynchronous calculation when input validation fails.


Anchor to Step 2: Poll for the calculation resultStep 2: Poll for the calculation result

The calculate mutation returns a pending calculation. Poll for the result and review it before committing.

Contract calculations run asynchronously. Most calculations finish in less than three seconds, but Functions and external services can increase processing time. Use the calculation ID returned by the calculate mutation to query subscriptionContractCalculation:

POST https://{shop}.myshopify.com/admin/api/2026-10/graphql.json

GraphQL query

query PollSubscriptionContractCalculation($id: ID!) {
subscriptionContractCalculation(id: $id) {
__typename
... on SubscriptionContractCalculationPending {
id
}
... on SubscriptionContractCalculationSuccess {
id
calculatedContract {
id
lines(first: 10) {
nodes {
id
quantity
title
variantId
}
}
}
warnings {
code
message
}
projectedOrderTotals {
subtotal {
amount
currencyCode
}
totalDelivery {
amount
currencyCode
}
totalTax {
amount
currencyCode
}
totalMerchandiseDiscounts {
amount
currencyCode
}
totalDeliveryDiscounts {
amount
currencyCode
}
total {
amount
currencyCode
}
}
}
... on SubscriptionContractCalculationFailure {
id
errors {
code
message
}
}
}
}

Variables

{
"id": "gid://shopify/SubscriptionContractCalculation/789"
}

Pending response

{
"data": {
"subscriptionContractCalculation": {
"__typename": "SubscriptionContractCalculationPending",
"id": "gid://shopify/SubscriptionContractCalculation/789"
}
}
}

The query returns one of the following types:

TypeMeaningAction
SubscriptionContractCalculationPendingShopify initiated or is processing the calculation.Continue polling.
SubscriptionContractCalculationSuccessThe calculated contract is ready to review and commit.Review the result before committing.
SubscriptionContractCalculationFailureThe calculation failed (processed with errors) or Shopify voided it (never processed, for example, because of an infrastructure issue).If it failed, read errors and correct the input before calculating again. If it was voided, errors is empty and there's nothing to fix in the input, so retry the calculation.

Wait two seconds before the first poll, poll every second, and stop after 30 seconds. If the calculation is still pending, then retry later or wait for a webhook instead of increasing the polling frequency.

Anchor to Review the calculated contractReview the calculated contract

Before committing, inspect the following fields on SubscriptionContractCalculationSuccess:

  • calculatedContract: The complete contract snapshot that the commit applies.
  • projectedOrderTotals: The projected merchandise, delivery, discount, tax, and total amounts.
  • warnings: Existing-data or compatibility problems that don't prevent the calculation from succeeding.

A successful calculation is immutable. If you need to change the input, then start a new calculation and commit only the result that you want to make active.

Review warnings

A successful calculation can contain warnings. Review them before committing because they can identify disabled currencies, delivery configuration problems, or other existing contract data that Shopify preserved instead of blocking the update.

Anchor to Use webhooks instead of pollingUse webhooks instead of polling

For event-driven processing, subscribe to the following webhook topics:

TopicDescription
subscription_contract_calculations/succeedThe calculation succeeded and is ready to review and commit.
subscription_contract_calculations/failThe calculation failed or Shopify voided it. A failed calculation has errors to query; a voided one has empty errors, so retry it.

Create a webhook subscription with webhookSubscriptionCreate:

POST https://{shop}.myshopify.com/admin/api/2026-10/graphql.json

GraphQL mutation

mutation CreateCalculationWebhook {
webhookSubscriptionCreate(
topic: SUBSCRIPTION_CONTRACT_CALCULATIONS_SUCCEED
webhookSubscription: {
callbackUrl: "https://example.com/webhooks/calculation-success"
format: JSON
}
) {
webhookSubscription {
id
}
userErrors {
field
message
}
}
}

Webhook payload

{
"id": 789,
"admin_graphql_api_id": "gid://shopify/SubscriptionContractCalculation/789",
"state": "succeeded"
}

Use admin_graphql_api_id to query the completed calculation. Webhook delivery doesn't commit the result automatically.


Anchor to Step 3: Commit the calculationStep 3: Commit the calculation

After the calculation succeeds and you've reviewed the result, call subscriptionContractCalculationCommit. The commit makes the calculated contract active for billing:

POST https://{shop}.myshopify.com/admin/api/2026-10/graphql.json

GraphQL mutation

mutation CommitSubscriptionContractCalculation {
subscriptionContractCalculationCommit(
id: "gid://shopify/SubscriptionContractCalculation/789"
) {
contract {
... on SubscriptionContract {
id
status
}
}
userErrors {
field
message
code
}
}
}

JSON response

{
"data": {
"subscriptionContractCalculationCommit": {
"contract": {
"id": "gid://shopify/SubscriptionContract/999",
"status": "ACTIVE"
},
"userErrors": []
}
}
}

Handle commit user errors by code:

CodeMeaningAction
NOT_READY_TO_COMMITThe calculation hasn't succeeded yet.Continue polling before retrying the commit.
CALCULATION_NOT_FOUNDThe calculation ID doesn't exist or isn't available to the app.Verify the ID and app access.
STALE_CONTRACTThe contract changed after this calculation started.Query the latest contract state and calculate again.
INVALIDShopify can't commit the calculation.Use field and message to correct the request.

You can safely retry polling and commit requests. Retrying a calculate mutation creates a new calculation, so retain the ID for the result that you intend to commit. Retrying a commit for an already committed calculation returns the committed result.


Anchor to View subscription contract detailsView subscription contract details

The View subscription button on the customer subscriptions card and the order subscriptions card allows merchants to navigate to the app and view the subscription contract details.

Anchor to Customers page in the Shopify adminCustomers page in the Shopify admin

Customers page screenshot

Anchor to Order page in the Shopify adminOrder page in the Shopify admin

Order page screenshot

Anchor to Redirecting to the subscription contract within the appRedirecting to the subscription contract within the app

To redirect merchants to the relevant subscription contract, the app needs to implement a specific endpoint. After it's implemented, the endpoint redirects to the subscription contract page within the app for the subscription defined by subscription_contract_id.

You can customize the View subscription link by managing the Subscription link app extension from your app through the Shopify CLI.

To learn how to create and manage a subscription link extension from the Shopify CLI, refer to Start building subscription link extensions.

If you don't customize the View subscription link, then the link is hardcoded. The hardcoded link has the following format:

{app_application_url}/subscriptions?customer_id={customer_id}&hmac={hmac}&id={subscription_contract_id}&shop={myshopify_domain}


Anchor to Step 4: Create a billing attemptStep 4: Create a billing attempt

To bill a subscription contract and create an order, apps need to create a billing attempt. A subscription is renewed when an app makes a billing attempt.

A billing attempt represents an attempt at executing a billing cycle and charging the customer payment method for a subscription contract. A billing attempt executes a contract based on the billing cycle at the origin time if provided. Otherwise, the billing attempt is created for the current billing cycle by default. You can also create a billing attempt on a specific billing cycle.

A billing attempt starts in a pending status. After it has been processed, it either transitions to successful or failed, both of which are terminal states:

  • If the billing attempt is successful, then an order is created.

  • If the billing attempt fails, then it means that the transaction has failed.

    If an action is pending on the part of the customer in regards to 3D Secure, then a 3D Secure challenge can occur before the billing attempt transitions to a terminal state.

Note

A billing attempt can fail if Shopify's fraud analysis service has flagged a subscription contract's origin order. It is strongly recommended to check the order risk level of a contract's origin order before executing a billing attempt.

To create a billing attempt, specify the following inputs in the subscriptionBillingAttemptCreate mutation:

  • subscriptionContractId: The ID of the subscription contract.

  • subscriptionBillingAttemptInput

    • idempotencyKey: A unique key generated by the client to avoid duplicate payments.
    • originTime: An optional field that changes the way fulfillment intervals are calculated. If nothing is provided, fulfillment is calculated using the date that the billing attempt was successful. Otherwise, fulfillment is calculated using the provided originTime value. The UTC offset of originTime should match the shop's timezoneOffset.

    Billing attempts are processed asynchronously, which means the resulting order won't be available right away. You can fetch the billing attempt and inspect the ready field to find out whether the order has been created (true) or not (false).

Note

If you have adopted Subscriptions Billing Cycle APIs, you can create orders by charging a billing cycle directly. This approach enables more precise management of billing cycles by directly linking order creation to the specific cycle being billed.

POST https://{shop}.myshopify.com/admin/api/{api_version}/graphql.json

GraphQL query

mutation {
subscriptionBillingAttemptCreate(
subscriptionContractId: "gid://shopify/SubscriptionContract/33"
subscriptionBillingAttemptInput: {
idempotencyKey: "abc123"
originTime: "2022-10-30T04:05:02+14:00"
}
)
{
subscriptionBillingAttempt {
id
originTime
errorMessage
nextActionUrl
order {
id
}
ready
}
}
}

JSON response

{
"data": {
"subscriptionBillingAttemptCreate": {
"subscriptionBillingAttempt": {
"id": "gid://shopify/SubscriptionBillingAttempt/82",
"originTime": "2022-10-30T04:05:02+14:00",
"errorMessage": null,
"nextActionUrl": null,
"order": null,
"ready": false
}
}
},
"extensions": {
"cost": {
"requestedQueryCost": 11,
"actualQueryCost": 11
}
}
}

Because the order isn't ready immediately, you can query the subscriptionBillingAttempt to get the resulting order information.

POST https://{shop}.myshopify.com/admin/api/{api_version}/graphql.json

GraphQL query

query {
subscriptionBillingAttempt(
id: "gid://shopify/SubscriptionBillingAttempt/524310"
) {
id
errorMessage
nextActionUrl
order {
id
}
ready
}
}

JSON response

{
"data": {
"subscriptionBillingAttempt": {
"id": "gid://shopify/SubscriptionBillingAttempt/32933",
"errorMessage": null,
"nextActionUrl": null,
"order": {
"id": "gid://shopify/Order/2014567596054"
},
"ready": true
}
},
"extensions": {
"cost": {
"requestedQueryCost": 2,
"actualQueryCost": 2,
"throttleStatus": {
"maximumAvailable": 1000.0,
"currentlyAvailable": 998,
"restoreRate": 50.0
}
}
}
}

Shopify handles 3D Secure authentication by emailing the customer when the financial institution requires a challenge. This flow is demonstrated in the diagram below:

Subscription contracts objects diagram

You can poll the subscriptionBillingAttempt object until the nextActionUrl field is available to see the URL.

Note

The subscription_billing_attempts/success and subscription_billing_attempts/failure webhooks aren't triggered until the challenge is completed. If the customer doesn't complete the challenge, then your app won't be notified.

POST https://{shop}.myshopify.com/admin/api/{api_version}/graphql.json

GraphQL query

query {
subscriptionBillingAttempt(
id: "gid://shopify/SubscriptionBillingAttempt/123"
) {
id
errorMessage
errorCode
nextActionUrl
order {
id
}
ready
}
}

JSON response

{
"data": {
"subscriptionBillingAttempt": {
"id": "gid:\/\/shopify\/SubscriptionBillingAttempt\/123",
"errorMessage": null,
"errorCode": null,
"nextActionUrl": "https:\/\/example.com\/subscriptions\/billing\/959c1a7cec286e06bfe7f16ff351c101\/challenge",
"order": null,
"ready": false
}
},
"extensions": {
"cost": {
"requestedQueryCost": 2,
"actualQueryCost": 2
}
}
}

Anchor to About re-billing failed payment attemptsAbout re-billing failed payment attempts

It's up to apps to attempt re-billing for failed payment attempts. We expose many signals to help you make the right decision about when to re-bill failed payment attempts and how often.

  • Only rebill payment attempts that failed with error codes that make sense to retry, such as insufficient_funds.
  • Avoid re-billing failed payments with the same customer payment method more than 30 times in 35 days. These requests will be failed and the payment method will be revoked.

You can keep track of how Shopify correlates failed payments by leveraging the payment_session_id and payment_group_id fields. Retrying billing for the same contract identity will result in billing attempts with the same payment_group_id. You can use this to track all failed, or the final successful, billing attempt linked to a final order. All billing attempts that kept their payment details identical will share the same payment_session_id. When surfacing merchants' payment success metrics, ensure that only the last billing attempt in a group that shares the same payment_session_id and payment_group_id is counted, as all the billing attempts in that group were retries of one another.

Similar to creating a new order through checkout, the availability of inventory is checked during the billing attempt process. Merchants can adjust inventory tracking so that they can continue to sell product variants when out of stock. They can also adjust inventory tracking to prevent selling product variants when out of stock.

If one or more of a subscription's product variants are out of stock (and aren't configured to continue selling), then the billing attempt moves to a failed state with either an insufficient inventory or a inventory location error.



Was this page helpful?