状态码
采用标准的HTTP状态码
状态码 | 描述 |
---|---|
200 | OK - 成功 |
201 | Created - 创建成功 |
204 | No Content - 成功但无返回内容 |
400 | Bad Request - 请求错误,一般是请求的参数不正确 |
401 | Unauthorized - 未授权,前端需要重新请求授权 |
403 | Forbidden - 权限不够 |
404 | Not Found |
500 | Internal Server Error |
步骤
1. 进入web app。
2. 前端重定向到 [https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect](https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect)
其中
APPID:wx9e64c093244fb42b
REDIRECT_URI:放api的地址
SCOPE:snsapi_userinfo
STATE:用户点击的前端url
3. 微信进入上述url后,会静默授权,直接跳转到`REDIRECT_URI`,并且会在url中携带CODE。
4. 后台接受到请求后,用CODE请求微信服务器得到token和openid,然后生成我们自己的token,然后重定向到步骤2中state填入的url,并且会把token填入cookie。
5. 前端检查cookies,得到token。
代码
在每个请求中判定是否符合登录条件。
initLogin (appid, role, callback) {
Vue.http.interceptors.push(() => {
return {
request (req) {
let token = Cookie.getCookie('token_' + role)
if (!token) {
document.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURI('http://' + document.location.host + '/wechat/auth/' + role) + '&response_type=code&scope=snsapi_userinfo&state=' +
document.location.href + '#wechat_redirect')
}
else
{
req.headers['x-access-token'] = token
return req
}
},
response (resp) {
if (resp.status === 401) {
document.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURI('http://' + document.location.host + '/wechat/auth/' + role) + '&response_type=code&scope=snsapi_userinfo&state=' +
document.location.href + '#wechat_redirect')
} else if (resp.status === 403) {
callback()
} else if (resp.status === 500) {
if (resp.data.message) {
Alert.show(resp.data.message)
} else {
Alert.show('网络错误')
}
return null
console.log('网络错误')
}
return resp
}
}
})
}
应用示例
因为此app有多个角色,每个角色对应不同的公众号,所以appid和角色都是参数。
wx.initLogin('wx8d52e52502d04610', 'worker', function () {
if (!window.user || !window.user.phoneNum) {
router.replace({
name: 'login'
})
}
show()
})
结语
该代码在vue套件下使用,如果是其他框架,原理一致。