---
title: "C++ SDK"
lang: en
canonical: https://doc.apibrasil.io/sdks/cpp
markdown: https://doc.apibrasil.io/sdks/cpp.md
source: apibrasil-documentation
---

# C++ SDK

- **Status:** published
- **Install:** `git clone https://github.com/APIBrasil/apigratis-sdk-cpp`
- **Registry:** GitHub — https://github.com/APIBrasil/apigratis-sdk-cpp
- **Repository:** https://github.com/APIBrasil/apigratis-sdk-cpp

## Do not make up the signature

DO NOT INVENT THE C++ SDK's API. Every library in this catalogue has its own constructor, method names and return shape, and none of them can be deduced from the package name. Open the README of the repository above and use exactly what is written there. If you cannot open the repository, DO NOT GUESS: write the client in plain HTTP, following the section below, and say in your answer that this is what you did and why.

## How to authenticate

The Bearer goes in the Authorization header, on every call. The DeviceToken only on plan-billed APIs — credit-billed ones don't ask for it. It's the same pair the SDK sets for you.

With homolog set to true in the body, the gateway answers from a fixed dataset. The document number 00000000000 belongs to that dataset and to no one.

## The repository on GitHub

- **Stars:** 0
- **Forks:** 0
- **Open issues:** 0
- **Language:** C++
- **Licence:** MIT License
- **Last push:** July 24, 2026
- **git clone:** `https://github.com/APIBrasil/apigratis-sdk-cpp.git`

## Repository README

Reproduced from the repository, on the default branch. It is the documentation written by whoever maintains the library: the SDK's signature is what is written here, not what is deduced from the package name.

# APIBrasil SDK — C++

SDK oficial **C++** da plataforma [APIBrasil](https://apibrasil.com.br) —
WhatsApp, SMS, consultas CPF/CNPJ, veículos, CEP, correios, pagamentos
PIX/boleto e muito mais.

- **C++17**, portável (Linux, macOS, Windows/MSVC).
- Transporte HTTP baseado em **libcurl**; JSON via **nlohmann/json**.
- Retry com backoff, hooks de observabilidade e hierarquia de erros tipados.

---

## Requisitos

- Compilador C++17 (GCC 8+, Clang 7+, MSVC 2019+).
- [CMake](https://cmake.org/) ≥ 3.16.
- [libcurl](https://curl.se/libcurl/) (desenvolvimento).
- [nlohmann/json](https://github.com/nlohmann/json) — encontrado no sistema ou
  baixado automaticamente via `FetchContent`.

No Ubuntu/Debian: `sudo apt install libcurl4-openssl-dev cmake g++`.
No macOS: `brew install curl cmake`.
No Windows: use [vcpkg](https://vcpkg.io/) (`vcpkg install curl nlohmann-json`)
ou o Visual Studio com CMake.

---

## Instalação

### Como subdiretório (mais simples)

Copie/clone este repositório para dentro do seu projeto e no seu `CMakeLists.txt`:

```cmake
add_subdirectory(apigratis-sdk-cpp)
target_link_libraries(seu_app PRIVATE apibrasil::apibrasil)
```

### Via FetchContent

```cmake
include(FetchContent)
FetchContent_Declare(apibrasil
    GIT_REPOSITORY https://github.com/jhowbhz/apigratis-sdk-cpp.git
    GIT_TAG v0.0.2)
FetchContent_MakeAvailable(apibrasil)
target_link_libraries(seu_app PRIVATE apibrasil::apibrasil)
```

Depois, no código:

```cpp
#include <apibrasil/apibrasil.hpp>
```

---

## Autenticação

Pegue suas credenciais em <https://apibrasil.com.br>. Existem dois tipos de
serviço:

| Família | Headers enviados | Serviços |
|---|---|---|
| **Device-based** | `Authorization: Bearer <token>` + `DeviceToken: <token>` | whatsapp, sms, dados, vehicles, cep, correios, ... |
| **Credit-based** | apenas `Authorization: Bearer <token>` (debita saldo) | `consulta.*` |

```cpp
#include <apibrasil/apibrasil.hpp>
using namespace apibrasil;

Config cfg;
cfg.bearerToken = "seu_bearer_token";   // JWT do login
cfg.deviceToken = "seu_device_token";   // serviços device-based
ApiBrasil api(cfg);
```

Ou deixe o SDK ler as variáveis de ambiente automaticamente
(`APIBRASIL_BEARER_TOKEN`, `APIBRASIL_DEVICE_TOKEN`, `APIBRASIL_SECRET_KEY`,
`APIBRASIL_BASE_URL`):

```cpp
ApiBrasil api;  // lê do ambiente
```

### Login por e-mail/senha (token guardado automaticamente)

```cpp
auto result = ApiBrasil::login({{"email", "voce@x.com"}, {"password", "******"}});
auto& api = *result.client;   // o token já está no cliente

// 2FA:
try {
    auto r = ApiBrasil::login({{"email", email}, {"password", senha}});
} catch (const ApiBrasilError& e) {
    // e.code() == "requires_2fa" -> conclua com auth.send2fa()/verify2fa()
}
```

### Criando um device (usa SecretKey)

```cpp
RequestOptions o;
o.secretKey = "SUA_SECRET_KEY";
Json device = api.devices.store({{"device_name", "meu-bot"}, {"type", "server"}}, o);
api.setDeviceToken(device["device"]["device_token"].get<std::string>());
```

---

## Uso

Todas as respostas voltam como `apibrasil::Json` (alias de `nlohmann::json`).

```cpp
// WhatsApp (device-based)
api.whatsapp.start({{"webhook_wh_message", "https://.../mensagens"}});
Json qr = api.whatsapp.qrcode();                 // qr["response"]["qrcode"]
api.whatsapp.sendText({{"number", "5511999999999"}, {"text", "Olá!"}});
api.whatsapp.sendFile({{"number", "..."}, {"path", "https://.../nota.pdf"}});

// Chamada genérica de qualquer action + fila (assíncrono)
api.whatsapp.request("sendLocation", {{"number", "..."}, {"lat", -23.5}, {"lng", -46.6}});
api.whatsapp.queue("sendText", {{"number", "..."}, {"text", "assíncrono"}});

// Consultas por crédito
Json cpf    = api.consulta.cpf({{"cpf", "00000000000"}});
Json socios = api.consulta.cnpj({{"cnpj", "..."}, {"tipo", "lista-socios"}});
Json score  = api.consulta.generic("cpf", {{"cpf", "..."}, {"tipo", "serasa-score-pf"}});
Json teste  = api.consulta.cpf({{"cpf", "..."}, {"homolog", true}});  // sandbox, sem cobrança

// Veículos (device-based) / SMS / Pagamentos
api.vehicles.dados({{"placa", "ABC1234"}});
api.sms.send({{"number", "..."}, {"message", "codigo: 123456"}});
Json pix = api.payments.pixGenerate("mercadopago", {{"amount", 100}});

// Boleto em PDF (bytes brutos)
std::string pdf = api.payments.boletoPdf("inter", "BOLETO_ID");
```

### Múltiplos devices

```cpp
auto comercial = api.withDevice("DEVICE_TOKEN_COMERCIAL");
comercial->whatsapp.sendText({{"number", "..."}, {"text", "..."}});
```

### Escape hatch genérico

```cpp
Json r1 = api.request("POST", "/consulta/cpf/credits", Json{{"cpf", "..."}});
Json r2 = api.request("GET", "/reports/quick-stats");
```

---

## Tratamento de erros

Toda resposta com status `>= 400` lança uma exceção da hierarquia
`apibrasil::ApiBrasilError`:

```cpp
try {
    api.consulta.cpf({{"cpf", "00000000000"}});
} catch (const InsufficientBalanceError& e) {
    // saldo insuficiente (HTTP 402) -> recarregar
} catch (const RateLimitError& e) {
    long ms = e.retryAfterMs().value_or(0);   // aguardar antes de repetir
} catch (const ValidationError& e) {
    // 400/422
} catch (const ApiBrasilError& e) {
    std::cerr << e.what() << " (status " << e.status().value_or(0) << ")\n";
}
```

| Exceção | Status |
|---|---|
| `ValidationError` | 400, 422 |
| `AuthenticationError` | 401 |
| `InsufficientBalanceError` | 402 |
| `PermissionError` | 403 |
| `NotFoundError` | 404, 410 |
| `RateLimitError` (tem `retryAfterMs()`) | 429 |
| `ServerError` | ≥ 500 |
| `NetworkError` / `TimeoutError` | falha de conexão / timeout |

---

## Configuração

```cpp
Config cfg;
cfg.bearerToken = "...";
cfg.deviceToken = "...";
cfg.baseUrl     = "https://gateway.apibrasil.io/api/v2";  // padrão
cfg.timeoutMs   = 30000;                                   // padrão (ms)

// Retry (padrão: 2 tentativas, apenas em 429 e falhas de conexão)
RetryConfig r;
r.retries = 3;
r.retryOnStatuses = {429, 503};
cfg.retry = r;                 // ou RetryConfig::disabled()

// Hooks de observabilidade
cfg.hooks.onRequest  = [](const RequestHookInfo& i)  { /* log */ };
cfg.hooks.onResponse = [](const ResponseHookInfo& i) { /* log */ };
cfg.hooks.onRetry    = [](const RetryHookInfo& i)    { /* log */ };

ApiBrasil api(cfg);
```

Timeouts **nunca** são repetidos automaticamente (para evitar cobranças/envios
duplicados). Não há URL separada de sandbox — a "homologação" das consultas por
crédito é feita por chamada com `{"homolog", true}` no corpo.

### Opções por requisição

Todo método aceita um `RequestOptions` opcional no fim:

```cpp
RequestOptions o;
o.query["page"]   = "2";
o.headers["X-Id"] = "abc";
o.bearerToken     = "token_de_uma_chamada";
o.timeoutMs       = 60000;
api.reports.recentRequests(o);
```

---

## Documentação

- Portal: <https://apibrasil.com.br>
- Docs: <https://doc.apibrasil.io>

## Licença

[MIT](https://github.com/APIBrasil/apigratis-sdk-cpp/blob/main/LICENSE) © APIBrasil.

## The same API over HTTP

Base URL: https://gateway.apibrasil.io/api/v2
Each endpoint's path and method are on that API's page in this documentation. Do not deduce a route from the service name.

### Authentication, as HTTP headers
- `Authorization: Bearer YOUR_TOKEN` — on every call.
- `DeviceToken: YOUR_DEVICE_TOKEN` — only on plan-billed APIs; credit-billed ones don't ask for it. The exact header name is whatever the endpoint's page declares.

```bash
curl -X POST https://gateway.apibrasil.io/api/v2/dados/cpf \
  -H "Authorization: Bearer $APIBRASIL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"cpf": "00000000000", "homolog": true}'
```

With `homolog` set to true in the body, the gateway answers from a fixed dataset and spends no credit. The document number 00000000000 belongs to that dataset and to no one — use it in tests, never in production.

## The other languages

- [Python](https://doc.apibrasil.io/sdks/python.md): `pip install api-brasil`
- [Lua](https://doc.apibrasil.io/sdks/lua.md): `luarocks install apibrasil`
- [PHP](https://doc.apibrasil.io/sdks/php.md): `composer require jhowbhz/apigratis-sdk-php`
- [Java](https://doc.apibrasil.io/sdks/java.md): `mvn dependency:get -Dartifact=br.com.apibrasil:apigratis-sdk-java:0.0.1`
- [Ruby](https://doc.apibrasil.io/sdks/ruby.md): `gem install apigratis-sdk-ruby`
- [C# / .NET](https://doc.apibrasil.io/sdks/csharp.md): `dotnet add package ApiBrasil`
- [Node.js / TypeScript](https://doc.apibrasil.io/sdks/javascript.md): `npm install apigratis-sdk-nodejs`
- [Go](https://doc.apibrasil.io/sdks/go.md): `go get github.com/APIBrasil/apigratis-sdk-go`
- [Rust](https://doc.apibrasil.io/sdks/rust.md): `cargo add apibrasil`
- [Dart / Flutter](https://doc.apibrasil.io/sdks/flutter.md): `flutter pub add apigratis_sdk_flutter`
- [Elixir](https://doc.apibrasil.io/sdks/elixir.md): `mix deps.get  # com {:apibrasil, "~> 0.0.1"} no mix.exs`

## See also

- Official SDKs: [Official SDKs](https://doc.apibrasil.io/sdks.md)
- Documentation index: https://doc.apibrasil.io/llms.txt
- HTML version of this page: https://doc.apibrasil.io/sdks/cpp
