Integration Code Samples

Production-ready code examples for integrating SafeBet IQ into your casino platform

Setup & Configuration

Install dependencies and configure the client

Install Dependencies

npm install axios dotenv

Environment Variables (.env)

SAFEPLAY_API_KEY=sk_prod_your_api_key_here
SAFEPLAY_BASE_URL=https://api.safeplay.ai/v1

SafePlay Client Class

Reusable client for all API operations

import axios, { AxiosInstance } from 'axios';

class SafePlayClient {
  private client: AxiosInstance;

  constructor(apiKey: string, baseURL: string = 'https://api.safeplay.ai/v1') {
    this.client = axios.create({
      baseURL,
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      timeout: 10000,
    });
  }

  async syncPlayer(playerData: {
    player_id: string;
    session_id?: string;
    timestamp?: string;
    game_type: string;
    bet_amount: number;
    win_amount?: number;
    session_duration_minutes: number;
    total_wagered: number;
    total_wins?: number;
    total_losses?: number;
    bet_frequency?: number;
    player_metadata?: {
      email?: string;
      phone?: string;
      join_date?: string;
    };
  }) {
    try {
      const response = await this.client.post('/players/sync', playerData);
      return response.data;
    } catch (error) {
      console.error('SafePlay API Error:', error);
      throw error;
    }
  }

  async batchSyncPlayers(players: any[]) {
    try {
      const response = await this.client.post('/players/batch-sync', { players });
      return response.data;
    } catch (error) {
      console.error('SafePlay Batch Sync Error:', error);
      throw error;
    }
  }

  async getPlayerRisk(playerId: string) {
    try {
      const response = await this.client.get(`/players/${playerId}/risk`);
      return response.data;
    } catch (error) {
      console.error('SafePlay Get Risk Error:', error);
      throw error;
    }
  }
}

export default SafePlayClient;

Real-Time Integration Example

Send player data after each bet is placed

import SafePlayClient from './SafePlayClient';

const safeplay = new SafePlayClient(process.env.SAFEPLAY_API_KEY!);

// Call this function after a player places a bet
async function onBetPlaced(bet: {
  playerId: string;
  gameType: string;
  betAmount: number;
  winAmount: number;
}) {
  // Get current session data for the player
  const session = await getPlayerSession(bet.playerId);

  try {
    const result = await safeplay.syncPlayer({
      player_id: bet.playerId,
      session_id: session.id,
      timestamp: new Date().toISOString(),
      game_type: bet.gameType,
      bet_amount: bet.betAmount,
      win_amount: bet.winAmount,
      session_duration_minutes: session.durationMinutes,
      total_wagered: session.totalWagered + bet.betAmount,
      total_wins: session.totalWins + (bet.winAmount || 0),
      total_losses: session.totalLosses + (bet.winAmount ? 0 : bet.betAmount),
      bet_frequency: session.betCount / session.durationMinutes,
      player_metadata: {
        email: session.player.email,
        phone: session.player.phone,
        join_date: session.player.joinDate,
      }
    });

    // Check if intervention is needed
    if (result.intervention?.required) {
      await handleIntervention(bet.playerId, result);
    }

    // Log risk score for monitoring
    console.log(`Player ${bet.playerId} risk score: ${result.risk_score}`);

    return result;
  } catch (error) {
    console.error('Failed to sync player risk:', error);
    // Continue game operation even if risk check fails
    return null;
  }
}

async function handleIntervention(playerId: string, riskData: any) {
  // Trigger intervention based on recommended channels
  const channels = riskData.intervention.channels || ['email'];

  if (channels.includes('whatsapp')) {
    await sendWhatsAppIntervention(playerId, riskData);
  }

  if (channels.includes('email')) {
    await sendEmailIntervention(playerId, riskData);
  }

  // Log intervention for compliance
  await logIntervention({
    player_id: playerId,
    risk_score: riskData.risk_score,
    risk_level: riskData.risk_level,
    triggers: riskData.triggers,
    channels: channels,
    timestamp: new Date().toISOString(),
  });
}

Webhook Handler

Receive real-time notifications from SafePlay

import { Request, Response } from 'express';
import crypto from 'crypto';

function verifyWebhookSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const hmac = crypto.createHmac('sha256', secret);
  const digest = hmac.update(payload).digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(digest)
  );
}

// Express route handler
export async function handleSafePlayWebhook(req: Request, res: Response) {
  const signature = req.headers['x-safeplay-signature'] as string;
  const payload = JSON.stringify(req.body);

  // Verify webhook signature
  const isValid = verifyWebhookSignature(
    payload,
    signature,
    process.env.SAFEPLAY_WEBHOOK_SECRET!
  );

  if (!isValid) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  const event = req.body;

  switch (event.event_type) {
    case 'risk_threshold_exceeded':
      await handleRiskThresholdExceeded(event);
      break;

    case 'intervention_triggered':
      await handleInterventionTriggered(event);
      break;

    default:
      console.log('Unknown event type:', event.event_type);
  }

  res.json({ received: true });
}

async function handleRiskThresholdExceeded(event: any) {
  console.log(`HIGH RISK ALERT: Player ${event.player_id}`);
  console.log(`Risk Score: ${event.risk_score}`);
  console.log(`Triggers: ${event.triggers.join(', ')}`);

  // Take immediate action
  if (event.risk_level === 'critical') {
    // Implement cool-off period
    await setCoolOffPeriod(event.player_id, 24); // 24 hours

    // Send emergency intervention
    await sendEmergencyIntervention(event.player_id);

    // Alert compliance team
    await notifyComplianceTeam(event);
  }
}

Need Help with Integration?

Our technical team is available to assist with your integration. Contact us for:

  • Custom integration support
  • Performance optimization guidance
  • Compliance consultation
  • Testing environment access

support@safeplay.ai