Time: about 30 minutes · Level: intermediate · You’ll build: a credit-based image generator where customers buy credits, each generation draws them down, and balances top up automatically.
Scenario
An AI image app sells credits. A generation costs one credit. Customers buy packs, a starter grant covers their first generations, and customers who opt in are topped up automatically when they run low.Prerequisites
- A sandbox workspace with a
developerkey and a customer, such ascust_tutorial_1from Meter your first API. - Node.js 20 or later with
@orvlin/nodeinstalled.
1
Create the credit type
A credit type defines what the credits are for, and how the balance behaves at zero. Here
block stops generations when the balance runs out, instead of billing overage.Check the response for the credit type’s
key and any field names your workspace returns. Use the key value in every later call.2
Give new customers a starter grant
A grant gives credits for free. Use Run it a second time. The response shows
idempotencyKey so a retried signup doesn’t grant twice.created: false, and the balance stays at 10.3
Let customers buy a pack
Selling a pack charges the card on file. Use the same idempotency approach, keyed to your order ID.A purchase starts as
pending_payment and becomes active once paid. Until then the credits aren’t spendable.4
Check the balance before each generation
Before you call the image model, check that the customer can pay for it. The check doesn’t spend anything.The check and the track are separate on purpose. The check decides whether to start the work. The track records the spend after it happens.
5
Turn on automatic top-up
Top up when the balance falls to 2 credits, buying 50 credits at a time, at most 5 times a month.The monthly cap stops a runaway loop from charging a customer repeatedly.
6
Show the balance and history
Production checklist
- Check credits before the expensive call, and track usage after it succeeds.
- Use an
idempotencyKeyon every grant, purchase, and generation. - Set
overage: "block"unless you want to bill customers for going over. - Surface
balancein your UI, so customers know before they run out.
Next steps
Prepaid credits reference
Every field for grants, purchases, and auto top-up.
Receive webhooks securely
Get notified when a pack’s invoice is paid.