当前位置:网站首页>Practical analysis: implementation principle of APP scanning code landing (app+ detailed logic on the web side) with source code
Practical analysis: implementation principle of APP scanning code landing (app+ detailed logic on the web side) with source code
2022-06-24 09:45:00 【BigChen_ up】
Make a note of a recent app Scan code to log in .
At the bottom of the article app And the specific logical thinking diagram of the web side
The idea is as follows :
1. A unique value is generated in the background , Attach to QR code , Back to the front page , This unique value is saved in a database , For subsequent comparison .( There are many ways to generate QR codes , There are many online introductions here , There is a code behind it ).
2. front end AJAX Polling the status of the QR code , Judge whether it has been scanned 、 Confirm login 、 Cancel login 、 Timeout and other information .
3.APP Sweep code , The user to use APP After scanning the code, a status field is passed to the web interface to indicate that the code has been scanned , front end ajax The status of polling judgment is that the QR code is hidden after being scanned . The user clicks "confirm login" to pass the confirmation login status to the web interface , And the unique identification of the user , front end ajax The judgment is to confirm the login , After obtaining the user's unique ID, query the database storage correspondence session, Jump to the corresponding page .
/** * Generate qr code * @param string $url Content in QR code , Add http:// In this way, scanning code can jump directly url * @param string $message Note below QR code * @param string $logo In the middle of the QR code logo picture * @param int $logo_w Picture size * @param int $size QR code size * @return string QR code */
function qrcode($url, $message = '', $logo = '', $logo_w = 50, $size = 300) {
$errorCorrectionLevel = 'L'; // Fault tolerance level
$matrixPointSize = 3; // Generate image size
// Generate QR code image
QrCode::png($url, '../qr/qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
$logo = 'static/img/logo.png'; // Ready logo picture
$QR = '../qr/qrcode.png'; // The original QR code graph that has been generated
if ($logo !== FALSE) {
$QR = imagecreatefromstring(file_get_contents($QR));
$logo = imagecreatefromstring(file_get_contents($logo));
if (imageistruecolor($logo)) imagetruecolortopalette($logo, false, 65535);
$QR_width = imagesx($QR); // QR code image width
$QR_height = imagesy($QR); // QR code image height
$logo_width = imagesx($logo); //logo Image width
$logo_height = imagesy($logo); //logo Picture height
$logo_qr_width = $QR_width / 6;
$scale = $logo_width / $logo_qr_width;
$logo_qr_height = $logo_height / $scale;
$from_width = ($QR_width - $logo_qr_width) / 2;
// Recombine the picture and resize
imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
$logo_qr_height, $logo_width, $logo_height);
}
// Output pictures
imagepng($QR, '../qr/appdownload.png');
//base64 QR code
$qrcode = file_get_contents('../qr/appdownload.png');
$qr_img = "data:image/jpg;base64," . base64_encode($qrcode);
return $qr_img;
}
Generate QR code interface
/** * Notes: Generation of two-dimensional code method */
public function sweepCodeOp() {
if (request()->isGet() && request()->isAjax()) {
// establish token
$token = get_token();
$check_token = check_token();
// Generate qr code
// The address on the side here is the analog address for the time being
$qr = qrcode('ceshi.cn/user/login?token=' . $token . '&check_token=' . $check_token);
$data = [
'token' => $token,
'addtime' => time(),
'check_token' => $check_token,
];
// Add a two-dimensional code table
$res = model('qrcode')->allowField(true)->validate('qrcode.add')->save($data);
if ($res === false) {
return false;
}
return return_msg(1, ' Verification code generated successfully ', $qr, $token);
}
return $this->fetch();
}
The front end clicks to obtain the QR code and requests the background interface to generate the QR code , Judge code be equal to 1 Identify that the QR code is obtained successfully , Then start to regularly poll the interface of QR code status , Specifically ajax Poll as follows :
var flag = true;
var timer;
var a = 1;
function qrcode() {
if (flag == true) {
// Prevent users from clicking frequently
flag = false;
clearInterval(timer);
$.ajax({
type:"GET",
url:"sweepCode",
data:{
},
success:function (adata) {
var data = JSON.parse(adata);
// console.log(data.token);
// var token = data.token;
if (data.code == 1) {
// 1 Indicates that the QR code is successfully generated
$("#qr").attr('src',data.data);
timer = setInterval(function () {
// console.log(a);
$.ajax({
type:"POST",
url:"getStatus",
data:{
token:data.token},
success:function (res) {
var ares = JSON.parse(res);
// console.log('T--'+data.token);
console.log(ares);
switch (ares.code) {
case 1201: // 1201 Indicates that the QR code is out of date
console.log(ares.msg);
$("#qr").attr('src','');
clearInterval(timer);
break;
case 1205: // Indicates that the user has scanned the QR code
$("#qr").attr('src','');
$("#success").css('display','block');
break;
case 1207: // 1207 Indicates that the user has scanned but clicked cancel login
$("#success").css('display','none');
$("#rem").css('display','block');
clearInterval(timer);
break;
case 1202: // 1202 Indicates that the account does not exist
break;
case 1203 : // 1203 Indicates that the account is not bound successfully
break;
case 200: // 200 Indicates successful login There should be a jump in it
$("#success").text(ares.username);
clearInterval(timer);
alert(ares.msg);
// location.href="/index/index/index";
break;
case 400: // Parameter error
clearInterval(timer);
break;
case 1211: // Data exception
break;
}
}
});
},2000);
} else {
console.log(' Unknown error !');
}
}
});
setTimeout(function () {
// Set click frequency
flag = true;
},2000);
a++;
} else {
console.log(' Click too often ');
a -- ;
}
}
The interface for querying QR code status is as follows : ( Because it is a function used in actual combat projects , Therefore, the judgment and the judgment of various situations encountered are more complex , If you practice, you can simplify writing )
/** * Notes: Polling and querying QR code status * @return string */
public function getStatusOp() {
if (request()->isAjax() && request()->isPost()) {
$token = preg_replace('/\s/', '', input('token'));
// Instantiate a two-dimensional code table
$qrcode = model('qrcode');
// Delete some QR codes that have not been polled for expiration
$del = $qrcode->field('addtime,numid')->select();
foreach ($del as $v) {
if (time() - $v['addtime'] > 400) {
$qrcode->where(['numid' => $v['numid']])->delete();
}
}
// Instantiate the user table
$user = model('user');
// Check the two-dimensional code table
$result = $qrcode->where(['token' => $token])->find();
if (!empty($result)) {
if (time() - $result['addtime'] > 300) {
// request timeout
$qrcode->where(['token' => $token])->delete();
return return_msg(1201, ' Please refresh the QR code when it is expired ');
}
switch ($result['status']) {
case 0: // Indicates not scanned
return return_msg(1200, ' QR code not scanned , Please scan QR code ');
break;
case 1: // Indicates that has been scanned
if ($result['qrstatus'] == 7) {
// QR code status 7 To cancel login
$qrcode->where(['token' => $token])->delete(); // Delete QR code
return return_msg(1207, ' QR code has been unlicensed ');
} elseif ($result['qrstatus'] == 9) {
// QR code status 9 To confirm login
if (!empty($result['uid'])) {
// Look up the user list
$res_user = $user->where(['numid' => $result['uid']])->field('username,numid')->find();
if ($res_user !== false) {
// to session assignment
session('username', $res_user['username']);
session('uid', $res_user['numid']);
// Delete QR code
$qrcode->where(['token' => $token])->delete();
return return_msg(200, ' Login successful ', session('username')); // Log in successfully to jump
} else {
return return_msg(1202, ' Account does not exist ');
}
} else {
// Delete QR code
$qrcode->where(['token' => $token])->delete();
return return_msg(1203, ' The account is not bound ');
}
} else {
return return_msg(1205, ' Please confirm your login with the mobile client ');
}
break;
default:
return return_msg(1211, ' Data exception !');
break;
}
} else {
return return_msg(400, ' Parameter error !');
}
}
}
APP The interface for passing parameters is as follows :
/** * Notes: app Pass in the parameters * @return string */
public function getAppOp() {
if (request()->isPost()) {
$arr = [
'token' => preg_replace('/\s/', '', input('token')),
'check_token' => preg_replace('/\s/', '', input('check_token')),
'type' => intval(input('type')), // 1 Scanning code 7 Sign out 9 Confirm login
'uid' => intval(input('uid')),
];
// Example two-dimensional code table
$qrcode = model('qrcode');
$token = $arr['token'];
$check_token = $arr['check_token'];
// The judgment passed on token Whether it is right
$addtime = $qrcode->where(['token' => $token, 'check_token' => $check_token])->value('addtime');
if (!empty($addtime)) {
// token correct
if ((time() - $addtime) < 300) {
// And No timeout
switch ($arr['type']) {
case 1: // Indicates that the has been scanned
$qrcode->isUpdate(true, ['token' => $token, 'check_token' => $check_token])->save(['status' => 1]);
return return_msg(1300, ' Scan code successfully !');
break;
case 7: // to update qrstatus Means to cancel login
$qrcode->isUpdate(true, ['token' => $token, 'check_token' => $check_token])->save(['qrstatus' => 7]);
return return_msg(1301, ' Sign out !');
break;
case 9: // Means confirm login
if (!empty($arr['uid'])) {
$qrcode->isUpdate(true, ['token' => $token, 'check_token' => $check_token])->save(['qrstatus' => 9, 'uid' => $arr['uid']]);
return return_msg(1302, ' Login successful !');
} else {
return return_msg(1303, ' Account binding failed !');
}
break;
default:
return return_msg(1401, ' Data exception !');
break;
}
} else {
return return_msg(1402, ' Overtime !');
}
} else {
return return_msg(1403, ' Validation failed !');
}
}
}
Specific logical thinking diagram on the web side :

APP Specific logical thinking diagram :

边栏推荐
- Netrca: an effective network fault cause localization
- WindowManager 简单悬浮框的实现
- Directly applicable go coding specification
- Weekly recommended short video: is the ultimate form of computing "meta universe"?
- Talking about the knowledge of digital transformation
- Summary of medical image open source datasets (II)
- Reasons for the failure of digital transformation and the way to success
- 买的长期理财产品,可以转短吗?
- LeetCode: 240. 搜索二维矩阵 II
- 如何让社交媒体成为跨境电商驱动力?这款独立站工具不能错过!
猜你喜欢

Latex formula and table recognition

英伟达这篇CVPR 2022 Oral火了!2D图像秒变逼真3D物体!虚拟爵士乐队来了!

【bug】@JsonFormat 使用时出现日期少一天的问题

Event registration Apache pulsar x kubesphere online meetup hot registration

Zero foundation self-study SQL course | sub query

Amazing tips for using live chat to drive business sales

ggplot2颜色设置总结

二十、处理器调度(RR时间片轮转,MLFQ多级反馈队列,CFS完全公平调度器,优先级翻转;多处理器调度)

5分钟,客服聊天处理技巧,炉火纯青

Thinkphp5 multi language switching project practice
随机推荐
如何解决独立站多渠道客户沟通难题?这款跨境电商插件一定要知道!
居家办公如何管理数据中心网络基础设施?
实战剖析:app扫码登陆实现原理(app+网页端详细逻辑)附源码
Longest public prefix of leetcode
LeetCode: 240. Search 2D matrix II
Directly applicable go coding specification
Servlet快速筑基
Handling method of Oracle data file header SCN inconsistency
PostgreSQL
L01_ How is an SQL query executed?
Weekly recommended short video: is the ultimate form of computing "meta universe"?
生产者/消费者模型
grpc本地测试联调工具BloomRPC
Xiaobai needs to learn MySQL - incremental statistical SQL
PRCT-1400 : 未能执行 getcrshome解决方法
Ora-16038 ora-19502 ora-00312 troubleshooting
P6698-[balticoi 2020 day2] virus [AC automata, DP, SPFA]
Algorithm - the K row with the weakest combat power in the matrix (kotlin)
Grpc local test joint debugging tool bloomrpc
June 13-19, 2022 AI industry weekly (issue 102): career development