Sell prepaid credit
This guide sells a customer prepaid credit with the API: they pay up front,
and later invoices in the same currency draw the credit down. It walks
through the calls: create the top-up (POST /), then take the
payment by charging the saved card (collect), sending the payment link
(send) or recording a payment (record-payment), or withdraw it (void).
Then what the customer sees, the top-up’s history, how to refund the credit
the customer has not used, and how to top up a customer’s credit
automatically from your own code.
Think of a gift card: the customer buys it once, and each purchase after that spends from it.
Before you start
Section titled “Before you start”- Hardcount running, with its address in
HARDCOUNTand a test secret key inHARDCOUNT_(first invoice).KEY - A customer with an email address, with its Hardcount ID (
hc_) incus_ … CUSTOMER_.ID - To charge the customer’s saved card, or to let them pay by card on their payment page: Stripe connected in this mode (Connect Stripe). Recording a payment you received needs neither.
Two settings are set in the dashboard, not with an API key, under Settings → Invoicing. One is how long bought credit lasts, from 1 to 3650 days (below). The other is the low-balance alert that automatic top-up starts from. The seller name in the customer’s email and on their payment page is the business name in Settings → General.
Words on this page
Section titled “Words on this page”| Word | Meaning |
|---|---|
| Top-up | The invoice that sells the credit: billing_ topup, with one line. It is a draft with no number until it is paid. |
| Issue | Give an invoice its number and make it final. An ordinary invoice is issued when you finalize it; a top-up is issued by its payment. |
| Bought credit | The credit a paid top-up adds to the customer’s balance (grant_ commit in the API). |
| Withdraw | Void a top-up nobody paid. It granted nothing, and its link stops working. |
In the dashboard, Sell credit on the customer’s page, or on the Credit page, makes the same top-up as step 1.
How long the credit lasts
Section titled “How long the credit lasts”Credit bought with a top-up stays usable for topup_ after
its payment, from 1 to 3650 days. Set it in the dashboard: Settings →
Invoicing → Bought credit lasts (days). Leave it blank and the credit never
expires, which is the default.
A top-up copies the setting when it is created, so a change applies to
top-ups created after it. The setting is changed from a dashboard session:
PUT / with an API key answers 403 “this endpoint requires a
dashboard session”.
1. Create the top-up
Section titled “1. Create the top-up”An invoice with one line that carries commit_, and nothing
else, is a top-up. unit_ is what the customer pays, and
commit_ is the credit they get. Here they pay $90 for $100 of
credit: a $10 discount.
TOPUP=$(jq -n --arg cus "$CUSTOMER_ID" \ '{customer_id: $cus, line_items: [{description: "Prepaid credit", line_type: "add_on", quantity: 1, unit_amount_cents: 9000, commit_granted_cents: 10000}]}' \ | curl -s -X POST "$HARDCOUNT/v1/invoices" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ -H "Content-Type: application/json" \ -d @-)TOPUP_ID=$(echo "$TOPUP" | jq -r .id)echo "$TOPUP" | jq -c '{id, status, billing_reason, invoice_number, amount_due_cents, due_at, tax_amount_cents}'You see:
{"id":"hc_
The top-up has no number and no due date: nothing is owed until it is paid.
The purchase carries no tax, because the usage the credit pays for is taxed
(tax on prepaid credit). Its line,
read with GET /, shows credit_ when the
credit expires, and leaves it out when it never does.
You never call finalize on a top-up: its payment issues it, numbering it in the same step. Finalizing it is refused.
curl -s -X POST "$HARDCOUNT/v1/invoices/$TOPUP_ID/finalize" \ -H "Authorization: Bearer $HARDCOUNT_KEY"You see: 409 with code invalid_ and the message “A top-up is
issued when it is paid: collect it, send it, or record a payment.”
2. Take the payment
Section titled “2. Take the payment”Pick one of the three ways. Each one, when the payment arrives, numbers the top-up, issues it, marks it paid and adds the credit, in one step.
Charge the saved card
Section titled “Charge the saved card”Send an Idempotency-Key. A retry with the same key answers what the first
call answered and never charges twice
(idempotency).
curl -s -X POST "$HARDCOUNT/v1/invoices/$TOPUP_ID/collect" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ -H "Idempotency-Key: $(uuidgen)"You see: the invoice, with status paid, its new invoice_ and
payment_ succeeded. Other answers:
- No saved card:
422validation_, “customer has no payment method set up”. Nothing was charged. Send the link instead.error - The card is declined:
502provider_, with the reason. The top-up stays an unpaid draft, and the customer gets no email. A retry with the same key answers the sameerror 502; to charge again, use a new key. - Stripe still confirming:
200withpayment_status processing. Theinvoice.webhook event follows when the payment settles.paid
Send the payment link
Section titled “Send the payment link”The customer gets an email with a link to their payment page, where they pay by card.
curl -s -X POST "$HARDCOUNT/v1/invoices/$TOPUP_ID/send" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ -H "Content-Type: application/json" \ -d '{"email": "ap@globex.test"}'You see: the email queued. The send is refused with 409 when the link
could not work, and the message says why. Without Stripe connected in this
mode, it begins “This top-up’s email is a link to pay it by card, and Stripe
isn’t connected in this mode”.
Record a payment you received
Section titled “Record a payment you received”For a bank transfer, a cheque or cash. note is your reference.
curl -s -X POST "$HARDCOUNT/v1/invoices/$TOPUP_ID/record-payment" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ -H "Content-Type: application/json" \ -d '{"note": "Wire 1042"}' \ | jq -c '{status, invoice_number, amount_paid_cents, paid_out_of_band, due_at}'You see:
{"status":"paid",
3. Check the credit
Section titled “3. Check the credit”curl -s "$HARDCOUNT/v1/credits/balance/$CUSTOMER_ID" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ | jq -c '.data[] | {currency, balance_cents, total_granted}'You see: {"currency":"USD",
The customer paid $90 and holds $100 of bought credit.
Withdraw a top-up nobody paid
Section titled “Withdraw a top-up nobody paid”Void it. It keeps no number, granted nothing, and its link stops working.
Here UNPAID_ is a second top-up, created as in step 1 and not paid.
curl -s -X POST "$HARDCOUNT/v1/invoices/$UNPAID_ID/void" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ | jq -c '{status, invoice_number}'You see: {"status":"voided",
A charge on it afterwards is refused with 422. A card payment that still
arrives is recorded as a payment on a voided invoice, which raises the
payment. event and grants no credit. Refund that
payment in Stripe: the customer paid for an offer you withdrew.
What the customer sees
Section titled “What the customer sees”The email (step 2, send): the subject “Buy prepaid credit from Acme Cloud”, then:
Acme Cloud sent you a link to buy USD 100.00 of prepaid credit for USD 90.00.
The credit is added to your account as soon as your payment goes through. It is valid for 365 days after payment.
This is not a bill: you pay only if you want the credit.
and a Buy credit button. The validity sentence is “It never expires.” when no validity is set.
The payment page, in each state:
| State | What it shows |
|---|---|
| Unpaid | “Buy prepaid credit”, then “You pay $90.00. You get $100.00 of credit, added to your account as soon as your payment goes through.”, the validity sentence and a Pay $90.00 button. No number, no amount due, no PDF. |
| Paid | The invoice, with its number and “Paid”, then “Credit added: $100.00”, the validity sentence and its PDF. |
| Withdrawn | “Offer withdrawn”, then “This offer was withdrawn by Acme Cloud.” No number and no PDF. |
The receipt, once paid: the usual receipt for the new invoice, plus “Credit added: USD 100.00” and the validity sentence.
No PDF until it is paid. GET /, and the PDF link
of the payment page, answer 409 invalid_, “A top-up has no document
until it is paid.”, for an unpaid or withdrawn top-up. A paid top-up’s PDF is
its invoice.
Its history
Section titled “Its history”GET / answers for an unpaid top-up
too: its creation, its declined charges and the emails sent for it. The
dashboard shows the same rows on the top-up’s page.
curl -s "$HARDCOUNT/v1/invoices/$TOPUP_ID/payment-timeline" \ -H "Authorization: Bearer $HARDCOUNT_KEY" | jq -c '.events[] | .line.title'You see, for the top-up paid by bank transfer above: "Top-up created",
"Invoice issued", "Offline payment received", "Credit added". The
credit row carries the amount and, when the credit expires, its expiry. A
withdrawn one ends in "Top-up withdrawn".
Refund unused credit
Section titled “Refund unused credit”A credit note with a commit_ block takes back the credit a customer
has not used on a paid top-up, and refunds what they paid for it, at the
price they paid. $60.00 of credit from a $90 top-up of $100 refunds $54.00.
Send an Idempotency-Key. A retry with the same key answers what the first
call answered and never refunds twice. Without one, a retried partial refund
(retire_) takes back more credit and refunds it again
(idempotency).
curl -s -X POST "$HARDCOUNT/v1/credit-notes" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d "{\"invoice_id\": \"$TOPUP_ID\", \"commit_relief\": {\"retire_all\": true}}" \ | jq -c '{status, total_cents, commit_retired_cents, refund_amount_cents, out_of_band_amount_cents}'You see (the top-up paid by bank transfer in step 2, with no credit used
and no usage reported):
{"status":"issued",
- Unused credit is what is left of the top-up’s credit now, but no more than the customer’s balance less the usage not invoiced yet, which has already used credit. Credit is usable up to its expiry instant, and expired after it, even before Hardcount writes the expiry off. Tax, a fee billed at the end of the period and what unpaid invoices owe are not taken off: an invoice bills them.
- Usage your gateway has not reported yet is not known to Hardcount. Pause the customer’s key and let reporting catch up before you refund.
- While an invoice is waiting to use the credit, such as the invoice of
a period that has just closed, the refund answers
409and names it. Try again after the next collection pass. A draft not yet finalized waits on you: finalize or void it. - How much:
retire_takes all the unused credit, but no more than the payment has left once money went back another way: a refund made in Stripe, or a dispute the customer’s bank won.all retire_takes part of it; more answerscents 422with the figure. Aretire_whose money is the rest of the payment answerscents 422asking forretire_, since that refund takes all the unused credit, so none outlives the money. With nothing left, it answersall 409“This payment has already been returned in full.” - Where the money goes: to the card that paid. The card gets at most
what it paid less every refund of that payment, including refunds made in
the Stripe dashboard; put the rest in
out_. For a top-up paid another way, the refund isof_ band_ amount_ cents out_: you pay the customer back, and Hardcount records it.of_ band_ amount_ cents - Refused with
409payment_while the customer’s bank disputes the payment (a chargeback, or your appeal of one). An inquiry, before any chargeback, does not stop a refund. Also refused withdisputed 409stripe_while a refund made in Stripe on the top-up is in flight or flagged: it may be the same money. Record it or dismiss it first.refund_ unresolved - After the bank won a dispute, Hardcount has already recorded the loss
and taken back the credit that money paid for
(Card disputes). A refund of what is
left cannot go to the card: it answers
422and says to send the money asout_if you pay it back another way. Hardcount does not choose that for you. While the loss’s credit note is not written yet, relief answersof_ band_ amount_ cents 409dispute_and namesloss_ unrecorded record-loss, which writes it. - A card refund that fails leaves the credit note’s
refund_status failed. Use Retry refund first (POST /): it looks in Stripe for the refund before it sends one, so it never refunds twice. When the refund failed because a chargeback opened during it, don’t pay the customer back while the dispute is open. If you win it, retry the refund. If you lose it, the bank has already returned the money: mark the refund as returned another way without paying (v1/ credit-notes/ {id}/ retry-refund POST /). Pay the customer back outside Stripe, then mark it, only when Stripe refused the card, such as a closed card. Returned another way means outside Stripe: a refund you make later in the Stripe dashboard is recorded as a refund made in Stripe, apart from this credit note.v1/ credit-notes/ {id}/ mark-returned-another-way
Money returned in Stripe takes the credit back
Section titled “Money returned in Stripe takes the credit back”A refund of a top-up’s payment made in the Stripe dashboard is recorded as a credit note for its amount, as on any invoice, and the note takes back the unused credit that amount paid for, at the price paid. $45.00 refunded on a $90 top-up of $100 takes back $50.00 of credit, or less if less is unused. Each refund stands alone; a refund for credit already used takes none. A dispute the customer’s bank wins on the payment does the same, with the money recorded as returned by the bank.
- For goodwill, grant credit or pay another way. Hardcount cannot tell a
goodwill refund from a refund of credit. Don’t refund the top-up’s payment
in Stripe unless the credit should go: grant credit with
POST /, or pay the customer outside Stripe.v1/ credits/ grant - A refund for credit already used, then a void of the usage invoice
that used it, gives the credit back on a payment already refunded. Both
are your own acts, and no more money can follow by card. If the customer
should not keep that credit, refund it with commit relief while the
payment’s credit notes leave part of it to return. Once they return all
of it, relief answers
409, so remove the credit withPOST /and a negativev1/ credits/ adjust amount_; a removal draws the customer’s credit in the order invoices do, promotional credit first.cents - Never top up automatically when the balance falls by
refund(below): that credit went back because its money went back.
Automatic top-up with your own code
Section titled “Automatic top-up with your own code”Hardcount does not top up a customer’s credit by itself yet. Your code can: when the customer’s credit runs low, create a top-up and charge their saved card.
The event: credit.
(its message). Its
data. names the customer (customer_), the currency and
the balance_ after the change, and data. is your
threshold.
- The threshold is Settings → Invoicing → Credit low-balance alert
(
credit_). It is one number for the whole account, applied in each currency’s own units, not one per customer. With none set, the event is never sent. Home also lists the balances below it, and the ones that ran out, under “needs attention”.balance_ low_ threshold_ cents - It fires once per crossing: when one change takes a currency’s balance from at or above the threshold to below it. Further spending below the threshold sends nothing more, until the balance is back at or above it.
- It follows the settled balance, which changes when an invoice, a grant, an adjustment or an expiry is written, not as usage arrives (why).
credit.fires when a balance reaches zero or less, with or without a threshold. After a low crossing whose top-up was not paid, it is the next event that comes, so the handler below takes both.balance_ depleted data.says why the balance fell:reason usage,expiry,adjustmentorrefund. Top up only onusage.refundis credit a top-up bought, taken back because its money went back to the customer: a refund, or a dispute the bank won. Pausing the customer’s key is right whatever the reason.
A handler for the event. This Python handler uses only the standard
library, and verify_ from
Receive webhooks.
Call on_ from your web framework’s route with the raw request body
and the Hardcount-Signature header, and answer with the status it returns.
import collections, json, os, threading, urllib.error, urllib.request
HARDCOUNT, KEY = os.environ["HARDCOUNT"], os.environ["HARDCOUNT_KEY"]SECRET = os.environ["HARDCOUNT_WEBHOOK_SECRET"] # whsec_…, shown when the endpoint is madeSELL = {"unit_amount_cents": 5000, "commit_granted_cents": 5000} # what one top-up sellshandled = set() # event ids you acted on: keep them in your databaselinked = set() # top-ups whose payment link you emailed: keep them in your database# One event per customer at a time. With more than one worker or process,# use a lock in your database instead.locks = collections.defaultdict(threading.Lock)
def api(method, path, body=None, key=None): headers = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"} if key: headers["Idempotency-Key"] = key req = urllib.request.Request(f"{HARDCOUNT}/v1{path}", None if body is None else json.dumps(body).encode(), headers, method=method) try: with urllib.request.urlopen(req) as r: return r.status, json.load(r) except urllib.error.HTTPError as e: return e.code, json.load(e)
def on_webhook(raw: bytes, signature: str) -> int: if not verify_hardcount_signature(raw, signature, SECRET): return 400 event = json.loads(raw) data = event["data"] if event["event_type"] not in ("credit.balance_low", "credit.balance_depleted") or event["id"] in handled: return 200 if data["reason"] != "usage": # never top up for credit taken back return 200 cus, cur = data["credit_balance"]["customer_id"], data["credit_balance"]["currency"] enough = data.get("threshold_cents", 1) # balance_depleted has no threshold: any credit is enough with locks[cus]: balances = api("GET", f"/credits/balance/{cus}")[1]["data"] if not any(b["currency"] == cur and b["balance_cents"] >= enough for b in balances): drafts = api("GET", f"/invoices?customer_id={cus}&status=draft")[1]["data"] topup = next((i for i in drafts if i["billing_reason"] == "topup" and i["currency"] == cur), None) if topup is None: line = {"description": "Prepaid credit", "line_type": "add_on", "quantity": 1, **SELL} status, topup = api("POST", "/invoices", {"customer_id": cus, "currency": cur, "line_items": [line]}, key=f"topup-create-{event['id']}") if status != 201: return 500 # keep the event: Hardcount sends it again status, inv = api("POST", f"/invoices/{topup['id']}/collect", key=f"topup-collect-{topup['id']}") if status != 200 or inv["status"] != "paid": status, body = api("GET", f"/invoices/{topup['id']}") # decide from the top-up, not the answer if status != 200: return 500 inv = body["invoice"] if inv["status"] == "draft" and inv["payment_status"] in ("processing", "unknown"): return 500 # still settling: invoice.paid or payment.failed follows if inv["status"] == "draft" and topup["id"] not in linked: # nothing was charged email = api("GET", f"/customers/{cus}")[1]["email"] status, _ = api("POST", f"/invoices/{topup['id']}/send", {"email": email}, key=f"topup-send-{topup['id']}") if status != 200: return 500 linked.add(topup["id"]) handled.add(event["id"]) return 200What it does, in order:
- Checks the signature and skips an event it has handled, by the
event’s
id(hc_), one that is neitherwhevt_ … credit.norbalance_ low credit., and one whosebalance_ depleted reasonis notusage. Keephandledandlinkedin your database, so a restart does not forget them. - Takes the customer’s lock. One change can send both events, and the second must find the first’s top-up. With more than one worker or process, use a lock in your database instead: a lock in memory holds only within one process.
- Reads the balance again. If it is back at or above the threshold (or
above zero, for
credit.), a payment already landed, and it does nothing.balance_ depleted - Reuses an unpaid top-up in the event’s currency, so a second event
never makes a second top-up, and a delivery after a crash between the
create and the charge charges the top-up already made. Otherwise it
creates one, with the key
topup-create-<event id>. - Charges it with the key
topup-collect-<top-up id>, so each top-up is charged at most once for all its events and deliveries. - Decides from the top-up, not from the charge’s answer. Unless the
charge answered
200withstatuspaid, it reads the top-up once and acts on its state. The answer alone misleads:422has six causes, from no saved card to a top-up you withdrew, and a stored502comes back unchanged for 24 hours under the same key.
What it does with the top-up’s state (GET /). A
top-up stays a draft until it is paid; it is never finalized or written off.
status |
payment_ |
What it means | The handler |
|---|---|---|---|
paid |
succeeded |
Paid, and the credit added | Done |
draft |
pending or failed |
Nothing was charged: no saved card, a declined or refused card, or no Stripe | Emails the payment link, once per top-up, and is done |
draft |
processing or unknown |
Stripe is confirming the payment, or did not answer | Answers 500, so the event comes again; invoice. or payment. settles it |
voided |
any | You withdrew the top-up | Done, and sends nothing |
Answering 500 keeps the event: Hardcount sends it again after 1 minute,
5 minutes, 30 minutes, 2 hours and 24 hours
(Retries). To charge the card again yourself, for
example after the customer adds a new one, collect the top-up with a new
key: the handler’s key keeps the first answer for 24 hours.
You see, on a test server with no Stripe connected: the handler creates
the top-up (201), and the charge answers 422 “customer has no payment
method set up”. The top-up is a draft with payment_ pending, so
the handler emails the payment link. That send answers 409, because the
payment page cannot take a card without Stripe, so the handler answers
500 and the event comes again.
What to ask a lawyer
Section titled “What to ask a lawyer”Prepaid credit can fall under consumer and payment rules that differ by country and state. Hardcount gives no legal advice. Before you sell credit, ask a lawyer where you sell:
- Credit that expires: what notice of the expiry you must give, and when. Whether consumer law limits expiry on bought credit, or sets a shortest allowed period. Whether unclaimed-property, escheat or gift-card rules apply to credit that is not spent.
- Refunds: whether a customer may claim back unspent credit, and on what terms. Refunding unused credit (above) is your decision in Hardcount, for each top-up.
- What your terms and your invoices must say about the credit, its validity and refunds.
Next: gate usage on what the customer can still spend: Stop usage when credit runs out.
Stuck, or found a bug? Ask in Discussions · Open an issue