当前位置:网站首页>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 :

 The specific logic of the web side

APP Specific logical thinking diagram :

 Insert picture description here

原网站

版权声明
本文为[BigChen_ up]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240807401914.html