-
在pbootcms中创建一个自定义模板页面(例如:wechat_login.html),并在该页面中添加以下代码,用于生成微信扫码登录的二维码:
<!-- 引入jquery库 -->
<script src="https://cdn.bootcss.com/jquery/3.5.1/jquery.min.js"></script>
<!-- 生成二维码的canvas -->
<div id="qrcode"></div>
<!-- 用于轮询检查扫码状态 -->
<div id="check_login"></div>
<script>
$(function({
// 生成二维码
var url = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
url = url.replace("APPID", "你的AppID";
url = url.replace("REDIRECT_URI", encodeURIComponent("http://你的域名/wechat_callback.php";
$('#qrcode'.qrcode({width: 200,height: 200,text: url};
// 轮询检查扫码状态
setInterval(function({
$.ajax({
url: "http://你的域名/check_login.php",
dataType: "json",
success: function(data{
if(data.code == 0{
alert("登录成功!";
window.location.reload(;
}
}
};
}, 3000;
};
</script>
- 创建一个名为wechat_callback.php的文件,用于接收微信的回调请求并获取用户的access_token和openid。代码如下:
<?php
// 获取微信授权码
$code = $_GET['code'];
// 获取access_token和openid
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=".urlencode($code."&grant_type=authorization_code";
$url = str_replace("APPID", "你的AppID", $url;
$url = str_replace("APPSECRET", "你的AppSecret", $url;
$json = file_get_contents($url;
$data = json_decode($json, true;
$access_token = $data['access_token'];
$openid = $data['openid'];
// 将access_token和openid存储在session中
session_start(;
$_SESSION['access_token'] = $access_token;
$_SESSION['openid'] = $openid;
// 跳转回原页面
header('Location: http://你的域名/wechat_login.html';
- 创建一个名为check_login.php的文件,用于检查用户是否已经扫码并确认登录。代码如下:
<?php
// 获取session中的access_token和openid
session_start(;
$access_token = $_SESSION['access_token'];
$openid = $_SESSION['openid'];
// 检查access_token和openid是否存在
if(empty($access_token || empty($openid{
echo json_encode(array('code' => -1, 'msg' => '未登录';
exit(;
}
// 检查用户是否已经扫码并确认登录
$url = "https://api.weixin.qq.com/sns/auth?access_token=".urlencode($access_token."&openid=".urlencode($openid;
$json = file_get_contents($url;
$data = json_decode($json, true;
if($data['errcode'] == 0{
echo json_encode(array('code' => 0, 'msg' => '已登录';
exit(;
} else {
echo json_encode(array('code' => 1, 'msg' => '未确认登录';
exit(;
}
完成以上步骤后,用户在访问wechat_login.html页面时,将会看到一个二维码,用户可以使用微信扫描二维码进行登录。同时,check_login.php文件会定时检查用户的登录状态,并在用户确认登录后,将access_token和openid存储在session中,以便于后续的操作。