Class: Wechat::AccessToken

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

Direct Known Subclasses

CorpAccessToken

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, appid, secret, token_file) ⇒ AccessToken



5
6
7
8
9
10
# File 'lib/wechat/access_token.rb', line 5

def initialize(client, appid, secret, token_file)
  @appid = appid
  @secret = secret
  @client = client
  @token_file = token_file
end

Instance Attribute Details

#appidObject (readonly)

Returns the value of attribute appid.



3
4
5
# File 'lib/wechat/access_token.rb', line 3

def appid
  @appid
end

#clientObject (readonly)

Returns the value of attribute client.



3
4
5
# File 'lib/wechat/access_token.rb', line 3

def client
  @client
end

#secretObject (readonly)

Returns the value of attribute secret.



3
4
5
# File 'lib/wechat/access_token.rb', line 3

def secret
  @secret
end

#token_dataObject (readonly)

Returns the value of attribute token_data.



3
4
5
# File 'lib/wechat/access_token.rb', line 3

def token_data
  @token_data
end

#token_fileObject (readonly)

Returns the value of attribute token_file.



3
4
5
# File 'lib/wechat/access_token.rb', line 3

def token_file
  @token_file
end

Instance Method Details

#refreshObject



24
25
26
27
28
29
# File 'lib/wechat/access_token.rb', line 24

def refresh
  data = client.get('token', params: { grant_type: 'client_credential', appid: appid, secret: secret })
  data.merge!(created_at: Time.now.to_i)
  File.write(token_file, data.to_json) if valid_token(data)
  @token_data = data
end

#tokenObject



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/wechat/access_token.rb', line 12

def token
  begin
    @token_data ||= JSON.parse(File.read(token_file))
    created_at = token_data['created_at'].to_i
    expires_in = token_data['expires_in'].to_i
    fail 'token_data may be expired' if Time.now.to_i - created_at >= expires_in - 3 * 60
  rescue
    refresh
  end
  valid_token(@token_data)
end