官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
1. 生成用户授权地址跳转
/* 生成用户授权地址跳转 */
wxAuthorize: () => {
let redirect_uri = window.location.href //回调地址
redirect_uri = encodeURIComponent(redirect_uri) //回调地址转码
let state = "" //要传递的参数
let appid = "公众号appid"
let scope = "snsapi_userinfo" //授权方式
let param = `appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}`
let url = `https://open.weixin.qq.com/connect/oauth2/authorize?${param}#wechat_redirect`
window.location.href = url
}
api地址:https://open.weixin.qq.com/connect/oauth2/authorize?#wechat_redirect
参数:
属性 | 是否必填 | 类型 | 备注 |
---|---|---|---|
appid | 是 | string | 公众号的唯一标识 |
redirect_uri | 是 | string | 公众号的唯一标识 |
response_type | 是 | string | 返回类型,请填写code |
scope | 是 | string | 授权类型: snsapi_base(不弹出授权页面,直接跳转,只能获取用户openid)、snsapi_userinfo (弹出授权页面,可通过 openid 拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) |
#wechat_redirect | 是 | string | 无论直接打开还是做页面302重定向时候,必须带此参数 |
state | 否 | string | 重定向后会带上 state 参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节 |
2. 接收回调参数
如果用户同意授权,页面将跳转至授权时填入的重定向地址,并且携带code、state参数
回调参数:
属性 | 备注 |
---|---|
code | code作为换取access_token的票据,每次用户授权带上的 code 将不一样,code只能使用一次,5分钟未被使用自动过期 |
state | 重定向后会带上 state 参数 |