PHP code example of jhowbhz / apigratis-sdk-php
1. Go to this page and download the library: Download jhowbhz/apigratis-sdk-php 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/ */
jhowbhz / apigratis-sdk-php example snippets
piBrasil\ApiBrasil;
$api = new ApiBrasil([
'bearerToken' => getenv('APIBRASIL_BEARER_TOKEN'), // JWT do login
'deviceToken' => getenv('APIBRASIL_DEVICE_TOKEN'), // device dos serviços device-based
]);
// WhatsApp
$api->whatsapp->sendText(['number' => '5511999999999', 'text' => 'Olá! 👋']);
// Consulta CNPJ (por créditos)
$empresa = $api->consulta->cnpj(['cnpj' => '00000000000000']);
print_r($empresa['data']);
$api = new ApiBrasil();
$api->auth->login(['email' => '[email protected] ', 'password' => '******']);
// contas com 2FA:
$session = $api->auth->login(['email' => $email, 'password' => $password]);
if (!empty($session['
$device = $api->devices->store(
['device_name' => 'meu-bot', 'type' => 'server'],
['secretKey' => 'SUA_SECRET_KEY']
);
$api->setDeviceToken($device['device']['device_token']);
// iniciar sessão e obter QR Code
$api->whatsapp->start(['webhook_wh_message' => 'https://seu-webhook.com/mensagens']);
$qr = $api->whatsapp->qrcode();
echo $qr['response']['qrcode']; // data URI base64
// envios
$api->whatsapp->sendText(['number' => '5511999999999', 'text' => 'Olá!']);
$api->whatsapp->sendFile(['number' => '5511999999999', 'path' => 'https://exemplo.com/nota.pdf']);
$api->whatsapp->sendAudio(['number' => '5511999999999', 'path' => 'https://exemplo.com/audio.mp3']);
// qualquer action da documentação, inclusive via fila
$api->whatsapp->request('sendLocation', ['number' => '5511999999999', 'lat' => -23.5, 'lng' => -46.6]);
$api->whatsapp->queue('sendText', ['number' => '5511999999999', 'text' => 'assíncrono 🚀']);
// CPF / CNPJ
$cpf = $api->consulta->cpf(['cpf' => '00000000000']);
$socios = $api->consulta->cnpj(['cnpj' => '00000000000000', 'tipo' => 'lista-socios']);
// veicular
$veiculo = $api->consulta->veiculos(['placa' => 'ABC1234']);
// qualquer produto do catálogo
$score = $api->consulta->generic('cpf', ['cpf' => '00000000000', 'tipo' => 'serasa-score-pf']);
// homologação (sandbox, sem cobrança)
$teste = $api->consulta->cpf(['cpf' => '00000000000', 'homolog' => true]);
$dados = $api->vehicles->dados(['placa' => 'ABC1234']);
$fipe = $api->vehicles->fipe(['placa' => 'ABC1234']);
$api->sms->send(['number' => '5511999999999', 'message' => 'Seu código: 123456']);
// ou debitando créditos da conta (sem device):
$api->sms->sendWithCredits(['number' => '5511999999999', 'message' => 'Olá!']);
$pix = $api->payments->pixGenerate('inter', ['amount' => 100]);
$status = $api->payments->pixStatus('inter', $pix['txId']);
$boleto = $api->payments->boletoGenerate('sicoob', ['amount' => 150]);
$pdf = $api->payments->boletoPdf('sicoob', $boleto['id']); // conteúdo binário
$comercial = $api->withDevice('DEVICE_TOKEN_COMERCIAL');
$suporte = $api->withDevice('DEVICE_TOKEN_SUPORTE');
$comercial->whatsapp->sendText(['number' => '55...', 'text' => 'Proposta enviada!']);
$suporte->whatsapp->sendText(['number' => '55...', 'text' => 'Como posso ajudar?']);
use ApiBrasil\Core\Errors\InsufficientBalanceError;
use ApiBrasil\Core\Errors\RateLimitError;
try {
$api->consulta->cpf(['cpf' => '00000000000']);
} catch (InsufficientBalanceError $e) {
echo 'Recarregue seus créditos';
} catch (RateLimitError $e) {
echo "Aguarde {$e->getRetryAfterMs()}ms";
}
$api = new ApiBrasil([
'retry' => ['retries' => 3, 'minDelayMs' => 500, 'retryOnStatuses' => [429, 503]], // ou 'retry' => false
'hooks' => [
'onRequest' => fn (array $i) => printf("→ %s %s (#%d)\n", $i['method'], $i['url'], $i['attempt']),
'onResponse' => fn (array $i) => printf("← %d em %dms\n", $i['status'], $i['durationMs']),
'onRetry' => fn (array $i) => printf("retry em %dms: %s\n", $i['delayMs'], $i['reason']),
],
]);
use ApiBrasil\ApiBrasil;
use ApiBrasil\Core\Transport\GuzzleTransport;
// Guzzle com opções próprias (proxy, verify, handler...)
$api = new ApiBrasil([
'transport' => new GuzzleTransport(null, [
'proxy' => 'http://proxy.local:3128',
'verify' => true,
]),
]);
use ApiBrasil\Core\Transport\TransportInterface;
use ApiBrasil\Core\Transport\TransportRequest;
use ApiBrasil\Core\Transport\TransportResponse;
final class MeuTransporte implements TransportInterface
{
public function request(TransportRequest $request): TransportResponse
{
// use o cliente HTTP que quiser e devolva status, headers e corpo
return new TransportResponse(200, [], ['ok' => true]);
}
}
use ApiBrasil\Generated\Catalog;
Catalog::WHATSAPP_ACTIONS; // ['sendText', 'sendFile', ...]
Catalog::serviceActions('whatsmeow'); // actions documentadas do serviço
Catalog::consultaTipo('lista-socios'); // ['service' => 'cnpj', 'fields' => ['cnpj']]
$api->request('POST', '/consulta/cpf/credits', ['cpf' => '00000000000']);
$api->request('GET', '/reports/quick-stats');
$api = new ApiBrasil([
'bearerToken' => '...', // ou APIBRASIL_BEARER_TOKEN
'deviceToken' => '...', // ou APIBRASIL_DEVICE_TOKEN
'secretKey' => '...', // usada em devices->store (ou APIBRASIL_SECRET_KEY)
'baseURL' => 'https://gateway.apibrasil.io/api/v2', // padrão (ou APIBRASIL_BASE_URL)
'timeout' => 30000, // milissegundos
'headers' => ['X-Custom' => 'valor'], // headers extras
'retry' => ['retries' => 2], // ou false
'hooks' => ['onRetry' => fn (array $i) => error_log($i['reason'])],
'transport' => null, // TransportInterface customizado
]);
$api->whatsapp->sendText(
['number' => '5511999999999', 'text' => 'Olá!'],
['deviceToken' => 'OUTRO_DEVICE', 'timeout' => 60000]
);
$login = Service::Auth("login", [
"body" => [
"email" => "[email protected] ",
"password" => "123456"
]
]);
$logout = Service::Auth("logout", [
"Bearer" => "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....",
]);
$store = Service::Device("store", [
"Bearer" => "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....",
"SecretKey" => "f87eb607-a8cc-43ea-b439.....",
"body" => [
"type" => "cellphone",
"device_name" => "zap1",
"device_key" => "zapzap1",
"device_ip" => "198.29.10.50",
"server_search" => "341d6f36-b888....",
"webhook_wh_message" => "",
"webhook_wh_status" => ""
]
]);
$show = Service::Device("show", [
"Bearer" => "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....",
"method" => "GET",
"query" => ["search" => "82faab0a-24f4-4b8b-9926-455ea9b3cdb7"],
]);
$servers = Service::Server(["Bearer" => "...", "method" => "GET"]);
$profile = Service::Profile(["Bearer" => "...", "method" => "GET"]);
$plans = Service::Plan("all", ["Bearer" => "...", "method" => "GET"]);
$plan = Service::Plan("me", ["Bearer" => "...", "method" => "GET"]);
$sendText = Service::WhatsApp("sendText", [
"Bearer" => "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....",
"DeviceToken" => "d019580b-3c8c-40e3-b9a0....",
"body" => [
"number" => "5531994359434",
"text" => "🟢 Bem vindo ao APIBrasil"
]
]);
$dados = Service::Vehicles("dados", [
"Bearer" => "...",
"DeviceToken" => "...",
"body" => ["placa" => "HBM6603"]
]);
$fipe = Service::Vehicles("fipe", [
"Bearer" => "...",
"DeviceToken" => "...",
"body" => ["placa" => "HBM6603"]
]);
// Vehicles Base (tipo como chave principal)
$base = Service::Vehicles("base/000/dados", [
"Bearer" => "...",
"timeout" => 120,
"body" => [
"tipo" => "fipe",
"placa" => "HBM6603",
"homolog" => false,
]
]);
// equivalente — a SDK normaliza o tipo automaticamente
$base = Service::Vehicles("base/000/dados", [
"Bearer" => "...",
"timeout" => 120,
"body" => [
"fipe" => ["placa" => "HBM6603", "homolog" => false],
]
]);
$rastreio = Service::Correios("rastreio", [
"Bearer" => "...", "DeviceToken" => "...",
"body" => ["code" => "NL249695552BR"]
]);
$cnpj = Service::CNPJ("cnpj", [
"Bearer" => "...", "DeviceToken" => "...",
"body" => ["cnpj" => "44.959.669/0001-80"]
]);
$cep = Service::CEP("cep", [
"Bearer" => "...", "DeviceToken" => "...",
"body" => ["cep" => "32146057"]
]);
$ddd = Service::DDD("ddd", [
"Bearer" => "...", "DeviceToken" => "...",
"body" => ["ddd" => "31"]
]);
$feriados = Service::HoliDays("feriados", [
"Bearer" => "...", "DeviceToken" => "...",
"body" => ["type" => "facultativo", "date" => "07/09", "year" => "2024"]
]);
bash
composer