AdminWeixinLogin.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace app\index\controller;
  3. use think\Db;
  4. /**
  5. * 后台微信登录
  6. * Created by PhpStorm.
  7. * User: Titan 名字就是密码
  8. * Date: 2019/5/5
  9. * Time: 17:21
  10. */
  11. class AdminWeixinLogin extends \think\Controller
  12. {
  13. private $appid =APPID;
  14. private $appsecret=APPSECRET;
  15. public function index()
  16. {
  17. if(isset($_GET['code'])){
  18. $code = $_GET['code'];
  19. $state = $_GET['state'];
  20. if(time()-$_GET['time']>120){//判断二维码失效
  21. $this->assign('isauth','hasexpire');
  22. return view();
  23. }
  24. //获取openid
  25. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=$this->appsecret&code=$code&grant_type=authorization_code";
  26. $info = json_decode($this->https_request($url), true);
  27. $openid = $info['openid'];
  28. if(!$openid){
  29. $this->assign('isauth','err');
  30. return view();
  31. }
  32. //查看是否绑定管理员
  33. $admin = \think\Db::name('admin')->where(['openid'=>$info["openid"],'status'=>0])->find();
  34. if(!$admin){
  35. $this->assign('isauth','nobind');
  36. return view();
  37. }
  38. //记录状态用于后台登录轮询
  39. $login_id = Db::name('login')->where(['openid'=>$openid,'uid'=>$admin['id']])->value('id');
  40. if(!$login_id){
  41. $res = Db::name('login')->insert(['openid'=>$openid,'uid'=>$admin['id'],'code'=>$state,'create_time'=>time()]);
  42. }else{
  43. $res = Db::name('login')->where('id',$login_id)->setField('code',$state);
  44. }
  45. if($res){
  46. $this->assign('isauth','suss');
  47. return view();
  48. }
  49. }else{
  50. $this->assign('isauth','err');
  51. return view();
  52. }
  53. }
  54. public function https_request($url, $data = null)
  55. {
  56. $curl = curl_init();
  57. curl_setopt($curl, CURLOPT_URL, $url);
  58. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  59. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  60. if (!empty($data)) {
  61. curl_setopt($curl, CURLOPT_POST, 1);
  62. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  63. }
  64. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  65. $output = curl_exec($curl);
  66. curl_close($curl);
  67. return $output;
  68. }
  69. }