PHPackages                             alissonlinneker/xgate-php-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. alissonlinneker/xgate-php-sdk

ActiveLibrary[API Development](/categories/api)

alissonlinneker/xgate-php-sdk
=============================

SDK PHP para integração com XGate Global API - Pagamentos, crypto e PIX

1.0.0(7mo ago)01Apache-2.0PHPPHP ^8.4CI failing

Since Sep 20Pushed 7mo agoCompare

[ Source](https://github.com/alissonlinneker/xgate-php-sdk)[ Packagist](https://packagist.org/packages/alissonlinneker/xgate-php-sdk)[ Docs](https://github.com/alissonlinneker/xgate-php-sdk)[ RSS](/packages/alissonlinneker-xgate-php-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (13)Versions (2)Used By (0)

XGate PHP SDK
=============

[](#xgate-php-sdk)

[![PHP Version](https://camo.githubusercontent.com/648ed134b95002a2a446ace9fa4ba020ed5bf9900d5d489832d911833f6d5212/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e342d3838393242462e737667)](https://php.net)[![License](https://camo.githubusercontent.com/b29de0acdfd19013f1f02689b15c933e4a6c145be9efa718288f88ba3280b1c5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d417061636865253230322e302d626c75652e737667)](LICENSE)[![Build Status](https://github.com/alissonlinneker/xgate-php-sdk/workflows/CI/badge.svg)](https://github.com/alissonlinneker/xgate-php-sdk/actions)

SDK PHP para integração com a API da XGate Global. Suporte completo para operações financeiras, criptomoedas e PIX.

Pré-requisitos
--------------

[](#pré-requisitos)

- PHP 8.4+
- Composer
- Extensões: curl, json, mbstring, bcmath

Instalação
----------

[](#instalação)

```
composer require alissonlinneker/xgate-php-sdk
```

Ou adicione no seu `composer.json`:

```
{
    "require": {
        "alissonlinneker/xgate-php-sdk": "^1.0"
    }
}
```

Como usar
---------

[](#como-usar)

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

// Configuração básica
$config = new Configuration([
    'email' => 'seu-email@exemplo.com',
    '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);
```

Exemplos práticos
-----------------

[](#exemplos-práticos)

### Operações com Crypto

[](#operações-com-crypto)

```
// 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";
```

### Operações PIX

[](#operações-pix)

```
// 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";
```

### Tratamento de erros

[](#tratamento-de-erros)

```
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()
    ));
}
```

### Paginação

[](#paginação)

```
// 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);
}
```

### Logging

[](#logging)

```
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);
```

### Custom HTTP Client

[](#custom-http-client)

```
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' => 'your-email@example.com',
    'password' => 'your-password',
    'http_client' => $httpClient
]);

$client = new Client($config);
```

### Rate Limiting

[](#rate-limiting)

```
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";
```

### Money Formatting

[](#money-formatting)

```
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";
```

### Validation

[](#validation)

```
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();
}
```

Configuration Options
---------------------

[](#configuration-options)

OptionTypeDefaultDescriptionemailstringrequiredAuthentication emailpasswordstringrequiredAuthentication passwordbase\_urlstringAPI base URLtimeoutint30Request timeout in secondsretry\_attemptsint3Number of retry attemptscache\_ttlint3600Token cache TTL in secondsverify\_sslbooltrueSSL certificate verificationdebugboolfalseEnable debug modehttp\_clientClientInterfacenullCustom HTTP clientEnvironment Variables
---------------------

[](#environment-variables)

You can use environment variables for configuration. Copy `.env.example` to `.env`:

```
cp .env.example .env
```

Then load configuration from environment:

```
$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'
]);
```

Testing
-------

[](#testing)

Run tests:

```
composer test
```

Run tests with coverage:

```
composer test:coverage
```

Run specific test suite:

```
vendor/bin/phpunit --testsuite unit
vendor/bin/phpunit --testsuite integration
```

Code Quality
------------

[](#code-quality)

Check code style:

```
composer cs:check
```

Fix code style:

```
composer cs:fix
```

Run static analysis:

```
composer phpstan
```

Run all CI checks:

```
composer ci
```

Recursos do PHP 8.4
-------------------

[](#recursos-do-php-84)

O SDK usa os recursos mais recentes do PHP 8.4:

- **Property hooks** - Validação automática de propriedades
- **Asymmetric visibility** - Propriedades read-only públicas
- **BcMath\\Number** - Cálculos financeiros precisos
- **array\_find()** e **array\_all()** - Novas funções de array

```
// 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
```

Serviços disponíveis
--------------------

[](#serviços-disponíveis)

- **Autenticação** - Login, refresh token, logout
- **Depósitos** - Criar, listar, cancelar, calcular taxas
- **Saques** - Fiat e crypto, múltiplas redes blockchain
- **Crypto** - Wallets, conversões, preços em tempo real
- **PIX** - QR Code, chaves PIX, transferências

Contribuindo
------------

[](#contribuindo)

Contribuições são bem-vindas! Por favor, abra uma issue primeiro para discutir mudanças maiores.

```
# Fork o projeto
git clone https://github.com/alissonlinneker/xgate-php-sdk.git
cd xgate-php-sdk

# Instalar dependências
composer install

# Rodar testes
composer test

# Verificar código
composer cs:check
composer phpstan
```

Problemas?
----------

[](#problemas)

Encontrou algum bug? Abra uma [issue](https://github.com/alissonlinneker/xgate-php-sdk/issues).

Autor
-----

[](#autor)

**Alisson Linneker**

- GitHub: [@alissonlinneker](https://github.com/alissonlinneker)

Licença
-------

[](#licença)

Apache 2.0 - veja o arquivo [LICENSE](LICENSE) para mais detalhes.

---

Desenvolvido com PHP 8.4 e muita ☕

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance63

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

233d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/bf684c6123d5bc0aaf004c9f8178e94bc663f2a537a46610193b8eb016951516?d=identicon)[alissonlinneker](/maintainers/alissonlinneker)

---

Top Contributors

[![alissonlinneker](https://avatars.githubusercontent.com/u/1760923?v=4)](https://github.com/alissonlinneker "alissonlinneker (6 commits)")

---

Tags

apisdkpaymentsbitcoincryptocurrencybrazilethereumpixxgate

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/alissonlinneker-xgate-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/alissonlinneker-xgate-php-sdk/health.svg)](https://phpackages.com/packages/alissonlinneker-xgate-php-sdk)
```

###  Alternatives

[kreait/firebase-php

Firebase Admin SDK

2.4k39.7M72](/packages/kreait-firebase-php)[tempest/framework

The PHP framework that gets out of your way.

2.1k23.1k9](/packages/tempest-framework)[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.5k311.5k5](/packages/theodo-group-llphant)[coinpaymentsnet/coinpayments-php

A PHP wrapper for the CoinPayments.net v1 API.

55126.2k](/packages/coinpaymentsnet-coinpayments-php)[bushlanov-dev/max-bot-api-client-php

Max Bot API Client library

281.6k](/packages/bushlanov-dev-max-bot-api-client-php)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
