class WxOpendata::Token
Attributes
access_token[R]
appid[R]
secret[R]
store_token_at[R]
token_expires_in[R]
token_file[R]
Public Class Methods
new(appid, appsecret, token_file)
click to toggle source
# File lib/wx_opendata/token.rb, line 8 def initialize(appid, appsecret, token_file) @appid = appid @appsecret = appsecret @token_file = token_file @random_generator = Random.new end
Public Instance Methods
token()
click to toggle source
# File lib/wx_opendata/token.rb, line 15 def token read_token_from_cache refresh_token if remain_seconds < @random_generator.rand(30..3 * 60) access_token end
Protected Instance Methods
read_token()
click to toggle source
# File lib/wx_opendata/token.rb, line 50 def read_token JSON.parse File.read(token_file) end
read_token_from_cache()
click to toggle source
# File lib/wx_opendata/token.rb, line 30 def read_token_from_cache token = read_token @token_expires_in = token.fetch('expires_in').to_i @store_token_at = token.fetch('store_token_at').to_i @access_token = token.fetch('access_token') rescue JSON::ParserError, Errno::ENOENT, KeyError, TypeError => e refresh_token end
refresh_token()
click to toggle source
# File lib/wx_opendata/token.rb, line 23 def refresh_token url = "#{WX_ACCESS_TOKEN}?grant_type=client_credential&appid=#{@appid}&secret=#{@appsecret}" resp = RestClient.get url store_token_to_cache(resp.body) read_token_from_cache end
remain_seconds()
click to toggle source
# File lib/wx_opendata/token.rb, line 54 def remain_seconds token_expires_in - (Time.now.to_i - store_token_at.to_i) end
store_token_to_cache(token)
click to toggle source
# File lib/wx_opendata/token.rb, line 39 def store_token_to_cache(token) token_hash = JSON.parse token raise InvalidCredentialError unless token_hash['access_token'] token_hash['store_token_at'.freeze] = Time.now.to_i write_token(token_hash.to_json) end
write_token(token)
click to toggle source
# File lib/wx_opendata/token.rb, line 46 def write_token(token) File.write(token_file, token) end