Registrar Boleto Depois
Esta funcionalidade permite criar um boleto e escolher quando habilitar o envio para registro. O boleto é gerado normalmente, mas não é enviado para registro até que você decida.
Como Funciona
Seção intitulada “Como Funciona”Ao criar um boleto com boleto.cobrancaBancaria.registrar = false:
- O boleto é criado e o PDF é gerado normalmente
- O boleto não é incluído em nenhuma remessa CNAB
- O boleto não é enviado automaticamente para o banco
- Você pode habilitar o registro posteriormente via nossa API
registrar × registrado
Seção intitulada “registrar × registrado”registrar é o que você pede; registrado é o que o banco confirmou. GET /boletos/{token}/registro responde com status.token, status.registrado e status.erro, sem o campo registrar.
GET /boletos/{token}/registro, GET /boletos/{token}/situacao e PUT /boletos/{token}/registro são do plano Personalizado. Sem ele, a resposta é 403 com o código 8D1C5814.
boleto.cobrancaBancaria.registrar — envio no POST /boletos e no PUT /boletos/{token}/registro. Boolean. Na criação, true é o padrão.
- Significa: habilita (
true) ou desabilita (false) o envio para registro pelo canal da conta. - Não significa: a confirmação do banco.
boleto.registro.registrar — resposta de GET /boletos/{token}/situacao, em boleto.registro. Boolean true ou false.
- Significa: se o boleto deve ser enviado para registro. Em
GET /boletos/{token}/situacao, acompanheboleto.registro.situacaoeboleto.registro.erro.codigo. - Não significa: que o banco já registrou o boleto.
status.registrado — resposta de GET /boletos/{token}/registro. Data AAAA-MM-DD ou null.
- Significa: a data em que o boleto foi registrado.
nullse não foi registrado. - Não significa: o valor
true.
status.erro — resposta de GET /boletos/{token}/registro. String ou null.
- Significa: a mensagem da rejeição do registro.
nullse não houve erro. - Não significa: que o boleto foi registrado.
Na rejeição que vem pelo arquivo de retorno, registrar passa a false. Esse valor está em boleto.registro.registrar, na resposta de GET /boletos/{token}/situacao. O boleto volta para o registro com PUT /boletos/{token}/registro.
Quando Usar
Seção intitulada “Quando Usar”- E-commerce: Criar boleto no checkout e registrar apenas quando o cliente confirmar
- Propostas comerciais: Gerar boleto para orçamento
- Distribuidoras: Imprimir boleto junto com a carga e registrar apenas após confirmação de entrega
- Controle de fluxo: Decidir quando habilitar o envio para registro conforme sua regra de negócio
1. Criar Boleto sem Registrar
Seção intitulada “1. Criar Boleto sem Registrar”O exemplo envia boleto.tokenControleUsuario. Repetir o mesmo valor responde 409 com o código 2B257710. A regra está em Idempotência - Evitar Duplicados.
codigo=$(curl -sS -D headers.txt -o corpo.bin -w "%{http_code}" \ "https://sandbox.boletocloud.com/api/v1/boletos" \ -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \ -X POST \ -u "api-key_SUA-API-KEY:token" \ -d boleto.conta.token="api-key_SEU-TOKEN-DA-CONTA" \ -d boleto.tokenControleUsuario="pedido-12345-abc" \ -d boleto.cobrancaBancaria.registrar="false" \ -d boleto.emissao="2024-01-15" \ -d boleto.vencimento="2024-01-30" \ -d boleto.documento="PROP-001" \ -d boleto.titulo="DM" \ -d boleto.valor="150.00" \ -d boleto.pagador.nome="Alberto Santos Dumont" \ -d boleto.pagador.cprf="111.111.111-11" \ -d boleto.pagador.endereco.cep="36240-000" \ -d boleto.pagador.endereco.uf="MG" \ -d boleto.pagador.endereco.localidade="Santos Dumont" \ -d boleto.pagador.endereco.bairro="Centro" \ -d boleto.pagador.endereco.logradouro="Rua Principal" \ -d boleto.pagador.endereco.numero="100")
if [ "$codigo" = "201" ]; then mv corpo.bin boleto.pdf echo "Boleto criado (sem registro)." grep -i "^X-BoletoCloud-Token:" headers.txt || trueelif [ "$codigo" = "409" ]; then echo "Erro: 409 boleto.tokenControleUsuario repetido" cat corpo.binelse echo "Erro: $codigo" cat corpo.binfiimport javax.ws.rs.client.ClientBuilder;import javax.ws.rs.client.Entity;import javax.ws.rs.core.Form;import javax.ws.rs.core.Response;import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Paths;import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class CriarBoletoSemRegistro { public static void main(String[] args) throws Exception { Form form = new Form() .param("boleto.conta.token", "api-key_SEU-TOKEN-DA-CONTA") .param("boleto.tokenControleUsuario", "pedido-12345-abc") .param("boleto.cobrancaBancaria.registrar", "false") .param("boleto.emissao", "2024-01-15") .param("boleto.vencimento", "2024-01-30") .param("boleto.documento", "PROP-001") .param("boleto.titulo", "DM") .param("boleto.valor", "150.00") .param("boleto.pagador.nome", "Alberto Santos Dumont") .param("boleto.pagador.cprf", "111.111.111-11") .param("boleto.pagador.endereco.cep", "36240-000") .param("boleto.pagador.endereco.uf", "MG") .param("boleto.pagador.endereco.localidade", "Santos Dumont") .param("boleto.pagador.endereco.bairro", "Centro") .param("boleto.pagador.endereco.logradouro", "Rua Principal") .param("boleto.pagador.endereco.numero", "100");
Response response = ClientBuilder.newClient() .target("https://sandbox.boletocloud.com/api/v1/boletos") .register(HttpAuthenticationFeature.basic("api-key_SUA-API-KEY", "token")) .request() .post(Entity.form(form));
switch (response.getStatus()) { case 201: String token = response.getHeaderString("X-BoletoCloud-Token"); System.out.println("Boleto criado (sem registro). Token: " + token); Files.copy(response.readEntity(InputStream.class), Paths.get("boleto.pdf"), REPLACE_EXISTING); break; case 409: System.out.println("Erro: 409 boleto.tokenControleUsuario repetido"); System.out.println(response.readEntity(String.class)); break; default: System.out.println("Erro: " + response.getStatus()); System.out.println(response.readEntity(String.class)); } }}import okhttp3.*import java.io.File
fun main() { val client = OkHttpClient() val credential = Credentials.basic("api-key_SUA-API-KEY", "token")
val body = FormBody.Builder() .add("boleto.conta.token", "api-key_SEU-TOKEN-DA-CONTA") .add("boleto.tokenControleUsuario", "pedido-12345-abc") .add("boleto.cobrancaBancaria.registrar", "false") .add("boleto.emissao", "2024-01-15") .add("boleto.vencimento", "2024-01-30") .add("boleto.documento", "PROP-001") .add("boleto.titulo", "DM") .add("boleto.valor", "150.00") .add("boleto.pagador.nome", "Alberto Santos Dumont") .add("boleto.pagador.cprf", "111.111.111-11") .add("boleto.pagador.endereco.cep", "36240-000") .add("boleto.pagador.endereco.uf", "MG") .add("boleto.pagador.endereco.localidade", "Santos Dumont") .add("boleto.pagador.endereco.bairro", "Centro") .add("boleto.pagador.endereco.logradouro", "Rua Principal") .add("boleto.pagador.endereco.numero", "100") .build()
val request = Request.Builder() .url("https://sandbox.boletocloud.com/api/v1/boletos") .header("Authorization", credential) .post(body) .build()
client.newCall(request).execute().use { response -> when (response.code) { 201 -> { val token = response.header("X-BoletoCloud-Token") println("Boleto criado (sem registro). Token: $token") File("boleto.pdf").writeBytes(response.body!!.bytes()) } 409 -> { println("Erro: 409 boleto.tokenControleUsuario repetido") println(response.body?.string()) } else -> { println("Erro: ${response.code}") println(response.body?.string()) } } }}using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
class Program { static async Task Main(string[] args) { using var client = new HttpClient(); var credentials = Convert.ToBase64String( Encoding.ASCII.GetBytes("api-key_SUA-API-KEY:token")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var content = new FormUrlEncodedContent(new Dictionary<string, string> { {"boleto.conta.token", "api-key_SEU-TOKEN-DA-CONTA"}, {"boleto.tokenControleUsuario", "pedido-12345-abc"}, {"boleto.cobrancaBancaria.registrar", "false"}, {"boleto.emissao", "2024-01-15"}, {"boleto.vencimento", "2024-01-30"}, {"boleto.documento", "PROP-001"}, {"boleto.titulo", "DM"}, {"boleto.valor", "150.00"}, {"boleto.pagador.nome", "Alberto Santos Dumont"}, {"boleto.pagador.cprf", "111.111.111-11"}, {"boleto.pagador.endereco.cep", "36240-000"}, {"boleto.pagador.endereco.uf", "MG"}, {"boleto.pagador.endereco.localidade", "Santos Dumont"}, {"boleto.pagador.endereco.bairro", "Centro"}, {"boleto.pagador.endereco.logradouro", "Rua Principal"}, {"boleto.pagador.endereco.numero", "100"} });
var response = await client.PostAsync( "https://sandbox.boletocloud.com/api/v1/boletos", content);
switch ((int)response.StatusCode) { case 201: var token = response.Headers.GetValues("X-BoletoCloud-Token").First(); Console.WriteLine($"Boleto criado (sem registro). Token: {token}"); var pdf = await response.Content.ReadAsByteArrayAsync(); await File.WriteAllBytesAsync("boleto.pdf", pdf); break; case 409: var repetido = await response.Content.ReadAsStringAsync(); Console.WriteLine("Erro: 409 boleto.tokenControleUsuario repetido"); Console.WriteLine(repetido); break; default: var erro = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Erro: {(int)response.StatusCode}"); Console.WriteLine(erro); break; } }}const https = require('https');const fs = require('fs');const querystring = require('querystring');
const data = querystring.stringify({ 'boleto.conta.token': 'api-key_SEU-TOKEN-DA-CONTA', 'boleto.tokenControleUsuario': 'pedido-12345-abc', 'boleto.cobrancaBancaria.registrar': 'false', 'boleto.emissao': '2024-01-15', 'boleto.vencimento': '2024-01-30', 'boleto.documento': 'PROP-001', 'boleto.titulo': 'DM', 'boleto.valor': '150.00', 'boleto.pagador.nome': 'Alberto Santos Dumont', 'boleto.pagador.cprf': '111.111.111-11', 'boleto.pagador.endereco.cep': '36240-000', 'boleto.pagador.endereco.uf': 'MG', 'boleto.pagador.endereco.localidade': 'Santos Dumont', 'boleto.pagador.endereco.bairro': 'Centro', 'boleto.pagador.endereco.logradouro': 'Rua Principal', 'boleto.pagador.endereco.numero': '100'});
const options = { hostname: 'sandbox.boletocloud.com', path: '/api/v1/boletos', method: 'POST', auth: 'api-key_SUA-API-KEY:token', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Content-Length': Buffer.byteLength(data) }};
const req = https.request(options, (res) => { if (res.statusCode === 201) { const token = res.headers['x-boletocloud-token']; console.log('Boleto criado (sem registro). Token:', token); res.pipe(fs.createWriteStream('boleto.pdf')); } else { let body = ''; res.on('data', chunk => body += chunk); res.on('end', () => { if (res.statusCode === 409) { console.log('Erro: 409 boleto.tokenControleUsuario repetido'); } else { console.log('Erro:', res.statusCode); } console.log(body); }); }});
req.write(data);req.end();package main
import ( "fmt" "io" "net/http" "net/url" "os" "strings")
func main() { data := url.Values{ "boleto.conta.token": {"api-key_SEU-TOKEN-DA-CONTA"}, "boleto.tokenControleUsuario": {"pedido-12345-abc"}, "boleto.cobrancaBancaria.registrar": {"false"}, "boleto.emissao": {"2024-01-15"}, "boleto.vencimento": {"2024-01-30"}, "boleto.documento": {"PROP-001"}, "boleto.titulo": {"DM"}, "boleto.valor": {"150.00"}, "boleto.pagador.nome": {"Alberto Santos Dumont"}, "boleto.pagador.cprf": {"111.111.111-11"}, "boleto.pagador.endereco.cep": {"36240-000"}, "boleto.pagador.endereco.uf": {"MG"}, "boleto.pagador.endereco.localidade": {"Santos Dumont"}, "boleto.pagador.endereco.bairro": {"Centro"}, "boleto.pagador.endereco.logradouro": {"Rua Principal"}, "boleto.pagador.endereco.numero": {"100"}, }
req, _ := http.NewRequest("POST", "https://sandbox.boletocloud.com/api/v1/boletos", strings.NewReader(data.Encode())) req.SetBasicAuth("api-key_SUA-API-KEY", "token") req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close()
switch resp.StatusCode { case 201: token := resp.Header.Get("X-BoletoCloud-Token") fmt.Println("Boleto criado (sem registro). Token:", token) file, _ := os.Create("boleto.pdf") defer file.Close() io.Copy(file, resp.Body) case 409: body, _ := io.ReadAll(resp.Body) fmt.Println("Erro: 409 boleto.tokenControleUsuario repetido") fmt.Println(string(body)) default: body, _ := io.ReadAll(resp.Body) fmt.Println("Erro:", resp.StatusCode) fmt.Println(string(body)) }}<?php$url = 'https://sandbox.boletocloud.com/api/v1/boletos';$api_key = 'api-key_SUA-API-KEY';
$data = http_build_query([ 'boleto.conta.token' => 'api-key_SEU-TOKEN-DA-CONTA', 'boleto.tokenControleUsuario' => 'pedido-12345-abc', 'boleto.cobrancaBancaria.registrar' => 'false', 'boleto.emissao' => '2024-01-15', 'boleto.vencimento' => '2024-01-30', 'boleto.documento' => 'PROP-001', 'boleto.titulo' => 'DM', 'boleto.valor' => '150.00', 'boleto.pagador.nome' => 'Alberto Santos Dumont', 'boleto.pagador.cprf' => '111.111.111-11', 'boleto.pagador.endereco.cep' => '36240-000', 'boleto.pagador.endereco.uf' => 'MG', 'boleto.pagador.endereco.localidade' => 'Santos Dumont', 'boleto.pagador.endereco.bairro' => 'Centro', 'boleto.pagador.endereco.logradouro' => 'Rua Principal', 'boleto.pagador.endereco.numero' => '100']);
$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $data);curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($ch, CURLOPT_USERPWD, "$api_key:token");curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);$headers = substr($response, 0, $header_size);$body = substr($response, $header_size);curl_close($ch);
if ($http_code == 201) { preg_match('/X-BoletoCloud-Token:\s*(.+)/i', $headers, $match); $token = trim($match[1] ?? ''); echo "Boleto criado (sem registro). Token: $token\n"; file_put_contents('boleto.pdf', $body);} elseif ($http_code == 409) { echo "Erro: 409 boleto.tokenControleUsuario repetido\n$body\n";} else { echo "Erro: $http_code\n$body\n";}?>import requestsfrom requests.auth import HTTPBasicAuth
response = requests.post( 'https://sandbox.boletocloud.com/api/v1/boletos', auth=HTTPBasicAuth('api-key_SUA-API-KEY', 'token'), data={ 'boleto.conta.token': 'api-key_SEU-TOKEN-DA-CONTA', 'boleto.tokenControleUsuario': 'pedido-12345-abc', 'boleto.cobrancaBancaria.registrar': 'false', 'boleto.emissao': '2024-01-15', 'boleto.vencimento': '2024-01-30', 'boleto.documento': 'PROP-001', 'boleto.titulo': 'DM', 'boleto.valor': '150.00', 'boleto.pagador.nome': 'Alberto Santos Dumont', 'boleto.pagador.cprf': '111.111.111-11', 'boleto.pagador.endereco.cep': '36240-000', 'boleto.pagador.endereco.uf': 'MG', 'boleto.pagador.endereco.localidade': 'Santos Dumont', 'boleto.pagador.endereco.bairro': 'Centro', 'boleto.pagador.endereco.logradouro': 'Rua Principal', 'boleto.pagador.endereco.numero': '100' })
if response.status_code == 201: token = response.headers.get('X-BoletoCloud-Token') print(f'Boleto criado (sem registro). Token: {token}') with open('boleto.pdf', 'wb') as f: f.write(response.content)elif response.status_code == 409: print('Erro: 409 boleto.tokenControleUsuario repetido') print(response.text)else: print(f'Erro: {response.status_code}') print(response.text)require 'net/http'require 'uri'
uri = URI('https://sandbox.boletocloud.com/api/v1/boletos')
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| request = Net::HTTP::Post.new(uri) request.basic_auth('api-key_SUA-API-KEY', 'token') request.set_form_data( 'boleto.conta.token' => 'api-key_SEU-TOKEN-DA-CONTA', 'boleto.tokenControleUsuario' => 'pedido-12345-abc', 'boleto.cobrancaBancaria.registrar' => 'false', 'boleto.emissao' => '2024-01-15', 'boleto.vencimento' => '2024-01-30', 'boleto.documento' => 'PROP-001', 'boleto.titulo' => 'DM', 'boleto.valor' => '150.00', 'boleto.pagador.nome' => 'Alberto Santos Dumont', 'boleto.pagador.cprf' => '111.111.111-11', 'boleto.pagador.endereco.cep' => '36240-000', 'boleto.pagador.endereco.uf' => 'MG', 'boleto.pagador.endereco.localidade' => 'Santos Dumont', 'boleto.pagador.endereco.bairro' => 'Centro', 'boleto.pagador.endereco.logradouro' => 'Rua Principal', 'boleto.pagador.endereco.numero' => '100' )
response = http.request(request) if response.code == '201' token = response['X-BoletoCloud-Token'] puts "Boleto criado (sem registro). Token: #{token}" File.write('boleto.pdf', response.body) elsif response.code == '409' puts 'Erro: 409 boleto.tokenControleUsuario repetido' puts response.body else puts "Erro: #{response.code}" puts response.body endend(require '[clj-http.client :as client])
(let [response (client/post "https://sandbox.boletocloud.com/api/v1/boletos" {:basic-auth ["api-key_SUA-API-KEY" "token"] :form-params {:boleto.conta.token "api-key_SEU-TOKEN-DA-CONTA" :boleto.tokenControleUsuario "pedido-12345-abc" :boleto.cobrancaBancaria.registrar "false" :boleto.emissao "2024-01-15" :boleto.vencimento "2024-01-30" :boleto.documento "PROP-001" :boleto.titulo "DM" :boleto.valor "150.00" :boleto.pagador.nome "Alberto Santos Dumont" :boleto.pagador.cprf "111.111.111-11" :boleto.pagador.endereco.cep "36240-000" :boleto.pagador.endereco.uf "MG" :boleto.pagador.endereco.localidade "Santos Dumont" :boleto.pagador.endereco.bairro "Centro" :boleto.pagador.endereco.logradouro "Rua Principal" :boleto.pagador.endereco.numero "100"} :as :byte-array :throw-exceptions false})] (case (:status response) 201 (let [token (get-in response [:headers "X-BoletoCloud-Token"])] (println "Boleto criado (sem registro). Token:" token) (clojure.java.io/copy (:body response) (clojure.java.io/file "boleto.pdf"))) 409 (do (println "Erro: 409 boleto.tokenControleUsuario repetido") (println (String. (:body response)))) (do (println "Erro:" (:status response)) (println (String. (:body response))))))2. Consultar Status do Registro
Seção intitulada “2. Consultar Status do Registro”Verifique se o banco já registrou o boleto ou se o registro foi rejeitado.
O 200 traz o JSON. Sem o plano Personalizado, a resposta é 403 com o código 8D1C5814 (Consultar Status do Registro). O 400 e o 404 aparecem no exemplo como tratamento defensivo: a referência desta rota documenta o 403.
codigo=$(curl -sS -o corpo.bin -w "%{http_code}" \ "https://sandbox.boletocloud.com/api/v1/boletos/{token_do_boleto}/registro" \ -u "api-key_SUA-API-KEY:token" \ -H "Accept: application/json")
if [ "$codigo" = "200" ]; then cat corpo.binelif [ "$codigo" = "403" ]; then echo "Erro: 403 sem o plano Personalizado" cat corpo.binelif [ "$codigo" = "400" ] || [ "$codigo" = "404" ]; then echo "Erro: $codigo" cat corpo.binelse echo "Erro: $codigo" cat corpo.binfiimport javax.ws.rs.client.ClientBuilder;import javax.ws.rs.core.Response;import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
public class ConsultaStatusRegistro { public static void main(String[] args) { String tokenBoleto = "TOKEN_DO_BOLETO"; Response response = ClientBuilder.newClient() .target("https://sandbox.boletocloud.com/api/v1/boletos") .path("/" + tokenBoleto + "/registro") .register(HttpAuthenticationFeature.basic("api-key_SUA-API-KEY", "token")) .request(APPLICATION_JSON) .get();
String corpo = response.readEntity(String.class); int status = response.getStatus(); if (status == 200) { System.out.println(corpo); } else if (status == 403) { System.out.println("Erro: 403 sem o plano Personalizado"); System.out.println(corpo); } else if (status == 400 || status == 404) { System.out.println("Erro: " + status); System.out.println(corpo); } else { System.out.println("Erro: " + status); System.out.println(corpo); } }}import okhttp3.Credentialsimport okhttp3.OkHttpClientimport okhttp3.Request
fun main() { val tokenBoleto = "TOKEN_DO_BOLETO" val client = OkHttpClient() val credential = Credentials.basic("api-key_SUA-API-KEY", "token")
val request = Request.Builder() .url("https://sandbox.boletocloud.com/api/v1/boletos/$tokenBoleto/registro") .header("Authorization", credential) .header("Accept", "application/json") .get() .build()
client.newCall(request).execute().use { response -> val corpo = response.body?.string() when (response.code) { 200 -> println(corpo) 403 -> { println("Erro: 403 sem o plano Personalizado") println(corpo) } 400, 404 -> { println("Erro: ${response.code}") println(corpo) } else -> { println("Erro: ${response.code}") println(corpo) } } }}using System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
class Program { static async Task Main(string[] args) { var tokenBoleto = "TOKEN_DO_BOLETO"; using var client = new HttpClient(); var credentials = Convert.ToBase64String( Encoding.ASCII.GetBytes("api-key_SUA-API-KEY:token")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync( $"https://sandbox.boletocloud.com/api/v1/boletos/{tokenBoleto}/registro"); var body = await response.Content.ReadAsStringAsync(); var status = (int)response.StatusCode;
if (status == 200) { Console.WriteLine(body); } else if (status == 403) { Console.WriteLine("Erro: 403 sem o plano Personalizado"); Console.WriteLine(body); } else if (status == 400 || status == 404) { Console.WriteLine($"Erro: {status}"); Console.WriteLine(body); } else { Console.WriteLine($"Erro: {status}"); Console.WriteLine(body); } }}const https = require('https');
const tokenBoleto = 'TOKEN_DO_BOLETO';const options = { hostname: 'sandbox.boletocloud.com', path: `/api/v1/boletos/${tokenBoleto}/registro`, method: 'GET', auth: 'api-key_SUA-API-KEY:token', headers: { 'Accept': 'application/json' }};
https.request(options, (res) => { let body = ''; res.on('data', chunk => body += chunk); res.on('end', () => { if (res.statusCode === 200) { console.log(JSON.parse(body)); } else if (res.statusCode === 403) { console.log('Erro: 403 sem o plano Personalizado'); console.log(body); } else if (res.statusCode === 400 || res.statusCode === 404) { console.log('Erro:', res.statusCode); console.log(body); } else { console.log('Erro:', res.statusCode); console.log(body); } });}).end();package main
import ( "fmt" "io" "net/http")
func main() { tokenBoleto := "TOKEN_DO_BOLETO" req, _ := http.NewRequest("GET", "https://sandbox.boletocloud.com/api/v1/boletos/"+tokenBoleto+"/registro", nil) req.SetBasicAuth("api-key_SUA-API-KEY", "token") req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) if resp.StatusCode == 200 { fmt.Println(string(body)) } else if resp.StatusCode == 403 { fmt.Println("Erro: 403 sem o plano Personalizado") fmt.Println(string(body)) } else if resp.StatusCode == 400 || resp.StatusCode == 404 { fmt.Printf("Erro: %d\n", resp.StatusCode) fmt.Println(string(body)) } else { fmt.Printf("Erro: %d\n", resp.StatusCode) fmt.Println(string(body)) }}<?php$tokenBoleto = 'TOKEN_DO_BOLETO';$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "https://sandbox.boletocloud.com/api/v1/boletos/$tokenBoleto/registro");curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($ch, CURLOPT_USERPWD, 'api-key_SUA-API-KEY:token');curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
$response = curl_exec($ch);$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);curl_close($ch);
if ($http_code == 200) { echo $response;} elseif ($http_code == 403) { echo "Erro: 403 sem o plano Personalizado\n$response\n";} elseif ($http_code == 400 || $http_code == 404) { echo "Erro: $http_code\n$response\n";} else { echo "Erro: $http_code\n$response\n";}?>import requestsfrom requests.auth import HTTPBasicAuth
token_boleto = 'TOKEN_DO_BOLETO'response = requests.get( f'https://sandbox.boletocloud.com/api/v1/boletos/{token_boleto}/registro', auth=HTTPBasicAuth('api-key_SUA-API-KEY', 'token'), headers={'Accept': 'application/json'})
if response.status_code == 200: print(response.json())elif response.status_code == 403: print('Erro: 403 sem o plano Personalizado') print(response.text)elif response.status_code in (400, 404): print(f'Erro: {response.status_code}') print(response.text)else: print(f'Erro: {response.status_code}') print(response.text)require 'net/http'require 'uri'require 'json'
token_boleto = 'TOKEN_DO_BOLETO'uri = URI("https://sandbox.boletocloud.com/api/v1/boletos/#{token_boleto}/registro")
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| request = Net::HTTP::Get.new(uri) request.basic_auth('api-key_SUA-API-KEY', 'token') request['Accept'] = 'application/json'
response = http.request(request) if response.code == '200' puts JSON.parse(response.body) elsif response.code == '403' puts 'Erro: 403 sem o plano Personalizado' puts response.body elsif ['400', '404'].include?(response.code) puts "Erro: #{response.code}" puts response.body else puts "Erro: #{response.code}" puts response.body endend(require '[clj-http.client :as client])
(let [token-boleto "TOKEN_DO_BOLETO" response (client/get (str "https://sandbox.boletocloud.com/api/v1/boletos/" token-boleto "/registro") {:basic-auth ["api-key_SUA-API-KEY" "token"] :accept :json :throw-exceptions false}) status (:status response) corpo (:body response)] (cond (= 200 status) (println corpo) (= 403 status) (do (println "Erro: 403 sem o plano Personalizado") (println corpo)) (#{400 404} status) (do (println "Erro:" status) (println corpo)) :else (do (println "Erro:" status) (println corpo))))Resposta
Seção intitulada “Resposta”Exemplo com o registro ainda sem confirmação do banco. Quando o banco confirma, registrado vem como data AAAA-MM-DD.
{ "status": { "token": "token_do_boleto", "registrado": null, "erro": null }}| Campo | Descrição |
|---|---|
token |
Token do boleto consultado |
registrado |
Data AAAA-MM-DD em que o boleto foi registrado. null se não foi registrado. Não compare com true |
erro |
Mensagem caso o registro tenha sido rejeitado. null se não houve erro |
3. Habilitar o Registro
Seção intitulada “3. Habilitar o Registro”Quando decidir habilitar o envio para registro, altere boleto.cobrancaBancaria.registrar pela API.
codigo=$(curl -sS -o corpo.bin -w "%{http_code}" \ -X PUT "https://sandbox.boletocloud.com/api/v1/boletos/{token_do_boleto}/registro" \ -u "api-key_SUA-API-KEY:token" \ -H "Content-Type: application/json; charset=utf-8" \ -d '{"boleto":{"cobrancaBancaria":{"registrar":true}}}')
if [ "$codigo" = "200" ]; then echo "Boleto habilitado para registro!"else echo "Erro: $codigo" cat corpo.binfiimport javax.ws.rs.client.ClientBuilder;import javax.ws.rs.client.Entity;import javax.ws.rs.core.Response;import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
public class AlterarRegistro { public static void main(String[] args) { String tokenBoleto = "TOKEN_DO_BOLETO"; String json = "{\"boleto\":{\"cobrancaBancaria\":{\"registrar\":true}}}";
Response response = ClientBuilder.newClient() .target("https://sandbox.boletocloud.com/api/v1/boletos") .path("/" + tokenBoleto + "/registro") .register(HttpAuthenticationFeature.basic("api-key_SUA-API-KEY", "token")) .request(APPLICATION_JSON) .put(Entity.entity(json, "application/json; charset=utf-8"));
if (response.getStatus() == 200) { System.out.println("Boleto habilitado para registro!"); } else { System.out.println("Erro: " + response.getStatus()); System.out.println(response.readEntity(String.class)); } }}import okhttp3.*import okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.RequestBody.Companion.toRequestBody
fun main() { val tokenBoleto = "TOKEN_DO_BOLETO" val client = OkHttpClient() val credential = Credentials.basic("api-key_SUA-API-KEY", "token") val json = """{"boleto":{"cobrancaBancaria":{"registrar":true}}}"""
val request = Request.Builder() .url("https://sandbox.boletocloud.com/api/v1/boletos/$tokenBoleto/registro") .header("Authorization", credential) .put(json.toRequestBody("application/json; charset=utf-8".toMediaType())) .build()
client.newCall(request).execute().use { response -> if (response.code == 200) { println("Boleto habilitado para registro!") } else { println("Erro: ${response.code}") println(response.body?.string()) } }}using System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
class Program { static async Task Main(string[] args) { var tokenBoleto = "TOKEN_DO_BOLETO"; using var client = new HttpClient(); var credentials = Convert.ToBase64String( Encoding.ASCII.GetBytes("api-key_SUA-API-KEY:token")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var json = "{\"boleto\":{\"cobrancaBancaria\":{\"registrar\":true}}}"; var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.ContentType = MediaTypeHeaderValue.Parse( "application/json; charset=utf-8");
var response = await client.PutAsync( $"https://sandbox.boletocloud.com/api/v1/boletos/{tokenBoleto}/registro", content);
if ((int)response.StatusCode == 200) { Console.WriteLine("Boleto habilitado para registro!"); } else { var erro = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Erro: {(int)response.StatusCode}"); Console.WriteLine(erro); } }}const https = require('https');
const tokenBoleto = 'TOKEN_DO_BOLETO';const data = JSON.stringify({ boleto: { cobrancaBancaria: { registrar: true } }});
const options = { hostname: 'sandbox.boletocloud.com', path: `/api/v1/boletos/${tokenBoleto}/registro`, method: 'PUT', auth: 'api-key_SUA-API-KEY:token', headers: { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(data) }};
const req = https.request(options, (res) => { if (res.statusCode === 200) { console.log('Boleto habilitado para registro!'); res.resume(); } else { let body = ''; res.on('data', chunk => body += chunk); res.on('end', () => { console.log('Erro:', res.statusCode); console.log(body); }); }});
req.write(data);req.end();package main
import ( "fmt" "io" "net/http" "strings")
func main() { tokenBoleto := "TOKEN_DO_BOLETO" json := `{"boleto":{"cobrancaBancaria":{"registrar":true}}}`
req, _ := http.NewRequest("PUT", "https://sandbox.boletocloud.com/api/v1/boletos/"+tokenBoleto+"/registro", strings.NewReader(json)) req.SetBasicAuth("api-key_SUA-API-KEY", "token") req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close()
if resp.StatusCode == 200 { fmt.Println("Boleto habilitado para registro!") } else { body, _ := io.ReadAll(resp.Body) fmt.Printf("Erro: %d\n", resp.StatusCode) fmt.Println(string(body)) }}<?php$tokenBoleto = 'TOKEN_DO_BOLETO';$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "https://sandbox.boletocloud.com/api/v1/boletos/$tokenBoleto/registro");curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');curl_setopt($ch, CURLOPT_POSTFIELDS, '{"boleto":{"cobrancaBancaria":{"registrar":true}}}');curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($ch, CURLOPT_USERPWD, 'api-key_SUA-API-KEY:token');curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json; charset=utf-8']);
$response = curl_exec($ch);$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);curl_close($ch);
if ($http_code == 200) { echo "Boleto habilitado para registro!\n";} else { echo "Erro: $http_code\n$response\n";}?>import requestsfrom requests.auth import HTTPBasicAuth
token_boleto = 'TOKEN_DO_BOLETO'response = requests.put( f'https://sandbox.boletocloud.com/api/v1/boletos/{token_boleto}/registro', auth=HTTPBasicAuth('api-key_SUA-API-KEY', 'token'), headers={'Content-Type': 'application/json; charset=utf-8'}, json={'boleto': {'cobrancaBancaria': {'registrar': True}}})
if response.status_code == 200: print('Boleto habilitado para registro!')else: print(f'Erro: {response.status_code}') print(response.text)require 'net/http'require 'uri'require 'json'
token_boleto = 'TOKEN_DO_BOLETO'uri = URI("https://sandbox.boletocloud.com/api/v1/boletos/#{token_boleto}/registro")
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| request = Net::HTTP::Put.new(uri) request.basic_auth('api-key_SUA-API-KEY', 'token') request['Content-Type'] = 'application/json; charset=utf-8' request.body = { boleto: { cobrancaBancaria: { registrar: true } } }.to_json
response = http.request(request) if response.code == '200' puts 'Boleto habilitado para registro!' else puts "Erro: #{response.code}" puts response.body endend(require '[clj-http.client :as client])
(let [token-boleto "TOKEN_DO_BOLETO" response (client/put (str "https://sandbox.boletocloud.com/api/v1/boletos/" token-boleto "/registro") {:basic-auth ["api-key_SUA-API-KEY" "token"] :content-type "application/json; charset=utf-8" :body "{\"boleto\":{\"cobrancaBancaria\":{\"registrar\":true}}}" :throw-exceptions false})] (if (= 200 (:status response)) (println "Boleto habilitado para registro!") (do (println "Erro:" (:status response)) (println (:body response)))))Resposta
Seção intitulada “Resposta”HTTP/1.1 200 OK| Código | HTTP | Tipo | Mensagem |
|---|---|---|---|
96660E9E | 400 | requisicao | O token identificador do boleto fornecido ({0}) está incorreto ou inválido. |
8D1C5814 | 403 | requisicao_nao_permitida | O usuário com token de acesso via API ({0}) não tem permissão para utilizar este recurso do plano personalizado. |
O 400 de JSON malformado fica sem código, como em Habilitar Boleto para Registro: JSON malformado (erro de parsing) ou requisição inválida. Verifique o formato do JSON.
A lista completa está em Códigos de erro.
