扫码登录之HTML+PHP+JS实现微信扫码登陆

rambo 3个月前 阅读:605 评论:0
演示地址:htps://cloud.huaxio.cn/php/wxdldemoJS部分-开始获取二维码并获取扫码状态<script>    //点击事件-获取二维码并展示给前台用于用户扫描  &n...

演示地址htps://cloud.huaxio.cn/php/wxdldemo

JS部分-开始获取二维码并获取扫码状态

<script>
    //点击事件-获取二维码并展示给前台用于用户扫描
    var jsonObj;
    $('#changeImageBtn').click(function () {
        $.ajax({
            type: "post",
            url: "wxlogin.php",
            success: function (res) {
                // console.log(jsonObj.imgurl)
                $('#imge').attr('src', res);
                $('#imge').attr('height', 300);
                $('#imge').attr('width', 300);
            }
        });
        // 开始轮询扫码状态
        let TimeOut = 0;
        let checklogin = setInterval('CheckStatus()', 1000);
    });

    // 时钟事件-查询扫码状态的方法
    function CheckStatus() {
        $.ajax({
            type: "POST",
            url: "rscenes.php?",
            success: function (data) {
                // console.log(jsonObj.scenes)
                data = JSON.parse(data);
                // console.log(jsonObj.scene)
                if (data.code === 200) {
                    $('#changeImageBtn').text('唯一标识:'+data.openid);
                }
                else if (data.code === 201) {
                    $('#changeImageBtn').text('请使用微信扫描二维码');
                }
                else if (data.code === 202) {//扫码成功,请确认登录
                    $('#changeImageBtn').text('扫码成功,请点击确认授权登录');
                }
                else if (data.code === 203) {
                    // $('#changeImageBtn').text('服务器发生错误');
                }
            },
            error: function (data) {
                console.log('服务器发生错误')
            }
        });
    }
</script>

PHP部分-1、获取二维码

<?php
error_reporting(0);
header('Content-type:text/html;charset=utf-8');
 function send_post($url, $post_data)
 {
     $postdata = http_build_query($post_data);
     $options = array(
         'http' => array(
             'method' => 'POST',
             'header' => 'Content-type:application/x-www-form-urlencoded',
             'content' => $postdata,
             'timeout' => 15 * 60 // 超时时间(单位:s)
         )
     );
     $context = stream_context_create($options);
     $result = file_get_contents($url, false, $context);
     return $result;
 }
 //使用方法
 $post_data = array(
     'apiname' => '',
     'apipwsd' => ''
 );
 $resdata= send_post('https://cloud.huaxio.cn/php/smdl/server/loginapi.php', $post_data);
 $array = json_decode($resdata, true);
 //存入scenes
 session_start();
 $_SESSION['scenes']=$array['scenes'];
 echo  $array['imgurl'];
?>

PHP部分-2、获取登录状态

<?php
error_reporting(0);
header('Content-type:text/html;charset=utf-8');
 //读取scenes
session_start();
$scene=$_SESSION['scenes'];
$url = "https://cloud.huaxio.cn/php/smdl/server/getstatus.php?scene=".$scene;
$response = file_get_contents($url);
echo $response;//用户点击确认登录则返回Openid唯一标识码
?>


热门文章
标签列表