Module: ChargeBee::Rest

Defined in:
lib/chargebee/rest.rb

Class Method Summary collapse

Class Method Details

.handle_for_error(e, rcode = nil, rbody = nil) ⇒ Object

Raises:



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/chargebee/rest.rb', line 75

def self.handle_for_error(e, rcode=nil, rbody=nil)
  if(rcode == 204)
    raise APIError.new("No response returned by the chargebee api", rcode)
  end
  begin
    error_obj = JSON.parse(rbody)
    error_obj = Util.symbolize_keys(error_obj)
  rescue JSON::ParseError
    raise APIError.new("Invalid JSON response #{rbody.inspect} received with HTTP response code #{rcode}", rcode, rbody)
  end
  raise APIError.new(error_obj.to_s, rcode, rbody, error_obj)
end

.request(method, url, env, params = nil) ⇒ Object

Raises:



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/chargebee/rest.rb', line 7

def self.request(method, url, env, params=nil)
  raise APIError.new('No environment configured.') unless env
  api_key = env.api_key
  headers = {}
  
  if(ChargeBee.verify_ca_certs?)
    ssl_opts = {
      :verify_ssl => OpenSSL::SSL::VERIFY_PEER,
      :ssl_ca_file => ChargeBee.ca_cert_path
    }
  else
    ssl_opts = {
      :verify_ssl => false
    }
  end
  case method.to_s.downcase.to_sym
  when :get, :head, :delete
    headers = { :params => params }.merge(headers)
    payload = nil
  else
    payload = params
  end
  
  user_agent = "Chargebee-Ruby-Client v#{ChargeBee::VERSION}"
  headers = { 
    "User-Agent" => user_agent,
    :accept => :json 
    }.merge(headers)      
  opts = {
    :method => method,
    :url => env.api_url(url),
    :user => api_key,
    :headers => headers,
    :payload => payload,
    :open_timeout => 50,
    :timeout => 100
    }.merge(ssl_opts)
    
  begin
    response = RestClient::Request.execute(opts)
  rescue Exception => e
    case(e)
    when SocketError
      raise APIError.new("Error while connecting to chargebee. If you see this repeatedly, contact us at [email protected]")
    when RestClient::ExceptionWithResponse
      if rcode = e.http_code and rbody = e.http_body
        raise handle_for_error(e, rcode, rbody)
      else
        raise APIError.new(e.message)
      end
    when RestClient::Exception
      raise APIError.new("Unexpected error received: #{e.message}", e.http_code, e.http_body)
    else
      raise APIError.new(e.message)
    end
  end
  rbody = response.body
  rcode = response.code
  begin
    resp = JSON.parse(rbody)
  rescue JSON::ParserError
    raise APIError.new("Invalid response object from API", rcode, rbody)
  end

  resp = Util.symbolize_keys(resp)
  resp
end