Class: Wechat::Qcloud::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/wechat/qcloud/token.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, access_token, qcloud_setting) ⇒ Token

Returns a new instance of Token.



13
14
15
16
17
18
19
20
# File 'lib/wechat/qcloud/token.rb', line 13

def initialize(client, access_token, qcloud_setting)
  @client = client
  @access_token = access_token
  @qcloud_env = qcloud_setting.qcloud_env
  @qcloud_token_file = qcloud_setting.qcloud_token
  @qcloud_token_lifespan = qcloud_setting.qcloud_token_lifespan
  @random_generator = Random.new
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



11
12
13
# File 'lib/wechat/qcloud/token.rb', line 11

def access_token
  @access_token
end

#clientObject (readonly)

Returns the value of attribute client.



11
12
13
# File 'lib/wechat/qcloud/token.rb', line 11

def client
  @client
end

#qcloud_envObject (readonly)

Returns the value of attribute qcloud_env.



11
12
13
# File 'lib/wechat/qcloud/token.rb', line 11

def qcloud_env
  @qcloud_env
end

#qcloud_tokenObject (readonly)

Returns the value of attribute qcloud_token.



11
12
13
# File 'lib/wechat/qcloud/token.rb', line 11

def qcloud_token
  @qcloud_token
end

#qcloud_token_expired_timeObject (readonly)

Returns the value of attribute qcloud_token_expired_time.



11
12
13
# File 'lib/wechat/qcloud/token.rb', line 11

def qcloud_token_expired_time
  @qcloud_token_expired_time
end

#qcloud_token_fileObject (readonly)

Returns the value of attribute qcloud_token_file.



11
12
13
# File 'lib/wechat/qcloud/token.rb', line 11

def qcloud_token_file
  @qcloud_token_file
end

#qcloud_token_lifespanObject (readonly)

Returns the value of attribute qcloud_token_lifespan.



11
12
13
# File 'lib/wechat/qcloud/token.rb', line 11

def qcloud_token_lifespan
  @qcloud_token_lifespan
end

Instance Method Details

#refreshObject



32
33
34
35
36
# File 'lib/wechat/qcloud/token.rb', line 32

def refresh
  data = client.post('getqcloudtoken', JSON.generate(lifespan: qcloud_token_lifespan), base: ::Wechat::ApiBase::TCB_BASE, params: { access_token: access_token.token })
  write_qcloud_token_to_store(data)
  read_qcloud_token_from_store
end

#token(tries = 2) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/wechat/qcloud/token.rb', line 22

def token(tries = 2)
  # Possible two worker running, one worker refresh ticket, other unaware, so must read every time
  read_qcloud_token_from_store
  refresh if remain_life_seconds < @random_generator.rand(30..(3 * 60))
  qcloud_token
rescue AccessTokenExpiredError
  access_token.refresh
  retry unless (tries -= 1).zero?
end