网页授权登录
概述
从企业微信终端打开的网页获取成员的身份信息,从而免去登录的环节。
企业应用中的URL链接(包括自定义菜单或者消息中的链接),均可通过OAuth2.0验证接口来获取成员的UserId身份信息。
设置“可信域名”
URL的域名,必须匹配企业应用设置项中的“可信域名”,否则跳转时会提示“redirect_uri参数错误”(匹配规则请看可信检验规则)。因此需要先配置应用的可信域名。
企业微信截图_00.png
登录到企业管理端后台,选择“企业应用”选项卡,进入需要使用网页授权的应用并编辑“可信域名”表单项,此选项将用于网页OAuth2.0授权的时候进行安全验证。请注意,这里填写的是域名,而不是URL,因此请勿加 http:// 等协议头。
前端流程
- 调用后端接口获取构造链接,JS打开构造链接,获取code
- 调用后端接口根据code参数获得员工的userid
// 构造链接
https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&agentid=AGENTID&state=STATE#wechat_redirect
// 打开链接,页面将跳转至
redirect_uri?code=CODE&state=STATE
例如:
https://vi.com/home?code=bQIyNHUkJenaDKD9OJH3TB-Jva1_4JHBeGvDEUUfuYXmE&state=STATE
项目案例:
async created(){
// 用户首次打开链接没有 code,调接口获取 OAuth2 链接
if (!this.$route.query.code) {
this.getOAuth()
}
// OAuth2 链接带 code
else {
// 没有UserId,使用code获取UserId
if (!localStorage.UserId) {
await this.getUserID()
}
// 有token,再去请求其它接口
this.getList()
}
},
methods:{
/* 获取OAuth2链接,打开 */
getOAuth() {
const urlHref = location.href
// 传当前 url 给后端
getOAuth(urlHref).then(res => {
const url = res.asstokenUrl
// 跳转到构造链接
url && (location.href = url)
})
},
/* 根据构造链接的 code 获取 UserId */
getUserID() {
return new Promise(resolve => {
getUserID({
code: this.$route.query.code
}).then(res => {
if (res.errcode == 0) {
localStorage.UserId = res.UserId
resolve()
}
// 获取 UserId 出错
else {
Toast({
type: 'fail',
message: '认证过期!',
duration: 3000
})
}
})
})
},
}