تخطي التنقل

API Integration Guide

Everything you need to authenticate and call the Customer API.

Download PDF

Customer API Integration Guide

The Customer API lets your own systems use the platform's catalog, place orders, and check order status. The catalog is supplier-neutral: you browse and buy products by their public ID, and the platform handles fulfilment behind the scenes.

With the API you can:

  • Read your account balance and discount level.
  • List the vouchers and top-ups available to you.
  • Place a purchase, which is paid from your wallet.
  • Look up an order and its delivered codes or status.

Base URL

https://cryptogamingcards.com/api/restful/v1

All requests use this base URL. There is no separate sandbox; use your own account carefully.

Endpoints

Method Path Purpose Effective rate limit
GET /me Account balance, currency, and discount level 60 / min
GET /products Browse the unified catalog 60 / min
POST /orders Place a purchase 10 / min
GET /orders/{reference} Check an order's status and delivered codes 60 / min

The read endpoints allow 120 requests per minute per key, but every gateway request also passes a baseline limiter of 60 requests per minute for the account or source IP. The lower ceiling applies, so 60 reads per minute is the limit to design against. See Errors and limits.

Every request must send an API key. See Authentication.

Guide contents

  1. Getting started: prerequisites, creating a key, your first request.
  2. Authentication: key format, IP allowlist, security rules, and auth errors.
  3. Catalog: listing and filtering products.
  4. Checkout: placing orders and handling idempotency.
  5. Order lifecycle: order statuses and how to read them.
  6. Errors and limits: error envelope, status codes, and rate limits.
  7. Recipes: end-to-end examples.

What this API does not have

  • Pagination. List responses return the full result set for the request.
  • Webhooks. There are no push notifications. Poll GET /orders/{reference} to check order status.
  • Sandbox. There is no test environment with fake money. Every completed purchase debits a real balance, so test carefully and use GET /orders/{reference} to verify an uncertain result.
  • Supplier selection. You cannot choose which supplier fulfils an order. The platform routes each order.

Support

Contact [email protected] for API access, key problems, or order issues. Include your key's prefix (the first characters only, never the full key) and the order reference if one exists.

Getting Started

This page takes you from a new account to a first successful API call.

Prerequisites

  • An active account on the platform, in good standing.
  • API access enabled. An administrator must turn on the API feature for your account. Until then, key requests are refused with feature_disabled (see Authentication).
  • A wallet balance. Orders are paid from your wallet, so top up before you place purchases.
  • An IP allowlist (optional). You can restrict a key to specific IP addresses or CIDR ranges. Leave it empty to allow all IPs.

Create an API key

  1. Sign in to the client panel and open API Keys.
  2. Click Generate API key.
  3. Copy the key immediately. The full key is shown once. After you leave the page it cannot be displayed again, so store it in a secret manager before you continue.

The key looks like cgw_ followed by 40 characters. Only a hash is stored on the platform, which is why the plaintext cannot be recovered.

Regenerating a key revokes the old one immediately. Any system still using the previous key will start receiving 401 responses. Update your integration before, or as part of, a regeneration.

Read Authentication for how to manage keys (regenerate, deactivate, delete) and how to restrict them by IP.

Make your first request

Call GET /me to confirm the key works. The endpoint returns your balance, currency, and discount level.

curl -sS https://cryptogamingcards.com/api/restful/v1/me \
  -H "Authorization: Bearer cgw_YOUR_KEY_HERE" \
  -H "Accept: application/json"

Example response:

{
  "data": {
    "balance": "25.000",
    "currency": "USD",
    "level": 2,
    "discount": {
      "type": "PERCENT",
      "value": 0.04
    }
  }
}

The values above are illustrative. Your balance, currency, and discount reflect your own account. A PERCENT discount is a fraction, so 0.04 means 4% off, not 4 units of currency. See Pricing.

If you get a 401 or 403, check the error code in the response body against the auth error table.

Base URL

All requests use https://cryptogamingcards.com/api/restful/v1.

Keys are issued per account. Keep one key per integration, never share it between environments, and rotate it if it is exposed.

Next steps

  • Authentication: headers, key lifecycle, IP allowlist, and security rules.
  • Catalog: list the products you can buy.
  • Checkout: place your first order.

Authentication

Every request to the Customer API must authenticate with an API key sent in the Authorization header as a Bearer token:

Authorization: Bearer cgw_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Key format

  • Keys start with the prefix cgw_, followed by 40 random characters.
  • Each account has one API key. Generating a new key while one exists is done by regenerating it, which replaces the old key.
  • The full key is shown once, at the moment it is generated. The platform keeps only a hash, so a lost key cannot be recovered. Regenerate it instead.

Managing your key

All key management happens on the client panel API Keys page.

Action Effect
Generate Creates a key and shows the plaintext once. Available when you have no key.
Regenerate Creates a new key and immediately revokes the old one. Requests with the old key get 401 invalid_api_key.
Deactivate The key stops working until you reactivate it. Requests get 403 api_key_inactive.
Activate Re-enables a deactivated key.
Delete Removes the key permanently. You can generate a new one later.
IP whitelist Restricts which IP addresses may use the key. See below.

API access flag

The API must be enabled for your account by an administrator. If it is not, every request with a valid key is refused with 403 feature_disabled and this message:

Contact the administration to enable this feature for your account.

Contact support to have access enabled.

IP allowlist

You can restrict a key to specific client IP addresses:

  • Enter single IP addresses (for example 203.0.113.10) or CIDR ranges (for example 203.0.113.0/24).
  • Each entry must be a valid IP address or CIDR range. The panel rejects anything else.
  • An empty allowlist allows all IP addresses.
  • A request from an IP that is not on the list is refused with 403 ip_not_allowed.

Use the allowlist when your integration runs from fixed servers. It limits damage if a key leaks.

Security rules

  • Never call the API from browser code. Browser JavaScript exposes the key to every visitor. Call the API from your server.
  • Store the key in a secret manager or an environment variable on your server. Do not commit it to source control or paste it into tickets or chat.
  • Rotate the key when staff change. Regenerate it whenever someone who had access leaves or changes role.
  • Use one key per integration. Never reuse a key between your own applications or between your team's tools, so a leak can be revoked without disrupting everything.

Auth errors

Authentication failures return a JSON body with an error code and a message:

{
  "error": {
    "code": "invalid_api_key",
    "message": "A valid API key is required."
  }
}
HTTP status error.code Message Cause and fix
401 invalid_api_key A valid API key is required. The header is missing, not a Bearer token, does not start with cgw_, or the key does not match any key. Check the header, or regenerate and use the new key.
403 api_key_inactive This API key has been deactivated. The key was deactivated. Reactivate it on the API Keys page.
403 account_disabled This account cannot use the API. The account is suspended, deleted, or not active. Contact support.
403 feature_disabled Contact the administration to enable this feature for your account. API access is not enabled for your account. Contact support.
403 ip_not_allowed This IP address is not allowed to use this API key. The request came from an IP that is not on the key's allowlist. Add the IP or range, or send the request from an allowed address.
503 api_disabled The API is not available. The API is switched off platform-wide. Retry later.

A 401 means the key itself is unusable. A 403 means the key is recognised but this request is not allowed. Fix the cause before retrying, because retrying the same request will fail the same way.

Catalog

GET /products returns the products you can buy through the API, with prices already adjusted for your account's discount level.

GET https://cryptogamingcards.com/api/restful/v1/products
Authorization: Bearer cgw_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Accept: application/json

Query parameters

Parameter Values Default Effect
kind voucher, topup none (all kinds) Returns only vouchers or only game top-ups.
sort default, price_asc, price_desc, name_asc, name_desc, newest default Orders the products array. price_* sorts by each product's lowest discounted price. newest sorts by creation date.

An unknown kind or sort value returns 422 validation_failed.

curl -sS "https://cryptogamingcards.com/api/restful/v1/products?kind=voucher&sort=price_asc" \
  -H "Authorization: Bearer cgw_YOUR_KEY_HERE" \
  -H "Accept: application/json"

Response

The response has two parts: discount, which describes the discount your account receives, and products, the list of products.

{
  "data": {
    "discount": {
      "level": 2,
      "type": "PERCENT",
      "value": 0.04
    },
    "products": [
      {
        "kind": "voucher",
        "public_id": "prd_7KQ2M9XW4T",
        "slug": "steam-wallet",
        "name": "Steam Wallet",
        "sub_title": "Global",
        "image_url": "https://cryptogamingcards.com/storage/products/steam-wallet.png",
        "dynamic_pricing": false,
        "requires_fields": [],
        "items": [
          {
            "public_id": "itm_3HB8RZ5N2C",
            "label": "$10 Steam Wallet Code",
            "sub_title": null,
            "unit_price": "10.000",
            "discounted_unit_price": "9.600",
            "currency": "USD",
            "available": true,
            "stock": 42,
            "min_quantity": 1,
            "max_quantity": 100,
            "requires_fields": []
          }
        ],
        "min_price": 9.6,
        "sort_order": 1,
        "created_at": "2026-09-14T08:30:00+00:00"
      },
      {
        "kind": "topup",
        "public_id": "prd_Q4YD1LN8VA",
        "slug": "mobile-legends",
        "name": "Mobile Legends",
        "sub_title": null,
        "image_url": "https://cryptogamingcards.com/storage/products/mobile-legends.png",
        "dynamic_pricing": null,
        "requires_fields": [
          { "name": "game_user_id", "required": true },
          { "name": "game_server_id", "required": false }
        ],
        "items": [
          {
            "public_id": "itm_9ZC5TW6EJP",
            "label": "86 Diamonds",
            "sub_title": null,
            "unit_price": "1.500",
            "discounted_unit_price": "1.440",
            "currency": "USD",
            "available": true,
            "stock": null,
            "min_quantity": 1,
            "max_quantity": 1,
            "requires_fields": [
              { "name": "game_user_id", "required": true },
              { "name": "game_server_id", "required": false }
            ]
          }
        ],
        "min_price": 1.44,
        "sort_order": 2,
        "created_at": "2026-10-02T12:00:00+00:00"
      }
    ]
  }
}

The values above are illustrative. Your prices and discount reflect your own account.

Product fields

Field Type Meaning
kind string voucher or topup.
public_id string Product identifier. Use it to find items. It is not a purchase identifier.
slug string URL-friendly product name.
name string Display name.
sub_title string or null Optional subtitle, such as a region.
image_url string or null Product image.
dynamic_pricing boolean or null true when the product's price is calculated dynamically rather than fixed. null for top-ups.
requires_fields array Customer fields the product needs. See Required fields.
items array Purchasable options for the product.
min_price JSON number or null The lowest discounted_unit_price among the product's items, for your account. Used for price sorting. null when the product has no items. This is the one money field returned as a number, not a decimal string. See Pricing.
sort_order integer Position used by the default sort. Lower values come first.
created_at ISO 8601 string When the product was created. Used by sort=newest.

Item fields

Items are the units you purchase. You send an item's public_id as item_public_id when you place an order.

Field Type Meaning
public_id string Send this as item_public_id in POST /orders.
label string Display name, such as $10 Steam Wallet Code.
sub_title string or null Optional subtitle.
unit_price decimal string List price for one unit, before your discount.
discounted_unit_price decimal string Price for one unit after your level discount. This is what your wallet is debited.
currency string Currency code for every money field in this item.
available boolean Whether the item can be purchased right now.
stock integer or null Units in stock. null when the item has no fixed stock count (dynamic pricing and top-ups).
min_quantity integer Smallest quantity you can order.
max_quantity integer Largest quantity you can order in one request.
requires_fields array Fields this item needs. Usually the same as the product's.

Pricing

  • Money is a decimal string, such as "9.600", in every money field except one. Parse it with a decimal library, not a float, to avoid rounding errors.
  • min_price is the exception. It is returned as a JSON number, such as 9.6, and is only a convenience for sorting and filtering. Do not use it for payment amounts. Use each item's discounted_unit_price instead.
  • unit_price is the list price. It is the same for every account.
  • discounted_unit_price is your price. It applies your account's level discount to unit_price. Higher levels receive larger discounts.
  • discount shows how the discount is calculated. When type is PERCENT, value is a fraction of the price: 0.04 means 4% off, and it is applied to each unit. When type is FLAT, value is an amount taken off each unit here in the catalog, while checkout takes that amount off the order total once. See Checkout pricing.
  • Your wallet is debited the discounted price. For PERCENT discounts a voucher order costs discounted_unit_price × quantity. For FLAT discounts the total is unit_price × quantity − discount.value, so discounted_unit_price × quantity is too low above a quantity of 1. See Checkout.

Required fields

Top-up products need information that identifies the game account. The requires_fields array lists these fields, with required telling you whether the field must be sent.

Field Required When
game_user_id Yes Every top-up. Send it in fields when you place the order.
game_server_id No Some top-ups need a server. Send it in fields when the product lists it.
game_zone_id No Some top-ups need a zone instead of a server. Send it in fields when the product lists it.

Send the fields in the fields object of POST /orders:

"fields": { "game_user_id": "123456789", "game_server_id": "2023" }

Vouchers have an empty requires_fields array, so they do not need fields.

Pagination

There is no pagination. GET /products returns the whole catalog in one response, filtered and sorted by the parameters above.

Quantity rules

  • Vouchers: quantity can be from 1 to 100. Check min_quantity and max_quantity for each item.
  • Top-ups: quantity is always 1. Any other value returns 422.

Caching and conditional requests

The catalog is cached for about 60 seconds. Changes to prices or stock can take up to a minute to appear.

Every response includes an ETag header. To avoid downloading an unchanged catalog, send the stored value in If-None-Match:

GET /products
If-None-Match: "3f9c2a1e0b7d4f56a8c1e2d3b4a59687"

If the catalog has not changed, the API returns:

HTTP/1.1 304 Not Modified
ETag: "3f9c2a1e0b7d4f56a8c1e2d3b4a59687"

A 304 response has no body. Reuse the payload you stored from the last 200 response that had this ETag.

Do not poll /products more often than once a minute. The data changes at most every 60 seconds, so faster polling only uses your rate limit. Cache the catalog in your system and refresh it on a schedule. The read limit is 120 requests per minute per key, but a baseline limiter caps the account or source IP at 60 requests per minute, shared with GET /me and GET /orders/{reference}. The lower ceiling applies.

Checkout

POST /orders buys one catalog item. The order is paid from your wallet at your account's discounted price.

Rate limit: 10 checkout requests per minute per key. Requests above that return 429 Too Many Requests, with a Retry-After header. Wait for that long before retrying.

POST https://cryptogamingcards.com/api/restful/v1/orders
Authorization: Bearer cgw_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Content-Type: application/json
Accept: application/json
Idempotency-Key: 7c1e9a0d-4b2f-4e8a-9d3c-5f6a1b2c3d4e

Request body

Field Required Type Rules
item_public_id Yes string The public_id of an item from GET /products. Maximum 26 characters.
quantity No integer Vouchers: 1 to 100. Default 1. Top-ups: must be 1.
fields Top-ups object Customer fields the product requires. game_user_id is required for top-ups. See Required fields.

Fields inside fields:

Name Pattern Max length
game_user_id letters, digits, _ or - 100
game_server_id letters, digits, _ or - 255
game_zone_id letters, digits, _ or - 255

Idempotency-Key header

Send an Idempotency-Key header with every purchase. It makes retries safe.

  • Format: 1 to 64 characters, using only letters, digits, ., _ and -. A UUID works well.
  • Scope: keys are scoped to your account. The same key used by another account does not clash with yours.
  • Replay window: a key can be replayed for 7 days after the first request. During that window, sending the same key again returns the same order and does not charge you again. The replay responds with 200 and the existing order, unless the order is held for review. See Replaying a held order.
  • After 7 days: the platform deletes idempotency records older than 7 days. Reusing a key after that point is treated as a brand-new purchase and can create and debit a second order. If you are unsure whether an old purchase went through, poll GET /orders/{reference} with the reference you stored, or contact support with the time of the request. Do not re-POST an uncertain old purchase.
  • New purchase, new key: use a fresh key for each new purchase.

A missing or malformed key is ignored. If the header is absent or does not match the format above, the API does not reject the request. It replaces your key with a key it generates from the item, your account, the quantity and the current 5-minute window. A retry in a later window gets a different key, so a retry more than 5 minutes later can create a second order. Always send your own valid key for every purchase, and reuse it for every retry of that purchase.

Replaying a held order

A replay is answered with 200 only when the stored order can be returned as a normal result. When the stored order is held_for_review, the API refuses the replay with 202 Accepted and an error envelope instead of data:

{
  "error": {
    "code": "held_for_review",
    "message": "This order is on hold and cannot be replayed."
  }
}

Read error.code before you read body.data, because a held replay has no data object. Store the reference from the first response and poll GET /orders/{reference} until the order is final. If you did not store the reference, contact support; do not send the purchase again.

The first response for a held order has the other shape: 202 Accepted with data.status set to held_for_review. In the rare case that the order record cannot be reloaded when the hold is created, the 202 body is {"reference": null, "status": "held_for_review"} at the top level, with no data wrapper.

Voucher example

curl -sS -X POST https://cryptogamingcards.com/api/restful/v1/orders \
  -H "Authorization: Bearer cgw_YOUR_KEY_HERE" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "Idempotency-Key: voucher-2026-10-28-0001" \
  -d '{"item_public_id": "itm_3HB8RZ5N2C", "quantity": 2}'

Response, 201 Created:

{
  "data": {
    "reference": "8f1c2b7e-8a3d-4c5f-9b6a-1d2e3f4a5b6c",
    "status": "completed",
    "message": "Voucher codes delivered successfully.",
    "kind": "voucher",
    "item_public_id": "itm_3HB8RZ5N2C",
    "quantity": 2,
    "amount": "19.200",
    "currency": "USD",
    "vouchers": [
      "STEAM-XXXX-XXXX-XXXX",
      "STEAM-YYYY-YYYY-YYYY"
    ],
    "refunded": false,
    "invoice_url": "https://cryptogamingcards.com/invoices/ORD-20261028-8F3K2Q",
    "created_at": "2026-10-28T09:14:02+00:00",
    "updated_at": "2026-10-28T09:14:03+00:00"
  }
}

The vouchers array contains the codes. Store them securely at once, because they are the product you paid for. The reference is the supplier's reference once the order is accepted; it is the value to store and poll, and GET /orders/{reference} also accepts the platform reference returned on the very first response. message is human-readable text for your customer and can change without notice.

Top-up example

curl -sS -X POST https://cryptogamingcards.com/api/restful/v1/orders \
  -H "Authorization: Bearer cgw_YOUR_KEY_HERE" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "Idempotency-Key: topup-player-123456789-0001" \
  -d '{"item_public_id": "itm_9ZC5TW6EJP", "fields": {"game_user_id": "123456789", "game_server_id": "2023"}}'

A top-up that completes immediately returns 201 Created, and vouchers is null because there are no codes to deliver:

{
  "data": {
    "reference": "S261029153628601GOOP",
    "status": "completed",
    "message": "Account top-up completed successfully.",
    "kind": "topup",
    "item_public_id": "itm_9ZC5TW6EJP",
    "quantity": 1,
    "amount": "1.440",
    "currency": "USD",
    "vouchers": null,
    "refunded": false,
    "invoice_url": "https://cryptogamingcards.com/invoices/ORD-20261028-K7Q2WD",
    "created_at": "2026-10-28T09:20:11+00:00",
    "updated_at": "2026-10-28T09:20:11+00:00"
  }
}

A top-up that is still being delivered returns 202 Accepted with status processing. Poll the order until it leaves processing. See Order lifecycle.

Status mapping

The HTTP status tells you the outcome of the request. The data.status field tells you the state of the order.

HTTP data.status Meaning What to do
201 completed The order is paid and fulfilled. Store the reference. Deliver the vouchers to your customer.
202 processing The order is paid and being delivered. Store the reference. Poll GET /orders/{reference} until the status changes.
202 held_for_review The order is on hold while the platform reviews and reconciles it. Store the reference. Poll the order and wait for its final status before buying the same item again.
502 refunded The provider failed and the wallet was refunded. Nothing was delivered and you were not charged. Retry with a new Idempotency-Key if you still want the item.

A 503 service_unavailable is not an order outcome. It means the service was busy (for example, a transient database lock) and the purchase was not charged. Retry with the same Idempotency-Key after a short backoff.

A replay of a held order has no data.status: it returns 202 with error.code held_for_review. See Replaying a held order.

Errors

Errors use the standard envelope:

{
  "error": {
    "code": "insufficient_balance",
    "message": "Your wallet balance is too low for this order."
  }
}

Validation failures add a fields object that maps each field to its messages.

HTTP error.code Cause and fix
409 insufficient_balance The wallet cannot cover the discounted price. Top up and retry with a new key.
409 duplicate_request An identical request with this key is still in flight. Poll the existing order instead of re-sending. See Errors and limits.
409 rates_mismatch, units_unavailable The quoted price or stock changed during checkout. Refresh GET /products, then place a new order.
422 validation_failed A field is missing or invalid. Read error.fields and correct the request. Top-ups without game_user_id also return this.
422 validation_failed An item_public_id that no longer resolves returns this with the message "The selected item is unavailable." Refresh the catalog and use a current public_id.
422 invalid_quantity, invalid_amount, invalid_item The quantity or item is not valid for this purchase. Check min_quantity and max_quantity.
404 item_unavailable, product_unavailable The item or product still resolves but is hidden or unavailable at checkout time. Refresh the catalog and do not retry the same item.
400 invalid_request The Idempotency-Key belongs to a different item or account scope. Use a new key for a different purchase.
400 withdrawal_failed The wallet debit could not be recorded. Nothing was charged. Retry with the same key; if it persists, contact support.
503 service_unavailable The supplier is temporarily unavailable. Retry later with the same key.
500 checkout_failed An unexpected server error. Retry with the same key. If it persists, contact support with the time of the request.

503 is safe to retry with the same key. For 409 duplicate_request, poll the order instead of re-sending. Retries with a new key after a request that may have been charged can cause a double purchase.

Timeouts

A network timeout means you do not know whether the order was created. Handle it carefully:

  1. Do not send the purchase again with a new key. That can create a second order and charge you twice.
  2. Retry with the same Idempotency-Key within the 7-day replay window. If the first request succeeded, you get the existing order back and are not charged again. If the existing order is held for review, the replay returns 202 held_for_review; use your stored reference to poll it.
  3. If you have the reference, poll GET /orders/{reference} instead of re-sending the purchase.
  4. If the request was more than 7 days ago, the key is no longer replayable. Look the order up by the stored reference, or contact support. Do not re-POST the old purchase.

Pricing and wallet

  • The wallet is debited the discounted total. discounted_unit_price is the price for one unit, but the order total depends on the discount type.
  • PERCENT discounts: the discount is a fraction of the total, so discounted_unit_price × quantity is exactly what you pay.
  • FLAT discounts: the catalog subtracts the flat amount from each unit, but checkout subtracts it once from the order total. For a quantity above 1, discounted_unit_price × quantity is therefore lower than the amount charged. Do not quote that product to your customer from the catalog if the discount is FLAT; read amount from the order response, or compute unit_price × quantity − discount.value.
  • The amount in the response is the total for the order, as a decimal string.
  • Top-ups always have a quantity of 1, so both discount types agree for them.

What the API does not do

  • No pagination, no webhooks. Poll GET /orders/{reference} to follow an order. See Order lifecycle.
  • No supplier selection. The platform chooses the supplier for each item. You buy the item, not a supplier.
  • No sandbox. Every order is a real purchase debited from your wallet.

Order lifecycle

Every order moves through a set of statuses. POST /orders returns the order's status at the moment of purchase. GET /orders/{reference} returns its current status, so use it to follow an order that was not finished when you first saw it.

The reference in the response is the reference to keep. It is the supplier's order reference once the order has been accepted, and the platform's own reference only while that is still unknown (for example, a local voucher order). GET /orders/{reference} resolves either form, so the reference you stored from the first response keeps working.

GET https://cryptogamingcards.com/api/restful/v1/orders/ORD-20261028-K7Q2WD
Authorization: Bearer cgw_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Accept: application/json
curl -sS https://cryptogamingcards.com/api/restful/v1/orders/ORD-20261028-K7Q2WD \
  -H "Authorization: Bearer cgw_YOUR_KEY_HERE" \
  -H "Accept: application/json"

Response

{
  "data": {
    "reference": "S261029153628601GOOP",
    "status": "processing",
    "message": "Your order is being processed. Poll this reference until it completes.",
    "kind": "topup",
    "item_public_id": "itm_9ZC5TW6EJP",
    "quantity": 1,
    "amount": "1.440",
    "currency": "USD",
    "vouchers": null,
    "refunded": false,
    "invoice_url": "https://cryptogamingcards.com/invoices/ORD-20261028-K7Q2WD",
    "created_at": "2026-10-28T09:20:11+00:00",
    "updated_at": "2026-10-28T09:20:14+00:00"
  }
}

The values above are illustrative. Here the order is still processing, so vouchers is null.

Field Type Meaning
reference string The order's reference. Store it; poll it here.
status string Current lifecycle status. See Statuses.
message string Human-readable explanation of status, safe to show to your customer.
kind string voucher or topup.
item_public_id string The item that was purchased.
quantity integer Units purchased.
amount decimal string Total for the order, in currency.
currency string Currency code.
vouchers array of strings, or null The voucher codes. null until they are delivered.
refunded boolean true when the order was refunded to your wallet.
invoice_url string or null Link to the order's invoice.
created_at ISO 8601 string When the order was placed.
updated_at ISO 8601 string When the order last changed.

An order that does not exist, or that belongs to another account, returns 404 order_not_found. The API does not tell you which of the two is the case.

message is presentation text, not a machine-readable field. Branch on status and error.code, never on the message text.

Statuses

status Meaning vouchers refunded What to do
completed The order is finished and delivered. Array of codes for vouchers. null for top-ups. false Deliver the result to your customer. No further action.
processing The order is paid and waiting for delivery from the supplier. null false Keep polling until the status changes.
held_for_review The order is on hold while the platform reviews and reconciles it. null false Keep polling. Do not buy the same item again while the order is on hold. It resolves to completed or refunded.
refunded The order could not be fulfilled, so the amount was returned to your wallet. null true Do not deliver anything. You were refunded. Buy again with a new Idempotency-Key if you still need the item.

refunded is final. completed is final. processing and held_for_review are not final, so keep polling until one of the two final statuses appears.

Polling

Poll only orders that are not final yet. Stop as soon as the status is completed or refunded.

  1. Start after about 2 seconds.
  2. Back off. Double the wait after each poll, up to a maximum of 30 seconds between polls.
  3. Stop after about 10 minutes. If the order is still processing or held_for_review, stop polling and contact support with the order reference. Do not place a new purchase for the same item while you wait.

Polling counts against the read limit: 120 requests per minute per key, and 60 per minute for the account or source IP through the baseline limiter. The lower ceiling applies. Do not poll many orders in a tight loop.

GET /orders/{reference} also supports ETag and If-None-Match, the same as Catalog. If the order has not changed, the API returns 304 Not Modified with no body. Reuse the order you stored from the last 200 response.

Vouchers

  • vouchers is an array of codes for voucher orders. It is null until the codes are delivered.
  • Do not treat null as an empty result. Wait for the order to reach completed.
  • Store the codes securely when you first receive them.

Refunds

  • refunded is true only when the order was refunded to your wallet.
  • A refunded order has status refunded. A 502 response from POST /orders with this status means the same thing.
  • A refund is not a second purchase. You will not receive codes for a refunded order.

References

  • Every order has a unique reference, such as ORD-20261028-K7Q2WD.
  • The reference is the only way to look up an order later with GET /orders/{reference}.
  • Store the reference in your system as soon as you receive it from POST /orders. Link it to your own order or customer record. The API cannot list your orders for you to find a reference you lost.

What the API does not do

  • No pagination. GET /products returns the full catalog in one response, and there is no endpoint that lists orders.
  • No webhooks. The API does not push status changes to you. Poll GET /orders/{reference} to follow an order.
  • No sandbox. Every order is a real purchase debited from your wallet.
  • No supplier selection. The platform chooses the supplier for each item.

Errors and Limits

This page is the reference for every error the Customer API gateway returns, the HTTP status each one uses, and how to respond. It also covers rate limits and the rules for retrying safely.

Error envelope

Every error generated by the gateway uses the same JSON shape:

{
  "error": {
    "code": "insufficient_balance",
    "message": "Your wallet balance is too low for this order."
  }
}
  • error.code is a stable identifier. Branch your code on it, not on message.
  • error.message is human-readable and may change. Do not parse it.

Framework-level responses are the exception. A rate-limit rejection (429) is produced by the framework limiter, so rely on the status and the Retry-After header, not on a body shape. See the 429 Too Many Requests section under Rate limits.

Validation errors

A 422 with the code validation_failed also includes a fields object. It maps each invalid field name to a list of messages:

{
  "error": {
    "code": "validation_failed",
    "message": "The item public id field is required.",
    "fields": {
      "item_public_id": [
        "The item public id field is required."
      ],
      "fields.game_user_id": [
        "The fields.game_user_id field is required."
      ]
    }
  }
}

Read every entry in fields, not only message, and correct each one before you resend.

Error codes

Each row is one error.code. Use the status to decide the broad response, and the code to decide the exact fix.

error.code HTTP When it happens What to do
invalid_api_key 401 The Authorization header is missing or malformed, the key does not start with cgw_, or the key does not match any key. Also returned after a key is regenerated. Check the header. If the key was regenerated, use the new key. Do not retry unchanged.
api_key_inactive 403 The key was deactivated. Reactivate the key on the API Keys page.
account_disabled 403 The account is suspended, deleted, or not active. Contact support.
feature_disabled 403 API access is not enabled for the account. Contact support to have API access enabled.
ip_not_allowed 403 The request came from an IP address that is not on the key's allowlist. Add the IP or range to the allowlist, or send the request from an allowed address.
api_disabled 503 The API is switched off platform-wide. Retry later with backoff.
validation_failed 422 A field is missing or invalid, or a catalog query uses an unknown kind or sort. Top-ups without game_user_id and top-ups sent with a quantity other than 1 also return this. An item_public_id that no longer resolves returns this too. Read error.fields. Correct the request. For an unresolved item, refresh GET /products and use a current public_id.
invalid_amount 422 The amount is not valid for this purchase. Recalculate the price from the current catalog.
invalid_quantity 422 The quantity is outside the item's range. Check min_quantity and max_quantity.
invalid_item 422 The item cannot be purchased in this way. Refresh GET /products and choose a current item.
invalid_request 400 The Idempotency-Key is valid in format but belongs to a different item or account scope. Use a new key for a different purchase. Do not reuse a key across items.
withdrawal_failed 400 The wallet debit could not be recorded, so the order was not created. Nothing was charged. Retry with the same Idempotency-Key. If it persists, contact support with the time of the request.
insufficient_balance 409 The wallet cannot cover the discounted price. Top up the wallet, then place a new order with a new Idempotency-Key.
duplicate_request 409 An identical request with the same Idempotency-Key is still in flight. Poll the existing order. Do not re-send in a loop. See Retry rules.
rates_mismatch 409 The quoted price changed during checkout. Refresh GET /products, then place a new order.
units_unavailable 409 Stock changed during checkout. Refresh GET /products, then place a new order if the item is still available.
service_unavailable 503 The service or supplier is temporarily busy. No charge or codes were created. Retry with backoff using the same Idempotency-Key.
item_unavailable 404 The item is hidden or unavailable at checkout time. Refresh GET /products. Do not retry the same item.
product_unavailable 404 The product is hidden or unavailable at checkout time. Refresh GET /products. Do not retry the same product.
held_for_review 202 Not an error on the first response. The order is paid and on hold while the platform reviews and reconciles it. On a replay of a held order it is returned as error.code; on the first response it is data.status. Store the reference and poll GET /orders/{reference} until the order is completed or refunded. Do not buy the same item again while it is on hold.
checkout_failed 500 An unexpected server error during checkout. Retry with the same Idempotency-Key. If it persists, contact support with the time of the request.
order_not_found 404 No order has this reference for your account. The API does not reveal whether the order exists under another account. Check the reference. If it is correct, contact support.

Two outcomes are not in error.code on a first response but matter for error handling:

  • 502 with data.status refunded. The provider failed and the wallet was refunded. Nothing was delivered. This is a response body with data, not error. See Checkout.
  • 202 with data.status processing or held_for_review. The order is paid and not finished. See Order lifecycle.

A replay of an order that is held for review is different: it returns 202 with error.code held_for_review and no data object. Check for error.code before reading body.data. A held order also has a top-level fallback body, {"reference": null, "status": "held_for_review"}, if the order record could not be reloaded. See Replaying a held order.

Authentication errors are described in more detail in Authentication.

HTTP statuses at a glance

Status Meaning in this API
200 Success. A replayed POST /orders with an Idempotency-Key from the last 7 days also returns 200 with the existing order, unless the order is held for review.
201 An order was created and completed.
202 An order was accepted and is still processing or on hold. A replay of a held order returns 202 held_for_review as an error.
304 Not modified. Use your stored copy. The body is empty.
400 The request reached checkout but the idempotency key did not match the purchase, or the wallet debit failed.
401 Invalid or missing API key.
403 The key is recognised, but this request is not allowed.
404 The product, item or order was not found or is unavailable.
409 Conflict with the current state of the wallet, stock or price. Or a duplicate request is still running.
422 The request is invalid.
429 Too many requests. Wait for Retry-After seconds.
500 Unexpected server error. Only checkout_failed uses this status.
502 The provider failed and the order was refunded.
503 The API or supplier is temporarily unavailable.

Rate limits

Limits apply per API key:

Endpoints Per-key limit
GET /me, GET /products, GET /orders/{reference} 120 requests per minute
POST /orders 10 per minute

A second, baseline limiter applies to every gateway request: 60 requests per minute for the same account, or for the same source IP before the key has been authenticated. Checkout also has a per-account fallback of 60 per minute. The lowest ceiling wins, so plan for these effective limits:

Endpoints Effective limit for one key
GET /me, GET /products, GET /orders/{reference} 60 requests per minute
POST /orders 10 per minute

Both layers count the same request. Keys or systems that share one account or source IP also share the 60 per minute baseline, so a busy integration can reach the baseline before any per-key limit.

The checkout limit is 10 per minute, so the checkout endpoint is the one to protect. Polling an order counts against the read limit, so keep polling intervals sensible. See Order lifecycle.

Rate-limit headers

Responses include the rate-limit headers:

Header Meaning
X-RateLimit-Limit The number of requests allowed in the current window.
X-RateLimit-Remaining The number of requests left in the current window.
Retry-After On a 429, the number of seconds to wait before retrying.

429 Too Many Requests

When you exceed a limit, the API returns:

HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 0

Wait at least Retry-After seconds before you send the next request to that endpoint. Do not retry immediately, because each rejected attempt still counts against the limit. Rely on the status and the Retry-After header rather than the body.

Retry rules

Response Retry? How
429 Yes Wait Retry-After seconds, then back off with jitter.
500, 503 Yes Back off exponentially with jitter. For POST /orders, reuse the same Idempotency-Key.
502 No, not with the same key The provider failed and the order was refunded, which is final. To buy again, use a new Idempotency-Key.
422 No The request is invalid. Fix it, then send a new request.
400 invalid_request No The key belongs to a different item or account scope. Use a new key for this purchase.
400 withdrawal_failed Yes Nothing was charged. Retry with the same Idempotency-Key with backoff.
403 No Fix the cause (key, account, feature flag or IP allowlist) first. The same request will fail again.
401 No Fix the key first.
409 duplicate_request Only by polling An identical request with this Idempotency-Key is still in flight. Do not send the purchase again. Poll GET /orders/{reference} for the existing order. If you have lost the reference, wait for the original request to settle, which can take several minutes, then re-send with the same Idempotency-Key. Do not re-send in a loop, because each attempt counts against the checkout limit.
409 (other codes) No The state changed. Refresh the catalog or top up, then place a new order with a new key.
404 No Refresh the catalog or check the reference.

Use exponential backoff with random jitter, for example waiting about 1 second, then 2, then 4, with a random offset added to each wait. Stop after a bounded number of attempts and record the failure for a person to review.

Idempotency recap

  • Send your own Idempotency-Key header on every POST /orders. Use a valid key: 1 to 64 characters, letters, digits, ., _ and -.
  • Reuse the same key for every retry of the same purchase. For 7 days the API returns the existing order and does not charge you again.
  • After 7 days the idempotency record is deleted. Reusing the key then creates and debits a new order. Look up the old order by its stored reference, or contact support; do not re-POST an uncertain old purchase.
  • Use a new key for each new purchase.
  • A missing or malformed key is replaced by a generated key that changes every 5 minutes, so a retry after that window can create a second order. See Checkout.

What the API does not do

  • No pagination. List responses return the full result set.
  • No webhooks. Poll GET /orders/{reference} to follow an order.
  • No sandbox. Every order is a real purchase.
  • No supplier selection. The platform routes each order.

Recipes

Copy-paste examples for the most common tasks. Every recipe uses https://cryptogamingcards.com/api/restful/v1 and your API key.

Read the key from an environment variable on your server. Never put it in browser code or source control.

export CGW_API_KEY="cgw_YOUR_KEY_HERE"
export CGW_BASE_URL="https://cryptogamingcards.com/api/restful/v1"

Every recipe assumes you have also read Checkout, Order lifecycle and Errors and limits.

cURL

List vouchers, cheapest first

curl -sS "$CGW_BASE_URL/products?kind=voucher&sort=price_asc" \
  -H "Authorization: Bearer $CGW_API_KEY" \
  -H "Accept: application/json"

Create a voucher order with an Idempotency-Key

Generate the key once per purchase and store it with your own order record before you send the request. The API replays that key for 7 days after the first request; after that the record is deleted, so reusing the key starts a new purchase.

IDEMPOTENCY_KEY="voucher-$(uuidgen)"

curl -sS -X POST "$CGW_BASE_URL/orders" \
  -H "Authorization: Bearer $CGW_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  -d '{"item_public_id": "itm_3HB8RZ5N2C", "quantity": 2}'

Poll a top-up order

Check an order by its reference. Use If-None-Match with the ETag from your last 200 response to receive 304 Not Modified when nothing has changed.

curl -sS -i "$CGW_BASE_URL/orders/ORD-20261028-K7Q2WD" \
  -H "Authorization: Bearer $CGW_API_KEY" \
  -H "Accept: application/json" \
  -H 'If-None-Match: "3f9c2a1e0b7d4f56a8c1e2d3b4a59687"'

PHP (Guzzle)

These examples use Guzzle, installed with composer require guzzlehttp/guzzle.

<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

$client = new Client([
    'base_uri' => rtrim(getenv('CGW_BASE_URL'), '/') . '/',
    'headers' => [
        'Authorization' => 'Bearer ' . getenv('CGW_API_KEY'),
        'Accept' => 'application/json',
    ],
    'http_errors' => false,
]);

$response = $client->get('products', [
    'query' => ['kind' => 'voucher', 'sort' => 'price_asc'],
]);

$catalog = json_decode((string) $response->getBody(), true);

Create a voucher order

$idempotencyKey = 'voucher-' . bin2hex(random_bytes(8));

$response = $client->post('orders', [
    'headers' => ['Idempotency-Key' => $idempotencyKey],
    'json' => [
        'item_public_id' => 'itm_3HB8RZ5N2C',
        'quantity' => 2,
    ],
]);

$status = $response->getStatusCode();
$order = json_decode((string) $response->getBody(), true)['data'] ?? null;

Poll a top-up order

$delay = 2;
$maximumDelay = 30;
$deadline = microtime(true) + 600;
$etag = null;
$order = null;

while (microtime(true) < $deadline) {
    $headers = $etag === null ? [] : ['If-None-Match' => $etag];

    try {
        $response = $client->get('orders/' . $reference, ['headers' => $headers]);
    } catch (\GuzzleHttp\Exception\GuzzleException $e) {
        sleep($delay);
        $delay = min($delay * 2, $maximumDelay);

        continue;
    }

    $status = $response->getStatusCode();

    if ($status === 429) {
        $retryAfter = (int) ($response->getHeaderLine('Retry-After') ?: 10);
        sleep(max($retryAfter, 1));

        continue;
    }

    if ($status >= 400 && $status < 500) {
        $body = json_decode((string) $response->getBody(), true);

        throw new RuntimeException('Order lookup failed: ' . ($body['error']['code'] ?? $status));
    }

    if ($status >= 500) {
        sleep($delay);
        $delay = min($delay * 2, $maximumDelay);

        continue;
    }

    if ($status === 200) {
        $order = json_decode((string) $response->getBody(), true)['data'];
        $etag = $response->getHeaderLine('ETag') ?: null;
    }

    if ($order !== null && in_array($order['status'], ['completed', 'refunded'], true)) {
        break;
    }

    sleep($delay);
    $delay = min($delay * 2, $maximumDelay);
}

if ($order === null || ! in_array($order['status'], ['completed', 'refunded'], true)) {
    throw new RuntimeException("Order {$reference} is not final. Contact support with the reference.");
}

The loop stops after about 10 minutes. It sends If-None-Match after the first 200, so a 304 keeps the stored order, and it backs off on 429, 5xx and network errors. A 4xx other than 429 is not retried.

Node.js (fetch)

Node 18 and later include fetch. No packages are needed.

These examples use top-level await, so save the file as .mjs (or set "type": "module" in package.json). For CommonJS, wrap the top-level calls in an async function main() { ... } and call main().

const baseUrl = process.env.CGW_BASE_URL;
const apiKey = process.env.CGW_API_KEY;

async function api(path, options = {}) {
  const response = await fetch(`${baseUrl}${path}`, {
    ...options,
    headers: {
      Authorization: `Bearer ${apiKey}`,
      Accept: 'application/json',
      ...options.headers,
    },
  });

  const body = response.status === 304 ? null : await response.json();

  return { status: response.status, body, headers: response.headers };
}

const { body: catalog } = await api('/products?kind=voucher&sort=price_asc');

Create a voucher order

const idempotencyKey = `voucher-${crypto.randomUUID()}`;

const { status, body } = await api('/orders', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Idempotency-Key': idempotencyKey,
  },
  body: JSON.stringify({ item_public_id: 'itm_3HB8RZ5N2C', quantity: 2 }),
});

console.log(status, body.data.reference, body.data.status);

Poll a top-up order until it is final

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function waitForFinalOrder(reference, { timeoutMs = 10 * 60 * 1000 } = {}) {
  const startedAt = Date.now();
  let delay = 2000;
  let order = null;
  let etag = null;

  while (Date.now() - startedAt < timeoutMs) {
    let result;

    try {
      result = await api(`/orders/${reference}`, {
        headers: etag ? { 'If-None-Match': etag } : {},
      });
    } catch (networkError) {
      await sleep(delay + Math.random() * 1000);
      delay = Math.min(delay * 2, 30000);

      continue;
    }

    const { status, body, headers } = result;

    if (status === 429) {
      const retryAfter = Number(headers.get('Retry-After') ?? 10);
      await sleep(Math.max(retryAfter, 1) * 1000);

      continue;
    }

    if (status >= 400 && status < 500) {
      throw new Error(`Order lookup failed with ${status}: ${body?.error?.code ?? 'unknown'}`);
    }

    if (status >= 500) {
      await sleep(delay + Math.random() * 1000);
      delay = Math.min(delay * 2, 30000);

      continue;
    }

    if (status === 200) {
      order = body.data;
      etag = headers.get('ETag');
    }

    if (order && ['completed', 'refunded'].includes(order.status)) {
      return order;
    }

    await sleep(delay);
    delay = Math.min(delay * 2, 30000);
  }

  throw new Error(`Order ${reference} is not final. Contact support with the reference.`);
}

const finalOrder = await waitForFinalOrder('ORD-20261028-K7Q2WD');

The loop sends If-None-Match after the first 200, so a 304 keeps the stored order instead of losing it. It waits for Retry-After on 429, retries 5xx and network errors with backoff, and stops immediately on any other 4xx.

Python (requests)

Install with pip install requests.

import os
import time
import uuid

import requests

BASE_URL = os.environ["CGW_BASE_URL"]
HEADERS = {
    "Authorization": f"Bearer {os.environ['CGW_API_KEY']}",
    "Accept": "application/json",
}

catalog = requests.get(
    f"{BASE_URL}/products",
    params={"kind": "voucher", "sort": "price_asc"},
    headers=HEADERS,
    timeout=15,
).json()["data"]

Create a voucher order

idempotency_key = f"voucher-{uuid.uuid4()}"

response = requests.post(
    f"{BASE_URL}/orders",
    json={"item_public_id": "itm_3HB8RZ5N2C", "quantity": 2},
    headers={**HEADERS, "Idempotency-Key": idempotency_key},
    timeout=30,
)

order = response.json()["data"]
print(response.status_code, order["reference"], order["status"])

Poll a top-up order until it is final

def wait_for_final_order(reference, timeout_seconds=600):
    deadline = time.monotonic() + timeout_seconds
    delay = 2
    order = None
    etag = None

    while time.monotonic() < deadline:
        headers = {**HEADERS}
        if etag:
            headers["If-None-Match"] = etag

        try:
            response = requests.get(
                f"{BASE_URL}/orders/{reference}",
                headers=headers,
                timeout=15,
            )
        except requests.RequestException:
            time.sleep(delay)
            delay = min(delay * 2, 30)
            continue

        if response.status_code == 429:
            retry_after = int(response.headers.get("Retry-After", 10))
            time.sleep(max(retry_after, 1))
            continue

        if 400 <= response.status_code < 500:
            raise RuntimeError(
                f"Order lookup failed: {response.json().get('error', {}).get('code', response.status_code)}"
            )

        if response.status_code >= 500:
            time.sleep(delay)
            delay = min(delay * 2, 30)
            continue

        if response.status_code == 200:
            order = response.json()["data"]
            etag = response.headers.get("ETag")

        if order and order["status"] in ("completed", "refunded"):
            return order

        time.sleep(delay)
        delay = min(delay * 2, 30)

    raise TimeoutError(f"Order {reference} is not final. Contact support with the reference.")


final_order = wait_for_final_order("ORD-20261028-K7Q2WD")

The loop stops after about 10 minutes. It sends If-None-Match after the first 200, so a 304 keeps the stored order, and it backs off on 429, 5xx and network errors. A 4xx other than 429 is not retried.

Mapping the catalog to an order

Use requires_fields to decide what to ask your customer for before you place a top-up. Vouchers have an empty list, so they need no extra fields.

function buildOrderPayload(item, product, customerValues, quantity = 1) {
  const fields = {};

  for (const field of product.requires_fields) {
    const value = customerValues[field.name];

    if (field.required && (value === undefined || value === '')) {
      throw new Error(`Missing required field: ${field.name}`);
    }

    if (value !== undefined && value !== '') {
      fields[field.name] = String(value);
    }
  }

  const payload = { item_public_id: item.public_id, quantity };

  if (Object.keys(fields).length > 0) {
    payload.fields = fields;
  }

  return payload;
}

const payload = buildOrderPayload(
  product.items[0],
  product,
  { game_user_id: '123456789', game_server_id: '2023' },
);

Top-ups must have quantity of 1. Pass the result to POST /orders with a new Idempotency-Key.

Safe retry

Store the idempotency key before the first attempt. If you do not know whether the request reached the API, retry with the same key. The API returns the existing order instead of creating a second one.

That replay window is 7 days. After 7 days the idempotency record is deleted, and reusing the key creates and debits a new order. Look the old order up by the reference you stored, or contact support; do not re-POST an uncertain old purchase. A replay of an order that is held_for_review returns 202 with error.code held_for_review, so read error.code before data. See Checkout.

async function placeOrderSafely(payload, idempotencyKey, maxAttempts = 4) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      const response = await fetch(`${baseUrl}/orders`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
          Accept: 'application/json',
          'Idempotency-Key': idempotencyKey,
        },
        body: JSON.stringify(payload),
      });

      if (response.status === 429) {
        const retryAfter = Number(response.headers.get('Retry-After') ?? 10);
        await sleep(retryAfter * 1000);
        continue;
      }

      if (response.status >= 500 && response.status !== 502) {
        await sleep(2 ** attempt * 1000 + Math.random() * 1000);
        continue;
      }

      return { status: response.status, body: await response.json() };
    } catch (networkError) {
      await sleep(2 ** attempt * 1000 + Math.random() * 1000);
    }
  }

  throw new Error(`Order not confirmed after ${maxAttempts} attempts. Check the idempotency key ${idempotencyKey} before buying again.`);
}

const idempotencyKey = `topup-player-123456789-${crypto.randomUUID()}`;
await db.saveIdempotencyKey(orderId, idempotencyKey);

const result = await placeOrderSafely(payload, idempotencyKey);

This retries on 429, on 5xx other than 502, and on network errors. It does not retry 422, 403, 401 or other 409 responses, which need a fix first. A 502 with refunded is final, so start a new purchase with a new key if you still want the item.

The db object in the last lines is a placeholder for your own storage. Save the key with your order before the first attempt, so a crash never loses it.

نستخدم ملفات تعريف الارتباط لتحسين تجربتك. باستمرارك في استخدام هذا الموقع، فإنك تقبل استخدامنا لملفات تعريف الارتباط. معرفة المزيد