<?php
/**
  * @method qq api
  * @author soul
  * @copyright 2016/3/31
  */
class MainQQ
{
	/*
	<method>
		<name>获取用户信息</name>
		<remark></remark>
		<exp.>https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839&token=&lang=zh_CN</exp.>
		<Parameter></Parameter>
		<return></return>
		<author>Soul 2017/1/9</author>
	</method>
	*/
	public function getAppUser($appKey, $token)
	{
		if(empty(mvc::$cfg['QQ'][$appKey])) return LibFc::ReturnData(false, 'app key 不存在');
		$LibCurl = new LibCurl();
		$cof = mvc::$cfg['QQ'][$appKey];
		$url = 'https://graph.qq.com/oauth2.0/me?access_token='.$token.'&unionid=1';
		$res = $LibCurl->fetch($url);
		$res =  substr($res, 9, -3);
		$baseRes = json_decode($res, true);
		//https://graph.qq.com/user/get_user_info?access_token=392C2D6F1D284C76F04AA5A7DEB2F357&openid=6DE380153BDAE183A4CCBE95AE202400&oauth_consumer_key=101534400
		$url = 'https://graph.qq.com/user/get_user_info?access_token='.$token.'&openid='.$baseRes['openid'].'&oauth_consumer_key='.$cof['appid'];
		$res = $LibCurl->fetch($url);
		$res = json_decode($res, true);
		if(empty($res['nickname'])) return LibFc::ReturnData(false, 'getAppUser 获取用户信息失败！');
		$res = array_merge($baseRes, $res);
		return LibFc::ReturnData(true, $res);
	}


	/**
	  * @method 获取用户信息
	  * @author soul
	  * @copyright 2017/8/16
	  * @return
			成功：['status'=>true, 'data'=>]
			失败：['status'=>false, 'data'=>'xxx', 'code'=>'xxx']
	  */
	public function getUserByCode($appKey, $userCode, $backUrl = '')
	{
		if(empty(mvc::$cfg['QQ'][$appKey])) return LibFc::ReturnData(false, 'app key 不存在');
		$LibCurl = new LibCurl();
		$cof = mvc::$cfg['QQ'][$appKey];
		$redirect_uri = urlencode($cof['redirect_url'].'&backurl='.base64_encode($backUrl));
		$url = 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id='.$cof['appid'].'&client_secret='.$cof['secret'].'&code='.$userCode.'&redirect_uri='.$redirect_uri;
		$html = $LibCurl->fetch($url);
		parse_str($html, $tokenArr);
		if(empty($tokenArr['access_token'])) return LibFc::ReturnData(false, 'getUserByCode 获取access_token失败！');
		return $this->getAppUser($appKey, $tokenArr['access_token']);
	}
}