Casino API Integration

Wallet callbacks: bet, win and rollback done correctly

How to implement the wallet endpoints of a casino API so that retries, timeouts and out-of-order calls never cost you or the player money.

Updated 5 min read

In a seamless wallet integration, the game server calls your platform every time money moves. At its core there are four calls. Each one is simple when everything works. The engineering is in what happens when a request is sent twice, arrives late, or arrives in the wrong order.

This guide describes the behaviour most providers and aggregators expect. Field names and error codes differ, so read the specification you are given. The rules below hold across nearly all of them.

The four calls

Call Purpose Changes the balance
Balance Show the current balance in the game No
Bet Subtract a stake Yes, down
Win Add a payout, including a zero win that closes the round Yes, up
Rollback Undo one earlier transaction, usually a bet Yes, usually up

Some APIs combine bet and win into one call for instant games. Many add an authenticate call at session start, an explicit round-end call, and calls for free spins, jackpots or tournament prizes. A round can also contain several bets and several wins, as in live games, crash games and bonus buys, and some wins arrive with no bet at all, such as jackpots and promotional prizes. They follow the same rules.

Rule 1: verify who is calling

Anyone who can reach your wallet endpoint can ask it to add money. Before doing anything else:

  • Check the signature. Many APIs sign each request with an HMAC of the body and a shared secret. Compute the same value and compare it in constant time. Others hash sorted parameters with a secret, use a token, or sign with RSA.
  • Restrict by IP to the addresses the provider publishes.
  • Reject old requests if the API includes a timestamp, to stop replays.
import { createHmac, timingSafeEqual } from "node:crypto";

function verified(rawBody, signatureHex, secret) {
  const expected = createHmac("sha256", secret).update(rawBody).digest();
  const given = Buffer.from(signatureHex, "hex");
  return given.length === expected.length && timingSafeEqual(given, expected);
}

For body signatures, verify against the raw bytes you received. If you parse the JSON and serialise it again, key order and spacing can change and the signature will not match.

Rule 2: every transaction is idempotent

Networks fail. When a provider does not get an answer in time, it sends the same request again. Your endpoint must give the same answer and move the money only once.

The pattern is the same for bet, win and rollback:

  1. Look up the transaction ID.
  2. If you have seen it, return the stored result. Do not touch the balance.
  3. If you have not, apply it and store the result in the same database transaction.
-- one row per provider transaction, unique on (provider, transaction_id)
-- status: 'ok' or 'failed'; response: the exact body you returned;
-- ref_transaction_id: for a rollback, the transaction it undoes
INSERT INTO wallet_tx (provider, transaction_id, player_id, round_id, kind, amount, status)
VALUES ($1, $2, $3, $4, 'bet', $5, 'pending')
ON CONFLICT (provider, transaction_id) DO NOTHING
RETURNING id;

If the insert returns no row, the request is a repeat: load the stored row and return its saved response. The unique index does the work, so two identical requests arriving in the same millisecond cannot both succeed. Run the insert and the balance update in one database transaction, then save the final status and response on the row. If a repeated transaction ID arrives with a different amount or player, reject it.

Rule 3: check and subtract in one step

Reading the balance, comparing it with the stake and then writing the new value is three steps. Two bets arriving together can both pass the check. Do it in one statement:

UPDATE wallets
SET balance = balance - $1
WHERE player_id = $2 AND balance >= $1
RETURNING balance;

No row returned means insufficient funds. Return the provider's error code for that, leave the balance unchanged, and store the transaction as failed, so a retry gets the same error. Many APIs expect this error as a code in the response body with HTTP 200, not as an HTTP error status.

Rule 4: wins are always accepted

A win must be credited even if the session has expired, the player has logged out, or the account has since been restricted. The stake has already been taken, so refusing the win means the player paid for a round and was not paid out.

Session checks belong on balance and bet. On win and rollback, identify the player from the round or the original bet instead.

Rule 5: rollbacks can arrive before the bet

A rollback is sent when the provider is not sure a bet succeeded. That includes the case where the bet never reached you. So:

  • Rollback for a known bet: refund the exact amount, once, and mark the bet as rolled back.
  • Rollback for an unknown bet: record the transaction ID as rolled back, credit nothing, and return what the specification prescribes: success in many APIs, a "transaction not found" code in others. Either way, reject the bet if it arrives later.
  • Rollback for a bet whose round has already been paid: follow the specification. Most APIs expect you to refuse it.

The second case is the one most first implementations miss, and it produces stakes that are taken and never returned.

Rule 6: one unit for money

Decide how amounts are stored and never mix representations. Many APIs send integers in the smallest unit of the currency, such as cents. Others send decimals as strings. Convert at the edge of your system and store integers or exact decimals, never floating point.

Check the currencies with no minor unit and the ones with three decimals, and check how the provider handles cryptocurrencies, which often use a fixed multiplier.

Rule 7: answer fast, or expect a rollback

Providers set a time limit on wallet responses, often a few seconds at most. A late answer counts as no answer. Keep the wallet path short: verify, write, respond. Bonus calculations, notifications and analytics belong in a queue that runs after the response is sent.

What to log

For each call, keep the raw request, your response, the transaction ID, the round ID and the balance before and after. When a player disputes a round, or a monthly invoice does not match your own numbers, this log is the only thing that settles it.

Tests to run before production

  • The same bet sent twice returns the same balance and subtracts once.
  • A bet larger than the balance is refused, leaves the balance unchanged, and returns the same error when retried.
  • Two bets sent in parallel that together exceed the balance: exactly one succeeds.
  • A win for an expired session is credited.
  • A rollback for an unknown transaction returns the response the specification asks for, and the late bet is then refused.
  • A rollback sent twice refunds once.
  • A request with a bad signature is rejected before any database work.

The full pre-launch list is in the go-live checklist.