Git Product home page Git Product logo

boletosimples-ruby's Introduction

Boleto Simples Ruby

Gem Version Ruby

Biblioteca Ruby para acessar informações da Kobana através da API.

Instalação

Adicione a linha a baixo no seu Gemfile:

gem 'boletosimples'

Execute:

$ bundle install

Ou instale você mesmo:

$ gem install boletosimples

Configuração

Saiba mais sobre o Token de API

require 'boletosimples'

BoletoSimples.configure do |c|
  c.environment = :production # defaut :sandbox
  # production - https://app.kobana.com.br/conta/api/tokens
  # sandbox - https://app-sandbox.kobana.com.br/conta/api/tokens
  c.api_token = 'api-token'
  c.user_agent = '[email protected]' #Colocar um e-mail válido para contatos técnicos relacionado ao uso da API.
  # c.debug = true
  # c.custom_headers = { 'X-CUSTOM' => 'CONTENT' }
end

Variáveis de ambiente

Você também pode configurar as variáveis de ambiente a seguir e não será necessário chamar BoletoSimples.configure

ENV['BOLETOSIMPLES_ENV']
ENV['BOLETOSIMPLES_API_TOKEN']
ENV['BOLETOSIMPLES_DEBUG']

Configurando cache

É altamente recomendável utilizar o cache para evitar chegar no limite de requisições

Para isso recomendamos a utilização da gem Dalli

Exemplo:

  require 'dalli'

  BoletoSimples.configure do |c|
    c.cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, ['localhost:11211'],
                                              namespace: 'boletosimples_client',
                                              compress: true)
  end

Exemplos

Boletos Bancários

# Criar um boleto
@bank_billet = BoletoSimples::BankBillet.create(
  amount: 9.01,
  description: 'Despesas do contrato 0012',
  expire_at: '2014-01-01',
  customer_address: 'Rua quinhentos',
  customer_address_complement: 'Sala 4',
  customer_address_number: '111',
  customer_city_name: 'Rio de Janeiro',
  customer_cnpj_cpf: '012.345.678-90',
  customer_email: '[email protected]',
  customer_neighborhood: 'Sao Francisco',
  customer_person_name: 'Joao da Silva',
  customer_person_type: 'individual',
  customer_phone_number: '2112123434',
  customer_state: 'RJ',
  customer_zipcode: '12312-123'
)

# Criar um novo boleto instanciando o objeto
@bank_billet = BoletoSimples::BankBillet.new(amount: 199.99, expire_at: '2020-01-01')
@bank_billet.description = 'Cobrança XPTO'
@bank_billet.save

# Mensagens de erro na criação do boleto
@bank_billet = BoletoSimples::BankBillet.create(amount: 199.99)
@bank_billet.response_errors
  # {:expire_at=>["não pode ficar em branco", "não é uma data válida"], :customer_person_name=>["não pode ficar em branco"], :customer_cnpj_cpf=>["não pode ficar em branco", "não é um CPNJ ou CPF válido"], :description=>["não pode ficar em branco"], :customer_zipcode=>["não pode ficar em branco"]

# Pegar informações de um boleto
@bank_billet = BoletoSimples::BankBillet.find(1) # onde 1 é o id do boleto.

 # Se o não for encontrado nenhum boleto com o id informado, uma exceção será levantada com a mensagem:
 # Couldn't find BankBillet with 'id'=1

# Listar os boletos
@bank_billets = BoletoSimples::BankBillet.all(page: 1, per_page: 50)
@bank_billets.each do |bank_billet|
  puts bank_billet.attributes
end

# Cancelar um boleto
@bank_billet = BoletoSimples::BankBillet.cancel(id: 1)

Clientes

# Criar um cliente
@customer = BoletoSimples::Customer.create(
  person_name: "Joao da Silva",
  cnpj_cpf: "012.345.678-90",
  email: "[email protected]",
  address: "Rua quinhentos",
  city_name: "Rio de Janeiro",
  state: "RJ",
  neighborhood: "bairro",
  zipcode: "12312-123",
  address_number: "111",
  address_complement: "Sala 4",
  phone_number: "2112123434"
)

# Mensagens de erro na criação do cliente
@customer = BoletoSimples::Customer.new(person_name: '')
@customer.response_errors
  # {:person_name=>["não pode ficar em branco"], :cnpj_cpf=>["não pode ficar em branco"], :zipcode=>["não pode ficar em branco"]}

# Listar os clientes
@customers = BoletoSimples::Customer.all(page: 1, per_page: 50)
@customers.each do |customer|
  puts customer.attributes
end

# Atualizar um cliente
@customer = BoletoSimples::Customer.find(1)
@customer.person_name = 'Novo nome'
@customer.save

boletosimples-ruby's People

Contributors

dirceu-jr avatar kivanio avatar marcioj avatar rafaelp avatar thiagodiniz avatar tiutalk avatar williamweckl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

boletosimples-ruby's Issues

Is oAuth2 obligatory?

Hello guys!

In my current use case, we don't need to access any user's info. I'm trying to use the SDK only with the API KEY. Is it possible? I've set the ENV for it, and when trying to make some request I'm receiving a 401 error. Ps.: I'm using the sandbox environment.

Thanks!!

Suporte para geração de Remessas para boletos registrados

Pessoal, a empresa que trabalhou é cliente de vocês e gostaria de saber se a biblioteca suporta a geração de remessas para registro de boletos? Consigo fazer via o site boleto simples mas nao encontra na plataforma.

Caso nao haja suporte no momento, poderima me informar se esta no roadmap de vcs ?

Ainda, tem algum webservice disponivel para isso? Podem indicar documentacoes?

Obg

Erro na criação do cliente

Na chamada
BoletoSimples::Customer.create({
person_name: "Joao da Silva", cnpj_cpf: "782.661.177-64", email: "[email protected]",
address: "Rua quinhentos", city_name: "Rio de Janeiro",
state: "RJ", neighborhood: "bairro",
zipcode: "20071004", address_number: "111", address_complement: "Sala 4",
phone_number: "2112123434", contact_person: "Nome do Contato", truncated_address:"Rua quinhentos", external_code:"12345678"
})

recebo o seguinte retorno

Response from the API must behave like a Hash or an Array (last JSON response was "\n<html xmlns="http://www.w3.org/1999/xhtml\" xml:lang="pt">\n\n <meta http-equiv="content-type" content="text/html;charset=utf-8"/>\n <link rel="SHORTCUT ICON" href="https://boletosimples.s3.amazonaws.com/maintenance/favicon.ico\"/>\n <style type="text/css" media="all"></style>\n <title>Boleto Simples: P\xC3\xA1gina n\xC3\xA3o encontrada</title>\n\n\n<div class="dialog">\n\n <div style="padding: 20px" class="content">\n\n

\n <img src="https://boletosimples.s3.amazonaws.com/maintenance/logo.png\"\n alt="Boleto Simples - https://boletosimples.com.br\" width="229" height="39"\n style="margin-top: 2em"/>\n

\n\n\n <p style="margin-bottom: 3em;">WOW! P\xC3\xA1gina N\xC3\xA3o Encontrada (Erro 404) :-(

\n\n

A p\xC3\xA1gina requisitada n\xC3\xA3o existe.

\n\n

Voc\xC3\xAA pode ter usado um endere\xC3\xA7o antigo, ou ter digitado incorretamente na Barra de Endere\xC3\xA7o do seu\n programa.

\n\n

Por favor, verifique o endere\xC3\xA7o digitado ou tente <a href="https://boletosimples.com.br/\">nosso site

\n\n

Caso voc\xC3\xAA esteja certo do endere\xC3\xA7o e este erro insista em aparecer, fique \xC3\xA0 vontade para nos <a\n href="http://suporte.boletosimples.com.br/\">avisar pelo suporte.

\n\n

Desejando a sua compreens\xC3\xA3o,
\n Equipe do Boleto Simples

\n\n \n\n <div style='margin-top: 3em; padding: 20px' class="foot">\n\n <p style="margin: 0;">Copyright\xC2\xA9 <a href="http://boletosimples.com.br\"\n style="color: cornflowerblue; text-decoration: none">Boleto Simples.

\n\n \n\n\n\n\n\n")

A gem não funciona no Rails versão 5.2

Olá,

Acabei de testar a gem de vocês em um projeto com Rails 5.2 e não está funcionando, aparentemente é um problenma relacionado ao Her, tem um PR aberto lá por isso: remi/her#492, será necessário fazer um update da gem de vocês pra utilizar a versão nova do Her, quando ela sair.

Uma amostra do output:

  68) BoletoSimples::Discharge all
      Failure/Error: it { expect(subject.first).to be_a_kind_of(BoletoSimples::Discharge) }

      NoMethodError:
        undefined method `changed?' for nil:NilClass
      # ./spec/boletosimples/resources/discharge_spec.rb:15:in `block (3 levels) in <top (required)>'

  69) BoletoSimples::Transaction all
      Failure/Error: it { expect(subject.first).to be_a_kind_of(BoletoSimples::Transaction) }

      NoMethodError:
        undefined method `changed?' for nil:NilClass
      # ./spec/boletosimples/resources/transactions_spec.rb:15:in `block (3 levels) in <top (required)>'

  70) BoletoSimples::Remittance all
      Failure/Error: it { expect(subject.first).to be_a_kind_of(BoletoSimples::Remittance) }

      NoMethodError:
        undefined method `changed?' for nil:NilClass
      # ./spec/boletosimples/resources/remittance_spec.rb:15:in `block (3 levels) in <top (required)>'

OAuthClient not working for some endpoints

Using oauth make some endpoints not work properly.

Given a client with these credentials:

c = BoletoSimples::OAuthClient.new(
  '1bcdbb3a2516a28f7f99f7a9a55430b4e22992c64c3b153a6f85b8cc8a501c8e', 
  'f0ea63a227fd9f7bb6df6f1454bf4cea2731a1c651aa1c35ed79f3403aa7347a', 
  { token: '9272f108adca48f22f562ea17eb248cd6ab466c9c182429e484119e7d815d531' }, 
  { user_agent: 'Meu e-Commerce ([email protected])', base_uri: 'https://staging.boletosimples.com.br/api/v1' }
)

And running c.userinfo, returns the json {"id"=>42, "login_url"=>"https://staging.boletosimples.com.br/welcome?email=marciojunior1991%40gmail.com&token=iTxyZSpHLGeaAxtiUsJR"}

But c.customers returns a string with a space (" ") so will throw an error in JSON.parse

Método "cancel" não está sendo reconhecido V.1.0.4

Agora o Find está funcionando, no entanto o método cancel parou também. segue o script de teste.

...0> @bank_billet.cancel
=> undefined method `cancel' for #BoletoSimples::BankBillet:0x00007fe3e74ae9f8
Did you mean? ...

Erro em find BoletoSimples::BankBillet.find

Ao Atualiza a gema e fazer teste, ao executar o find do método, recebo o seguinte erro

0> self.boleto_simples_id
=> 8220255

0> BoletoSimples::BankBillet.find(self.boleto_simples_id)
Cache read: afbf0ddef9ffc775cddf61090d10e4125c491057
Cache read: afbf0ddef9ffc775cddf61090d10e4125c491057
Cache write: afbf0ddef9ffc775cddf61090d10e4125c491057
=> undefined method `[]' for nil:NilClass

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.