借助平台:易登 (https://yd.jylt.cc/#/apiDoc)
代码整理:
本文付费阅读内容 - 星球会员免费
回调地址:
http://xxxxxxx.com/api/index/index
文件路径:application/api/controller/Index.php
use think\Log;
use think\Cache;
public function index()
{
$datas = $this->request->param();
Log::info("微信回调成功");
Log::info($datas);
if(isset($datas["tempUserId"]) && isset($datas["wxMaUserInfo"])){
Cache::set($datas["tempUserId"],$datas["wxMaUserInfo"],60);
$this->error('扫码成功');
}
else{
$this->success('扫码失败,请重新扫码!');
}
}
login.html
新增一个按钮
路径:application/index/view/user/login.html
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block" id="wxlogin-btn">微信扫码登录</button>
</div>
user.js新增按钮点击事件
获取二维码图片,弹出显示,轮训请求是否已登录
路径:public/assets/js/frontend/user.js
var timer = null
$('#wxlogin-btn').click(function (e) {
e.preventDefault();
console.log('点击了登录');
timer && clearInterval(timer)
$.ajax({
type: "post",
url: "/index/user/getWxCode",
data: {},
dataType: "json",
success: function (response) {
console.log(response);
if(response.code == 0){
layer.alert(response.msg)
}
else{
// 成功
layer.open({
type: 1,//1 dom或文本,2 iframe,3 加载层,4 tips
shadeClose:true,
content: '<div><img src="'+response.data.qrUrl+'" width="300"></div>'
,success: function(layero){
console.log('打开成功');
timer = setInterval(()=>{
$.ajax({
type: "post",
url: "/index/user/checkWxUserStatus",
data: {
tempUserId:response.data.tempUserId
},
dataType: "json",
success: function (response) {
console.log(response);
if(response.code == 1){
clearInterval(timer)
location.href = response.url
}
}
});
},3000)
}
});
}
}
});
});
user.php新增2个方法
获取二维码和验证用户登录状态
路径:application/index/controller/User.php
/**
* 获取二维码
*
* @return void
*/
public function getWxCode()
{
$result = Http::get('https://yd.jylt.cc/api/wxLogin/tempUserId',[
"secret"=>"2e572b30"
]);
if(is_string($result)){
$result = json_decode($result,true);
}
if($result["code"] === 0){
$this->success('成功','',$result["data"]);
}
else{
$this->error($result["msg"]);
}
}
/**
* 轮训请求的接口,验证用户是否已经正常登录上了
*
* @return void
*/
public function checkWxUserStatus()
{
$tempUserId = input('tempUserId');
if($userinfo = Cache::get($tempUserId)){
// 注册或者登录
$user = Db::name('user')->where('openId',$userinfo["openId"])->find();
if($user){
// 登录
$this->auth->direct($user["id"]);
$this->success(__('Logged in successful'), url('user/index'));
}
else{
// 自动注册 并 登录
$res = $this->auth->register($userinfo["nickName"], '12121sadsd', '','',[
"openId"=>$userinfo["openId"],
"unionId"=>$userinfo["unionId"],
]);
if($res){
// 注册成功,登录
$this->auth->direct($this->auth->getUser()->id);
$this->success(__('Logged in successful'), url('user/index'));
}
else{
$this->error('获取信息成功,但注册失败,请重试','',$res);
}
}
}
else{
$this->error('等待');
}
}
© 版权声明
Comments