Module: Model::Platform

Extended by:
ActiveSupport::Concern
Included in:
Wechat::Platform
Defined in:
app/models/wechat/model/platform.rb

Instance Method Summary collapse

Instance Method Details

#access_token_valid?Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'app/models/wechat/model/platform.rb', line 38

def access_token_valid?
  return false unless access_token_expires_at.acts_like?(:time)
  access_token_expires_at > Time.current
end

#apiObject



22
23
24
25
# File 'app/models/wechat/model/platform.rb', line 22

def api
  return @api if defined? @api
  @api = Wechat::Api::Platform.new(self)
end

#auth_urlObject



59
60
61
62
63
64
65
66
67
68
69
# File 'app/models/wechat/model/platform.rb', line 59

def auth_url
  return if verify_ticket.blank?
  refresh_pre_auth_code unless pre_auth_code_valid?
  url = URI('https://mp.weixin.qq.com/dashboard/cgi-bin/componentloginpage')
  url.query = {
    component_appid: appid,
    pre_auth_code: pre_auth_code,
    redirect_uri: Rails.application.routes.url_for(controller: 'wechat/platforms', action: 'callback', id: self.id)
  }.to_query
  url.to_s
end

#click_auth_urlObject



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'app/models/wechat/model/platform.rb', line 71

def click_auth_url
  return if verify_ticket.blank?
  refresh_pre_auth_code unless pre_auth_code_valid?
  url = URI('https://mp.weixin.qq.com/safe/bindcomponent')
  url.query = {
    action: 'bindcomponent',
    auth_type: 1,
    no_scan: 1,
    component_appid: appid,
    pre_auth_code: pre_auth_code,
    redirect_uri: Rails.application.routes.url_for(controller: 'wechat/platforms', action: 'callback', id: self.id)
  }.to_query
  url.to_s
end

#pre_auth_code_valid?Boolean

Returns:

  • (Boolean)


43
44
45
46
# File 'app/models/wechat/model/platform.rb', line 43

def pre_auth_code_valid?
  return false unless pre_auth_code_expires_at.acts_like?(:time)
  pre_auth_code_expires_at > 3.minutes.since
end

#refresh_access_tokenObject



48
49
50
51
# File 'app/models/wechat/model/platform.rb', line 48

def refresh_access_token
  r = api.component_token
  store_access_token(r)
end

#refresh_pre_auth_codeObject



27
28
29
30
31
32
33
34
35
36
# File 'app/models/wechat/model/platform.rb', line 27

def refresh_pre_auth_code
  token_hash = api.create_preauthcode
  if token_hash.is_a?(Hash) && token_hash['pre_auth_code']
    self.pre_auth_code = token_hash['pre_auth_code']
    self.pre_auth_code_expires_at = Time.current + token_hash['expires_in'].to_i
    self.save
  else
    raise Wechat::InvalidCredentialError, Hash(token_hash)['errmsg']
  end
end

#store_access_token(token_hash) ⇒ Object



53
54
55
56
57
# File 'app/models/wechat/model/platform.rb', line 53

def store_access_token(token_hash)
  self.access_token = token_hash['component_access_token']
  self.access_token_expires_at = Time.current + token_hash['expires_in'].to_i
  self.save
end