最近开发微信公众号,需要用到微信公众号授权登录以及微信的一些其他功能,现在存在一个BUG就是,刷新后重新授权,导致缓存里面的access_token过期,然后在用这个token去请求微信其他功能,就报错了。

一、官方解释

1、网页授权access_token:公众号授权后,可以获得一个特有的调用凭证(网页授权access_token)通过该access_token可进行接口调用,例如:获取用户基本信息。

2、全局access_token:微信其他接口,需要通过基础支持中的【获取access_token】接口来获取到普通的access_token调用。

文档:
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html`

二、异同点

相同点:

都是access_token,有效期为7200秒;

不同点:

1、网页授权access_token需要先获取一次性使用的code;全局access_token可直接调用接口获取。
2、网页授权access_token是微信的一对一关系,只能获取对应的微信用户信息;全局access_token可重复使用,可获取不同微信用户的信息。
3、网页授权access_token获取次数没有限制;全局access_token每天获取最多次数为2000次;

三、官方文档

1、网页授权access_token:

第一步:用户同意授权,获取code:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

用户同意授权后,页面将跳转至 redirect_uri/?code=CODE&state=STATE

code作为换取access_token的票据,每次用户授权带上的 code 将不一样,code只能使用一次,5分钟未被使用自动过期。

第二步:通过code获取网页授权access_token

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

返回结果:

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

详见文档:
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

2、全局access_token

全局access_token是公众号的全局唯一接口调用凭据,各个接口的调用都需要access_token,需要保存至少2个小时,有效期为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

调用方式:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

详见:
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html


来源:
作者:e0yu
链接:https://www.cnblogs.com/e0yu/p/16698959.html