Module: WechatGate::Oauth

Included in:
Config
Defined in:
lib/wechat_gate/oauth.rb

Instance Method Summary collapse

Instance Method Details

#oauth2_access_token(code) ⇒ Object

TODO

code:

code

该接口会返回:{

  "access_token" => "access_token",
  "expires_in"=>7200,
  "refresh_token"=>"refresh_token",
  "openid"=>"MZkwG5sAx-d4PMQ6Lq1xisE",
  "scope"=>"snsapi_base"
}

此时已经获得了用户的openid,如果用户为公众号的订阅用户,就可以直接利用Tokens::AccessToken的token来对改用户调用业务接口了,此时这里的access_token意义就不大了,这里的access_token和Tokens::AccessToken的token是完全不一样的。



48
49
50
# File 'lib/wechat_gate/oauth.rb', line 48

def oauth2_access_token(code)
  WechatGate::Request.send("https://api.weixin.qq.com/sns/oauth2/access_token?appid=#{self.specs['app_id']}&secret=#{self.specs['app_secret']}&code=#{code}&grant_type=authorization_code")
end

#oauth2_access_token_valid?(access_token, openid) ⇒ Boolean

access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token拥有较长的有效期(7天、30天、60天、90天),当refresh_token失效的后,需要用户重新授权。

Returns:

  • (Boolean)


55
56
57
# File 'lib/wechat_gate/oauth.rb', line 55

def oauth2_access_token_valid?(access_token, openid)
  WechatGate::Request.send("https://api.weixin.qq.com/sns/auth?access_token=#{access_token}&openid=#{openid}")
end

#oauth2_entrance_url(ops = {}) ⇒ Object

用户点击授权入口页面



21
22
23
24
25
26
27
28
29
# File 'lib/wechat_gate/oauth.rb', line 21

def oauth2_entrance_url(ops = {})
  ops = {
    state: 'empty', # 自定义参数值
    redirect_uri: self.specs["oauth2_redirect_uri"],
    scope: 'snsapi_base' # snsapi_base | snsapi_userinfo
  }.merge(ops)

  "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{self.specs['app_id']}&redirect_uri=#{CGI.escape(ops[:redirect_uri])}&response_type=code&scope=#{ops[:scope]}&state=#{ops[:state]}#wechat_redirect"
end

#oauth2_refresh_access_token(refresh_token) ⇒ Object

利用refresh_token刷新access_token

response:

"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"



69
70
71
# File 'lib/wechat_gate/oauth.rb', line 69

def oauth2_refresh_access_token(refresh_token)
  WechatGate::Request.send("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=#{self.specs['app_id']}&grant_type=refresh_token&refresh_token=#{refresh_token}")
end

#oauth2_user(access_token, openid) ⇒ Object

获取用户信息



75
76
77
# File 'lib/wechat_gate/oauth.rb', line 75

def oauth2_user(access_token, openid)
  WechatGate::Request.send("https://api.weixin.qq.com/sns/userinfo?access_token=#{access_token}&openid=#{openid}&lang=zh_CN")
end