介紹
隨著互聯網的發展,二維碼在人們的生活中出現的越來越頻繁,二維碼的使用場景也越來越廣泛:二維碼登錄、二維碼支付、加好友、打開鏈接等等。
因為用戶使用二維碼很容易,只需打開相機對著二維碼,想要完成的業務就可以輕松完成。
掃碼登錄流程
包涵三個節點:服務器、登錄頁面、授權頁面
登錄頁面:一般是用戶通過電腦瀏覽器訪問的待授權頁面
服務器:用于登錄頁面與授權頁面進行消息傳遞
授權頁面:一般是用戶掃描登錄二維碼后打開的頁面,待用戶點擊確認登錄
流程:
- 用戶打開登錄頁面
- 在登錄頁面與服務器建立websocket連接
- 服務器將生成唯一標識發送給登錄頁面
- 登錄頁面用這個標志來生成相應的二維碼并顯示到頁面
- 用戶通過客戶端的掃一掃打開授權頁面
- 授權頁面通過唯一標志與服務器建立連接
- 服務器通知登錄頁面:這個登錄頁面的二維碼已被掃了
- 用戶點擊確認登錄,拿到服務器端返回的授權Token
- 授權頁面將此Token發送給登錄頁面
- 登錄頁面用這個Token進行驗證,成功則登錄成功
需要用到的技術
ThinkPHP
因為服務器端API使用此框架,所以這個業務使用此框架也是理所應當的。GatewayWorker
它是一個基于PHP的Socket應用框架。Vue.js
進行一些前端渲染,與頁面的控制。
ThinkPHP集成GatewayWorker需要做些額外的操作,不清楚的請看我另外的一篇文章。
Index控制器
<?php
namespace 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事件處理類
<?php
namespace 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