微信掃碼無刷新登錄

前端(index.html):

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>測試微信掃碼登陸</title>
</head>

<body>
  <img id="qrcode" src="" />
  <h1 id="code"></h1>
  <p style="font-weight: 600">使用您的應用測試?</p>
  <p>您的AppID:<input type="text" id="appid" /></p>
  <p>開放平臺設置的授權回調域(以http/https開頭):<input type="text" id="redirectUri" /></p>
  <p><input type="button" value="測試" id="test" /></p>
  <a href="https://github.com/yi-ge/weixin-login-php"><img style="position: absolute; top: 0; right: 0; border: 0;" src="" alt="Fork me on GitHub"></a>
  <script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
  <script>
    function GetQueryString(name) {
      var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if(r!=null)return unescape(r[2]); return '';
    }

    $(function () {

      var api_url = "http://www.xxx.com/weixin.php";
      
      var getCode = function (uuid, last) {
        $.ajax({
          type: "GET",
          url: api_url + "&uuid=" + uuid + (last ? '&last=' + last : ''),
          dataType: "json",
          cache: !1,
          timeout: 6e4,
          xhrFields:{
            withCredentials:true
          },
          success: function (data) {
              console.log(data)
            data = data.content
            if (data.status === 405) {
              $('#code').text('登陸成功,code = ' + data.result.code)
            } else if (data.status === 404) {
              $('#code').text(data.msg.title + ', ' + data.msg.content)
              getCode(uuid, data.result.wxErrCode)
            } else if (data.status === 403) {
              $('#code').text(data.msg.title + ', ' + data.msg.content)
              getCode(uuid, data.result.wxErrCode)
            } else if (data.status === 500) {
              getUUID()
            } else {
              setTimeout(function () {
                getCode(uuid)
              }, 2000)
            }
          },
          error: function () {
            setTimeout(function () {
              getCode(uuid)
            }, 2000)
          }
        })
      }

      var getUUID = function (uuid) {
        $.ajax({
          type: "GET",
          url: api_url,
          dataType: "json",
          cache: !1,
          timeout: 6e4,
          xhrFields:{
            withCredentials:true
          },
          success: function (data) {
            data = data.content
            if (data.status === 1) {
              var uuid = data.result.wxUUID
              $('#qrcode').attr('src', data.result.imgData)
              getCode(uuid)
            } else {
              // setTimeout(function () {
              //   window.location.reload();
              // }, 2000)
            }
          },
          error: function () {
            // setTimeout(function () {
            //   window.location.reload();
            // }, 2000)
          }
        })
      }

      $("#appid").val(GetQueryString("appid"))
      $("#redirectUri").val(GetQueryString("redirect_uri"))

      $("#test").click(function () {
        window.location.href = window.location.origin + "/index.html?appid=" + $("#appid").val() + "&redirect_uri=" + $("#redirectUri").val();
      })

      getUUID()
    });
  </script>
</body>
</html>

 

後端(weixin.php):

<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Headers: Authorization, DNT, User-Agent, Keep-Alive, Origin, X-Requested-With, Content-Type, Accept, x-clientid');
header('Access-Control-Allow-Methods: PUT, POST, GET, DELETE, OPTIONS');
header('Access-Control-Allow-Origin: *');

if (!empty($_GET['uuid'])) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://long.open.weixin.qq.com/connect/l/qrconnect?uuid=' . $_GET['uuid'] . (empty($_GET['last']) ? '' : '&last=' . $_GET['last']));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cache-Control: no-cache', 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3522.0 Safari/537.36'));
    $output = curl_exec($ch);
    curl_close($ch);
    $preg = '/window.wx_errcode=(.*?);w/i';
    $preg1 = "/window.wx_code='(.*?)';/i";
    preg_match_all($preg, $output, $res);
    $wxErrCode = $res[1][0];
    switch ($wxErrCode) {
        case 405:
            preg_match_all($preg1, $output, $res);
            $wxCode = $res[1][0];
            $r = array(
                'status' => 405,
                'msg' => '登陸成功',
                'result' => array(
                    'code' => $wxCode,
                ),
            );
            break;
        case 404:
            $r = array(
                'status' => 404,
                'msg' => array(
                    'title' => '登陸成功',
                    'content' => '請在微信中點擊確認即可登錄',
                ),
                'result' => array(
                    'wxErrCode' => $wxErrCode,
                ),
            );
            break;
        case 403:
            $r = array(
                'status' => 403,
                'msg' => array(
                    'title' => '您已取消此次登錄',
                    'content' => '您可再次掃描登錄,或關閉窗口',
                ),
                'result' => array(
                    'wxErrCode' => $wxErrCode,
                ),
            );
            break;
        case 402:
        case 500:
            $r = array(
                'status' => 500,
                'msg' => '需要重新獲取uuid',
            );
            break;
        case 408:
            $r = array(
                'status' => 408,
                'msg' => '需要再次請求',
            );
            break;
    }
    echo json_encode($r);
} else {
    $ch = curl_init();
    $appid = empty($_GET['appid']) ? 'wx827225356b689e24' : $_GET['appid'];
    $redirect_uri = empty($_GET['redirect_uri']) ? 'https://qq.jd.com/' : $_GET['redirect_uri'];
    $redirect_uri = urlencode(iconv('gb2312', 'UTF-8', $redirect_uri));
    curl_setopt($ch, CURLOPT_URL, 'https://open.weixin.qq.com/connect/qrconnect?appid=' . $appid . '&scope=snsapi_login&redirect_uri=' . $redirect_uri . '&state=&login_type=jssdk&self_redirect=default');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cache-Control: no-cache', 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3522.0 Safari/537.36'));
    $output = curl_exec($ch);
    curl_close($ch);
    // var_dump($output);die;
    $preg = '/src="\/connect\/qrcode\/(.*?)" \/>/i';
    preg_match_all($preg, $output, $res);
    $uuid = $res[1][0];
    if (isset($_GET['img'])) { // 不推薦 - 如果設置了img參數,則返回圖片的下載地址,但此地址無法解決Chrome70不信任騰訊域名證書的問題
        $r = array('status' => 1, 'result' => array('wxUUID' => $uuid, 'imgURL' => 'https://open.weixin.qq.com/connect/qrcode/' . $uuid));
    } else {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://open.weixin.qq.com/connect/qrcode/' . $uuid);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cache-Control: no-cache', 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3522.0 Safari/537.36'));
        $output = curl_exec($ch);
        curl_close($ch);
        $r = array('status' => 1, 'result' => array('wxUUID' => $uuid, 'imgData' => 'data:image/jpeg;base64,' . base64_encode($output)));
    }
    echo json_encode($r);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章