class Youzan::TokenClient

Attributes

client[R]
got_token_at[R]
token_life_in_seconds[R]

Public Class Methods

new() click to toggle source
# File lib/youzan/token_client.rb, line 25
def initialize
  @random_generator = Random.new
end

Public Instance Methods

access_token() click to toggle source
# File lib/youzan/token_client.rb, line 29
def access_token
  read_token_from_store
  refresh if remain_life_seconds < @random_generator.rand(60..5 * 60)
  @access_token
end

Private Instance Methods

connection() click to toggle source
# File lib/youzan/token_client.rb, line 37
def connection
  @client ||= Faraday.new
end
fetch_access_token() click to toggle source
# File lib/youzan/token_client.rb, line 64
def fetch_access_token
  res = generate_oauth_token
  JSON.parse(res.body)
end
generate_oauth_token() click to toggle source
# File lib/youzan/token_client.rb, line 69
def generate_oauth_token
  connection.post do |req|
    req.url oauth_token_url
    req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    req.body = {
      'client_id' => CLIENT_ID, 'client_secret' => CLIENT_SECRET,
      'grant_type' => GRANT_TYPE, 'kdt_id' => KDT_ID
    }
  end
end
oauth_token_url() click to toggle source
# File lib/youzan/token_client.rb, line 80
def oauth_token_url
  Youzan::Api::BASE_API_URL + '/oauth/token'
end
read_token() click to toggle source
# File lib/youzan/token_client.rb, line 50
def read_token
  JSON.parse(Youzan.redis.get(youzan_token_key)) || {}
end
read_token_from_store() click to toggle source
# File lib/youzan/token_client.rb, line 41
def read_token_from_store
  td = read_token
  @token_life_in_seconds = td.fetch('expires_in').to_i
  @got_token_at = td.fetch('got_token_at').to_i
  @access_token = td.fetch('access_token') # return access_token same time
rescue JSON::ParserError, Errno::ENOENT, KeyError, TypeError
  refresh
end
refresh() click to toggle source
# File lib/youzan/token_client.rb, line 58
def refresh
  data = fetch_access_token
  write_token_to_store(data)
  read_token_from_store
end
remain_life_seconds() click to toggle source
# File lib/youzan/token_client.rb, line 54
def remain_life_seconds
  token_life_in_seconds - (Time.now.to_i - got_token_at)
end
write_token(token_hash) click to toggle source
# File lib/youzan/token_client.rb, line 92
def write_token(token_hash)
  Youzan.redis.set youzan_token_key, token_hash.to_json
end
write_token_to_store(token_hash) click to toggle source
# File lib/youzan/token_client.rb, line 84
def write_token_to_store(token_hash)
  raise InvalidTokenParameter unless token_hash.is_a?(Hash) && token_hash['access_token']

  token_hash['got_token_at'.freeze] = Time.now.to_i
  token_hash['expires_in'.freeze] = token_hash.delete('expires_in')
  write_token(token_hash)
end
youzan_token_key() click to toggle source
# File lib/youzan/token_client.rb, line 96
def youzan_token_key
  "youzan_token_#{CLIENT_ID}"
end