class BS2::Connection

Public Class Methods

new() click to toggle source
# File lib/bs2.rb, line 39
def initialize
  # configuration.validate_config!
end

Public Instance Methods

cancel_billet(id, reason) click to toggle source
# File lib/bs2.rb, line 74
def cancel_billet(id, reason)
  connector = create_connector

  params = {
    justificativa: reason
  }

  resp = connector.post("/pj/forintegration/cobranca/v1/boletos/#{id}/solicitacoes/cancelamentos", params)

  resp.body
end
create_billet(data) click to toggle source
# File lib/bs2.rb, line 86
def create_billet(data)
  connector = create_connector

  resp = connector.post("/pj/forintegration/cobranca/v1/boletos/simplificado", data)

  return false unless resp.success?

  resp.body
end
create_connector(json = true) click to toggle source
# File lib/bs2.rb, line 43
def create_connector(json = true)
  create_token

  Faraday.new(BS2.configuration.endpoint) do |conn|
    conn.request :json
    conn.response :json if json
    conn.response :logger, BS2.configuration.logger, { headers: true, bodies: json }
    conn.adapter Faraday.default_adapter

    conn.authorization('Bearer', @access_token)
  end
end
create_token() click to toggle source
# File lib/bs2.rb, line 96
def create_token
  # TODO check if is expired
  connection = Faraday.new(BS2.configuration.endpoint) do |conn|
    conn.basic_auth(BS2.configuration.api_key, BS2.configuration.api_secret)
    conn.response :json
    conn.adapter Faraday.default_adapter
    # conn.response :logger, BS2.configuration.logger, { headers: true, bodies: true }
  end

  # TODO: test connection errors
  response = connection.post("/auth/oauth/v2/token", {
    grant_type: "password",
    scope: "forintegration",
    username: BS2.configuration.username || "d",
    password: BS2.configuration.password || "e"
  }.map { |(key, value)| "#{key}=#{value}" }.join("&"), { 'Accept': 'application/json' })

  body = response.body
  @access_token = body.fetch('access_token')
  @token_type = body.fetch('token_type')
  @expires_in = Time.now + body.fetch('expires_in').to_i
  @refresh_token = body.fetch('refresh_token')

  true
end
fetch_billet(id) click to toggle source
# File lib/bs2.rb, line 66
def fetch_billet(id)
  connector = create_connector

  resp = connector.get("/pj/forintegration/cobranca/v1/boletos/#{id}")

  resp.body
end
generate_pdf(id) click to toggle source
# File lib/bs2.rb, line 56
def generate_pdf(id)
  connector = create_connector(false)

  response = connector.get("/pj/forintegration/cobranca/v1/boletos/#{id}/imprimivel")

  return false unless response.success?

  response.body
end