关于vue实现公众号页面使用微信号登陆

项目描述:pc端+公众号页面(移动端)

登陆方式:pc端微信扫码登陆,公众号内授权登陆

pc端实现方式:将公众号开发功能生成的登陆链接(回调code由后端接收)+前端uuid生成二维码,循环获取后端扫码接口(参数为uuid),成功后获取用户信息,登陆成功。

移动端实现方式:不支持浏览器打开,只能在微信内打开页面,点击使用微信登陆,首先检测路径中是否带参(code),有的话证明已回调成功,使用code请求接口登陆。没有的话,重定向微信登陆链接(回调地址为 window.location.href.split('?')[0];)接收code。

代码如下:

created() {

// 从 window.location.href 中截取 code 并且赋值

if (window.location.href.indexOf('code') !== -1) { // 此方法仅供参考!!!

this.code = window.location.href.split('?')[1].split('=')[1].split('&')[0];

}

if (this.code) { // 存在 code 直接调用接口

this.handGetUserInfo(this.code);

}

},

methods: {

handLogin() {

// 重定向地址重定到当前页面,在路径获取 code

const hrefUrl = window.location.href.split('?')[0];

if (this.code === '') {

window.location.href =

`

https://open.weixin.qq.com/connect/oauth2/authorize

?appid=wxdb6e943

&redirect_uri=${encodeURIComponent(hrefUrl)}

&response_type=code

&scope=snsapi_userinfo

`

}

},

// 提交微信登陆code

handGetUserInfo(code) {

this.$http

.post('/Client-User/Code/Login', {

code:code

})

.then((res) => {

if (res.success) {

localStorage.setItem('ClientToken', res.data.token);

this.getUserInfo();

}

})

.catch((err) => {

console.info(err)

})

},

// 获取用户信息

getUserInfo() {

this.$http

.get('Client-User/Cur', {})

.then((res) => {

if (res.success) {

localStorage.setItem('userInfo', JSON.stringify(res.data));

this.$store.commit('setUserInfo', res.data);

if (res.data.filledInfo === 1) {

this.$message({

message: '登陆成功,为您跳转至引导页',

type: 'success'

});

this.$router.push({ name: 'guide' });

} else if (res.data.filledInfo === 0) {

this.$router.push({ name: 'registered' });

}

}

})

.catch((err) => {

console.info(err)

})

}


附注:公众号页面微信登陆本地开发测试方式。

首先在vue.config.js将项目端口号改成80(微信回调地址只支持80端口),其次在C:\Windows\System32\drivers\etc,hosts中修改本机域名,最后在公众号中将本机域名填到回调域名白名单中。

最最后,在微信开发者工具>公众号网页调试,使用域名访问项目即可。

你可能感兴趣的:(关于vue实现公众号页面使用微信号登陆)