介绍
随着互联网的发展,二维码在人们的生活中出现的越来越频繁,二维码的使用场景也越来越广泛:二维码登录、二维码支付、加好友、打开链接等等。
因为用户使用二维码很容易,只需打开相机对着二维码,想要完成的业务就可以轻松完成。
扫码登录流程
包涵三个节点:服务器、登录页面、授权页面
登录页面:一般是用户通过电脑浏览器访问的待授权页面
服务器:用于登录页面与授权页面进行消息传递
授权页面:一般是用户扫描登录二维码后打开的页面,待用户点击确认登录
流程:
用户打开登录页面
在登录页面与服务器建立websocket连接
服务器将生成唯一标识发送给登录页面
登录页面用这个标志来生成相应的二维码并显示到页面
用户通过客户端的扫一扫打开授权页面
授权页面通过唯一标志与服务器建立连接
服务器通知登录页面:这个登录页面的二维码已被扫了
用户点击确认登录,拿到服务器端返回的授权Token
授权页面将此Token发送给登录页面
登录页面用这个Token进行验证,成功则登录成功
需要用到的技术
ThinkPHP
因为服务器端API使用此框架,所以这个业务使用此框架也是理所应当的。GatewayWorker
它是一个基于PHP的Socket应用框架。Vue.js
进行一些前端渲染,与页面的控制。
ThinkPHP集成GatewayWorker需要做些额外的操作,不清楚的请看我另外的一篇文章。
Index控制器
<?phpnamespace app\index\controller;use think\Controller;use think\Request;class Index extends Controller{ /**
* 登录页面
* @return [type] [description]
*/
public function login()
{ return $this->fetch('login');
} /**
* 授权页面
* @return [type] [description]
*/
public function auth()
{ // 此页面应该要验证客户端是否已登录
// 拿到待授权页面的client_id
$client_id = $this->request->param('client_id'); if (empty($client_id)) { return $this->error('客户端ID不存在');
} return $this->fetch('auth', ['client_id' => $client_id]);
} /**
* 生成二维码
* @return [type] [description]
*/
public function qrcode()
{ // 引入phpqrcode.php
include APP_PATH . 'extra' . DS . 'phpqrcode' . DS . 'phpqrcode.php';
$data = $this->request->param('data');
\QRcode::png($data, false, 'L', 4);
header('Content-Type:image/png'); exit();
}
}登录页面 login.html
<!DOCTYPE html><html><head>
<title>扫码登录</title>
<style type="text/css">
.main { width: 500px; margin:50px auto;
} .main .qrcode { width: 166px; margin:10px auto;
} .main .tips { text-align: center; font-size: 14px;
} .main .qrcode img { border: 1px solid #eaeaea; width: 164px; height: 164px;
} </style></head><body><div class="main" id="app">
<div class="qrcode">
<img v-bind:src="qrcode" v-if="client_id != null" alt="二维码">
</div>
<div class="tips">
{{ tips }} </div></div><script type="text/javascript" src="/static/js/vue.js"></script><script type="text/javascript">
var app = new Vue({ el: '#app', data: { ws: null, client_id: null, qrcode: '/index/index/qrcode?data=load', tips: '获取二维码中',
}, methods:{ open: function (evt) { this.tips = '请扫码来登录'
}, close: function (evt) { this.tips = '服务器错误'
}, message: function (evt) { console.log(evt) try { var data = JSON.parse(evt.data)
} catch (e) { this.tips = '服务器响应错误'
return
} switch (data.type) { // 获取client_id
case 'client_id': this.client_id = data.client_id break; case 'scaned': this.tips = '已扫码,请确认'
break; case 'auth': this.tips = data.token // 这里用Token进行登录服务器
break;
}
}
}, watch: { client_id: function () { var url = 'http://localhost:8129/index/index/auth?client_id=' + this.client_id this.qrcode = '/index/index/qrcode?data=' + encodeURI(url)
}
}, created: function () { this.ws = new WebSocket('ws://127.0.0.1:5678') if (this.ws != null) { this.ws.onopen = this.open this.ws.onmessage = this.message this.ws.onclose = this.close
}
}
})</script></body></html>预览:

登录页面
授权页面 auth.html
<!DOCTYPE html><html><head>
<title>确认登录</title>
<style type="text/css">
.main { width: 500px; margin:50px auto;
} .main .button { text-align: center; margin-top: 20px;
} .main .tips { text-align: center; font-size: 14px;
} .main .qrcode img { border: 1px solid #eaeaea; width: 164px; height: 164px;
} </style></head><body><div class="main" id="app">
<div class="tips">
{{ tips }} </div>
<div class="button">
<button v-on:click="auth">确认登录</button>
</div></div><script type="text/javascript" src="/static/js/vue.js"></script><script type="text/javascript">
var app = new Vue({ el: '#app', data: { ws: null, client_id: '{$client_id}', qrcode: '/index/index/qrcode?data=load', tips: '获取权限中',
}, methods:{ open: function (evt) { this.ws.send(JSON.stringify({ type: 'scan', client_id: this.client_id
})) this.tips = '请确认登录'
}, close: function (evt) { this.tips = '服务器响应错误'
}, message: function (evt) { console.log(evt) try { var data = JSON.parse(evt.data)
} catch (e) { this.tips = '服务器错误'
return
} switch (data.type) { case 'used': this.tips = '二维码已失效'
break;
}
}, auth: function () { // 这里来获取服务器Token
this.ws.send(JSON.stringify({ type: 'auth', token: 'MTIzMTIzMTIzMTI0MnIzNDNyNDNyZzh1aWozNHIzOTJ1ZWk='
}))
}
}, watch: { client_id: function () { var url = 'http://localhost:8129/index/index/auth?client_id=' + this.client_id this.qrcode = '/index/index/qrcode?data=' + encodeURI(url)
}
}, created: function () { this.ws = new WebSocket('ws://127.0.0.1:5678') if (this.ws != null) { this.ws.onopen = this.open this.ws.onmessage = this.message this.ws.onclose = this.close
}
}
})</script></body></html>预览:

授权页面
Socket事件处理类
<?phpnamespace app\push\controller;use GatewayWorker\Lib\Gateway;class Events{ /**
* 有消息时
* @param integer $client_id 连接的客户端
* @param mixed $message
* @return void
*/
public static function onMessage($client_id, $message)
{ try {
$data = json_decode($message, true); if (empty($data) || empty($data['type'])) { return;
}
} catch (\Exception $e) { return;
} // 处理消息
switch ($data['type']) { // 客户端扫码
case 'scan': if (!empty($data['client_id'])) {
$_SESSION['auth_client_id'] = $data['client_id'];
Gateway::sendToClient($data['client_id'], json_encode([ 'type' => 'scaned',
]));
} break; // 客户端授权
case 'auth':
$auth_client_id = $_SESSION['auth_client_id']; if (!empty($auth_client_id) && !empty($data['token'])) {
Gateway::sendToClient($auth_client_id, json_encode([ 'type' => 'auth', 'token' => $data['token'],
])); // 授权后直接关闭客户端连接
Gateway::closeClient($client_id);
} break; default: # code...
break;
}
} /**
* 当用户连接时触发的方法
* @param integer $client_id 连接的客户端
* @return void
*/
public static function onConnect($client_id)
{ // 连接时将client_id发给客户端
Gateway::sendToClient($client_id, json_encode(['client_id' => $client_id, 'type' => 'client_id']));
} /**
* 当用户断开连接时触发的方法
* @param integer $client_id 断开连接的客户端
* @return void
*/
public static function onClose($client_id)
{ // Gateway::sendToAll("client[$client_id] logout\n");
} /**
* 当进程启动时
* @param integer $businessWorker 进程实例
*/
public static function onWorkerStart($businessWorker)
{ echo "WorkerStart\n";
} /**
* 当进程关闭时
* @param integer $businessWorker 进程实例
*/
public static function onWorkerStop($businessWorker)
{ echo "WorkerStop\n";
}
}有问题?
在学习的过程中有问题?请直接在评论区回复。
本项目GIT:https://git.coding.net/xtype/qrcode_login.git
作者:赵晓天
链接:https://www.jianshu.com/p/029d0ff6779e



随时随地看视频