B2B API Integration Guide

Welcome to the Win20X Developer Documentation. Our platform enables seamlessly embedding 100+ top-tier casino game suppliers (including Aviator, Slots, Table Games, and Live dealers) directly into your website via a unified B2B gateway.

This integration is executed in an A-Z flow: retrieving providers, fetching game lists, generating launch links, and processing transactional webhooks on your player ledger.

Key Features

The Win20X B2B API provides a unified, secure gateway to manage casino gaming sessions, provider integrations, and player ledger updates in real-time.

Feature Details
100+ Premium Game Providers Access to the industry's leading casino content suppliers (including Pragmatic Play, Spribe, Jili, PG Soft, Evoplay, etc.).
10,000+ Casino Games Includes Slots, Crash games (e.g. Aviator), Table Games, and Live Dealer tables.
Real-Time Callbacks Immediate transaction callbacks for bets, wins, and round updates sent to your system.
Secure Launch URLs High-security, single-use launch sessions that expire within 60 seconds to protect against link hijacking.
Cross-Platform Optimization Full, native support for Desktop, Mobile web, and Tablet devices.
Unified API Architecture Simple, documented JSON REST API that hides white-label tenancy separation from gaming suppliers.

Base URL & Connectivity

All Win20X API queries must be submitted over secure HTTPS connection to the following endpoint:

https://api.win20x.com

Port Configuration: Standard SSL Port 443 is used. Please ensure your backend firewall permits outbound connections to this destination.

Integration Flow

To take a player from your lobby to a live game session, complete these five sequential steps:

Step Action Details
1 Call GET /api/v1/getallproviders Retrieve all active game suppliers configured on your white-label account.
2 Call GET /api/v1/getallgamesandprovider Fetch the portfolio catalogue and game codes for a chosen provider.
3 Call POST /api/v1/getgameurl Obtain a secure session launch URL using the player's username and balance details.
4 Redirect Player Load the returned launcher URL in an iframe or redirect the player. (URL expires in 60s).
5 Receive Callbacks Listen to real-time POST webhooks on your callback target URL and update player balance.

API Credentials & Authentication

All outbound API requests from your server to our gateway must connect over HTTPS to https://api.win20x.com and present B2B credentials in the request headers.

Header Name Description
x-api-key Your B2B Client API Key (issued via your B2B Client Portal).
x-api-secret Your B2B Client API Secret (issued via your B2B Client Portal).

Note: API requests will be rejected unless the originating server IP address is whitelisted in your B2B dashboard.

1. Retrieve Game Providers

Fetch all active game suppliers integrated on the SaaS gateway.

GET /api/v1/getallproviders

Sample Response:

{
  "success": true,
  "message": "All games grouped by provider fetched successfully",
  "games": [
    "SPRIBE",
    "EVOPLAY",
    "PRAGMATIC",
    "ODIN"
  ]
}

2. Retrieve Games List

Retrieve the complete game portfolio mapping of a specific supplier.

GET /api/v1/getallgamesandprovider?provider={providerName}

Query Parameters:

Param Type Required Description
provider string Yes E.g. SPRIBE or EVOPLAY

Sample Response:

{
  "success": true,
  "message": "All games for EVOPLAY fetched successfully",
  "games": [
    {
      "id": "75f81c56565d394503f544f3431ef370",
      "name": "Aviator",
      "provider_name": "SPRIBE",
      "game_type": "crash"
    }
  ]
}

3. Generate Game Session URL

Requests a secure session launcher link to frame or load the game for your player. When you call this, player balances are automatically synchronized with our transaction ledger.

POST /api/v1/getgameurl

JSON Body Parameters:

Param Type Required Description
username string Yes Your player's unique username or ID on your system.
gameId string Yes The unique game code (from Step 2).
money number Yes The player's current balance in BDT (৳) (Decimal format).
platform number Yes 1 for Desktop, 2 for Mobile/Tablet.
currency string Yes Must pass BDT (or your client currency code).
home_url string Yes The absolute redirect target URL when the player exits the game session.
lang string No Language (defaults to en).
ip string No The player's real originating IP address.
operator_code string No Your B2B tenancy/operator identifier name (e.g. skeybet).

Integration Code Snippets

cURL
Node.js
PHP
Python
curl -X POST "https://api.win20x.com/v1/getgameurl" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "x-api-secret: YOUR_API_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "player123",
    "gameId": "aviator",
    "money": 1500.00,
    "platform": 1,
    "currency": "BDT",
    "home_url": "https://yourwebsite.com/lobby",
    "ip": "103.151.22.45",
    "operator_code": "skeybet"
  }'

Sample Response:

{
  "code": 0,
  "msg": "Success",
  "payload": {
    "game_launch_url": "https://livecasinoapi.betnex.co/game?token=8bf95935-...",
    "game_name": "Aviator",
    "provider": "SPRIBE",
    "expires_in": 60
  }
}

4. Inbound Transaction Callbacks

During game play (placing bets, wins, and bonus updates), our system will send HTTP POST webhooks back to your registered Inbound Callback Webhook URL. Your backend must listen to these events, update the player balance on your system in real-time, and return a successful JSON confirmation.

POST Request Payload:

{
  "bet_amount": 100.0000,
  "win_amount": 250.0000,
  "member_account": "p_1_user99",
  "game_uid": "75f81c56565d394503f544f3431ef370",
  "game_round": "round_unique_12345",
  "currency_code": "BDT",
  "api_key": "wjr4_api_key_xyz",
  "serial_number": "txn_unique_serial_556"
}

Required Response Body (JSON, HTTP Status 200):

{
  "success": true,
  "message": "Callback processed successfully"
}

Callback Security & Webhook Rules

To avoid security vulnerabilities (such as double payout exploits or replay attacks), your system must strictly follow these rules:

  1. Validate the API Key: Check that the incoming api_key in the payload matches your own B2B API Key.
  2. Player Username Masking: The incoming member_account will contain the internal masked player token we generated (e.g. p_{clientId}_{username}). Map this back to your user.
  3. Strict Idempotency Check: Log the unique transaction serial_number in your database. If you receive a webhook with a serial_number that is already marked as processed in your ledger, do not deduct or credit balances again. Simply respond with success 200 OK immediately.
  4. Atomic Ledger Updates: Calculate: New Balance = Current Balance - bet_amount + win_amount in a single database transaction.

Integration Code Snippets

PHP Callback Handler
NodeJS / Express Handler
<?php
// Inbound callback route (listen at your registered callback URL)
header('Content-Type: application/json');

$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 1. Basic validation
if (!$data || !isset($data['serial_number']) || !isset($data['member_account'])) {
    echo json_encode(['success' => false, 'message' => 'Malformed payload']);
    exit;
}

$apiKey = $data['api_key'];
$memberAccount = $data['member_account'];
$betAmount = (float)$data['bet_amount'];
$winAmount = (float)$data['win_amount'];
$serialNumber = $data['serial_number'];

// 2. Validate API Key
$myApiKey = "YOUR_API_KEY"; // Set your API key here
if ($apiKey !== $myApiKey) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Connect to Database
$db = new PDO('mysql:host=localhost;dbname=casino', 'db_user', 'db_pass');

try {
    $db->beginTransaction();

    // 3. Idempotency Check
    $stmt = $db->prepare("SELECT 1 FROM processed_txs WHERE serial_number = ? FOR UPDATE");
    $stmt->execute([$serialNumber]);
    if ($stmt->fetch()) {
        $db->rollBack();
        echo json_encode(['success' => true, 'message' => 'Duplicate transaction']);
        exit;
    }

    // Extract player ID from secure token (p_{clientId}_{username})
    $parts = explode('_', $memberAccount);
    $playerUsername = end($parts);

    // Lock player balance row
    $userStmt = $db->prepare("SELECT balance FROM users WHERE username = ? FOR UPDATE");
    $userStmt->execute([$playerUsername]);
    $user = $userStmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => 'Player not found']);
        exit;
    }

    $currentBalance = (float)$user['balance'];
    $newBalance = $currentBalance - $betAmount + $winAmount;

    if ($newBalance < 0) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => 'Insufficient funds']);
        exit;
    }

    // Update player balance
    $updateStmt = $db->prepare("UPDATE users SET balance = ? WHERE username = ?");
    $updateStmt->execute([$newBalance, $playerUsername]);

    // Record serial number to prevent replay attacks
    $logStmt = $db->prepare("INSERT INTO processed_txs (serial_number, amount) VALUES (?, ?)");
    $logStmt->execute([$serialNumber, $winAmount - $betAmount]);

    $db->commit();
    echo json_encode(['success' => true, 'message' => 'Callback processed successfully']);

} catch (Exception $e) {
    $db->rollBack();
    echo json_encode(['success' => false, 'message' => 'Database transaction failed: ' . $e->getMessage()]);
}

Callback Processing Logic

Every spin or game action initiates a callback sequence. A single game round can have multiple transaction events (for example, a bet callback first, followed by a win/settlement callback). Your integration must match and process these events accurately.

Callback Lifecycle & Primary Identifier

The primary unique key for any callback session is game_round. Do not treat serial_number as the round identifier. Multiple callbacks sharing the same game_round belong to the same bet round and must be aggregated rather than created as separate wagers.

Step-by-Step Processing Pipeline

Step Operation Details
1 Authenticate Request Validate that the payload api_key matches your B2B API Key credentials.
2 Idempotency Check Verify if the incoming serial_number has already been successfully written to your logs. If yes, skip balance update and return a 200 OK response with the current player balance.
3 Look up game_round Query your database for the game_round identifier.
4a Round Not Found (Create) If the round doesn't exist, insert a new round record. Set the bet and win amounts from the request body. Deduct the bet_amount from the player's wallet.
4b Round Exists (Update) If the round exists, increment the existing record's bet_amount and win_amount fields by the values in the webhook body.
5 Recalculate Wallet Balance Perform the mathematical equation: New Balance = Current Balance - bet_amount + win_amount.
6 Atomic DB Transaction Commit Save both the ledger logs and updated wallet balances in a single database transaction. If any queries fail, trigger a ROLLBACK.
7 Return JSON Acknowledgment Respond with HTTP 200 and the JSON payload shown below (including the player's updated wallet balance).

Your Response to the Callback

After successfully updating the player's ledger, your handler must return a 200 OK response containing the following parameters:

Field Type Description
success boolean Must return true if processed without error.
msg string A short success/error debug message.
handle boolean Set to true to acknowledge receipt. Return false if you want Win20X to retry the webhook.
money number Required. The player's exact new balance in decimal/double format AFTER the callback updates are applied.

Example Round with Two Callbacks

Here is a walkthrough of how player balance calculates across multiple sequential callbacks for a single round:

Callback Event Type Bet Amount Win Amount Calculation Formula Returned Balance (money)
#1 Player places bet of ৳600 600.00 0.00 Starting 1000.00 - 600.00 + 0.00 = 400.00 400.00
#2 Round resolves with ৳800 win 0.00 800.00 Previous 400.00 - 0.00 + 800.00 = 1200.00 1200.00

Error Handling & Retries

The Win20X gateway uses standard HTTP status codes to communicate request results. Your integration must properly handle these codes:

HTTP Code Status Meaning Recommended Action
400 Bad Request Missing or malformed request parameters. Validate all required body and query parameters before dispatch.
401 Unauthorized API credentials (key or secret) are missing or invalid. Check your request headers and verify API credentials in your B2B Client Panel.
403 Forbidden Originating IP address is not whitelisted, or security deposit is exhausted. Whitelist your server IP in the B2B dashboard and check your billing balances.
404 Not Found The endpoint path or game ID does not exist. Verify target URL routes and query parameters.
500 / 502 / 503 Server Error Win20X or downstream provider temporary issue. Implement retry logic using Exponential Backoff with Jitter.

Warning: Always implement retry logic with exponential backoff delays (e.g. 1s, 2s, 4s, 8s) for all 5xx connection issues. Do not hammer failing servers with immediate requests.

Best Practices

Caching Guidelines

  • Cache game catalogues: Cache results of /getallproviders and /getallgamesandprovider for up to 24 hours to reduce backend latency.
  • Do not cache launcher URLs: Game session URLs expire within 60 seconds. Always request a fresh URL dynamically when a player clicks "Play".

Callback Reliability

  • 5-Second Webhook Deadline: Your webhook callback endpoint must respond within 5 seconds. If a webhook hangs, our BullMQ worker will time out and mark it as a retry.
  • Offload heavy processing: Perform slow database jobs (such as sending emails, alerts, or analytics logs) asynchronously. Return HTTP 200 first.

Logging & Auditing

  • Log all operations: Store complete records of all outbound API requests and inbound callback payloads for at least 90 days. This is mandatory for transaction disputes.

Security Guidelines

API Key Protection

Your API Secret is highly sensitive. Keep it safe by adhering to the following regulations:

  • Never store API keys/secrets in client-side code, frontend templates, or public Git repositories.
  • Use secure environment variables (`.env`) or database secrets managers.

Callback Security & Validation

  • Validate the api_key parameter of every incoming callback against your configured key before processing.
  • Always enforce strict database-level unique constraints on the serial_number column to prevent double-payout exploits.
  • Reject invalid or unauthenticated webhooks with a success: false response body and HTTP 200 status code so that the gateway retries. Do not return 4xx/5xx codes as they will not stop retries.

Transport Security & Input Sanitization

  • Enforce HTTPS with TLS 1.2 or higher for all callback endpoints.
  • Sanitize all webhook request inputs and use parameterized SQL queries to prevent SQL Injection vulnerabilities.

Support & Contact

Need help with your integration? Get in touch with our engineering team via the following channels:

Channel Details
Website https://win20x.com
Telegram Support @win20x_support
Email Support support@win20x.com