Class: Payhere::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/payhere-sdk/client.rb

Direct Known Subclasses

Inpayments, Outpayments

Instance Method Summary collapse

Instance Method Details

#create_connectionObject

set authorization and authentication



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/payhere-sdk/client.rb', line 50

def create_connection
  url = "https://api.payhere.africa" if Payhere.config.environment.eql?"production"
  url = "https://api-sandbox.payhere.africa/api" if Payhere.config.environment.eql?"sandbox"
  
  headers = {
    "Content-Type": 'application/json'
  }

  conn = Faraday.new(url: url)
  conn.headers = headers

  get_credentials
  conn.basic_auth(@username, @password)

  conn
end

#get_credentialsObject



67
68
69
70
# File 'lib/payhere-sdk/client.rb', line 67

def get_credentials
  @username = Payhere.config.username
  @password = Payhere.config.password
end

#get_transaction_status(path) ⇒ Object

retrieve transaction information



73
74
75
# File 'lib/payhere-sdk/client.rb', line 73

def get_transaction_status(path)
  send_request('get', path)
end

#handle_error(response_body, response_code) ⇒ Object

Raises:



45
46
47
# File 'lib/payhere-sdk/client.rb', line 45

def handle_error(response_body, response_code)
  raise Payhere::Error.new(response_body, response_code)
end

#interpret_response(resp) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/payhere-sdk/client.rb', line 31

def interpret_response(resp)
  body = resp.body.empty? ? '' : JSON.parse(resp.body)

  response = {
    body: body,
    code: resp.status
  }
  unless resp.status >= 200 && resp.status < 300
    handle_error(response[:body], response[:code])
  end

  body
end

#send_request(method, path, body = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/payhere-sdk/client.rb', line 14

def send_request(method, path, body = {})
  begin
    conn = create_connection
    relative_path = "/api/#{Payhere.config.version}#{path}"

    case method
      when 'get'
        response = conn.get(relative_path)
      when 'post'
        response = conn.post(relative_path, body.to_json)
    end
  rescue ArgumentError
    raise "Missing configuration key(s)"
  end
  interpret_response(response)
end