Class: Mpesa::Token

Inherits:
Resource show all
Defined in:
lib/mpesa/resources/token.rb

Instance Attribute Summary

Attributes inherited from Resource

#args, #client

Instance Method Summary collapse

Methods inherited from Resource

#format_phone, #get_request, #handle_response, #initialize, #post_request

Constructor Details

This class inherits a constructor from Mpesa::Resource

Instance Method Details

#cacheObject



33
34
35
# File 'lib/mpesa/resources/token.rb', line 33

def cache
  @cache ||= ActiveSupport::Cache::MemoryStore.new
end

#cache_tokenObject



21
22
23
24
25
# File 'lib/mpesa/resources/token.rb', line 21

def cache_token
  res = call
  cache.write('token', res.access_token, expires_in: res.expires_in.to_i)
  res
end

#callObject

Raises:



27
28
29
30
31
# File 'lib/mpesa/resources/token.rb', line 27

def call
  res = get_request(url: 'oauth/v1/generate?grant_type=client_credentials', basic_auth: true)
  raise Error, res.reason_phrase if res.body.empty?
  Object.new(res.body)
end

#tokenObject



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/mpesa/resources/token.rb', line 9

def token
  if cache.exist?('token')
    expires_at = cache.send(:read_entry, 'token')&.expires_at
    Object.new({
                 "access_token": cache.fetch('token'),
                 "expires_in": expires_at - Time.now.to_f
               })
  else
    cache_token
  end
end