brcobranca Ruby Gem
repository·master·Indexed 18 days ago
https://github.com/kivanio/brcobrancaA Ruby gem for managing the issuance and processing of Brazilian bank slips (boletos). It supports various banking institutions and handles complex CNAB file formats for both 'Remessa' (sending payment instructions to the bank) and 'Retorno' (processing bank responses). The library includes modules for boleto generation, remittance file creation, and return file handling, with support for multiple banks including Banco do Brasil, Itaú, Bradesco, and Santander.
What's inside brcobranca
- brcobranca is a Ruby gem designed for the issuance of bank slips (boletos de cobrança) for Brazilian banks. It supports various banking institutions, handling different CNAB (Centro Nacional de Automação Bancária) formats for both 'Remessa' (sending files to the bank) and 'Retorno' (receiving files from the bank).
Use the brcobranca API Server
masterIf you prefer not to use the gem directly in your application, you can use theboleto_cnab_apiserver created by Akretion, which provides an API interface for brcobranca functionality.Overview of Brcobranca modules
masterThe
Brcobrancagem is organized into several functional modules:Brcobranca::Boleto: Contains classes for different Brazilian banks (e.g.,BancoBrasil,Itau,Bradesco,Santander,Caixa, etc.) and templates (e.g.,Rghost,RghostCarne,RghostBolepix).Brcobranca::Retorno: Handles bank return files (e.g.,RetornoCbr643,RetornoCnab240,RetornoCnab400).Brcobranca::Remessa: Generates remittance files for payments and Pix, supporting various formats likeCnab400,Cnab240, andCnab444.Brcobranca::Util: Provides utility classes likeEmpresaandErrors.
Calculate bank verification digits using Brcobranca::Calculo
masterThe
Brcobranca::Calculomodule provides mathematical utilities for calculating verification digits (check digits) according to BACEN (Central Bank of Brazil) standards. This module is mixed intoStringandNumericclasses, allowing you to call these methods directly on numbers or numeric strings.Available Methods
modulo10: Calculates the Modulo 10 verification digit.modulo11(options = {}): Calculates the Modulo 11 verification digit. Supports custom multipliers and value mapping (e.g., mapping10to'X').duplo_digito: Calculates a double verification digit using both Modulo 10 and Modulo 11 logic.is_number?: Validates if the object contains only numeric characters.soma_digitos: Sums the digits of a positive integer (used internally for digit reduction).multiplicador(options = {}): Performs multiplication by a set of factors, useful for custom checksum algorithms.
Error Handling
Most methods will raise an
ArgumentErrorif the receiver is not a valid integer or number.require 'brcobranca' # Example: Modulo 10 number = 12345 puts number.modulo10 # Example: Modulo 11 with mapping (e.g., 10 -> 'X') puts "12345".modulo11(mapeamento: { 10 => 'X' }) # Example: Double digit puts 12345.duplo_digitoUse dynamic format methods in Rghost2
masterThe
Rghost2module implementsmethod_missingto allow calling dynamic methods for any valid format supported byrghost. Any method starting withto_will be interpreted as a request to generate the boleto in that specific format.Example:
boleto.to_pdfis equivalent toboleto.to(:pdf)boleto.to_pngis equivalent toboleto.to(:png)
# Example of dynamic method usage @boleto.to_pdf #=> boleto generated in pdf format @boleto.to_gif #=> boleto generated in gif formatHandle Boleto and Remessa validation errors
masterWhen generating boletos or remessa files, the gem may raise specific exceptions if the provided data is invalid. You can rescue these exceptions to access the validation errors.
Brcobranca::BoletoInvalido: Raised when data provided for a boleto is invalid. The exception message contains the joined error messages.Brcobranca::RemessaInvalida: Raised when data provided for a remessa file is invalid.
To access the specific error messages, you can rescue the exception and call
.errorson the exception object (which internally uses the object's validation messages).# For Boletos begin # code to generate boleto rescue Brcobranca::BoletoInvalido => invalido puts invalido.errors end # For Remessa begin # code to generate remessa rescue Brcobranca::RemessaInvalida => invalido puts invalido.errors endConfigure Brcobranca settings
masterYou can customize the global configuration of the
Brcobrancagem using thesetupblock. This is typically done in a Rails initializer or a configuration file.Available configuration options in
Brcobranca::Configuration:gerador: The generator used (Default::rghost).formato: The file format for the generated boleto (Default::pdf). Supported formats depend on the generator (e.g.,:gif).resolucao: The pixel resolution of the generated file (Default:150).external_encoding: The encoding for text sent to GhostScript (Default:'ascii-8bit'). Using'ascii-8bit'helps avoid issues with accents and special characters.
Brcobranca.setup do |config| config.formato = :gif config.resolucao = 300 endConfigure Rghost external encoding
masterTheBrcobranca::Boleto::Template::Rghostmodule automatically configuresRGhost::Config::GS[:external_encoding]using the value set inBrcobranca.configuration.external_encoding. It also appends-dNOSAFERto the default Ghostscript parameters for compatibility.Available Banks and Supported Wallets
masterThe gem supports a wide range of Brazilian banks. Below is a list of supported institutions and their available wallet types (carteiras):
Bank Code Bank Name Supported Wallets 001 Banco do Brasil All wallets in documentation 004 Banco do Nordeste All wallets in documentation 021 Banestes All wallets in documentation 033 Santander All wallets in documentation 041 Banrisul All wallets in documentation 070 Banco de Brasília All wallets in documentation 104 Caixa All wallets in documentation 237 Bradesco All wallets in documentation 341 Itaú All wallets in documentation 399 HSBC CNR, CSB 748 Sicredi C (03) 756 Sicoob All wallets in documentation 085 AILOS All wallets in documentation 136 Unicred 21 097 CREDISIS All wallets in documentation 745 Citibank 3 Supported CNAB Formats for Remessa and Retorno
masterWhen integrating with banks, you need to know which CNAB formats (e.g., 400, 240, 444) are supported for sending files (Remessa) and receiving files (Retorno).
| Bank | Retorno | Remessa | | ----------------- | ------------------- | --------------------- | | Banco do Brasil | 400 (ou CBR643) | 400 (ou CBR641) e 240 | | Banco do Nordeste | 400 | 400 | | Banco de Brasília | 400 | 400 | | Banestes | Não | Não | | Banrisul | 400 | 400 | | Bradesco | 400 | 400 | | Caixa | 240 | 240 | | Citibank | Não | 400 | | HSBC | Não | Não | | Itaú | 400 | 400 e 444 | | Santander | 400 e 240 | 400 e 240 | | Sicoob | 240 | 400 e 240 | | Sicredi | 240 | 240 | | UNICRED | 400 | 400 e 240 | | AILOS | 240 | 240 | | CREDISIS | 400 | 400 |Use dynamic format methods (to_pdf, to_jpg, etc.)
masterThe
Rghosttemplate module implementsmethod_missingto provide convenient dynamic methods for every supported format. Instead of calling.to(:format), you can call.to_formatdirectly on a boleto instance.Example:
boleto.to_pdfgenerates a PDF.boleto.to_jpggenerates a JPG.boleto.to_pnggenerates a PNG.
# Using dynamic methods for convenience pdf_stream = boleto.to_pdf jpg_stream = boleto.to_jpgGenerate Ailos barcode second part
masterThe
codigo_barras_segunda_partemethod returns the 25-character numeric string required for the second part of the Ailos barcode. It is composed of theconvenio, thenosso_numero_boleto, and thecarteira.# Returns a 25-character numeric string boleto.codigo_barras_segunda_parte