Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 55 ยท Billing

Implementing Billing with the Billing API

Create app subscriptions, send merchants to the confirmation URL, record capped usage charges, upgrade and cancel plans, with a runnable subscription state machine.

If you chose the Billing API in App Pricing Models and Billing Options, you now own the whole charging flow: ask Shopify to create a charge, send the merchant to approve it, find out the result, and keep your app's features in step with what the merchant really pays for. The flow is short, but each step has a trap, and most billing bugs come from treating a pending charge as an active one.

This lesson walks through the lifecycle of an app subscription (a recurring charge, optionally with a usage part), then usage records, upgrades and cancellation. The GraphQL and server code is real platform code and read-only here: billing needs a real app and a shop in test mode. The runnable examples are a state machine and a usage meter in plain JavaScript that behave like the real thing at the level of rules, so you can reason about edge cases before touching an API. The examples target the Admin GraphQL API; use the latest stable version when you build and check field names there, because Shopify changes APIs often.

The lifecycle at a glance

sequenceDiagram
    participant M as Merchant
    participant A as Your app
    participant S as Shopify
    A->>S: appSubscriptionCreate (plan, returnUrl, trialDays)
    S-->>A: confirmationUrl + subscription (PENDING)
    A->>M: Redirect the top window to confirmationUrl
    M->>S: Approve the charge
    S->>M: Redirect to returnUrl
    M->>A: Load your app again
    A->>S: Query activeSubscriptions
    S-->>A: Subscription is ACTIVE

The merchant must approve before the subscription becomes active.

Step 1: create the subscription

You call the appSubscriptionCreate mutation. It takes a name, a returnUrl, an optional number of trial days, a test flag and a list of line items. Each line item has a pricing plan: a recurring plan (price and interval) and, optionally, a usage plan (a cap and a description of the terms).

GRAPHQL
# Admin GraphQL (read-only example)
mutation CreateSubscription($returnUrl: URL!) {
  appSubscriptionCreate(
    name: "Growth plan"
    returnUrl: $returnUrl
    trialDays: 14
    test: true
    lineItems: [
      {
        plan: {
          appRecurringPricingDetails: {
            price: { amount: 49.00, currencyCode: USD }
            interval: EVERY_30_DAYS
          }
        }
      }
      {
        plan: {
          appUsagePricingDetails: {
            cappedAmount: { amount: 100.00, currencyCode: USD }
            terms: "$0.06 per message above 1,000 messages a month"
          }
        }
      }
    ]
  ) {
    confirmationUrl
    appSubscription { id status }
    userErrors { field message }
  }
}

Points to notice:

  • test: true creates a charge that is never really billed. Use it on development stores and in automated tests. Shopify also treats charges on development stores specially, but do not rely on that: set the flag from configuration (test = process.env.NODE_ENV !== "production"), so production code cannot accidentally create test charges and vice versa.
  • returnUrl is where the merchant lands after approving. Make it a URL inside your embedded app, so the app loads and can check the new status.
  • terms is shown to the merchant on the approval screen. Write it as plain language: it is your promise about when usage is charged.
  • Always read userErrors. A rejected input (for example a missing line item) comes back there with HTTP status 200, as explained in Mutations and userErrors.

In the app template, the authenticate.admin(request) helper gives you the admin client to run this mutation, and the template also ships billing helpers if you configure plans in code. Either way, the underlying call is the mutation above.

Step 2: send the merchant to the confirmation URL

The mutation returns confirmationUrl, an address on Shopify's admin. Your embedded app lives in an iframe, and Shopify's approval page cannot be shown inside it, so you must redirect the top-level window. With App Bridge or the template's redirect helper that is one call; a plain window.location assignment inside the iframe will fail.

TypeScript
// app/routes/app.billing.tsx  (read-only sketch)
import { authenticate } from "../shopify.server";

export const action = async ({ request }) => {
  const { admin, redirect } = await authenticate.admin(request);
  const response = await admin.graphql(CREATE_SUBSCRIPTION, {
    variables: { returnUrl: `${process.env.SHOPIFY_APP_URL}/app/billing/return` },
  });
  const { data } = await response.json();
  const result = data.appSubscriptionCreate;

  if (result.userErrors.length > 0) {
    return { errors: result.userErrors };
  }
  // The redirect helper takes the merchant out of the iframe.
  return redirect(result.confirmationUrl, { target: "_top" });
};

Three things can happen next: the merchant approves, declines, or closes the tab. Only the first leads back to your returnUrl. For the other two, nothing reaches you immediately, and the subscription stays PENDING until it expires or is declined. So never mark a plan as active just because you created the subscription.

Step 3: confirm the status

When the merchant lands on your return page, ask Shopify what is true. Querying currentAppInstallation.activeSubscriptions returns subscriptions in the ACTIVE state. The possible statuses are roughly:

Status Meaning
PENDING Created, waiting for the merchant to approve
ACTIVE Approved and being billed (or in trial)
DECLINED The merchant refused it
EXPIRED The merchant never approved it in time
FROZEN Billing is paused, for example because the store is on hold
CANCELLED Cancelled by the app, the merchant, or an uninstall

Subscription changes also trigger the app_subscriptions/update webhook, which is how you learn about a cancellation or a freeze that happened while your app was not open. Handle it like any webhook: verify the signature (Verifying Webhook Signatures) and process it idempotently (Reliable Webhook Handlers).

A subscription state machine

The rules above are a finite state machine. Writing one in your own code, even a small one, stops impossible transitions such as "cancelled to active". This stand-in is plain JavaScript and has no connection to Shopify. It captures the rules so you can test your app logic without a network.

JS Subscription state machine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that access is granted by exactly one state. Your feature gate should be status === "ACTIVE", not "a subscription exists". Also decide what FROZEN means for your product; many apps show a banner and restrict writes instead of locking everything.

Step 4: usage charges

If your plan has a usage line item, you report each charge with the appUsageRecordCreate mutation. It needs the ID of the usage line item (not the subscription), a price, a description and, importantly, an idempotency key.

GRAPHQL
# Admin GraphQL (read-only example)
mutation RecordUsage($lineItemId: ID!, $key: String!) {
  appUsageRecordCreate(
    subscriptionLineItemId: $lineItemId
    price: { amount: 1.50, currencyCode: USD }
    description: "250 messages sent on 2026-03-14"
    idempotencyKey: $key
  ) {
    appUsageRecord { id }
    userErrors { field message }
  }
}
  • Cap. The sum of usage records in a billing period cannot exceed the capped amount the merchant approved. A record that would pass the cap is rejected with a userErrors entry. Plan for that: stop the metered action, or tell the merchant to raise the cap (a separate mutation, which sends them to another approval page).
  • Idempotency. If your job retries after a timeout, the same record could be created twice and double-charge a merchant. The idempotency key makes Shopify ignore duplicates. Generate the key from something stable, for example shopDomain + billingPeriod + batchId, never a random value created on each attempt. The general idea is in Idempotency.
  • Batch your records. One record per tiny event creates noise and hits rate limits. Aggregate per hour or per day, and describe the batch.
  • Money. Compute in integer cents and convert only at the API boundary, as in Money as Integers.
JS A usage meter with cap and idempotency

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The retried batch is ignored instead of billed twice, and the oversized batch is rejected without changing the total. Those two behaviors are what you rely on in production.

Upgrades, downgrades and cancellation

Upgrade or downgrade. You create a new subscription for the new plan; the mutation has a replacementBehavior argument that controls what happens to the current one. In outline: replace it immediately (typical for an upgrade, the merchant pays the new price from now), apply the change at the end of the current cycle (typical for a downgrade, so the merchant keeps what they paid for), or use Shopify's standard behavior. The merchant still sees an approval page for the new terms. Check the argument values in the documentation for the API version you target.

Cancel. appSubscriptionCancel takes the subscription ID and cancels it; a prorate option can refund the unused part of the cycle if you choose to offer that. If the merchant uninstalls, active charges end automatically, which is why app/uninstalled is the moment to clean up your plan record. Remember to also drop any stored plan for that shop so a later reinstall starts clean.

Changing the usage cap. Raising the cap needs the merchant's approval again, through an update mutation that returns another confirmation URL. Do not silently work around the cap by creating many small subscriptions.

Never decide that a shop has paid by looking only at your own database. Merchants cancel and freeze billing from their admin. Re-check the real subscription when the app loads, and keep your copy in sync with the app_subscriptions/update webhook.

Test charges and where to go next

Always develop with test: true on a development store. You can approve the confirmation screen without any payment method, and the subscription behaves as a normal one, so you can walk through approval, trial, upgrade and cancel. Automated tests should stub the GraphQL client rather than call Shopify; Testing Shopify Apps shows how. The final project, A Paid App with Plans and Usage Billing, puts these steps together in one app.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After appSubscriptionCreate succeeds, what status does the new subscription have?

    The subscription starts as PENDING. Only the merchant's approval on the confirmation page moves it to ACTIVE, so your app must not unlock paid features yet.
  2. 2. Why does the app redirect the top-level window to confirmationUrl?

    The approval screen is a Shopify admin page that cannot run in your embedded iframe, so you take the merchant out of it with a top-level redirect (App Bridge or the template's redirect helper).
  3. 3. A background job retries creating the same usage record after a network timeout. How do you avoid charging twice?

    A stable idempotency key lets Shopify recognise the repeat and ignore it. A random key per attempt defeats the purpose, because every retry looks new.
  4. 4. What happens when a usage record would push the total above the approved capped amount?

    The cap is the merchant's agreed maximum. Records beyond it are rejected, so your app should stop metering or ask the merchant to approve a higher cap.
  5. 5. Which condition should gate a paid feature?

    Only an ACTIVE subscription grants access. Existence, a click or a page load says nothing about approval or later cancellation.

Summary

  • appSubscriptionCreate makes a PENDING subscription and returns a confirmationUrl; redirect the top window there and wait for approval.
  • Confirm the result on the return page by querying active subscriptions, and keep in sync with the app_subscriptions/update webhook.
  • Gate features on ACTIVE only, and treat DECLINED, EXPIRED, CANCELLED and FROZEN as first-class states.
  • Usage records need the usage line item ID, respect the approved cap and must carry a stable idempotency key.
  • Upgrades create a new subscription with a replacement behavior; use test: true for development and tests.

Next: Privacy, GDPR and Mandatory Webhooks