Utilize as bibliotecas abaixo para integrar rapidamente com a API do gateway. Todas as classes seguem o mesmo padrao: autenticacao via OAuth2, chamadas autenticadas com Bearer token, e tratamento de erros HTTP.
<?php
class GatewayClient
{
private string $baseUrl;
private string $clientId;
private string $clientSecret;
private ?string $accessToken = null;
public function __construct(string $baseUrl, string $clientId, string $clientSecret)
{
$this->baseUrl = rtrim($baseUrl, '/');
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
}
/**
* Autentica com o gateway e obtem o token de acesso.
*/
public function authenticate(): self
{
$ch = curl_init("{$this->baseUrl}/api/v1/oauth/token");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . base64_encode("{$this->clientId}:{$this->clientSecret}"),
'Content-Type: application/json',
],
CURLOPT_RETURNTRANSFER => true,
]);
$response = json_decode(curl_exec($ch), true);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400 || empty($response['access_token'])) {
throw new \Exception("Falha na autenticacao: " . json_encode($response));
}
$this->accessToken = $response['access_token'];
return $this;
}
/**
* Gera um QR Code PIX para recebimento.
*/
public function createPixQrCode(float $amount, array $options = []): array
{
return $this->post('/api/v1/pix/qrcode', array_merge(['amount' => $amount], $options));
}
/**
* Envia um pagamento PIX (saque/transferencia).
*/
public function createPixPayment(float $amount, string $pixKey, string $pixKeyType, array $options = []): array
{
return $this->post('/api/v1/pix/payment', array_merge([
'amount' => $amount,
'pix_key' => $pixKey,
'pix_key_type' => $pixKeyType,
], $options));
}
/**
* Gera um boleto bancario.
*/
public function createBoleto(float $amount, array $payer, array $options = []): array
{
return $this->post('/api/v1/boleto/create', array_merge([
'amount' => $amount,
], $payer, $options));
}
/**
* Realiza cobranca no cartao de credito.
*/
public function createCardCharge(float $amount, string $cardToken, array $options = []): array
{
return $this->post('/api/v1/card/charge', array_merge([
'amount' => $amount,
'card_token' => $cardToken,
], $options));
}
/**
* Consulta o saldo disponivel.
*/
public function getBalance(): array
{
return $this->get('/api/v1/balance');
}
private function post(string $endpoint, array $data): array
{
$ch = curl_init("{$this->baseUrl}{$endpoint}");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer {$this->accessToken}",
'Content-Type: application/json',
'Accept: application/json',
],
CURLOPT_RETURNTRANSFER => true,
]);
$response = json_decode(curl_exec($ch), true);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new \Exception("Erro na API ({$httpCode}): " . json_encode($response));
}
return $response;
}
private function get(string $endpoint): array
{
$ch = curl_init("{$this->baseUrl}{$endpoint}");
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => [
"Authorization: Bearer {$this->accessToken}",
'Accept: application/json',
],
CURLOPT_RETURNTRANSFER => true,
]);
$response = json_decode(curl_exec($ch), true);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new \Exception("Erro na API ({$httpCode}): " . json_encode($response));
}
return $response;
}
}
<?php
require_once 'GatewayClient.php';
$client = new GatewayClient('https://seugateway.com', 'client_id', 'client_secret');
$client->authenticate();
// Gerar QR Code PIX
$pix = $client->createPixQrCode(100.00, [
'external_id' => 'pedido-123',
'payer_name' => 'Joao Silva',
'payer_document' => '12345678900',
'postback_url' => 'https://seusite.com/webhook',
]);
echo "Codigo PIX: " . $pix['copy_paste'] . "\n";
echo "QR Code: " . $pix['qr_code_base64'] . "\n";
// Enviar pagamento PIX (saque)
$payment = $client->createPixPayment(50.00, '12345678900', 'cpf', [
'external_id' => 'saque-456',
]);
echo "Pagamento ID: " . $payment['transaction_id'] . "\n";
// Gerar boleto
$boleto = $client->createBoleto(200.00, [
'payer_name' => 'Maria Santos',
'payer_document' => '98765432100',
'payer_email' => 'maria@email.com',
], [
'external_id' => 'pedido-789',
'due_date' => '2025-02-15',
]);
echo "Linha digitavel: " . $boleto['digitable_line'] . "\n";
// Consultar saldo
$balance = $client->getBalance();
echo "Saldo disponivel: R$ " . number_format($balance['balance'], 2, ',', '.') . "\n";
const axios = require('axios');
class GatewayClient {
/**
* @param {string} baseUrl - URL base do gateway (ex: https://seugateway.com)
* @param {string} clientId - Client ID da chave de integracao
* @param {string} clientSecret - Client Secret da chave de integracao
*/
constructor(baseUrl, clientId, clientSecret) {
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.clientId = clientId;
this.clientSecret = clientSecret;
this.accessToken = null;
}
/**
* Autentica com o gateway e obtem o token de acesso.
*/
async authenticate() {
const credentials = Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64');
const { data } = await axios.post(`${this.baseUrl}/api/v1/oauth/token`, {}, {
headers: {
'Authorization': `Basic ${credentials}`,
'Content-Type': 'application/json',
},
});
this.accessToken = data.access_token;
return this;
}
/**
* Gera um QR Code PIX para recebimento.
*/
async createPixQrCode(amount, options = {}) {
return this._post('/api/v1/pix/qrcode', { amount, ...options });
}
/**
* Envia um pagamento PIX (saque/transferencia).
*/
async createPixPayment(amount, pixKey, pixKeyType, options = {}) {
return this._post('/api/v1/pix/payment', {
amount,
pix_key: pixKey,
pix_key_type: pixKeyType,
...options,
});
}
/**
* Gera um boleto bancario.
*/
async createBoleto(amount, payer, options = {}) {
return this._post('/api/v1/boleto/create', { amount, ...payer, ...options });
}
/**
* Realiza cobranca no cartao de credito.
*/
async createCardCharge(amount, cardToken, options = {}) {
return this._post('/api/v1/card/charge', { amount, card_token: cardToken, ...options });
}
/**
* Consulta o saldo disponivel.
*/
async getBalance() {
return this._get('/api/v1/balance');
}
async _post(endpoint, data) {
const { data: response } = await axios.post(`${this.baseUrl}${endpoint}`, data, {
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
return response;
}
async _get(endpoint) {
const { data: response } = await axios.get(`${this.baseUrl}${endpoint}`, {
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Accept': 'application/json',
},
});
return response;
}
}
module.exports = GatewayClient;
const GatewayClient = require('./GatewayClient');
(async () => {
const client = new GatewayClient('https://seugateway.com', 'client_id', 'client_secret');
await client.authenticate();
// Gerar QR Code PIX
const pix = await client.createPixQrCode(100.00, {
external_id: 'pedido-123',
payer_name: 'Joao Silva',
payer_document: '12345678900',
postback_url: 'https://seusite.com/webhook',
});
console.log('Codigo PIX:', pix.copy_paste);
// Enviar pagamento PIX
const payment = await client.createPixPayment(50.00, '12345678900', 'cpf', {
external_id: 'saque-456',
});
console.log('Pagamento ID:', payment.transaction_id);
// Consultar saldo
const balance = await client.getBalance();
console.log('Saldo:', `R$ ${balance.balance.toFixed(2)}`);
})();
import requests
from base64 import b64encode
from typing import Optional
class GatewayClient:
"""Cliente para integracao com a API do gateway de pagamentos."""
def __init__(self, base_url: str, client_id: str, client_secret: str):
self.base_url = base_url.rstrip('/')
self.client_id = client_id
self.client_secret = client_secret
self.access_token: Optional[str] = None
def authenticate(self) -> 'GatewayClient':
"""Autentica com o gateway e obtem o token de acesso."""
credentials = b64encode(f"{self.client_id}:{self.client_secret}".encode()).decode()
response = requests.post(
f"{self.base_url}/api/v1/oauth/token",
headers={
'Authorization': f'Basic {credentials}',
'Content-Type': 'application/json',
}
)
response.raise_for_status()
self.access_token = response.json()['access_token']
return self
def create_pix_qrcode(self, amount: float, **options) -> dict:
"""Gera um QR Code PIX para recebimento."""
return self._post('/api/v1/pix/qrcode', {'amount': amount, **options})
def create_pix_payment(self, amount: float, pix_key: str, pix_key_type: str, **options) -> dict:
"""Envia um pagamento PIX (saque/transferencia)."""
return self._post('/api/v1/pix/payment', {
'amount': amount,
'pix_key': pix_key,
'pix_key_type': pix_key_type,
**options,
})
def create_boleto(self, amount: float, payer: dict, **options) -> dict:
"""Gera um boleto bancario."""
return self._post('/api/v1/boleto/create', {'amount': amount, **payer, **options})
def create_card_charge(self, amount: float, card_token: str, **options) -> dict:
"""Realiza cobranca no cartao de credito."""
return self._post('/api/v1/card/charge', {
'amount': amount,
'card_token': card_token,
**options,
})
def get_balance(self) -> dict:
"""Consulta o saldo disponivel."""
return self._get('/api/v1/balance')
def _post(self, endpoint: str, data: dict) -> dict:
response = requests.post(
f"{self.base_url}{endpoint}",
json=data,
headers={
'Authorization': f'Bearer {self.access_token}',
'Content-Type': 'application/json',
'Accept': 'application/json',
}
)
response.raise_for_status()
return response.json()
def _get(self, endpoint: str) -> dict:
response = requests.get(
f"{self.base_url}{endpoint}",
headers={
'Authorization': f'Bearer {self.access_token}',
'Accept': 'application/json',
}
)
response.raise_for_status()
return response.json()
from gateway_client import GatewayClient
client = GatewayClient('https://seugateway.com', 'client_id', 'client_secret')
client.authenticate()
# Gerar QR Code PIX
pix = client.create_pix_qrcode(
amount=100.00,
external_id='pedido-123',
payer_name='Joao Silva',
payer_document='12345678900',
postback_url='https://seusite.com/webhook',
)
print(f"Codigo PIX: {pix['copy_paste']}")
# Enviar pagamento PIX
payment = client.create_pix_payment(
amount=50.00,
pix_key='12345678900',
pix_key_type='cpf',
external_id='saque-456',
)
print(f"Pagamento ID: {payment['transaction_id']}")
# Gerar boleto
boleto = client.create_boleto(
amount=200.00,
payer={
'payer_name': 'Maria Santos',
'payer_document': '98765432100',
'payer_email': 'maria@email.com',
},
external_id='pedido-789',
due_date='2025-02-15',
)
print(f"Linha digitavel: {boleto['digitable_line']}")
# Consultar saldo
balance = client.get_balance()
print(f"Saldo: R$ {balance['balance']:.2f}")
| Linguagem | Dependencia | Instalacao |
|---|---|---|
| PHP | ext-curl (nativo) | Nenhuma instalacao necessaria |
| Node.js | axios | npm install axios |
| Python | requests | pip install requests |