zoukankan      html  css  js  c++  java
  • Fastadmin/thinkphp 微信登录授权 Demo

    由于经常用这些 就搞个示例方便调用吧!

    这是index里面的文件

    到时候就直接访问    /index.php/index/index/wxindex

    <?php
    
    namespace appindexcontroller;
    
    use appcommoncontrollerFrontend;
    use fastWxsdk;
    
    
    class Index extends Frontend
    {
    
        protected $noNeedLogin = '*';
        protected $noNeedRight = '*';
        // protected $layout = '';
        public function  _initialize(){
            $this->appId = 'wx63c391768f362ca8';  //wxe6747dc052817254
            $this->appSecret = '512ec5eb6117b86bcaccf3f10b45edc2';  //
        }
    
    
    
    
    
        public function wxindex()
        {    
    
            $this->Wxsdk = new Wxsdk($this->appId,$this->appSecret);
    
            if(!$this->Wxsdk->islogin()){
                $user = $this->Wxsdk->login();
                if(!empty($user['openid'])){
                    //存数据库
                    $this->add_Wxuser($user);//获取到微信用户  存数据
    
                    // 然后继续操作
                }else{
                   $this->success('error', $user);
                }
    
            }
    
        }
    
        public function add_Wxuser($user){
            //在你的数据库 添加用户信息
            dump($user);
        }
    
    
    
    }

    里面加载的类文件(QQ496631085)

    文件名Wxsdk.php  放在extendfast目录下面  看框架及版本 定义

      1 <?php
      2 
      3 namespace fast;
      4 
      5 
      6     class Wxsdk
      7     {
      8         private $appId;
      9         private $appSecret;
     10         
     11         public function __construct($appId, $appSecret) {
     12             $this->appId = $appId;
     13             $this->appSecret = $appSecret;
     14         }
     15 
     16 
     17         public function islogin(){
     18             //验证是否登录过,如果没有登录就跳转
     19              if(empty(session('openid'))){
     20                     // $this->getUserOpenId();
     21                     return false;
     22                 // $this->redirect('/index/index/me');
     23                     // exit();
     24                 }else{
     25                     // echo " ";
     26                     return true;
     27                     // dump(session('openid'));
     28                 }
     29         }
     30 
     31         public function login(){
     32             // $user ='1111';
     33             $user = $this->getUserOpenId();
     34 
     35             return $user;
     36         }
     37 
     38 
     39         public function getBaseInfo(){
     40             //1.获取到code        
     41            
     42            
     43             // $redirect_uri=urlencode($this->domain()."/index/index/index");//跳转 可以自己改参数 QQ496631085
     44             $redirect_uri=urlencode($this->domain()."/index/index/wxindex");
     45 
     46             $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appId."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=xiaohe#wechat_redirect";
     47 
     48             echo '<script>;location.href="'.$url.'";</script>;';
     49             exit();
     50         }
     51 
     52 
     53 
     54 
     55         /**
     56      * 判断是否为https
     57      * @return bool 是https返回true;否则返回false
     58      */
     59       public function domain() {
     60             if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
     61                 return 'https://'.$_SERVER['HTTP_HOST'];
     62             } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
     63                 return 'https://'.$_SERVER['HTTP_HOST'];
     64             } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
     65                 return 'https://'.$_SERVER['HTTP_HOST'];
     66             }else{
     67                 return 'http://'.$_SERVER['HTTP_HOST'];
     68             }
     69         }
     70 
     71          //查询这个用户的信息
     72         public function openid_nickname($openid){
     73            $nickname = Db::name('wxuser')->where('openid',$openid)->find();
     74            return $nickname['nickname'];
     75         }
     76 
     77         //获取用户的openid等信息
     78         public function getUserOpenId(){
     79             if(!empty($_SERVER['HTTP_REFERER']))
     80             file_put_contents('tiaozhuan.txt', $_SERVER['HTTP_REFERER'].'
    ',FILE_APPEND);
     81             // exit($_GET);
     82             //2.获取到网页授权的access_token        
     83             
     84             
     85             // if(empty($this->request->get('code'))){
     86             if(empty($_GET['code'])){
     87                 $this->getBaseInfo();
     88                 exit();
     89             }
     90             // dump($this->request->get());
     91             $code = $_GET['code'];//?????????????????
     92             $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code ";
     93             //3.拉取用户的openid
     94             $res = file_get_contents($url);
     95 
     96             $data = json_decode($res,true);
     97             if(!empty($data['access_token']) && !empty($data['openid'])){
     98                 $this->access_token=$data['access_token'];
     99                 $this->refresh_token=$data['refresh_token'];
    100                 
    101                 $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN"; 
    102                 $userInfo = file_get_contents($url);
    103                 $user_res = json_decode($userInfo,true);
    104                 // echo $userInfo;
    105                 return $user_res;
    106     //             $this->openid = $user_res['openid'];
    107     //             $this->nickname = base64_encode($user_res['nickname']);
    108     //             $this->headimgurl = $user_res['headimgurl'];
    109     //             $this->sex = $user_res['sex'];
    110     // // dump($user_res);
    111     //             //获取都用户信息然后判断是否新用户 存表
    112     //             session('openid',$this->openid);
    113  //                if(!empty($_SERVER['HTTP_REFERER'])){
    114  //                   $this->redirect($_SERVER['HTTP_REFERER']);
    115  //                }
    116  //                else{
    117  //                   $this->redirect($this->_domain.'/index/index/index');
    118  //                }
    119 
    120             }else{
    121                 return($data);
    122                 // $this->getUserOpenId();
    123                 exit();
    124             }
    125         }
    126 
    127 
    128 
    129         
    130         public function getSignPackage() {
    131             $jsapiTicket = $this->getJsApiTicket();
    132             
    133             // 注意 URL 一定要动态获取,不能 hardcode.
    134             $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    135             $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    136             
    137             $timestamp = time();
    138             $nonceStr = $this->createNonceStr();
    139             
    140             // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    141             $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    142             
    143             $signature = sha1($string);
    144             
    145             $signPackage = array(
    146                 "appId"     => $this->appId,
    147                 "nonceStr"  => $nonceStr,
    148                 "timestamp" => $timestamp,
    149                 "url"       => $url,
    150                 "signature" => $signature,
    151                 "rawString" => $string
    152             );
    153             return $signPackage;
    154         }
    155         
    156         private function createNonceStr($length = 16) {
    157             $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    158             $str = "";
    159             for ($i = 0; $i < $length; $i++) {
    160                 $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    161             }
    162             return $str;
    163         }
    164         
    165         private function getJsApiTicket() {
    166             // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    167             if(file_get_contents("jsapi_ticket.json")){
    168                 $data = json_decode(file_get_contents("jsapi_ticket.json"));
    169             }else{
    170                 $data = null;
    171             }
    172             
    173 
    174             if ($data->expire_time < time()) {
    175                 $accessToken = $this->getAccessToken();
    176                 // 如果是企业号用以下 URL 获取 ticket
    177                 // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
    178                 $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
    179                 $res = json_decode($this->httpGet($url));
    180                 $ticket = $res->ticket;
    181                 if ($ticket) {
    182                     $data->expire_time = time() + 7000;
    183                     $data->jsapi_ticket = $ticket;
    184                     $fp = fopen("jsapi_ticket.json", "w");
    185                     fwrite($fp, json_encode($data));
    186                     fclose($fp);
    187                 }
    188             } else {
    189                 $ticket = $data->jsapi_ticket;
    190             }
    191             
    192             return $ticket;
    193         }
    194         
    195         private function getAccessToken() {
    196             // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    197             $data = json_decode(file_get_contents("access_token.json"));
    198             if ($data->expire_time < time()) {
    199                 // 如果是企业号用以下URL获取access_token
    200                 // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
    201                 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
    202                 $res = json_decode($this->httpGet($url));
    203                 $access_token = $res->access_token;
    204                 if ($access_token) {
    205                     $data->expire_time = time() + 7000;
    206                     $data->access_token = $access_token;
    207                     $fp = fopen("access_token.json", "w");
    208                     fwrite($fp, json_encode($data));
    209                     fclose($fp);
    210                 }
    211             } else {
    212                 $access_token = $data->access_token;
    213             }
    214             return $access_token;
    215         }
    216         
    217         private function httpGet($url) {
    218             $curl = curl_init();
    219             curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    220             curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    221             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    222             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    223             curl_setopt($curl, CURLOPT_URL, $url);
    224             
    225             $res = curl_exec($curl);
    226             curl_close($curl);
    227             
    228             return $res;
    229         }
    230     }
    View Code

    然后就可以继续操作了  

  • 相关阅读:
    获取文件夹下的所有文件名,并修改某些文件名 Alec
    生成XML文件,并保存到本地文件 Alec
    按Enter键起到Tab键的效果 Alec
    网站底部浮动js Alec
    NET Framework4.0注册 Alec
    从FTP上下载文件到本地 Alec
    生成txt日志操作文件 Alec
    不使用第三个变量,实现两个变量值的交换 Alec
    生成指定位数的回文素数 Alec
    单击gridview某一列弹出详细信息 Alec
  • 原文地址:https://www.cnblogs.com/xiaohe520/p/12447042.html
Copyright © 2011-2022 走看看