网页授权流程分为四步:
1.引导用户进入授权页面同意授权,获取code
2.通过code换取网页授权access_token(与基础支持中的access_token不同)
3.如果需要,开发者可以刷新网页授权access_token,避免过期
4.通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)
需要注意的是只有微信认证的服务号才有微信网页授权的权限。
微信官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
注意的是:scope有两个取值,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
参考链接(请在微信客户端中打开此链接体验):
scope为snsapi_base:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
scope为snsapi_userinfo:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx807d86fb6b3d4fd2&redirect_uri=http%3A%2F%2Fdevelopers.weixin.qq.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
尤其注意:跳转回调redirect_uri,应当使用https链接来确保授权code的安全性。
注意:在开发代码时如果使用encodeURIComponent()转义链接时,不要换行,否则会转义一个空格出来。
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=${scope}&state=state#wechat_redirect`