FourPlay

Examples

Exemplos completos de integração em cURL, Node.js, PHP, Python e C#

Fluxo Completo de Integração

Os exemplos abaixo demonstram o fluxo completo: autenticar → criar sessão → redirecionar jogador.


cURL

cURL — Fluxo completo
# 1. Obter token
TOKEN=$(curl -s -X POST https://api.fourplay.studio/v1/auth/token \
  -H "Content-Type: application/json" \
  -d '{"client_id":"op_abc123","client_secret":"sk_live_xxx","grant_type":"client_credentials"}' \
  | jq -r '.access_token')

# 2. Criar sessão
curl -X POST https://api.fourplay.studio/v1/sessions \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "player_id": "player_123",
    "game_id": "mines-classic",
    "currency": "BRL",
    "balance": 10000
  }'

Node.js

Node.js (fetch nativo)
const API_URL = 'https://api.fourplay.studio/v1';

class FourPlayClient {
  #token = null;
  #expiresAt = 0;

  constructor(clientId, clientSecret) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
  }

  async #getToken() {
    if (Date.now() < this.#expiresAt - 60_000) return this.#token;
    const res = await fetch(`${API_URL}/auth/token`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        client_id: this.clientId,
        client_secret: this.clientSecret,
        grant_type: 'client_credentials',
      }),
    });
    if (!res.ok) throw new Error(`Auth failed: ${res.status}`);
    const { access_token, expires_in } = await res.json();
    this.#token = access_token;
    this.#expiresAt = Date.now() + expires_in * 1000;
    return this.#token;
  }

  async createSession({ playerId, gameId, currency, balance }) {
    const token = await this.#getToken();
    const res = await fetch(`${API_URL}/sessions`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        player_id: playerId,
        game_id: gameId,
        currency,
        balance,
      }),
    });
    if (!res.ok) throw new Error(`Session error: ${res.status}`);
    return res.json();
  }

  async getBalance(playerId) {
    const token = await this.#getToken();
    const res = await fetch(`${API_URL}/wallet/${playerId}/balance`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    return res.json();
  }
}

// Uso
const client = new FourPlayClient(
  process.env.FOURPLAY_CLIENT_ID,
  process.env.FOURPLAY_CLIENT_SECRET
);

const session = await client.createSession({
  playerId: 'player_123',
  gameId: 'mines-classic',
  currency: 'BRL',
  balance: 10000,
});

console.log('Launch URL:', session.launch_url);

PHP

PHP 8.1+
<?php

class FourPlayClient
{
    private ?string $token = null;
    private int $expiresAt = 0;

    public function __construct(
        private string $clientId,
        private string $clientSecret,
        private string $apiUrl = 'https://api.fourplay.studio/v1'
    ) {}

    private function getToken(): string
    {
        if ($this->token && time() < $this->expiresAt - 60) {
            return $this->token;
        }

        $ch = curl_init("{$this->apiUrl}/auth/token");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode([
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret,
                'grant_type' => 'client_credentials',
            ]),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        ]);

        $response = json_decode(curl_exec($ch), true);
        curl_close($ch);

        $this->token = $response['access_token'];
        $this->expiresAt = time() + $response['expires_in'];
        return $this->token;
    }

    public function createSession(array $data): array
    {
        $token = $this->getToken();
        $ch = curl_init("{$this->apiUrl}/sessions");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer {$token}",
                'Content-Type: application/json',
            ],
        ]);
        $result = json_decode(curl_exec($ch), true);
        curl_close($ch);
        return $result;
    }
}

// Uso
$client = new FourPlayClient(
    clientId: $_ENV['FOURPLAY_CLIENT_ID'],
    clientSecret: $_ENV['FOURPLAY_CLIENT_SECRET']
);

$session = $client->createSession([
    'player_id' => 'player_123',
    'game_id'   => 'mines-classic',
    'currency'  => 'BRL',
    'balance'   => 10000,
]);

header("Location: {$session['launch_url']}");

Python

Python 3.10+ (httpx)
import os
import time
import httpx

class FourPlayClient:
    API_URL = "https://api.fourplay.studio/v1"

    def __init__(self, client_id: str, client_secret: str):
        self.client_id = client_id
        self.client_secret = client_secret
        self._token: str | None = None
        self._expires_at: float = 0

    def _get_token(self) -> str:
        if self._token and time.time() < self._expires_at - 60:
            return self._token
        res = httpx.post(f"{self.API_URL}/auth/token", json={
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "grant_type": "client_credentials",
        })
        res.raise_for_status()
        data = res.json()
        self._token = data["access_token"]
        self._expires_at = time.time() + data["expires_in"]
        return self._token

    def create_session(self, player_id: str, game_id: str,
                       currency: str, balance: int) -> dict:
        token = self._get_token()
        res = httpx.post(f"{self.API_URL}/sessions",
            headers={"Authorization": f"Bearer {token}"},
            json={"player_id": player_id, "game_id": game_id,
                  "currency": currency, "balance": balance})
        res.raise_for_status()
        return res.json()

# Uso
client = FourPlayClient(
    os.environ["FOURPLAY_CLIENT_ID"],
    os.environ["FOURPLAY_CLIENT_SECRET"],
)

session = client.create_session(
    player_id="player_123",
    game_id="mines-classic",
    currency="BRL",
    balance=10000,
)
print("Launch URL:", session["launch_url"])

C#

C# (.NET 8)
using System.Net.Http.Json;
using System.Text.Json;

public class FourPlayClient
{
    private readonly HttpClient _http;
    private string? _token;
    private DateTime _expiresAt;

    public FourPlayClient(string clientId, string clientSecret)
    {
        _http = new HttpClient { BaseAddress = new Uri("https://api.fourplay.studio/v1/") };
        ClientId = clientId;
        ClientSecret = clientSecret;
    }

    private string ClientId { get; }
    private string ClientSecret { get; }

    private async Task<string> GetTokenAsync()
    {
        if (_token is not null && DateTime.UtcNow < _expiresAt.AddSeconds(-60))
            return _token;

        var res = await _http.PostAsJsonAsync("auth/token", new
        {
            client_id = ClientId,
            client_secret = ClientSecret,
            grant_type = "client_credentials",
        });
        res.EnsureSuccessStatusCode();

        var data = await res.Content.ReadFromJsonAsync<JsonElement>();
        _token = data.GetProperty("access_token").GetString()!;
        _expiresAt = DateTime.UtcNow.AddSeconds(data.GetProperty("expires_in").GetInt32());
        return _token;
    }

    public async Task<JsonElement> CreateSessionAsync(
        string playerId, string gameId, string currency, int balance)
    {
        var token = await GetTokenAsync();
        _http.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        var res = await _http.PostAsJsonAsync("sessions", new
        {
            player_id = playerId,
            game_id = gameId,
            currency,
            balance,
        });
        res.EnsureSuccessStatusCode();
        return await res.Content.ReadFromJsonAsync<JsonElement>();
    }
}

// Uso
var client = new FourPlayClient(
    Environment.GetEnvironmentVariable("FOURPLAY_CLIENT_ID")!,
    Environment.GetEnvironmentVariable("FOURPLAY_CLIENT_SECRET")!
);

var session = await client.CreateSessionAsync("player_123", "mines-classic", "BRL", 10000);
Console.WriteLine($"Launch URL: {session.GetProperty("launch_url").GetString()}");

On this page