Obter PDF do Batch
Obter PDF do Batch (GET)
Seção intitulada “Obter PDF do Batch (GET)”Recupera o PDF consolidado do batch com todos os boletos (1 por página). Este é o segundo passo após criar o batch.
O Que Este Endpoint Faz
Seção intitulada “O Que Este Endpoint Faz”- Recebe o token do lote
- Recupera os boletos associados
- Gera o PDF consolidado (1 boleto por página)
- Retorna o arquivo PDF pronto para impressão
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐│ GET /batch/ │─────▶│ Recuperar │─────▶│ Gerar PDF ││ boletos/{token} │ │ boletos │ │ consolidado │└──────────────────┘ └──────────────────┘ └──────────────────┘ │ ▼ ┌──────────────────────┐ │ Retornar PDF │ │ (application/pdf) │ └──────────────────────┘Quando Usar
Seção intitulada “Quando Usar”| Cenário | Descrição |
|---|---|
| Após criar lote | Obter o PDF consolidado logo após POST /batch/boletos |
| Reimpressão | Reimprimir lote completo usando o token salvo |
| Download por demanda | Permitir que o usuário baixe o lote via sistema |
Endpoint
Seção intitulada “Endpoint”GET https://sandbox.boletocloud.com/api/v1/batch/boletos/{token}| Ambiente | URL Base |
|---|---|
| Sandbox | https://sandbox.boletocloud.com/api/v1/batch/boletos/{token} |
| Produção | https://app.boletocloud.com/api/v1/batch/boletos/{token} |
Requisição
Seção intitulada “Requisição”Parâmetros de Path
Seção intitulada “Parâmetros de Path”| Parâmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
token | string | Sim | Token do lote retornado na criação (batch.token ou header X-BoletoCloud-Token) |
Headers
Seção intitulada “Headers”| Header | Valor | Obrigatório |
|---|---|---|
Authorization | Basic {credenciais_base64} | Sim |
Respostas
Seção intitulada “Respostas”200 OK — Sucesso
Seção intitulada “200 OK — Sucesso”O PDF do lote foi gerado com sucesso.
Headers da Resposta (200)
Seção intitulada “Headers da Resposta (200)”| Header | Descrição | Exemplo |
|---|---|---|
Content-Type | Tipo do conteúdo | application/pdf; charset=UTF-8 |
Content-Disposition | Nome sugerido para download | attachment; filename="boletos.pdf" |
X-BoletoCloud-Version | Versão da plataforma | 2.0.0 |
Body da Resposta (200)
Seção intitulada “Body da Resposta (200)”O body contém o arquivo PDF binário do lote, com 1 boleto por página, pronto para impressão.
404 Not Found — Token Não Encontrado
Seção intitulada “404 Not Found — Token Não Encontrado”Retornado quando o token informado não corresponde a nenhum lote.
{ "erro": { "status": 404, "tipo": "nao_encontrado", "causas": [ { "codigo": "XXXXXXXX", "mensagem": "Recurso não encontrado.", "suporte": "https://developers.boleto.cloud/" } ] }}401 Unauthorized — Autenticação Inválida
Seção intitulada “401 Unauthorized — Autenticação Inválida”Retornado quando as credenciais de autenticação são inválidas.
Exemplos de Código
Seção intitulada “Exemplos de Código”curl -v "https://sandbox.boletocloud.com/api/v1/batch/boletos/{token_do_batch}" \ -u "api-key_SUA-API-KEY:token" \ -o boletos-batch.pdfimport javax.ws.rs.client.ClientBuilder;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 javax.ws.rs.core.MediaType.WILDCARD;import static javax.ws.rs.core.Response.Status.OK;import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class BuscarPdfBatch { public static void main(String[] args) throws Exception { String batchToken = "TOKEN_DO_BATCH";
Response response = ClientBuilder.newClient() .target("https://sandbox.boletocloud.com/api/v1/batch/boletos") .path("/" + batchToken) .register(HttpAuthenticationFeature.basic("api-key_SUA-API-KEY", "token")) .request(WILDCARD) .get();
if (response.getStatus() == OK.getStatusCode()) { Files.copy(response.readEntity(InputStream.class), Paths.get("boletos-batch.pdf"), REPLACE_EXISTING); System.out.println("PDF do batch salvo com sucesso!"); } else { System.out.println("Erro: " + response.getStatus()); } }}import okhttp3.*import java.io.File
fun main() { val client = OkHttpClient() val credential = Credentials.basic("api-key_SUA-API-KEY", "token") val batchToken = "TOKEN_DO_BATCH"
val request = Request.Builder() .url("https://sandbox.boletocloud.com/api/v1/batch/boletos/$batchToken") .header("Authorization", credential) .get() .build()
client.newCall(request).execute().use { response -> if (response.code == 200) { File("boletos-batch.pdf").writeBytes(response.body!!.bytes()) println("PDF do batch salvo com sucesso!") } else { println("Erro: ${response.code}") } }}using System;using System.IO;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 batchToken = "TOKEN_DO_BATCH"; var response = await client.GetAsync( $"https://sandbox.boletocloud.com/api/v1/batch/boletos/{batchToken}");
if (response.IsSuccessStatusCode) { var bytes = await response.Content.ReadAsByteArrayAsync(); await File.WriteAllBytesAsync("boletos-batch.pdf", bytes); Console.WriteLine("PDF do batch salvo com sucesso!"); } else { Console.WriteLine($"Erro: {(int)response.StatusCode}"); } }}const https = require('https');const fs = require('fs');
const batchToken = 'TOKEN_DO_BATCH';
const options = { hostname: 'sandbox.boletocloud.com', path: `/api/v1/batch/boletos/${batchToken}`, method: 'GET', auth: 'api-key_SUA-API-KEY:token'};
const req = https.request(options, (res) => { if (res.statusCode === 200) { const file = fs.createWriteStream('boletos-batch.pdf'); res.pipe(file); file.on('finish', () => console.log('PDF do batch salvo com sucesso!')); } else { console.log(`Erro: ${res.statusCode}`); }});
req.end();package main
import ( "fmt" "io" "net/http" "os")
func main() { batchToken := "TOKEN_DO_BATCH" req, _ := http.NewRequest("GET", "https://sandbox.boletocloud.com/api/v1/batch/boletos/"+batchToken, nil) req.SetBasicAuth("api-key_SUA-API-KEY", "token")
resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close()
if resp.StatusCode == 200 { file, _ := os.Create("boletos-batch.pdf") defer file.Close() io.Copy(file, resp.Body) fmt.Println("PDF do batch salvo com sucesso!") } else { fmt.Printf("Erro: %d\n", resp.StatusCode) }}<?php$batch_token = 'TOKEN_DO_BATCH';$url = "https://sandbox.boletocloud.com/api/v1/batch/boletos/$batch_token";$api_key = 'api-key_SUA-API-KEY';
$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_USERPWD, "$api_key:token");curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$response = curl_exec($ch);$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);curl_close($ch);
if ($http_code == 200) { file_put_contents("boletos-batch.pdf", $response); echo "PDF do batch salvo com sucesso!\n";} else { echo "Erro: $http_code\n";}?>import requestsfrom requests.auth import HTTPBasicAuth
batch_token = 'TOKEN_DO_BATCH'
response = requests.get( f'https://sandbox.boletocloud.com/api/v1/batch/boletos/{batch_token}', auth=HTTPBasicAuth('api-key_SUA-API-KEY', 'token'))
if response.status_code == 200: with open('boletos-batch.pdf', 'wb') as f: f.write(response.content) print('PDF do batch salvo com sucesso!')else: print(f'Erro: {response.status_code}')require 'net/http'require 'uri'
batch_token = 'TOKEN_DO_BATCH'uri = URI("https://sandbox.boletocloud.com/api/v1/batch/boletos/#{batch_token}")
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')
response = http.request(request) if response.code == '200' File.write('boletos-batch.pdf', response.body) puts 'PDF do batch salvo com sucesso!' else puts "Erro: #{response.code}" endend(require '[clj-http.client :as client])
(let [batch-token "TOKEN_DO_BATCH" response (client/get (str "https://sandbox.boletocloud.com/api/v1/batch/boletos/" batch-token) {:basic-auth ["api-key_SUA-API-KEY" "token"] :as :byte-array :throw-exceptions false})] (if (= 200 (:status response)) (do (clojure.java.io/copy (:body response) (clojure.java.io/file "boletos-batch.pdf")) (println "PDF do batch salvo com sucesso!")) (println "Erro:" (:status response))))Boletos Individuais
Seção intitulada “Boletos Individuais”Além do PDF consolidado, você pode acessar cada boleto individualmente usando o token retornado na criação:
| Operação | Endpoint | Descrição |
|---|---|---|
| Segunda via | GET /boletos/{token} | PDF de um boleto específico |
| Status do registro | GET /boletos/{token}/registro | Verificar se foi registrado |
| Baixa | PUT /boletos/{token}/baixa | Cancelar boleto específico |
Veja Também
Seção intitulada “Veja Também” Criar Lote de Boletos Primeira etapa: criar o lote e receber os tokens
Buscar Boleto Individual Obter PDF de um boleto específico
Status do Registro Verificar se boleto foi registrado no banco
Criar Carnê Alternativa com 3 boletos por página