用户
 找回密码
 入住 CI 中国社区
搜索
查看: 10387|回复: 1
收起左侧

[库 Library] 微信登录授权,适合H5页面使用

[复制链接]
发表于 2017-1-11 14:46:55 | 显示全部楼层 |阅读模式
欢迎一起讨论,使用ci半年,获益良多。希望一起进步,qq 1113288996


weixin.php
PHP复制代码
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');        
        Class Weixin
        {
                private $appId;
                private $appSecret;
                function __construct()
                {
                        $this->appId = trim('');
                        $this->appSecret = trim('');
                }
               
                function redirect_url($redirect)
                {
                        /*授权页面*/
                       
                        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appId&redirect_uri=$redirect&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                        return $url;
                }
                /* 通过code换取access_token*/
                function access_token($code)
                {
                        /*获取到的code换取access_token和openid*/
                       
                        $post_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appId&secret=$this->appSecret&code=$code&grant_type=authorization_code";
                        $return = $this->postdata($post_url);
                       
                        $access_token = $return['access_token'];
                        $openid = $return['openid'];
                       
                        /*获取微信用户数据*/
                        $get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
                        $userinfo = json_decode(file_get_contents($get_userinfo));
                       
                        return $userinfo;
                }
               
                function eff($access_token,$openid)
                {
                        /*检测access_token是否正确,errcode=0 为正确*/
                        $eff_url = "https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid";
                        $get_eff =json_decode(file_get_contents($eff_url));
                        return $get_eff;
                       
                }
               
                function get_subscribe($openid)
                {
                        /*
                                通过用户openid拉取用户信息中subscribe,0为未关注,1为已关注
                        */

 
                                $acc_token = json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}"));
                                $acc_token = $acc_token->access_token;
                                // return $acc_token;
                                $get_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$acc_token}&openid={$openid}&lang=zh_CN";
                                $subscribe_obj = json_decode(file_get_contents($get_url));
                                $subscribe            =        $this->obj_to_arr($subscribe_obj);
 
                                return $subscribe['subscribe'];
 
                }
 
                //通过curl方式提交code换取access_token数据
                function postdata($url)
                {
                         header('Content-Type:text/html;charset=utf-8');
               
                    $curl = curl_init();
                    curl_setopt($curl, CURLOPT_URL, $url);
                    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
                    curl_setopt($curl, CURLOPT_SSLVERSION, 1);
               
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                    $output = curl_exec($curl);
                    curl_close($curl);
                   
                    $access = json_decode($output,true);
                    return $access;
                }
                /*
                        这个位置开始是控制器index()传入的微信用户资料处理
                */

                        function save_session($data)
                        {
                                foreach ($data as $key => $value)
                                {
                                       
                                        $_SESSION[$key] = $value;
 
                                }
                                return $_SESSION;
                                // print_r($_SESSION);exit();
                                // unset($_SESSION[0]);
                               
                        }
                function obj_to_arr($data)
                {
                        // 进行转换成数组 使用 obj_to_arr方式
                        $data = is_object($data)?get_object_vars($data):$data;
                                foreach ($data as $key => $value)
                                {
                                       
                                        $arr[$key] = $value;
                                }
                                return $arr;
                }
 
 
 
 
 
 
        }
 
 
复制代码




  1. Controller页面中需要简单的调用下即可。
  2. 示例
  3. --其他controller以后这样调用即可----
  4. function vipIndex()
  5.                             {
  6.                                     $bid        =        $this->uri->segment(5);
  7.                                     $openid =        $this->session->openid;

  8.                                     $_SESSION['return_url'] =  $_SERVER['REQUEST_URI'];
  9.                                     // 如果openid为空,则需要授权后再进入该页面
  10.                                     if(empty($this->session->openid))header('location:'.'http://h5.imchaotan.com/coupon/index.php/Vip/Coupon/instance_game');

  11.                                     

  12.                                     $getBusiness        =        $this->VipModel->GeneralQuery('cou_business',array('bid'=>$bid));
  13.                                     $data         =        $getBusiness[0] ;
  14.                                     $Jssdk              = new Jssdk();
  15.                                          $signPackage        = $Jssdk->getSignPackage();
  16.                             $data['signPackage']= $signPackage;
  17.                                     $this->load->view('/vip/vip.html',$data);
  18.                             }


  19. --------以下是某一controller必备。-----------
  20.                          /*

  21.                                  微信授权基本设置

  22.                          */

  23.                                   function instance_game()
  24.                                     {
  25.                                         /*进入领取页面,需要先经过授权*/
  26.                                             $redirect_url = 'Vip/Coupon/weixinAccess';
  27.                                             $redirect     = urlencode('http://h5.imchaotan.com/coupon/index.php/'.$redirect_url);
  28.                                             $return       = $this->weixin->redirect_url($redirect);
  29.                                             // echo $return;exit();
  30.                                             header('location:'.$return);
  31.                                     }

  32.                             function weixinAccess()
  33.                                     {
  34.                                         /*
  35.                                                 检测改微信用户是否存在
  36.                                                 $user_arr 获取的是通过get_code返回的微信用户信息,此时的信息是通过微信服务器返回的,不能记录session
  37.                                                 $user std_obj模式,转换为数组
  38.                                                 $user_exists 扔入model中,检测数据表中是否存在该用户
  39.                                                 $redirect 走完流程后,跳转到首页
  40.                                                 if语句的作用,是 判断通过model返回数据表的信息,如果为空则把微信用户信息录入到表中,再读取出来,存进session。
  41.                                                 else 则数据表已经存在该用户,直接读取,存进session
  42.                                                 需要注意的是,使用foreach的原因,是二维数组转一维数组
  43.                                            */
  44.                                                 $user_arr    = $this->get_code();
  45.                                                 // print_r($user_arr);exit();
  46.                                                 $user        = $this->weixin->obj_to_arr($user_arr);
  47.                                                 //检测头像是否和数据库相同
  48.                                                 $user_exists = $this->VipModel->GeneralQuery('cou_user',array('openid'=>$user['openid']));
  49.                                                 if($user_exists['headimgurl'] !== $user['headimgurl'] || $user_exists['nickname'] !== $user['nickname'])
  50.                                                 {
  51.                                                         $this->VipModel->GeneralUpdate('cou_user',array('openid'=>$user['openid']),array('headimgurl'=>$user['headimgurl'],'nickname'=>$user['nickname']));
  52.                                                 }

  53.                                                 $redirect    = 'http://h5.imchaotan.com'.$this->session->return_url;
  54.                                                 
  55.                                                 if(empty($user_exists))
  56.                                                 {
  57.                                                 

  58.                                                 //加入自定义的字符进入数组
  59.                                                 unset($user['privilege']);
  60.                                                 $user_exists['nickname']      = $user['nickname'];
  61.                                                 $user_exists['openid']        = $user['openid'];
  62.                                                 $user_exists['language']      = $user['language'];
  63.                                                 $user_exists['city']          = $user['city'];
  64.                                                 $user_exists['country']       = $user['country'];
  65.                                                 $user_exists['province']      = $user['province'];
  66.                                                 $user_exists['headimgurl']    = $user['headimgurl'];
  67.                                                 $user_exists['sex']           = $user['sex'];
  68.                                                 $user_exists['fullname']      = $user['nickname'];
  69.                                                 $user_exists['telphone']      = '';
  70.                                                 $user_exists['login_ip']      = $this->input->ip_address();
  71.                                                 $user_exists['last_ip']       = $this->input->ip_address();
  72.                                                 $user_exists['groups']        = REGISTER_GROUP_ID;
  73.                                                 $user_exists['status']        = 1;
  74.                                                 $user_exists['login_time']    = date("Y-m-d");
  75.                                                

  76.                                                 try {
  77.                                                                  $insert_id  = $this->VipModel->insertOne('cou_user',$user_exists);
  78.                                                                  $user_exists['uid'] = $insert_id;
  79.                                                 } catch (Exception $e) {
  80.                                                          echo 'Message: ' .$e->getMessage();
  81.                                                 }
  82.                                                 
  83.                                                
  84.                                                 }
  85.                                                 else{
  86.                                                   $user_exists = $user_exists[0];
  87.                                                 }

  88.                                                 
  89.                                                 $this->session->set_userdata($user_exists);

  90.                                                 /*如果session中有return_url,就跳转到return_url中*/
  91.                                                 if(isset($this->session->return_url))header('location:'.$this->session->return_url);
  92.                                                 
  93.                                                 // header('location:'.$redirect);

  94.                                     }

  95.                             function get_subscribe($openid)
  96.                                     {
  97.                                         /*
  98.                                             通过subscribe检测该用户是否是否关注公众号
  99.                                         */
  100.                                         $subscribe = $this->weixin->get_subscribe($openid);
  101.                                         return $subscribe;
  102.                                     }


  103.                             function get_code()
  104.                                 {
  105.                                     if(isset($_GET['code']))
  106.                                     {
  107.                                         $code = $_GET['code'];
  108.                                         // echo $code;exit();
  109.                                         $user_arr = $this->weixin->access_token($code);
  110.                                         //跳转到用户检测中check_exists()去
  111.                                        

  112.                                         return $user_arr;
  113.                                        
  114.                                     }else{
  115.                                         //否则检测cookie中是否存在该用户,如果有,则return回首页
  116.                                             echo 'error';
  117.                                     }
  118.                                  }

复制代码


评分

参与人数 1威望 +5 收起 理由
Hex + 5 很给力!

查看全部评分

发表于 2017-4-19 14:21:16 | 显示全部楼层
access_token 有7200s的有效时间  有次数限制 你每次都刷新了access_token

本版积分规则