Class: Iugu::APIRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/iugu/api_request.rb

Class Method Summary collapse

Class Method Details

.build_request(method, url, data, authorization_token) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/iugu/api_request.rb', line 25

def self.build_request(method, url, data, authorization_token)
  data = data.to_json unless data[:multipart]
  {
    verify_ssl: true,
    headers: default_headers(authorization_token),
    method: method,
    payload: data,
    url: url,
    timeout: 30
  }
end

.default_headers(authorization_token) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/iugu/api_request.rb', line 51

def self.default_headers(authorization_token)
  token = authorization_token || Iugu.api_key
  {
    authorization: "Basic " + Base64.strict_encode64(token + ":"),
    accept: "application/json",
    accept_charset: "utf-8",
    user_agent: "Iugu RubyLibrary",
    accept_language: "pt-br;q=0.9,pt-BR",
    content_type: "application/json; charset=utf-8"
  }
end

.handle_response(response) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/iugu/api_request.rb', line 37

def self.handle_response(response)
  response_json = JSON.parse(response.body)
  raise ObjectNotFound if response_json.is_a?(Hash) && response_json["errors"] == "Not Found"

  if response_json.is_a?(Hash) && response_json["errors"] && response_json["errors"].length.positive?
    raise RequestWithErrors,
          response_json["errors"]
  end

  response_json
rescue JSON::ParserError
  raise RequestFailed
end

.request(method, url, data = {}, authorization_token = nil) ⇒ Object



9
10
11
12
13
# File 'lib/iugu/api_request.rb', line 9

def self.request(method, url, data = {}, authorization_token = nil)
  Iugu::Utils.auth_from_env if Iugu.api_key.nil?
  raise Iugu::AuthenticationException, "Chave de API não configurada. Utilize Iugu.api_key = ... para configurar." if Iugu.api_key.nil?
  handle_response send_request method, url, data, authorization_token
end

.send_request(method, url, data, authorization_token) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/iugu/api_request.rb', line 15

def self.send_request(method, url, data, authorization_token)
  RestClient::Request.execute build_request(method, url, data, authorization_token)
rescue RestClient::ResourceNotFound
  raise ObjectNotFound
rescue RestClient::UnprocessableEntity => e
  raise RequestWithErrors, JSON.parse(e.response)["errors"]
rescue RestClient::BadRequest => e
  raise RequestWithErrors, JSON.parse(e.response)["errors"]
end