Mastodon

Field notes

7 checks before a game payments integration goes live

One purchase, four checks on the same player. Three different catalog mistakes behind one “Cart is empty”. A test card that moved the tax to another country. Here's what I found running a full purchase, refund and webhook flow in Xsolla's sandbox, and what to check before your game store takes real payments.

· 7 checks · tested in a sandbox

I built a small Node.js reference for selling an item through , the commerce platform for game developers, and ran it end to end in a sandbox project: create a payment token, take a test payment, receive the webhooks, grant the item, then refund it. Nothing was charged.

The payment itself was the easy part. What needed care was everything around it. These are the seven checks I'd go through with any studio before its store takes real payments, each with what the sandbox actually did.

Where the checks fit

Checkout
Checks 4, 5 and 7
The payment token: what the cart really holds, errors that share one message, and the tax country
Payment
Check 2
user_validation: is this a real player? Asked several times in one purchase
Webhooks
Checks 1, 3 and 6
Signature first, grant once from order_paid, and the right status code
Where each check fits in a purchase. Tested in Xsolla's sandbox in November 2026.

1. Check the signature over the raw bytes, before anything else

Xsolla signs every webhook in its Authorization header:

text
Authorization: Signature <sha1 of the raw body followed by your secret>

Hash the body exactly as it arrived. If your framework parses the JSON for you and you serialise it again, the bytes change and the signature never matches; in Express, use express.raw() on the webhook route. Use the secret marked Active, too: a project can have several, but only one signs.

The kit checks the signature first and compares in constant time. In the live run it verified every real webhook, and refused an unsigned request with 400 INVALID_SIGNATURE.

2. Keep user_validation fast and read-only

Before taking payment, Xsolla asks your server whether the player exists. For one purchase, it asked four times:

The kit's log, one purchase
checkout: order 800504023 for player-1
webhook 204: user_validation: player-1 accepted
webhook 204: user_validation: player-1 accepted
webhook 204: user_validation: player-1 accepted
webhook 204: user_validation: player-1 accepted
webhook 204: order_paid 800504023 (sandbox): granted

That's expected: Xsolla checks the player at several stages. So the handler should only look the player up. Anything it creates or changes, it will do four times.

A rejection, though, is final. When the kit turned a player away on purpose, its log showed:

The kit's log, a rejected player
checkout: order 800505353 for stranger
webhook 400: user_validation: stranger rejected

The payment UI then refused to take payment, with “A valid User ID is required ... Error 1205”, and no payment webhooks followed. Xsolla user_validation, and an error, a timeout or no answer at all counts as a rejection.

3. Grant once per order, from order_paid

Grant items when order_paid arrives, keyed on order.id. The same webhook can arrive more than once, after a timeout or a 5xx, so a repeat gets 204 and changes nothing. In production, put a unique key on the order ID, and write the grant and the order record in one transaction.

Two details catch people out:

  • The player is user.external_id in order_paid, but user.id in user_validation.
  • The return page is for display only. A player can close the tab before the redirect, and anyone can open a return URL by hand.

Refunds work the same way in reverse. The refunded test order sent order_canceled once, and the kit took the item back once.

4. Expect the cart to drop what it can't sell

Ask for a good item plus one that doesn't exist, and the token request still succeeds: 201, no error. Xsolla drops the item it can't sell, and the payment UI showed a cart with only the good item, for RM8.70.

So grant from the items listed in order_paid, never from what your checkout asked for. If a partial cart is unacceptable, like a bundle that only makes sense whole, look each SKU up before you create the token.

5. Look it up. Don't guess from the message

Three different catalog problems all came back exactly like this:

Creating a payment token
{
  status: 422,
  errorCode: 1455,
  errorMessage: '[0401-1455]: Cart is empty',
  transactionId: '3d165bdcf636e4d8a3d945b80d6a759c'
}

The three problems were:

  • an SKU that isn't in the project's catalog
  • an item that exists but is disabled
  • an item that's enabled but hidden from the store

The last one surprises people: is_show_in_store isn't just about display. Look each SKU up as an admin, and the answer is one field away: 404 with code 4001, is_enabled: false, or is_show_in_store: false.

Auth errors work the same way. A wrong API key and a correct key sent with another project's ID both got 401, code 1501. And every error carries a transactionId: log it, and quote it when you contact support.

6. Answer each webhook with the status code you mean

Xsolla reads your answer:

  • 204 when it's handled, including repeats and types you don't act on, so they never hold up the webhooks that follow.
  • 400 only for a genuinely bad request. Xsolla doesn't retry a 4xx, and if automatic refunds are switched on, a 4xx to order_paid .
  • 500 when something fails on your side, so Xsolla retries: up to 20 attempts within 12 hours.

Answer quickly, too. Xsolla recommends under 3 seconds, so record the order, return 204, and do the slow work afterwards.

7. Test tax with a card from that country

The kit asked for every token with Malaysia as the country, and before a card was entered, the payment UI showed what you'd expect: US$1.99 = RM8.70, including 6% tax. The paid test order's receipt read US$1.99 = £1.62, including UK VAT at 20%.

The test card 4242 4242 4242 4242 is a UK card, and the tax and currency followed the card's country, not the token request. To test a country's pricing and tax, set the country and pay with a test card issued there. can be sorted by country.

One more: keep 64-bit IDs exact

Xsolla's API types its IDs as 64-bit integers, and JavaScript's JSON.parse rounds whole numbers above 2^53. The sandbox's IDs have 9 or 10 digits, so it hasn't happened yet, but the kit's demo shows what it would do:

npm run demo:ids
With JSON.parse:
  first order ID:  9007199254740992
  second order ID: 9007199254740992
  same ID? true. An exactly-once check keyed on this ID would skip the second order.

Two different orders, one ID, and an exactly-once check would skip the second. The kit's json.js keeps big IDs exact.

The checklist

  1. Check the signature over the raw bytes, first.
  2. Keep user_validation fast and read-only.
  3. Grant once per order, from order_paid.
  4. Expect the cart to drop what it can't sell.
  5. Look errors up. Don't guess from the message.
  6. Answer each webhook with the status code you mean.
  7. Test tax with a card from that country.

And before you go live:

  • Check order.mode. Sandbox orders arrive as "sandbox", real ones as "default", so never grant real items for a sandbox order.
  • Turn off sandbox in the token request only once your licensing agreement with Xsolla is signed. Until then, only sandbox payments work.

The kit

Everything above comes from , a small Node.js reference with no dependencies. It creates payment tokens, receives and checks webhooks, and grants and takes back items exactly once. It also has : 13 problems, each with Xsolla's real answer, how to tell the causes apart, and the fix.

The three files behind the checks above, in full:

src/signature.js (28 lines)
src/signature.js
import { createHash, timingSafeEqual } from "node:crypto";

/**
 * Xsolla signs every webhook: the Authorization header holds "Signature <hex>", where <hex> is the
 * lowercase SHA-1 of the raw request body followed by your secret key.
 *
 * Hash the bytes exactly as they arrived. Parsing the JSON and serialising it again changes them,
 * and the signature never matches.
 */
export function verifySignature(rawBody, authorizationHeader, secretKey) {
  const provided = String(authorizationHeader ?? "").replace(/^Signature\s+/i, "").trim();
  const expected = sha1Hex(rawBody, secretKey);
  const a = Buffer.from(provided, "utf8");
  const b = Buffer.from(expected, "utf8");
  // Compare in constant time, so the check doesn't leak how much of a guess was right.
  return a.length === b.length && timingSafeEqual(a, b);
}

/** Signs a body the way Xsolla does: for tests, and for replaying webhooks locally. */
export function signBody(rawBody, secretKey) {
  return `Signature ${sha1Hex(rawBody, secretKey)}`;
}

function sha1Hex(rawBody, secretKey) {
  return createHash("sha1")
    .update(Buffer.concat([Buffer.from(rawBody), Buffer.from(secretKey, "utf8")]))
    .digest("hex");
}
src/webhooks.js (70 lines)
src/webhooks.js
/**
 * Handles one webhook from Xsolla: check the signature, then act on notification_type.
 * Returns { status, body, summary } so it can be tested without a server.
 *
 * How Xsolla reads the response:
 *   2xx                accepted.
 *   4xx + error body   rejected and not retried. A 4xx to order_paid can trigger an automatic
 *                      refund, so this kit sends one only for a genuinely bad request.
 *   5xx                a temporary problem on our side. Xsolla retries order_paid and
 *                      order_canceled (up to 20 attempts over 12 hours).
 */
import { parseJson } from "./json.js";
import { verifySignature } from "./signature.js";

const reject = (status, code, message, summary) => ({ status, body: { error: { code, message } }, summary });

export function handleWebhook({ rawBody, authorization, secretKey, store, log = console }) {
  if (!verifySignature(rawBody, authorization, secretKey)) {
    return reject(400, "INVALID_SIGNATURE", "Signature mismatch", "rejected: bad signature");
  }

  let event;
  try {
    event = parseJson(Buffer.from(rawBody).toString("utf8"));
  } catch {
    return reject(400, "INVALID_PARAMETER", "Body is not valid JSON", "rejected: not JSON");
  }
  const type = event?.notification_type;

  try {
    switch (type) {
      case "user_validation": {
        // A gate before payment. It's never retried, and no payment webhook follows a rejection,
        // so answer 204 only for players that really exist. The player is user.id here.
        const id = event.user?.id;
        return store.hasPlayer(id)
          ? { status: 204, summary: `user_validation: ${id} accepted` }
          : reject(400, "INVALID_USER", "User not found", `user_validation: ${id} rejected`);
      }

      case "order_paid": {
        // The fulfilment trigger. The player is user.external_id here, not user.id.
        const orderId = event.order?.id;
        const playerId = event.user?.external_id;
        if (orderId === undefined || !playerId || !Array.isArray(event.items)) {
          return reject(400, "INVALID_PARAMETER", "order.id, user.external_id and items are required", "order_paid: incomplete");
        }
        // Keyed on order.id, so a retry never grants twice.
        const outcome = store.grant(String(orderId), String(playerId), event.items, event.order.mode);
        return { status: 204, summary: `order_paid ${orderId} (${event.order.mode ?? "default"}): ${outcome}` };
      }

      case "order_canceled": {
        // A refund or chargeback: take back what this order granted, once.
        const orderId = event.order?.id;
        if (orderId === undefined) return reject(400, "INVALID_PARAMETER", "order.id is required", "order_canceled: incomplete");
        const outcome = store.revoke(String(orderId));
        return { status: 204, summary: `order_canceled ${orderId}: ${outcome}` };
      }

      default:
        // Acknowledge types this kit doesn't act on, so they never hold up the ones that follow.
        return { status: 204, summary: `${type ?? "unknown"}: acknowledged` };
    }
  } catch (error) {
    // Our side failed (storage, a bug), not the request: 5xx, so Xsolla retries instead of refunding.
    log.error?.(error);
    return { status: 500, summary: `${type}: failed on our side, Xsolla will retry` };
  }
}
src/json.js (23 lines)
src/json.js
/**
 * JSON that keeps 64-bit IDs exact.
 *
 * JavaScript numbers are exact only up to 2^53 - 1 (Number.MAX_SAFE_INTEGER, 9007199254740991).
 * JSON.parse silently rounds anything bigger: 9007199254740993 becomes 9007199254740992, so two
 * different orders can end up with the same ID. Node 22 gives JSON.parse's reviver each value's
 * original text (context.source), so whole numbers past the safe range can become BigInt, with no
 * extra package. JSON.rawJSON writes them back out as the same digits.
 */

/** JSON.parse, except that whole numbers past the safe range become BigInt. */
export function parseJson(text) {
  return JSON.parse(text, (key, value, context) =>
    typeof value === "number" && !Number.isSafeInteger(value) && /^-?\d+$/.test(context?.source ?? "")
      ? BigInt(context.source)
      : value,
  );
}

/** JSON.stringify, except that BigInt values are written as plain digits, the way they arrived. */
export function stringifyJson(value, space) {
  return JSON.stringify(value, (key, v) => (typeof v === "bigint" ? JSON.rawJSON(v.toString()) : v), space);
}

To run it yourself, you need Node.js 22.9 or newer and a free . Webhooks also need an HTTPS tunnel, and the README has the steps.

Your turn

Which error message cost you the most time?

Every payments integration has one. If you're building game commerce or payments in Southeast Asia, I'd like to hear yours.

Get in touch

From the same kind of sandbox run: 7 checks before a hotel booking API goes live in a new market.