admin管理员组文章数量:1558091
项目需求:微信公众号(服务号)访问网页,第一次登录后,再次访问默认自动登录,执行退出后,可重新手动登录。
具体实现如下:
- 微信公众号 - 设置 - 公众号设置 - 功能设置 - 配置网页授权域名,用于获取授权code
(以下是订阅号截图,服务号对应位置配置网页授权域名地址)
- 微信公众号 - 开发 - 开发者工具 - 绑定开发者微信号,用于调试
- 前端使用 appid 调用授权获取code,用code调用接口获取对应的openid实现自动登录
// 以下为具体实现代码
async mounted () {
// 判断是否包含code
const href = window.location.href
if (href.includes('mp-fe/?code')) { // url包括 mp-fe/?code 证明为从微信跳转回来的
const url = href.substring(0, href.length - 2) // vue自动在末尾加了 #/ 符号,截取去掉
const jingPosit = url.indexOf('mp-fe/') + 6 // 获取域名结束的位置
const urlLeft = url.substring(0, jingPosit) // url左侧部分
const urlRight = url.substring(jingPosit, url.length) // url右侧部分
window.location.href = urlLeft + '#/' + urlRight // 拼接跳转
} else {
// 判断是否为微信环境
const ua = navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
// 第一次登录或退出登录,获取code
if (!this.$route.query.code && !localStorage.OPEN_ID) {
const appid = '对应appid'
const redirectUrl = encodeURIComponent(window.location.href)
const url = `https://open.weixin.qq/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=2020&connect_redirect=1#wechat_redirect`
window.location.href = url
// 使用code获取openid
} else if (this.$route.query.code && !localStorage.OPEN_ID) {
// 获取openid
const userInfo = await getOpenId({ code: this.$route.query.code })
if (userInfo.data.openId && userInfo.data.openId !== null) {
localStorage.OPEN_ID = userInfo.data.openId
localStorage.autoLogin = false
}
this.$router.push('/')
// 处理自动登录
} else if (localStorage.OPEN_ID) {
if (localStorage.autoLogin === 'true') {
const res = await chkLog({ openId: localStorage.OPEN_ID })
if (res.data.data.success) {
this.saveUserInfo(res.data.data)
localStorage.setItem('userid', res.data.data.sessionid)
localStorage.userId = res.data.data.userId
this.$router.push('/home')
}
}
}
}
}
},
版权声明:本文标题:Vue 微信网页授权自动登录 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1727385881a1112344.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论