fastadmin微信扫码登录网页登录
21-06-01
slbcun
760℃
0
登录页面添加微信登录按钮
{if $openid==''}//判断是否登录状态 <div class="col-xs-4"> <a href="javascript:;" class="btn btn-block btn-success btn-wechat" data-url="third/wechatlogin"> <i class="fa fa-wechat"></i> 微信登录 </a> </div> {/if} //扫码登录页面 <div class="back_black">//back_black灰色半透明背景 <div> <img src="" class="e_img"> <i class="fa fa-close gb"></i> <p>请使用微信扫描二维码登录</p> </div> </div>
2.点击微信登录按钮,发送ajax请求,获取临时二维码并显示在页面
$(".btn-wechat").click(function(){ let url = $(this).data('url'); Fast.api.ajax({ url:url, data:{} }, function(data,ret){ $(".e_img").attr('src',ret.url); $(".back_black").show(); Controller.checkWait('1',ret.data);//定时请求登录状态 return false; //成功的回调 }, function(){ return false; //失败的回调 }); }) //每隔2秒请求数据,获取登录状态 checkWait(d,r){ $("input[name='start']").val(d); var st=setInterval( function(){ Fast.api.ajax({ url:'third/checkLogin', data:{scene_str:r}//随机值赋值给scene_str }, function(data,ret){ window.location.href=ret.url; return false; //成功的回调 }, function(){ return false; //失败的回调 }); var start = Number($("input[name='start']").val()); if(start == 0){ clearInterval(st); } }, 2000); //每2.5秒发送一次请求 }
//php生成二维码 public function wechatlogin(){ $content=Random::uuid();//随机不重复字符串 $app = Factory::officialAccount(Config::get('wechat'));//获取微信配置 $result = $app->qrcode->temporary($content, 600);//二维码有效时间 $url = $app->qrcode->url($result['ticket']); $dir = iconv("UTF-8", "GBK", ROOT_PATH."extend/qrcode");//创建路径 if (!file_exists($dir)) { mkdir($dir, 0777, true); } $dir = ROOT_PATH."extend/qrcode/".$content.".txt";//随机字符串命名一个txt空文档 $myfile=fopen($dir,"w"); fwrite($myfile,''); fclose($myfile); $this->success('生成二维码', $url,$content);//返回二维码链接和随机值 } //扫码登录的时候,获取随机字符串就是$message['EventKey']的值,再把扫码用户的openid写入这个txt文档 $myfile=fopen(ROOT_PATH."extend/qrcode/".$eventKey.".txt","w"); fwrite($myfile,$this->openid); fclose($myfile); //检查登录状态 public function checkLogin(){ if($this->request->post("scene_str")){//获取到随机值 $rand=$this->request->post("scene_str"); $url = $this->request->get('url', 'index/index'); if(file_exists(ROOT_PATH."extend/qrcode/".$rand.".txt")){//获取txt文档里面的openid $info = file_get_contents( ROOT_PATH."extend/qrcode/".$rand.".txt"); if(!empty($info)){//如果有openid,表示已扫码登录,保存登录用户 $user_admin = Db::name('admin')->where('openid',$info)->find(); Session::set('admin', $user_admin); $keeptime=86400*7; $expiretime = time() + $keeptime; $key = md5(md5($user_admin['id']) . md5($keeptime) . md5($expiretime) . $user_admin['token'] . config('token.key')); $data = [$user_admin['id'], $keeptime, $expiretime, $key]; Cookie::set('keeplogin', implode('|', $data), 86400 * 7); } $myfile=fopen(ROOT_PATH."extend/qrcode/".$rand.".txt","w");//清空openid fwrite($myfile,''); fclose($myfile); } if ($this->auth->isLogin()) { $this->success('登录成功', $url,'登录成功');//返回url登录成功后跳转的url } } }