Class: Mpesa::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/mpesa/resource.rb

Direct Known Subclasses

Payout, Register, Reversal, Status, Stk, Token

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, args = {}) ⇒ Resource

Returns a new instance of Resource.



7
8
9
10
# File 'lib/mpesa/resource.rb', line 7

def initialize(client, args = {})
  @client = client
  @args = args
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



5
6
7
# File 'lib/mpesa/resource.rb', line 5

def args
  @args
end

#clientObject (readonly)

Returns the value of attribute client.



5
6
7
# File 'lib/mpesa/resource.rb', line 5

def client
  @client
end

Instance Method Details

#format_phone(phone) ⇒ Object



38
39
40
41
42
43
# File 'lib/mpesa/resource.rb', line 38

def format_phone(phone)
  phone = phone.to_s
  return phone if phone.match?(/\A254/)

  phone.sub(/\A[+0]?(254)?(\d+)/, '254\2')
end

#get_request(url:, params: {}, headers: {}, basic_auth: true) ⇒ Object



12
13
14
# File 'lib/mpesa/resource.rb', line 12

def get_request(url:, params: {}, headers: {}, basic_auth: true)
  handle_response client.connection(basic_auth: basic_auth).get(url, params, headers)
end

#handle_response(response) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mpesa/resource.rb', line 20

def handle_response(response)
  return response unless client.raise_errors

  case response.status
  when 400
    raise Error, "Your request was malformed. #{response.body['errorMessage']}"
  when 401
    raise Error, "You did not supply valid authentication credentials. #{response.body['errorMessage']}"
  when 403
    raise Error, "You are not allowed to perform that action. #{response.body['errorMessage']}"
  when 404
    raise Error, "No results were found for your request. #{response.body['errorMessage']}"
  when 500
    raise Error, "Something wrong happened. #{response.body['errorMessage']}"
  end
  response
end

#post_request(url:, body: {}, headers: {}) ⇒ Object



16
17
18
# File 'lib/mpesa/resource.rb', line 16

def post_request(url:, body: {}, headers: {})
  handle_response client.connection.post(url, body, headers)
end