PHP code example of alissonlinneker / xgate-php-sdk

1. Go to this page and download the library: Download alissonlinneker/xgate-php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alissonlinneker / xgate-php-sdk example snippets


use XGateGlobal\SDK\Client;
use XGateGlobal\SDK\Configuration;
use BcMath\Number;

// Configuração básica
$config = new Configuration([
    'email' => '[email protected]',
    'password' => 'sua-senha'
]);

$client = new Client($config);

// Login (automático na primeira requisição)
$client->auth->login();

// Listar moedas disponíveis
$currencies = $client->deposits->getCurrencies();
foreach ($currencies as $currency) {
    echo "{$currency->symbol}: {$currency->name}\n";
}

// Criar depósito
$transaction = $client->deposits->create(
    new Number('100.50'),
    'customer_123',
    'USD'
);

printf("Transação criada: %s\n", $transaction->id);

// Pegar carteira do cliente
$wallet = $client->crypto->getWallet('customer_123');

// Listar redes blockchain disponíveis
$networks = $client->withdrawals->getBlockchainNetworks();

// Saque em crypto
$withdrawal = $client->crypto->withdraw(
    amount: new Number('0.5'),
    wallet: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb4',
    customerId: 'customer_123',
    cryptocurrency: 'USDT',
    network: 'BSC'
);

// Consultar preços
$prices = $client->crypto->getPrices(['BTC', 'ETH', 'USDT'], 'USD');
foreach ($prices as $symbol => $price) {
    echo "$symbol: $$price\n";
}

// Converter crypto para fiat
$conversion = $client->crypto->convertToFiat(
    new Number('0.5'),
    'BTC',
    'USD'
);
echo "0.5 BTC = ${$conversion['to_amount']} USD\n";

// Consultar chaves PIX do cliente
$pixKeys = $client->pix->getKeys('customer_123');

// Cadastrar nova chave PIX
$key = $client->pix->registerKey(
    'customer_123',
    '12345678900',
    'cpf'
);

// Fazer saque via PIX
$withdrawal = $client->withdrawals->create(
    amount: new Number('500.00'),
    customerId: 'customer_123',
    currency: 'BRL',
    pixKey: '12345678900'
);

// Gerar QR Code PIX
$qrCode = $client->pix->generateQRCode(
    new Number('100.00'),
    'Pagamento pedido #123'
);

echo "QR Code: " . $qrCode['qrcode'] . "\n";

use XGateGlobal\SDK\Exceptions\{
    AuthenticationException,
    ValidationException,
    RateLimitException,
    ApiException
};

try {
    $transaction = $client->deposits->create(
        new Number('100.00'),
        'customer_123',
        'USD'
    );
} catch (AuthenticationException $e) {
    error_log('Falha na autenticação: ' . $e->getMessage());
    // Tentar renovar token...
} catch (ValidationException $e) {
    echo "Dados inválidos: " . $e->getMessage() . "\n";

    if ($e->hasFieldError('amount')) {
        echo "Erro no campo amount: " . $e->getFieldError('amount') . "\n";
    }
} catch (RateLimitException $e) {
    $retry = $e->getRetryAfter();
    echo "Limite de requisições excedido. Aguarde $retry segundos.\n";
    sleep($retry);
    // Tentar novamente...
} catch (ApiException $e) {
    error_log(sprintf(
        "Erro na API: %s (Código: %s)",
        $e->getMessage(),
        $e->getErrorCode()
    ));
}

// Listar depósitos com paginação
$result = $client->deposits->list(
    filters: ['status' => 'completed'],
    page: 1,
    perPage: 20
);

foreach ($result['items'] as $transaction) {
    echo "{$transaction->id}: R$ {$transaction->amount}\n";
}

// Próxima página
if ($result['pagination']['has_more']) {
    $nextPage = $client->deposits->list([], 2, 20);
}

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('xgate');
$logger->pushHandler(new StreamHandler('path/to/xgate.log', Logger::DEBUG));

$client = new Client($config, $logger);

use GuzzleHttp\Client as GuzzleClient;

$httpClient = new GuzzleClient([
    'proxy' => 'tcp://localhost:8080',
    'verify' => false, // For development only
    'headers' => [
        'X-Custom-Header' => 'value'
    ]
]);

$config = new Configuration([
    'email' => '[email protected]',
    'password' => 'your-password',
    'http_client' => $httpClient
]);

$client = new Client($config);

use XGateGlobal\SDK\Utils\RateLimiter;

// Create a rate limiter (60 requests per 60 seconds)
$rateLimiter = new RateLimiter(60, 60);

// Check if request is allowed
try {
    $rateLimiter->allow('api_key_123');

    // Make API request
    $transaction = $client->deposits->create(
        new Number('100.00'),
        'customer_123',
        'USD'
    );
} catch (RateLimitException $e) {
    echo "Rate limit exceeded. Wait {$e->getRetryAfter()} seconds\n";
}

// Get rate limit info
$info = $rateLimiter->getInfo('api_key_123');
echo "Remaining requests: {$info['remaining']}\n";
echo "Reset at: " . date('H:i:s', $info['reset_at']) . "\n";

use XGateGlobal\SDK\Utils\MoneyFormatter;
use BcMath\Number;

$formatter = new MoneyFormatter('en_US', 'USD');

// Format currency
echo $formatter->format(new Number('1234.56')); // $1,234.56

// Format crypto
echo $formatter->formatCrypto(new Number('0.00000123'), 'BTC'); // 0.00000123 BTC

// Calculate fees
$result = $formatter->calculateFee(
    new Number('100.00'),
    new Number('2.5'), // 2.5%
    true // is percentage
);

echo "Amount: " . $formatter->format($result['amount']) . "\n";
echo "Fee: " . $formatter->format($result['fee']) . "\n";
echo "Total: " . $formatter->format($result['total']) . "\n";

use XGateGlobal\SDK\Utils\Validator;

// Validate CPF (Brazilian document)
try {
    Validator::validateCPF('123.456.789-00');
} catch (ValidationException $e) {
    echo "Invalid CPF: " . $e->getMessage();
}

// Validate crypto address
try {
    Validator::validateCryptoAddress(
        '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb4',
        'ETH'
    );
} catch (ValidationException $e) {
    echo "Invalid address: " . $e->getMessage();
}

// Validate amount
try {
    Validator::validateAmount('100.50', 10, 1000);
} catch (ValidationException $e) {
    echo "Invalid amount: " . $e->getMessage();
}

$config = new Configuration([
    'email' => $_ENV['XGATE_EMAIL'],
    'password' => $_ENV['XGATE_PASSWORD'],
    'base_url' => $_ENV['XGATE_BASE_URL'] ?? 'https://api.xgateglobal.com',
    'debug' => $_ENV['XGATE_DEBUG'] === 'true'
]);

// Validação automática com property hooks
$currency = new Currency();
$currency->symbol = 'usd'; // Converte automaticamente para 'USD'

// Cálculos precisos com BcMath
$amount = new Number('100.50');
$fee = new Number('2.5');
$total = $amount->add($fee); // 103.00
bash
composer