qq登陸

<?php
// =============qq登陸(僅供測試使用)==============
$qq = new QQ;
if( !isset($_GET['code']) ){
	$qq->login();
}else{
	$qq->access_token($_GET['code']);
	$qq->get_user_info(); // 獲取用戶信息。
}

class QQ{
	private $appid,$appkey,$redirect_uri,$access_token,$openid,$img;

	public function __construct(){
		$this->appid = "";
		$this->appkey =  "";
		$this->redirect_uri = "http://www.useryx.net";
		$this->img = "./qq_login.png"; // qq登陸圖片
		echo '<html>
		<head>
			<meta charset="UTF-8">
			<meta property="qc:admins" content="126626657765352106654" />
		</head>
		<body>';
	}
	// 測試
	public function html($url){
		// 等同於加載模板
		echo '<a href="'.$url.'"><img src="'.$this->img.'" alt="QQ登陸"></a>';
	}
	// qq登陸,頁面
	public function login(){
		// $this->ceshi(); exit;  // 此處打開做驗證。默認關閉。
		$url = "https://graph.qq.com/oauth2.0/authorize";
		$array = array(
	            "response_type" => "code",
	            "client_id" => $this->appid,
	            "redirect_uri" => $this->redirect_uri,
	            "state" => time(),
	            "scope" => "get_user_info,get_info,add_t,del_t,add_pic_t,get_repost_list,get_other_info,get_fanslist,get_idollist,add_idol,del_idol", // 以獲取的權限。
	        );
		$url = $url.'?'.http_build_query($array);
		$this->html($url);
	}
	public function access_token($code){
		$url = "https://graph.qq.com/oauth2.0/token";
		$array = array(
			"grant_type" => "authorization_code",
			"client_id" => $this->appid,
			"client_secret" => $this->appkey,
			"code" => $code,
			"redirect_uri" => $this->redirect_uri,
		);
		$url = $url.'?'.http_build_query($array);
		$token = file_get_contents($url);
		// 獲取token,解析字符串
		$a = explode("&",$token);
		for ($i=0; $i < count($a); $i++) { 
			$ar = explode("=",$a[$i]);
			$arr[$ar[0]] = $ar[1];
		}
		$this->access_token = $arr['access_token'];
		$this->openid();
	}
	// 用戶基礎信息。
	public function openid(){
		$url = "https://graph.qq.com/oauth2.0/me?access_token=$this->access_token";
		$str = file_get_contents($url);
		// 正則匹配
		preg_match("/{.*}/i",$str,$m); 
		$user = json_decode($m[0],true);
		// echo '<pre>用戶基礎信息爲:<br>';
		// print_r($user);
		// echo '<pre>';
		$this->openid = $user['openid'];
	}
	public function get_user_info(){
		$url = "https://graph.qq.com/user/get_user_info?";
		$array = array(
			"access_token" => $this->access_token,
			"oauth_consumer_key" => $this->appid,
			"openid" => $this->openid,
		);
		$get_user_info = file_get_contents($url.http_build_query($array));
		$get_user_info =  json_decode($get_user_info,true);
		echo '<pre>';
		print_r($get_user_info);
	}
	// 析構方法
	public function __destruct(){
		echo "</body>	</html>";
	}
}

發佈了86 篇原創文章 · 獲贊 18 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章