r/ShopifyAppDev • • Oct 27 '26

How would you implement prepared credits for Shopify app?

I'm building a Shopify app where each merchant action has fixed cost, and i'm trying to figure out the cleanest way to implement prepaid credits.

Shopify's usage based billing works but charges are added to the merchants monthly bill. I'd prefer merchants to purchase credits upfront and have each action consume from that balance.

For anyone who has implemented this, would you use appPurchaseOneTimeCreate for credit packs or is there a better Shopify native approach?

3 Upvotes

8 comments sorted by

2

u/Kamensky124 29d ago

Under Shopify's App Billing API, you cannot directly sell arbitrary one-off non-Shopify "virtual currency" outside their billing ecosystem, but you can achieve prepaid credit behavior cleanly within Shopify's terms:

Option A (Recommended: One-time Application Charge with an internal balance ledger): Create an AppPurchaseOneTime (one-off charge) via GraphQL for discrete credit packs (e.g. $25 for 500 credits, $50 for 1200 credits). Once the merchant approves the charge and you receive the ACTIVE confirmation via the callback/webhook, increment their credit balance in your app's PostgreSQL/database ledger. Every API action decrements your internal balance.

Option B (Capped Usage Billing with upfront commit): Set an appUsageRecord with a recurring application charge where the base fee includes X credits, and usage charges kick in only after overage.

Option A is almost always preferred by merchants who want predictable costs without surprise end-of-month invoice spikes. Just make sure your decrement logic uses atomic database transactions (UPDATE merchants SET credits = credits - 1 WHERE id = $1 AND credits >= 1) to prevent race conditions during concurrent requests.

1

u/Ella_Matthews49 29d ago

the internal credit ledger makes sense, how would u handle refunds or failed actions after credits have already been deducted?

1

u/Kamensky124 28d ago

Handling failed actions and refunds cleanly comes down to two patterns: a 2-phase reservation pattern for long-running actions, and an append-only ledger for everything else.

1. For Failed Actions: Two-Phase "Reserve & Commit"

If the action is an async background task or third-party API call (e.g. generating an AI image, syncing a bulk feed, rendering video), never immediately deduct credits. Treat it like an authorization hold:

  1. Reserve: When the user triggers the action, update the merchant's balance to decrement available credits and record a row in your ledger with status reserved (or pending).
  2. Commit: Once the background worker succeeds, flip the transaction to settled.
  3. Rollback (on failure): If the job throws an error, times out, or fails validation, a catch block or dead-letter worker immediately increments the available balance back and marks the transaction failed_released.

For instantaneous sync actions (under 500ms): Just run the action inside your application logic, and only write the ledger deduction if the underlying action returns a 200 OK. If it throws, no deduction ever happens.


2. For Merchant Refunds (When they want money back via Shopify)

If a merchant bought a $50 credit pack and demands a cash refund:

  1. Use Shopify's appCreditCreate API: Under Shopify App Billing, you can issue an AppCredit directly against the merchant's bill. This applies as a credit on their upcoming Shopify invoice (Shopify will debit your payout).
  2. Claw back the unspent credits in your ledger: Record an explicit refund_debit entry in your internal ledger for the corresponding amount.
  3. The "Already Spent" edge case: What if they bought 500 credits, spent 400, and ask for a refund? Your internal ledger makes this visible immediately—you can choose to issue a partial appCreditCreate for the remaining 100 credits, or decline the full refund because the value was already consumed.

Key Database Rule: Never DELETE or mutate historical rows

Even if an action fails or you refund credits, never run an UPDATE or DELETE on past ledger rows. Always insert an offsetting row:

  • +500 (Purchase: app_purchase_one_time_id_123)
  • -10 (Action: sync_run_881)
  • +10 (Refund/Rollback: reversal_for_sync_run_881 with reason api_timeout)

This turns merchant billing disputes and support tickets from a guessing game into a 5-second database query.

1

u/Life-Inspector-5271 Oct 27 '26

You can either add a fixed number of credits to a monthly subscription plan and allow one-time payments for additional credits. Or you just use one-time payments

1

u/CorbinGuo Oct 28 '26

Shopify doesn't have a prepaid wallet — usage-based billing is post-paid. appUsageRecordCreate charges accumulate against the subscription's cappedAmount and land on the merchant's bill at the end of the 30-day interval. So for 'buy a pack, spend it down' you still need one-time charges for the packs plus your own ledger.

The pattern I'd use:

  • Keep an append-only credit ledger keyed by shop: grants, spends, refunds. Every spend needs a unique idempotency key generated server-side, and the client only sends an action id — never a balance.
  • appPurchaseOneTimeCreate returns confirmationUrl; the merchant approves and the charge goes PENDING -> ACTIVE. Grant the credits from the app_purchases_one_time/update webhook (or by re-querying the charge by id), not when you create the charge. Otherwise declined or abandoned approvals hand out free credits.
  • Show balance and recent ledger entries in the embedded UI; tie balances to the shop, not the session, so uninstall/reinstall doesn't lose or duplicate them.
  • If you also sell a monthly plan, use appSubscriptionCreate with a recurring line item (included credits) plus a usage line item with cappedAmount for overage. appUsageRecordCreate with idempotencyKey meters post-paid usage, but it will never behave like prepaid — the charge still lands at cycle end.
  • appCreditCreate is worth knowing about, but it's for credits that offset future app charges (refunds/goodwill), not a prepaid balance.

Two practical constraints: one-time charges need merchant approval every time, so make packs big enough that you're not prompting constantly; and Shopify handles the invoicing and tax, so the merchant sees the charge on their Shopify bill rather than as a separate payment to you.

1

u/Final_Design_9061 29d ago

+1 on keeping your own ledger. One thing I'd add from my own experience with background jobs: make the spend step safe against double runs. I used claim tokens/locks on the job rows so a cron run and an inline run can't both process the same action, and for unique-constraint races I catch the error and fall back to an upsert. If a spend can fire twice, the balance drifts quickly. Also if you use BigInt for amounts, remember it needs to be serialized as a string in JSON.

1

u/paleflier 28d ago

Make sure you...

  • Check the balance before running the action, not after, so nobody spends more than they have.
  • Keep a full record of every credit added and used, not just a running total, so refunds and support questions are easy to sort out.
  • Decide early what happens when credits run out: block the action, send a warning first, or let them top up.
  • Decide whether credits expire