Conceder Abatimento no Boleto
Conceder Abatimento (PUT)
Seção intitulada “Conceder Abatimento (PUT)”Concede um abatimento (desconto incondicional) sobre o valor original do boleto. O abatimento reduz o valor a ser pago pelo cliente de forma permanente e é comunicado ao banco para atualização do registro.
O Que é Abatimento?
Seção intitulada “O Que é Abatimento?”O abatimento é uma redução no valor do boleto concedida após a emissão. Diferente do desconto (condicional, vinculado a prazo), o abatimento é um valor fixo que será deduzido do total, independentemente da data de pagamento.
| Característica | Desconto | Abatimento |
|---|---|---|
| Momento da definição | Na criação do boleto | Após criação/registro |
| Condicionalidade | Condicional (vinculado a prazo) | Incondicional |
| Aplicação | Automática se pago no prazo | Sempre aplicado |
| Uso típico | Incentivo a pagamento antecipado | Correção de valor, bonificação, acordo comercial |
Quando Usar
Seção intitulada “Quando Usar”Cenários Recomendados
Seção intitulada “Cenários Recomendados”| Cenário | Exemplo |
|---|---|
| Acordo comercial | Cliente negociou redução após a emissão |
| Devolução parcial | Parte do pedido foi devolvida/cancelada |
| Bonificação | Conceder crédito por fidelidade ou compensação |
| Correção de valor | Erro no valor original que precisa ser ajustado para menor |
| Renegociação | Ajuste de valor em processo de cobrança |
Pré-requisitos
Seção intitulada “Pré-requisitos”Antes de conceder abatimento, verifique:
- O boleto já está registrado no banco
- O boleto não foi baixado/cancelado
- O boleto não possui abatimento já concedido
- O valor do abatimento é menor que o valor do boleto
Ciclo de Vida do Boleto
Seção intitulada “Ciclo de Vida do Boleto”O abatimento pode ser concedido apenas em boletos no estado REGISTRADO/ATIVO:
┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐│ CRIADO │────▶│ REGISTRADO │────▶│ COM ABATIMENTO │└─────────────┘ │ ATIVO │ │ (valor reduzido) │ └──────┬──────┘ └──────────┬──────────┘ │ │ │ PUT /abatimento │ │◀──────────────────────┘ │ ┌────────────┼────────────┐ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌───────────┐ │ PAGO │ │ VENCIDO │ │ BAIXADO │ └──────────┘ └──────────┘ └───────────┘Endpoint
Seção intitulada “Endpoint”PUT https://sandbox.boletocloud.com/api/v1/boletos/{token_do_boleto}/abatimentoParâmetros de Path
Seção intitulada “Parâmetros de Path”| Parâmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
token_do_boleto | string | Sim | Token do boleto retornado na criação |
Headers
Seção intitulada “Headers”| Header | Valor |
|---|---|
Content-Type | application/json; charset=utf-8 |
Authorization | Basic {credenciais} |
Corpo da Requisição (JSON)
Seção intitulada “Corpo da Requisição (JSON)”{ "boleto": { "abatimento": { "valor": 10.00 } }}Campos do Abatimento
Seção intitulada “Campos do Abatimento”| Campo | Tipo | Obrigatório | Tamanho/Limite | Exemplo | Descrição |
|---|---|---|---|---|---|
boleto.abatimento.valor | decimal | Sim | 0.00 a 99.999.999,99 | 10.00 | Valor do abatimento em reais (8 inteiros + 2 decimais) |
Validações
Seção intitulada “Validações”| Validação | Regra | Mensagem de Erro |
|---|---|---|
| Obrigatório | Campo não pode ser nulo | Valor do abatimento é obrigatório |
| Valor mínimo | Mínimo 0.00 | Valor do abatimento deve ser maior ou igual a zero |
| Valor máximo | Máximo 99999999.99 | Valor do abatimento deve ser menor ou igual a 99.999.999,99 |
| Casas decimais | Máximo 2 casas decimais | Valor do abatimento deve ter no máximo 2 casas decimais |
| Menor que o boleto | Abatimento menor que valor do boleto | Abatimento não pode ser maior ou igual ao valor do boleto |
Códigos de Resposta
Seção intitulada “Códigos de Resposta”| Código | Descrição | Causa |
|---|---|---|
200 OK | Abatimento concedido com sucesso | - |
400 Bad Request | Requisição inválida | Valor inválido, boleto já tem abatimento, ou boleto baixado |
401 Unauthorized | Não autorizado | API Key inválida ou ausente |
404 Not Found | Boleto não encontrado | Token do boleto inválido |
500 Internal Server Error | Erro interno | Erro no servidor |
Exemplo de Erro
Seção intitulada “Exemplo de Erro”{ "erro": { "status": 400, "mensagem": "Boleto já possui abatimento concedido" }}Comportamento por Tipo de Comunicação
Seção intitulada “Comportamento por Tipo de Comunicação”| Tipo de Comunicação | O que acontece |
|---|---|
| API/Webservice (automático) | Abatimento enviado automaticamente ao banco |
| Arquivo CNAB (manual) | Instrução de abatimento incluída no próximo arquivo de remessa |
Exemplos de Código
Seção intitulada “Exemplos de Código”curl -v "https://sandbox.boletocloud.com/api/v1/boletos/{token_do_boleto}/abatimento" \ -H "Content-Type: application/json; charset=utf-8" \ -X "PUT" \ -u "api-key_SUA-API-KEY:token" \ -d '{"boleto":{"abatimento":{"valor":10.00}}}'import 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 ConcederAbatimento { public static void main(String[] args) { String tokenBoleto = "TOKEN_DO_BOLETO"; String json = "{\"boleto\":{\"abatimento\":{\"valor\":10.00}}}";
Response response = ClientBuilder.newClient() .target("https://sandbox.boletocloud.com/api/v1/boletos") .path("/" + tokenBoleto + "/abatimento") .register(HttpAuthenticationFeature.basic("api-key_SUA-API-KEY", "token")) .request(APPLICATION_JSON) .put(Entity.json(json));
if (response.getStatus() == 200) { System.out.println("Abatimento concedido com sucesso!"); } 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":{"abatimento":{"valor":10.00}}}"""
val request = Request.Builder() .url("https://sandbox.boletocloud.com/api/v1/boletos/$tokenBoleto/abatimento") .header("Authorization", credential) .put(json.toRequestBody("application/json".toMediaType())) .build()
client.newCall(request).execute().use { response -> if (response.code == 200) println("Abatimento concedido com sucesso!") else println("Erro: ${response.code} - ${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\":{\"abatimento\":{\"valor\":10.00}}}"; var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PutAsync( $"https://sandbox.boletocloud.com/api/v1/boletos/{tokenBoleto}/abatimento", content);
if ((int)response.StatusCode == 200) Console.WriteLine("Abatimento concedido com sucesso!"); else Console.WriteLine($"Erro: {(int)response.StatusCode}"); }}const https = require('https');
const tokenBoleto = 'TOKEN_DO_BOLETO';const data = JSON.stringify({boleto: {abatimento: {valor: 10.00}}});
const options = { hostname: 'sandbox.boletocloud.com', path: `/api/v1/boletos/${tokenBoleto}/abatimento`, 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) => { let body = ''; res.on('data', chunk => body += chunk); res.on('end', () => { if (res.statusCode === 200) console.log('Abatimento concedido com sucesso!'); else console.log(`Erro: ${res.statusCode} - ${body}`); });});
req.write(data);req.end();package main
import ( "fmt" "io" "net/http" "strings")
func main() { tokenBoleto := "TOKEN_DO_BOLETO" json := `{"boleto":{"abatimento":{"valor":10.00}}}` url := "https://sandbox.boletocloud.com/api/v1/boletos/" + tokenBoleto + "/abatimento"
req, _ := http.NewRequest("PUT", url, 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()
body, _ := io.ReadAll(resp.Body) if resp.StatusCode == 200 { fmt.Println("Abatimento concedido com sucesso!") } else { fmt.Printf("Erro: %d - %s\n", resp.StatusCode, string(body)) }}<?php$tokenBoleto = 'TOKEN_DO_BOLETO';$url = "https://sandbox.boletocloud.com/api/v1/boletos/$tokenBoleto/abatimento";$api_key = 'api-key_SUA-API-KEY';$data = json_encode(['boleto' => ['abatimento' => ['valor' => 10.00]]]);
$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');curl_setopt($ch, CURLOPT_POSTFIELDS, $data);curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($ch, CURLOPT_USERPWD, "$api_key:token");curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);curl_close($ch);
if ($http_code == 200) echo "Abatimento concedido com sucesso!\n";else echo "Erro ($http_code): $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}/abatimento', auth=HTTPBasicAuth('api-key_SUA-API-KEY', 'token'), json={'boleto': {'abatimento': {'valor': 10.00}}})
if response.status_code == 200: print('Abatimento concedido com sucesso!')else: print(f'Erro: {response.status_code} - {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}/abatimento")
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: {abatimento: {valor: 10.00}}}.to_json
response = http.request(request) if response.code == '200' puts 'Abatimento concedido com sucesso!' else puts "Erro: #{response.code} - #{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 "/abatimento") {:basic-auth ["api-key_SUA-API-KEY" "token"] :content-type :json :body "{\"boleto\":{\"abatimento\":{\"valor\":10.00}}}" :throw-exceptions false})] (if (= 200 (:status response)) (println "Abatimento concedido com sucesso!") (println "Erro:" (:status response) "-" (:body response))))Exemplo Prático
Seção intitulada “Exemplo Prático”Cenário: Devolução Parcial de Mercadoria
Seção intitulada “Cenário: Devolução Parcial de Mercadoria”Um cliente comprou R$ 500,00 em produtos, mas devolveu R$ 50,00. O boleto já foi emitido e registrado.
Antes do abatimento:
- Valor do boleto: R$ 500,00
Requisição:
{ "boleto": { "abatimento": { "valor": 50.00 } }}Depois do abatimento:
- Valor original: R$ 500,00
- Abatimento: R$ 50,00
- Valor a pagar: R$ 450,00
Veja Também
Seção intitulada “Veja Também” Alterar Vencimento Alterar a data de vencimento do boleto
Baixar/Cancelar Cancelar a cobrança do boleto
Arquivo de Remessa Integração via arquivo CNAB
Arquivo de Retorno Processar confirmações do banco