Skip to content

3 min read

Crediting a prepaid balance from payment webhooks

Keeping customers' balances as a ledger, crediting each top-up exactly once from its webhook, and what every payment outcome should do to the balance.

A stack of ledger rows growing upward from a webhook mark, the newest row in greenA stack of ledger rows growing upward from a webhook mark, the newest row in green
On this page

Panels, proxy sellers, API platforms, and games all keep a prepaid balance: customers add funds, then spend them on many small things. The payment side is one 402pay payment per top-up. The hard part is the other side, turning a stream of webhook deliveries into a balance that's always right, even when deliveries repeat, arrive out of order, or describe a payment that came in short.

This post walks through the design we recommend: a ledger instead of a number, one credit per payment keyed by its id, and a clear rule for each payment outcome.

A balance is a ledger, not a number

The tempting design is a balance column you add to and subtract from. It works until the first support ticket asks why a balance is what it is, and then nothing can answer. Keep every movement as a row instead: a top-up credited, an order paid, a refund back to the balance, an adjustment by your team. The balance is their sum.

A ledger for prepaid balancesSQL
create table balance_entries (  id          bigserial primary key,  user_id     bigint not null references users(id),  kind        text not null,          -- 'top_up', 'order', 'refund', 'adjustment'  source_id   text not null,          -- the payment's id, or your order's  amount      numeric(12, 2) not null, -- positive adds, negative spends  created_at  timestamptz not null default now(),  unique (kind, source_id)); -- The balance customers see, kept in step in the same transaction.alter table users add column balance numeric(12, 2) not null default 0  check (balance >= 0);

Two details do most of the work. The unique pair of kind and source_id means one payment can credit a balance only once, however many times you try. And the cached balance on the user, changed only in the same transaction as an entry, with a check that it never goes below zero, keeps reads fast without letting the two drift apart.

From webhook to ledger entry

The endpoint itself should do as little as possible: verify the signature, store the event by its id, answer with a 2xx, and do the rest in a worker. Our post on verifying webhook signatures covers that part in full. A delivery your server doesn't answer is retried, up to 8 attempts in all, so every step after it has to be safe to run twice.

In the worker, read the payment again from the API rather than trusting the delivery's body. That gives you its status as it is now, whatever order events arrived in, and a payment that isn't succeeded credits nothing.

Credit a top-up onceNode.js
async function onPaymentEvent(event) {  const response = await fetch(`https://dash.402pay.co/api/v1/payments/${event.subject.id}`, {    headers: { Authorization: `Bearer ${process.env.PAY402_SECRET_KEY}` },  });  const { data: payment } = await response.json();  if (payment.status !== "succeeded") return; // nothing to credit yet   const topUp = await db.topUps.find(payment.reference);  if (!topUp) return;   // Paid in full (or more): credit the top-up's amount.  // Accepted short: credit in proportion to what arrived.  const due = Number(payment.amount) + Number(payment.customer_fee);  const received = Number(payment.amount_received);  const credit =    received >= due      ? Number(payment.amount)      : Math.floor((Number(payment.amount) * received * 100) / due) / 100;   await db.transaction(async (tx) => {    const added = await tx.balanceEntries.insertIfAbsent({      user_id: topUp.userId,      kind: "top_up",      source_id: payment.id,      amount: credit,    });    if (!added) return; // a repeat delivery: already credited    await tx.users.addToBalance(topUp.userId, credit);    await tx.topUps.markCredited(topUp.id, credit);  });}
A verified delivery, with the payment read again, branches three ways: a payment that succeeded for the first time adds a ledger entry, the same payment again is skipped, and a payment that's underpaid or needs review credits nothing yet.A verified delivery, with the payment read again, branches three ways: a payment that succeeded for the first time adds a ledger entry, the same payment again is skipped, and a payment that's underpaid or needs review credits nothing yet.
Every delivery ends in one of three places. Only the first sight of a succeeded payment moves the balance.

How much to credit

On a normal top-up the answer is simply the payment's amount, what the customer chose on your Add funds page. Two settings change the arithmetic, and the handler above covers both:

Customers pay the feeIf you let customers pay the fees, the total they send includes customer_fee. That part covers 402pay's fee, not their balance, so credit amount, not everything that arrived.
An accepted short paymentIf you accept a payment that arrived short, amount_received is less than what was due. Credit the same share of the amount, rounded down to the cent, so accepting never hands out more than was paid.
Credit the balance with what the customer paid for it, never with what they meant to send.

What the other events should do

Only payment.succeeded credits a balance. The rest are worth handling, but none of them should move money in the ledger:

payment.underpaidCheckout is already asking the customer for the rest at the same rate. Show the top-up as waiting; payment.succeeded follows if the rest arrives.
payment.needs_reviewA late transfer or one on another network. Credit nothing until you decide; accepting it makes the payment succeed, and the handler credits it then.
payment.overpaidComes with or after payment.succeeded. Record the excess, then credit its value as an adjustment or send it back from your wallet, as your policy says.
payment.failed and payment.expiredNo funds landed. Close the top-up so the customer can start a new one.

The guide to underpayments and overpayments covers each of those outcomes from the customer's side.

Spending and refunding the balance

The debit needs the same care as the credit. Two orders placed at the same moment, by a reseller's script for example, must not both spend the same dollars. Do the check and the debit in one statement, and write the entry from its result:

Spend from the balance only if it covers the orderSQL
with debit as (  update users     set balance = balance - $2   where id = $1 and balance >= $2  returning id)insert into balance_entries (user_id, kind, source_id, amount)select id, 'order', $3, -$2 from debit;-- No row inserted means the balance didn't cover the order.
  • An order that fails or delivers only partly goes back as a refund entry that names the order. The unique pair stops a refund from being applied twice.
  • A refund out of your platform is a send from your wallet. Record it as a negative adjustment when you send it, so the balance and your wallet agree.
  • At the end of the month, the sum of every balance is what your customers have paid and not yet spent. Our post on reconciling crypto payments shows how to tie it to your wallet and fee statement.

Testing it

There's no test mode, so rehearse the handler with a signed test event, which your handler should skip, and then a small real top-up of your own. See testing a crypto checkout before launch.

Common questions

  • Write each credit as a ledger entry with a unique key made of its kind and the payment's id, in the same transaction that changes the balance. A repeat delivery finds the entry already there and does nothing.
  • Read the payment again from the API and credit only if its status is succeeded. That gives you its current state whatever order deliveries arrive in.
  • Credit the payment's amount. The customer_fee part of what they sent covers the fee and isn't balance. For an accepted short payment, credit the same share of the amount that arrived.
  • Not while it's underpaid. Checkout asks the customer for the rest. Credit only when the payment succeeds, either because the rest arrived or because you accepted what came.

See what 402pay can do for you.

Discover how 402pay helps your business accept any card and get paid in crypto, straight to a wallet you control.