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

    public $info = array(
        'name'=>'qq',
        'title'=>'qq登录插件',
        'description'=>'qq登录插件',
        'status'=>1,
        'author'=>'bymall',
        'version'=>'0.1',
		'admin'=>'0',
		'index'=>'0',
		 'ids'=>''
    );
//qq认证链接
    public function index(){ 

	$config=$this->getConfig();
	
	$app_id =  $config['QQKEY']; 
      //应用的APPKEY 
     $app_secret = $config['QQSECRET']; 
	 if(!$app_id||!$app_secret){
		    $this->error( "插件配置不能为空");
	          } 
   //【成功授权】后的回调地址，即此地址在腾讯的信息中有储存 
    $code_url= plugin_url("qq://qq/callback");
	//root_url().url('callback');//回调地址
    //state参数用于防止CSRF攻击，成功授权后回调时会原样带回 
     session('state', md5(uniqid(rand(), TRUE))); 
    //拼接URL 
    $url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
     . $app_id . "&redirect_uri=" . urlencode($code_url) . "&state="
     .session('state'); 
     header('Location: '.$url);
	 exit;
	}
      //用户同意授权链接获取code
   public function callback(){ 
    $app_id = api('QQKEY');  $code_url=root_url().url('callback');//回调地址
      //应用的APPKEY 
     $app_secret =api('QQSECRET'); 
	  	   if(input('state') == session('state')) { 
    //拼接URL 
    $url= "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
     . "client_id=" . $app_id . "&redirect_uri=" . $code_url
     . "&client_secret=" . $app_secret . "&code=" . $code; 
    $result = file_get_contents($url); 
    if (strpos($result, "callback") !== false){ 
        $lpos = strpos($result, "("); 
        $rpos = strrpos($result, ")"); 
        $result = substr($result, $lpos + 1, $rpos - $lpos -1); 
        $msg = json_decode($result); 
        if (isset($msg->error)) { 
           $this->error( $msg->error);
           exit; 
        } 
    } 
    $params = array(); 
    parse_str($result, $params);//把传回来的数据参数变量化 
    $access_token_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token']; 
    $str = file_get_contents($access_token_url); 
    if (strpos($str, "callback") !== false) { 
     $lpos = strpos($str, "("); 
     $rpos = strrpos($str, ")"); 
     $str = substr($str, $lpos + 1, $rpos - $lpos -1); 
    } 
    $user = json_decode($str);//存放返回的数据 client_id ，openid 
	$openid=$user->openid;
    //dump($user);
    if ( !$openid) { 
       $this->error( $user->error); 
       exit; 
    }
 
    $get_user_info_url = "https://graph.qq.com/user/get_user_info?access_token={$params['access_token']}&oauth_consumer_key={$app_id}&openid={$user->openid}&format=json"; 
      
    $arr = file_get_contents($get_user_info_url);//此为获取到的user信息 
	$arr = json_decode ( $arr, true );
    } 
    else
    { 
     echo("The state does not match. You may be a victim of CSRF."); 
    } 
	$uid= $this->get_uid_by_ucenter($openid,$app_id,$arr["nickname"]);
		if(0 < $uid){ //UC登录成功
						/* 登录用户 */
			        $User=new \app\common\model\User;
					if($User->send($uid)){ 
							//登录用户，记录日志
						 $url= session("url");
						 session("url".null);
						 $url=$url?$url:url('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();
				 $data2["reg_ip"]=request()->ip();
				 $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;
		}
	}

    public function install(){
		$prefix = config("database.prefix");
        $sql="INSERT INTO {$prefix}hooks (name,description,addons,status) VALUES ('qq', 'qq登录插件','qq','1');";
        Db::query($sql);
        return true;
    }

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

}