דלגו לתוכן

דוגמאות קוד

נקודת ארנק שלמה שאפשר להריץ, וקריאת השקה בשלוש שפות.

בעמוד זה

נקודת ארנק (Node.js, PostgreSQL)#

בדיקת חתימה ולוגיקת ארנק בקובץ אחד, לכל הספקים. הדוגמה הורצה מול קוד הקולבקים של AGIXX לכל משפחות הספקים, כפילויות מקבילות ו-6 בדיקות הולידטור. התאימו את האחסון למסד הנתונים שלכם ושמרו על הכללים.

  • עסקת מסד נתונים אחת עם נעילת שורה לכל שחקן.
  • אידמפוטנטיות לפי provider + action + transactionId (או refTransactionId).
  • rollback לפי refTransactionId, לפי rollback_transactions או לפי סיבוב; פעם אחת בלבד.
  • ספינים חינם לא מחויבים; מקור חסר לא מוחזר.
  • יתרה אחת לשחקן, בסנטים. אם לשחקן יכולים להיות כמה מטבעות, נהלו ארנק לפי מטבע הסשן שהושק.
schema.sqlSQL
-- PostgreSQL. Money is stored in minor units (cents).
CREATE TABLE players (
  id      text PRIMARY KEY,        -- the playerId you send to /api/v1/launch
  balance bigint NOT NULL
);

CREATE TABLE wallet_tx (
  tx_key    text PRIMARY KEY,      -- provider|action|transactionId  (idempotency)
  player_id text NOT NULL REFERENCES players(id),
  provider  text NOT NULL,
  action    text NOT NULL,         -- bet | win | betwin | rollback
  tx_id     text,
  round_id  text,
  stake     bigint NOT NULL DEFAULT 0,  -- bet amount as sent
  bet       bigint NOT NULL DEFAULT 0,  -- what was really debited (0 = free spin)
  win       bigint NOT NULL DEFAULT 0,  -- what was really credited
  refs      text[] NOT NULL DEFAULT '{}', -- rollback: transactions it cancels
  reversed  boolean NOT NULL DEFAULT false,
  response  jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON wallet_tx (player_id, provider, tx_id);
CREATE INDEX ON wallet_tx (player_id, provider, round_id);
wallet.jsJavaScript
// wallet.js - Node.js 18+, npm install express pg
const crypto = require('crypto');
const express = require('express');
const { Pool } = require('pg');

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

// Key id (first 16 characters of the API key) -> that key's secret. List the old and the
// new key while you rotate:  AGIXX_KEYS="pk_test_1a2b3c4d=secret1,pk_live_9f8e7d6c=secret2"
const SECRETS = new Map((process.env.AGIXX_KEYS || '').split(',').filter(Boolean)
  .map((pair) => pair.trim().split('=')));

// ---- 1. Signature -----------------------------------------------------------
function verified(req) {
  const ts = req.get('X-AGIXX-Timestamp') || '';
  const sig = Buffer.from(req.get('X-AGIXX-Signature') || '');
  const secret = SECRETS.get(req.get('X-AGIXX-Key-Id') || '');
  if (!secret || !Buffer.isBuffer(req.body)) return false;
  if (!/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const expected = Buffer.from('sha256=' + crypto.createHmac('sha256', secret)
    .update(ts + '.').update(req.body).digest('hex'));
  return sig.length === expected.length && crypto.timingSafeEqual(sig, expected);
}

// Providers whose free spins (POST /api/v1/freespins) are funded by the provider.
const FREE_SPIN_PROVIDERS = ['GAME_AGGREGATOR', 'SOFTGAMING'];

// ---- 2. Helpers -------------------------------------------------------------
const str = (v) => (v === undefined || v === null || v === '' ? null : String(v));

// Amounts are decimal strings. amount is negative on some bets, so take the absolute value.
function cents(v) {
  const n = Math.round(Math.abs(Number(v ?? 0)) * 100);
  if (!Number.isSafeInteger(n)) throw new Error('Invalid amount: ' + v);
  return n;
}

const rejected = (code, message, balance) =>
  ({ code, message, ...(balance === undefined ? {} : { balance: balance / 100 }) });

// ---- 3. Wallet --------------------------------------------------------------
async function handle(db, e) {
  const action = e.action === 'refund' ? 'rollback' : e.action; // refund = Validator only
  const provider = String(e.provider);
  const playerId = str(e.playerId ?? e._originalPlayerId);      // the Validator sends the old names
  const txId = str(e.transactionId ?? e.transaction_id);
  const roundId = str(e.roundId ?? e.round_id);
  const refId = str(e.refTransactionId);

  if (provider === 'VALIDATION' && playerId.startsWith('val_')) {
    await db.query('INSERT INTO players VALUES ($1, 100000) ON CONFLICT DO NOTHING', [playerId]);
  }

  // Locks this player: parallel and repeated callbacks run one after the other.
  const { rows: [player] } = await db.query('SELECT balance FROM players WHERE id = $1 FOR UPDATE', [playerId]);
  if (!player) {
    // Never reject a win / rollback: it would be final. An error (HTTP 500) is sent again.
    if (action === 'win' || action === 'rollback') throw new Error('Unknown player ' + playerId);
    return { code: 2, error_code: 'PLAYER_NOT_FOUND', message: 'Player not found' };
  }
  const balance = Number(player.balance);

  if (!['bet', 'win', 'betwin', 'rollback'].includes(action)) { // balance, auth, anything new
    return { code: 0, balance: balance / 100 };
  }

  // ---- Idempotency: provider + action + transactionId (rollback may carry only refTransactionId)
  const id = txId ?? (action === 'rollback' && refId ? 'ref:' + refId : null);
  if (!id) throw new Error('Money callback without a transaction id');
  const txKey = [provider, action, id].join('|');
  const { rows: [seen] } = await db.query('SELECT reversed, response FROM wallet_tx WHERE tx_key = $1', [txKey]);
  if (seen && action !== 'win' && action !== 'rollback' && seen.reversed) {
    return rejected(1, 'Bet was already rolled back', balance);
  }
  if (seen) return seen.response; // same reply as the first time, nothing moves

  let stake = 0, bet = 0, win = 0, delta = 0, refs = [];

  if (action === 'bet' || action === 'betwin') {
    // A rollback that overtook its bet: do not accept the bet afterwards.
    const { rows: [early] } = await db.query(
      "SELECT 1 FROM wallet_tx WHERE player_id = $1 AND provider = $2 AND action = 'rollback' AND $3 = ANY(refs)",
      [playerId, provider, txId]);
    if (early) return rejected(1, 'Bet was already rolled back', balance);

    stake = cents(e.bet ?? (action === 'bet' ? e.amount : 0));
    const isFreeSpin = FREE_SPIN_PROVIDERS.includes(provider) && str(e.freespinId) !== null;
    bet = isFreeSpin ? 0 : stake;                                // free spins: never debit
    win = action === 'betwin' ? cents(e.win) : 0;
    if (bet > balance) return rejected(1, 'Insufficient funds', balance);
    delta = win - bet;
  }

  if (action === 'win') {
    win = cents(e.win ?? e.amount);
    delta = win;
  }

  if (action === 'rollback') {
    const list = Object.values(e.rollback_transactions || {}).map((t) => str(t && t.transaction_id)).filter(Boolean);
    refs = list.length ? list : [refId ?? txId].filter(Boolean);
    const originals = await findOriginals(db, { playerId, provider, roundId, refs, isList: list.length > 0, refId, e });
    for (const o of originals) {
      // Each transaction is reversed once. A betwin gives back the bet and keeps the win;
      // a win is taken back only when rollback_transactions lists it.
      delta += o.action === 'win' ? -Number(o.win) : Number(o.bet);
      await db.query('UPDATE wallet_tx SET reversed = true WHERE tx_key = $1', [o.tx_key]);
    }
    // No original found: it never reached this wallet, so nothing changes (code 0).
  }

  const response = { code: 0, balance: (balance + delta) / 100, transaction_id: id };
  await db.query('UPDATE players SET balance = balance + $2 WHERE id = $1', [playerId, delta]);
  await db.query(
    'INSERT INTO wallet_tx (tx_key, player_id, provider, action, tx_id, round_id, stake, bet, win, refs, response) ' +
    'VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)',
    [txKey, playerId, provider, action, txId, roundId, stake, bet, win, refs, response]);
  return response;
}

// Which not-yet-reversed transactions does this rollback cancel?
async function findOriginals(db, { playerId, provider, roundId, refs, isList, refId, e }) {
  const open = 'SELECT * FROM wallet_tx WHERE player_id = $1 AND provider = $2 AND NOT reversed AND action = ANY($3) AND ';
  const bets = ['bet', 'betwin'];

  // a) rollback_transactions (GAME_AGGREGATOR): an array of bets and wins to reverse
  if (isList) return (await db.query(open + 'tx_id = ANY($4)', [playerId, provider, ['bet', 'win'], refs])).rows;

  // b) refTransactionId, or a rollback that reuses the transactionId of its bet
  const byId = (await db.query(open + 'tx_id = ANY($4)', [playerId, provider, bets, refs])).rows;
  if (byId.length || refId) return byId;

  // c) no reference at all (ALGNET, some SOFTGAMING, the Validator): the bet of this round
  if (!roundId) return [];
  const { rows } = await db.query(open + 'round_id = $4', [playerId, provider, bets, roundId]);
  const amount = e.bet ?? e.amount;
  const hasAmount = amount !== undefined && amount !== null;
  const match = rows.find((r) => (hasAmount ? Number(r.stake) === cents(amount) : rows.length === 1));
  if (match) return [match];
  if (rows.length) throw new Error('Rollback does not match any bet of round ' + roundId); // needs a human
  return [];
}

// ---- 4. HTTP ----------------------------------------------------------------
const app = express();

// express.raw keeps the exact signed bytes. Register this route BEFORE any app.use(express.json()).
app.post('/wallet', express.raw({ type: '*/*', limit: '2mb' }), async (req, res) => {
  if (!verified(req)) return res.status(401).json({ message: 'Invalid signature' });
  let db;
  try {
    db = await pool.connect();
    await db.query('BEGIN');                                     // check + move + store: one transaction
    const reply = await handle(db, JSON.parse(req.body.toString('utf8')));
    await db.query('COMMIT');
    res.json(reply);                                             // always HTTP 200, also for code 1 / 2
  } catch (err) {
    if (db) await db.query('ROLLBACK').catch(() => {});
    console.error('[wallet]', err);                              // alert on this
    res.status(500).json({ message: 'Temporary error' });        // nothing was saved
  } finally {
    if (db) db.release();
  }
});

app.listen(process.env.PORT || 3000);

השקת משחק#

בצד השרת בלבד. אותה קריאה עובדת לכל ספק: שנו את provider ואת gameId.

// launch.js - Node.js 18+, npm install express
// Server side only: the API key must never reach the browser.
const express = require('express');
const app = express();
app.set('trust proxy', 1); // so req.ip is the player's address behind your proxy

app.get('/play/:gameId', async (req, res) => {
  try {
    const r = await fetch('https://api.tagbet.net/api/v1/launch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'x-api-key': process.env.AGIXX_API_KEY },
      body: JSON.stringify({
        provider: 'PRAGMATIC_PLAY',          // a key from GET /api/v1/providers
        gameId: req.params.gameId,           // for example "2376", always a string
        playerId: 'player_123',              // take it from your own session
        currency: 'TRY',
        language: 'tr',
        playerIp: req.ip,                    // the player's real public IP
        returnUrl: 'https://your-casino.com/lobby'
      })
    });
    const body = await r.json();
    if (!r.ok) throw new Error(body.canonical?.errorCode + ': ' + body.message);
    res.redirect(body.gameUrl);
  } catch (err) {
    console.error('[launch]', err.message);
    res.status(502).send('The game could not be opened');
  }
});

app.listen(process.env.PORT || 3000);
שאלות על האינטגרציה?כתבו לנו עם שם החשבון, ואם יש גם sessionId או transactionId. integration@agixx.net
דוגמאות קוד - תיעוד API | AGIXX