Skip to main content
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 developer key and a customer, such as cust_tutorial_1 from Meter your first API.
  • Node.js 20 or later with @orvlin/node installed.
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 idempotencyKey so a retried signup doesn’t grant twice.
Run it a second time. The response shows 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.
Use "collection": "send_invoice" for enterprise customers who pay by bank transfer. They get an emailed invoice instead of a card charge.
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.
Usage reported with track is drawn from the customer’s wallet as it arrives. Before you launch, generate a few test images in the sandbox and confirm the balance on the ledger goes down.
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

The ledger lists every grant, purchase, and draw-down. It’s the first place to look when a customer asks why their balance changed.

Production checklist

  • Check credits before the expensive call, and track usage after it succeeds.
  • Use an idempotencyKey on every grant, purchase, and generation.
  • Set overage: "block" unless you want to bill customers for going over.
  • Surface balance in 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.