Class: MpesaStk::Client
- Inherits:
-
Object
show all
- Defined in:
- lib/mpesa_stk/client.rb
Overview
Shared OAuth, HTTP, and configuration helpers for Daraja API clients
Direct Known Subclasses
AccountBalance, B2B, B2C, C2B, IMSI, IoT, PullTransactions, Push, Ratiba, Reversal, StkPushQuery, TransactionStatus
Constant Summary
collapse
- AUTH_KEYS =
%i[key secret].freeze
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(key: nil, secret: nil, **options) ⇒ Client
Returns a new instance of Client.
14
15
16
17
18
|
# File 'lib/mpesa_stk/client.rb', line 14
def initialize(key: nil, secret: nil, **options)
@key = key
@secret = secret
@options = options
end
|
Class Method Details
63
64
65
|
# File 'lib/mpesa_stk/client.rb', line 63
def self.(kwargs)
kwargs.slice(*AUTH_KEYS)
end
|
Instance Method Details
33
34
35
36
37
38
|
# File 'lib/mpesa_stk/client.rb', line 33
def
{
'Authorization' => "Bearer #{token}",
'Content-Type' => 'application/json'
}
end
|
#option(env_key, keyword_key = nil) ⇒ Object
53
54
55
56
|
# File 'lib/mpesa_stk/client.rb', line 53
def option(env_key, keyword_key = nil)
keyword_key ||= env_key.to_s.tr('-', '_').to_sym
Config.fetch(env_key.to_s, @options[keyword_key])
end
|
#optional_option(env_key, keyword_key = nil) ⇒ Object
58
59
60
61
|
# File 'lib/mpesa_stk/client.rb', line 58
def optional_option(env_key, keyword_key = nil)
keyword_key ||= env_key.to_s.tr('-', '_').to_sym
Config.env(env_key.to_s, @options[keyword_key])
end
|
#post(path_env_key, body, error_message: 'Request failed') ⇒ Object
24
25
26
27
28
29
30
31
|
# File 'lib/mpesa_stk/client.rb', line 24
def post(path_env_key, body, error_message: 'Request failed')
url = "#{Config.fetch('base_url')}#{Config.fetch(path_env_key)}"
response = HTTParty.post(url, headers: , body: body.to_json)
raise StandardError, "#{error_message}: #{response.code} - #{response.body}" unless response.success?
JSON.parse(response.body)
end
|
#random_reference(length = 5) ⇒ Object
48
49
50
51
|
# File 'lib/mpesa_stk/client.rb', line 48
def random_reference(length = 5)
charset = Array('A'..'Z') + Array('a'..'z')
Array.new(length) { charset.sample }.join
end
|
#stk_password(short_code, passkey, timestamp = stk_timestamp) ⇒ Object
44
45
46
|
# File 'lib/mpesa_stk/client.rb', line 44
def stk_password(short_code, passkey, timestamp = stk_timestamp)
Base64.encode64("#{short_code}#{passkey}#{timestamp}").delete("\n")
end
|
#stk_timestamp ⇒ Object
40
41
42
|
# File 'lib/mpesa_stk/client.rb', line 40
def stk_timestamp
DateTime.now.strftime('%Y%m%d%H%M%S').to_i
end
|
#token ⇒ Object
20
21
22
|
# File 'lib/mpesa_stk/client.rb', line 20
def token
@token ||= AccessToken.call(@key, @secret)
end
|