用户在扫码成功后,自动登录网页
过程解析
- 用户加载登录页面,JS自动生成unicode,并且两秒钟后自动发送给websocket服务器,将unicode存储在websocketSession中,
- 用户点击微信扫码按钮,将Unicode用作sceneId,随机生成二维码,并在当前页面不跳转的情况下,显示给当前用户
- 用户扫码后,微信服务号后台获取到Unicode作为的sceneId,通知websocket服务器,让它给session中有Unicode值和传给它的Unicode值一致的session发送特定消息,将自动登录命令和openID一同发送过去
- 页面接收到特定消息:自动登录命令和openID,自动帮助用户跳转登录
//html
<p>使用微信 扫码登录/注册</p>
<img v-bind:src="wechatUrl">
import sockjs from '../assets/js/sockjs-1.1.2.min' //根据本地路径,引入sockjs
export default {
data () {
return{
wechatUrl:'',
websocket: null,
openId:''
}
}
}
beforeMount () {
var that = this;
var unicode;
var websocket = null;
var transports = [];
var url = `${IPLOCATION}/sockjs`;
websocket = new SockJS(url, undefined, {
transports: transports
});
websocket.onopen = function () {
console.log('that.websocket: connection is opened');
};
websocket.onclose = function () {
console.log('that.websocket: connection is closed');
};
websocket.onheartbeat = function () {
console.log('that.websocket: connection heartbeat...');
};
websocket.onmessage = function (e) {
if (e.data.indexOf("AUTOMATIC_LOGIN") != -1) {
websocket.onclose();
that.toLogin(e);
} else {
console.log('websocket:', e.data);
}
};
that.websocket = websocket
},
mounted(){
var that=this;
that.unicode = Math.round(Math.random() * 100000000) + "1";
$.get(IPLOCATION + `${接口}sceneId=${that.unicode}`, null, function (url) {
that.wechatUrl = url
});
setTimeout(function () {that.websocket.send(that.unicode)}, 2000);
}
//扫码登录
toLogin(e) {
var that=this;
that.openId = e.data.split("####")[1];
// var mixedValues = e.data.split('####');
// var openId = mixedValues[1]; // 用户的openId
var sceneId = 911; // 登录系统默认场景值
// 关闭二维码
// 通过ajax访问后台登录接口认证并登录
......
}