<?php
namespace plugin\wechat;
use app\index\behavior\Plugin;
use think\Db;
class Wechat extends Plugin{

    public $info = array(
        'name'=>'wechat',
        'title'=>'微信登录插件',
        'description'=>'微信登录插件',
        'status'=>1,
        'author'=>'bymall',
        'version'=>'0.1',
		'admin'=>'0',
		'index'=>'0',
		 'ids'=>''
    );

     //微信认证链接
       public function index(){
		   
		  $config=$this->getConfig();
	
	  $config=$this->getConfig();
	
	  $appid= $config['appid']; 
      //应用的APPKEY 
     $secret = $config['appSecret']; 
	 if(!$appid||!$secret){
		        $this->error( "插件配置不能为空");
	          } 
		    $code_url=plugin_url("wechat://wechat/callback");//回调地址
			//$appid=api("APPID") ;
			$code_url="https://open.weixin.qq.com/connect/qrconnect?appid=".$appid."&redirect_uri="
			.$code_url."&response_type=code&scope=snsapi_login&state=mahuateng&connect_redirect=1#wechat_redirect";
            //  echo $url;
			header('Location: '.$code_url);
			exit;
        }
      //用户同意授权链接获取code
       public function callback(){        
           $code=$_GET['code'];
		   if (empty ( $code )) {
			    $this->error ( '获取code失败' );
		   }  
		   $config=$this->getConfig();
	
	  $appid= $config['appid']; 
      //应用的APPKEY 
     $secret = $config['appSecret']; 
	 if(!$appid||!$secret){
		         exception( "插件配置不能为空");
	          }   
		   //$appid=api("APPID") ;
		   //$secret=api("APPSECRET");
		   $state = 'a-zA-Z0-9';
		 
           $url ='https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid. '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code'; 
	         $ch1 = curl_init ();
		     $timeout = 5;
		     curl_setopt ( $ch1, CURLOPT_URL, $url );
		     curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
		     curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
		     $res = curl_exec ( $ch1 );
		     curl_close ( $ch1 );
		     $access = json_decode ( $res, true );//取得access_token

		    if (empty ( $access ['access_token'] )) {
			   $this->error ( '获取access_token失败,请确认AppId和Secret配置是否正确,然后再重试。'.$info ['appid'].$info ['secret'] );
		    }else{
				$access_token=$access ['access_token'];
				$openid =$access['openid'];
				$access_token=$access ['access_token'];
			   // 拉取用户信息(需scope为 snsapi_userinfo)
                session('access',$access_token); //保存授权信息  
			    session('refresh_token ',$access["refresh_token "]); //保存授权信息   
				$refresh_token=$access["refresh_token "];
				//$re=$this->get_refresh_token($appid, $refresh_token); 
				$data= $this->get_user_info($access_token ,$access['openid']); 
				$condition ['openid'] =$openid;
				$condition ['token'] = $appid;
                $uid= $this->get_uid_by_ucenter($openid,$appid,$data["nickname"]);
				if(0 < $uid){ //UC登录成功
						/* 登录用户 */
					$User=new \app\common\model\User;
					if($User->send($uid)){ 
							//登录用户，记录日志
						 $url= session("url");
						 session("url".null);
						 $url=$url?$url:root_url().url('index/index/index');
                         Header("Location:". $url);
						 exit;
					}
				}
			}         				
	   }
	 // 自动初始化用户
	 public function get_uid_by_ucenter($openid,$appid,$nickname) {
		
		$info ['openid'] = $openid;
		$info ['token'] =  $appid;
		$res = db ( 'thirdLogin' )->where ( $info )->find ();
		if ($res){
			return $res ['uid'];
		}
		else {
			 $data2["username"]=$nickname;//用户名
              $data2["password"]=encode("123456");//密码
		     $user = db ( 'user' )->where ( $data2 )->find ();
		    if ($user){
		       $uid=$user['id'];
		     }else{
				 $data2["email"]="1213@qq.com";//密码
				 $data2["status"]=1;
				 $data2["reg_time"]=time();
				 
				 $uid=db ( 'User' )->insertGetId($data2);
		     	
		     }
			 //写入用户
             $info["uid"]=$uid;
			 $info["access_token"]=session("access_token");
			 $info["refresh_token"]=session("refresh_token");
			 $info["create_time"]=time();
             $id=db ( 'thirdLogin' )->insertGetId($info);
			return $uid?$uid:0;
		}
	}
 // 拉取用户信息(需scope为 snsapi_userinfo)
 
      public function get_user_info($access_token = '', $openid = ''){
             $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
             $ch1 = curl_init ();
		     $timeout = 5;
		     curl_setopt ( $ch1, CURLOPT_URL, $url );
		     curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
		     curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
		     $data = curl_exec ( $ch1 );
		     curl_close ( $ch1 );
		     $info = json_decode ( $data, true );//取得access_token
			return $info;          
    }
    public function get_refresh_token($appid= '', $r = ''){
            $url = "https://api.weixin.qq.com/sns/refresh_token?a?appid={$appid}&grant_type=refresh_token&refresh_token={$r}}";
             $ch1 = curl_init ();
		     $timeout = 5;
		     curl_setopt ( $ch1, CURLOPT_URL, $url );
		     curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
		     curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
		     $data = curl_exec ( $ch1 );
		     curl_close ( $ch1 );
		     $access = json_decode ( $data, true );//取得access_token
		
			return $access;          
    }
    
	public function install(){
		$prefix = config("database.prefix");
        $sql="INSERT INTO {$prefix}hooks (name,description,addons,status) VALUES ('wechat', 'wechat登录插件','wechat','1');";
        Db::query($sql);
        return true;
    }

    public function uninstall(){
		$prefix = config("database.prefix");
        $sql="delete from {$prefix}hooks where name='wechat' and addons='wechat';";
        Db::query($sql);
        return true;
    }
     
	 /**
     * 实现demo钩子
     * @param array $params
     */
     public function wechat($params = [])
    { 
	    //print_r($this->getConfig());
        //echo 'demo hook!page is ' . $params['p'];
	    return $this->fetch('info');
	  
		
    }
}