移动端微信免登录
微信免登录技术实现
1、首先在路由拦截里判断是否进行过登录操作-index.js
/* 路由拦截 */
router.beforeEach((to, from, next) => {const userId= window.localStorage.getItem("userId");const { title } = to.metaif (title) {document.title = title}if (to.path !== location.pathname) {// 此处不可使用location.replacelocation.assign(to.fullPath)} else {next()} if (to.meta.auth) {if (userId) {console.log('有userId')next();} else {console.log('没有userId跳登录')next({path: '/login'})}
} else {next()
}
})
2、当用户第一次进入的时候,必定是没有userId的,所以会跳到登录页去走用户登录,进入login.vue
login 页token未失效 截取地址栏code 获取openid--页面mounted的时候获取code,此时没有token走else,什么都不执行
mounted() {document.getElementsByTagName("body")[0].style.height = window.innerHeight + 'px';if(window.localStorage.getItem('token')){this.getOpenid();//页面mounted的时候获取openid,此时没有code走else,什么都不执行}else{}},methods: {/* 截取地址栏code */getCode(name) {let href = location.href;return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(href) || [, ""])[1].replace(/\+/g, '%20')) || null;},// 获取openidgetOpenid() {var wxcode = this.getCode('code');if (wxcode) {// 微信code与userID进行绑定let params = { code: wxcode, user_id:window.localStorage.getItem('userId') }wxlogin(params).then((res) => {window.location.href = 'http://electronic.bigtax.cn'})} else {}},}
登录页正常填写登录信息,点击登录是校验信息是否正确
3、登录成功 存储userId 获取code(存储token和userId后,绑定微信免登录并将重定向地址指回当前页,当页面重定向到当前页时,页面mounted的时候获取到了token,此时调用getOpenid方法,截取到了地址栏的微信code,发送给后端将code与userId进行绑定)
if (!this.$refs.idNum.value || !this.$refs.pwd.value) {this.isShowToast = truethis.toastText = "请先输入身份证号和密码"} else {this.type = 2let params = { type: this.type, identity_num: this.$refs.idNum.value, password: this.$refs.pwd.value}login(params).then((res) => {if (res.code == 200) {this.isShowToast = truethis.toastText = "登录成功!"window.localStorage.setItem('token', res.data.token)window.localStorage.setItem('userId', res.data.user_id)// // 绑定微信免登录window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + this.AppId + '&redirect_uri=' + this.redirect_uri + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'} else {this.isShowToast = truethis.toastText = res.message}}).catch((err) => {console.log(err)this.isShowToast = truethis.toastText = res.message})}
4、用户登录信息与userId绑定成功,userId与微信code绑定成功,那么用户登录信息与微信code绑定成功,此时绑定成功跳到项目首页,我们在路由守卫中设置了项目主页为index.vue,路由拦截中判断缓存中存在userId了,直接进入首页
这样微信免登录就做好了,当你第一次登陆成功后,下次再进入的话,路由守卫中会判断有userId,直接进入index.vue,就不会走login.vue了。缺陷就是当获取微信code的时候,路由重定向到当前页,会导致页面刷新闪一下,这个微信官方的地址重定向无可避免,当然这只会在登录的时候闪一次,后续不登录不会出现这个小瑕疵。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
