Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 55 ยท Real-World Projects

Project: A Paid App with Plans and Usage Billing

Add plans and usage charges to a Shopify app: plan gating, a billing check on load, capped usage records with idempotency, uninstall cleanup and runnable simulators.

A useful app is not yet a business. This project takes an imaginary app, "Label Maker", and adds money to it: a free plan, a paid plan billed monthly, and a usage charge for extra labels beyond the plan's allowance. You will design the plans, gate features by plan, check billing on every load, record usage safely and clean up on uninstall.

The billing calls and routes shown here are real-looking Shopify code, but they are read-only: this site cannot create a charge or talk to a merchant's store. The rules (what a plan allows, what a subscription status means, when a usage record is allowed) are plain JavaScript and are runnable stand-ins. They behave like the real thing in the ways that matter, and the lesson says where they simplify. Examples target Admin GraphQL API 2026-07; check the billing documentation for current field names before you ship. Background reading: App Pricing Models and Billing Options and Implementing Billing with the Billing API. The theory of subscriptions and metered charges in general is in Pricing Models.

Design the plans

Write the plans down as data before any code. Everything else (the UI, the gate, the billing request) reads from this one table.

Plan Price Labels per month Features
Free $0 50 basic templates
Pro $12 per 30 days, 7-day trial 500 included, then $0.02 each all templates, bulk print

Two decisions are hidden in this table. First, the free plan has no Shopify charge at all: it is simply the state "no active subscription". Second, usage is billed after the fact and capped: the merchant agrees to a maximum amount per billing period when they approve the subscription, and Shopify refuses any usage record that would exceed it. The cap protects the merchant from surprises and protects you from disputes. Choose it with care: a cap that is too low interrupts your own billing, a cap that is too high scares merchants at the approval screen.

Keep the plan definitions in one module so that the gate, the pricing page and the billing request cannot disagree.

flowchart LR
    I["Install"] --> Free
    Free -->|"Upgrade clicked"| Pending["Pending approval"]
    Pending -->|"approved (ACTIVE)"| Pro
    Pending -->|"declined or abandoned"| Free
    Pro -->|"merchant cancels"| Free
    Pro -->|"payment fails"| Frozen
    Frozen -->|"paid again"| Pro
    Pro -->|"uninstall"| X["Removed"]
    Free -->|"uninstall"| X

An app's view of billing is a small state machine. Treat any status you do not recognise as "not paid".

The billing check on load

Merchants can upgrade, downgrade, cancel or fail a payment at any time, outside your app. So your app must ask Shopify what the merchant currently has, not trust a flag in its own database. The usual place is the loader of the embedded app's main route: the app authenticates the request, asks for the active subscriptions, and derives the plan.

GRAPHQL
# read-only
query CurrentPlan {
  currentAppInstallation {
    activeSubscriptions {
      id
      name
      status
      trialDays
      currentPeriodEnd
      lineItems {
        id
        plan {
          pricingDetails {
            __typename
            ... on AppRecurringPricing { price { amount currencyCode } interval }
            ... on AppUsagePricing { cappedAmount { amount currencyCode } balanceUsed { amount } terms }
          }
        }
      }
    }
  }
}
TypeScript
// app/routes/app._index.tsx (read-only sketch)
export async function loader({ request }: LoaderFunctionArgs) {
  const { admin, session } = await authenticate.admin(request);
  const response = await admin.graphql(CURRENT_PLAN);
  const json = await response.json();
  const subscriptions = json.data.currentAppInstallation.activeSubscriptions;
  const plan = planFromSubscriptions(subscriptions); // "free" | "pro"
  return { plan, shop: session.shop };
}

activeSubscriptions lists subscriptions that currently count (usually zero or one for a simple app). Deriving the plan is a small pure function that you can test: no active subscription means Free, a subscription named "Pro" with status ACTIVE means Pro. The template's shopifyApp helper also offers a billing configuration with billing.require and billing.check helpers that wrap these requests; they are convenient, but the raw query above is what they do under the hood, and it is worth knowing.

Node.js Plan table, gate and subscription-to-plan mapping

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each shop above gets a plan from its subscriptions alone. Only the shop with an ACTIVE Pro subscription can use bulk print; the others receive a clear message and an HTTP 402 status (Payment Required), which a route can turn into an upgrade prompt. Check the gate on the server in every action that does the paid work. Hiding a button is not enforcement, because anyone can call your route directly.

Creating a subscription

The Upgrade button posts to a route that creates a subscription and redirects the merchant to Shopify's approval page. Nothing is charged until the merchant approves there.

GRAPHQL
# read-only
mutation Subscribe($returnUrl: URL!) {
  appSubscriptionCreate(
    name: "Pro"
    returnUrl: $returnUrl
    trialDays: 7
    test: true
    lineItems: [
      { plan: { appRecurringPricingDetails: {
          price: { amount: 12.0, currencyCode: USD }, interval: EVERY_30_DAYS } } }
      { plan: { appUsagePricingDetails: {
          cappedAmount: { amount: 30.0, currencyCode: USD },
          terms: "$0.02 per label above 500 labels in a billing period" } } }
    ]
  ) {
    confirmationUrl
    appSubscription { id }
    userErrors { field message }
  }
}

Points to remember:

  • test: true creates a test charge that never bills anyone; use it in development stores and make it depend on an environment variable so it can never leak into production by accident (see Testing Shopify Apps).
  • The returnUrl is where Shopify sends the merchant afterwards. On that route, run the billing check again: if the merchant declined, the plan is still Free.
  • confirmationUrl lives outside your embedded app, so the redirect must leave the iframe; the template has helpers for this.
  • Check userErrors, as always (Mutations and userErrors).
  • Shopify may offer managed pricing instead, where you describe plans in the Partner Dashboard and Shopify handles the approval screens. Then you only read the subscription, as in the loader above. Pick one approach per app.

Usage charges

A usage record says: "this shop used something worth $X; add it to the bill." You create one with appUsageRecordCreate, passing the id of the usage line item (not of the subscription), a price, a description and an idempotency key.

GRAPHQL
# read-only
mutation RecordUsage($lineItemId: ID!, $key: String!) {
  appUsageRecordCreate(
    subscriptionLineItemId: $lineItemId
    price: { amount: 0.4, currencyCode: USD }
    description: "20 extra labels on 2026-03-14"
    idempotencyKey: $key
  ) {
    appUsageRecord { id }
    userErrors { field message }
  }
}

The idempotency key is what makes retries safe. If your job times out after sending the request, you do not know whether the record was created; sending the same key again is harmless, as explained in Idempotency. Build the key from something stable: the shop, the billing period and the day, for example.

Do not send a usage record for every single label. Count labels in your own database, and send one record per day (or per hour) for the extra labels beyond the allowance. This keeps you far from API limits and makes the merchant's invoice readable.

Node.js A usage meter with allowance, cap and idempotency

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output from the top: the first day is inside the allowance, the second crosses it and bills only the 60 labels over the line, and the third bills its 100 in full. The retry with an existing key reports "repeated" and charges nothing. The last big day is refused because it would exceed the cap; in the real app you would keep the unbilled count, tell the merchant that the cap was reached, and offer to raise it by creating a new subscription. This stand-in simplifies one thing: the real balance and cap belong to Shopify, and your counter is only a mirror of it, so on startup and after errors you should read balanceUsed from the subscription instead of trusting memory.

Uninstall and cleanup

When a merchant uninstalls your app, Shopify cancels the subscription for you. It does not clean up your data. Subscribe to app/uninstalled and, in a reliable handler (Reliable Webhook Handlers):

  1. delete the shop's sessions and tokens at once (they are useless and sensitive),
  2. mark the shop as uninstalled and stop its scheduled jobs, including the daily usage job,
  3. schedule the deletion of the shop's remaining data, honouring the privacy rules in Privacy, GDPR and Mandatory Webhooks,
  4. keep a minimal record (shop, install and uninstall dates) for your analytics and for a possible reinstall.

A merchant who reinstalls later should start on Free, with a fresh check against Shopify. Never assume that an old Pro flag in your database is still valid.

Test checklist

  • Free shop: gated features return 402; the upgrade flow reaches the approval page.
  • Approval: the plan switches to Pro after the return URL; declining leaves Free.
  • Trial days apply once per shop, not once per install (Shopify tracks this for you).
  • Usage: identical keys never double bill; the cap is respected; the daily job survives a failure and a rerun.
  • Cancel, freeze and uninstall paths work, and nothing keeps running for an uninstalled shop.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the app ask Shopify for the active subscription on load instead of trusting a flag in its database?

    The merchant's billing state changes outside your app. Checking the live subscription keeps the gate honest; a local copy can only be a cache.
  2. 2. What does the idempotency key on appUsageRecordCreate protect against?

    If you cannot tell whether a request succeeded, you may resend it with the same key; the repeat is recognised and charged once. The cap is a separate protection.
  3. 3. Where should the plan gate be enforced?

    Hidden buttons do not stop direct requests. The server action must check the plan before doing the work.
  4. 4. A merchant uninstalls the app. Which statement is right?

    Billing stops with the uninstall, yet your database, tokens and jobs are your responsibility. Handle app/uninstalled.
  5. 5. Why send one usage record per day instead of one per label?

    Aggregating in your own database avoids a flood of API calls and gives the merchant a readable bill.

Summary

  • Define plans as data in one module; the gate, pricing page and billing request all read it.
  • Ask Shopify for activeSubscriptions on load and map unknown or inactive statuses to the free plan.
  • Create subscriptions with appSubscriptionCreate, use test charges outside production, and re-check billing when the merchant returns.
  • Record usage in aggregate with appUsageRecordCreate, an idempotency key and respect for the capped amount.
  • Enforce gates on the server, and on app/uninstalled remove sessions, stop jobs and schedule data deletion.

Next, test your knowledge in Practice Exercises with Solutions.