<?php
global $db,$baseUrl;
$config = getConfig("taobaoLogin");
if(!$config || !$config['appKey'] || !$config['appSecret']){
	Msg::show("淘宝账号登录未配置或未启用");
}
$appKey = $config['appKey'];
$appSecret = $config['appSecret'];
$host = $_SERVER['HTTP_HOST'];
$callback = "http://".$host.$baseUrl."user/quicklogin/type/taobao/act/callback/";
$path = str_replace("/taobao.inc.php","/",str_replace("\\","/",__FILE__));
require($path."function.php");
$act = getgpc("act");
if($act=="callback"){
	 $code = $_REQUEST['code'];   //通过访问https://oauth.taobao.com/authorize获取code
	 $grant_type = 'authorization_code';
	 $redirect_uri = $callback;  //此处回调url要和后台设置的回调url相同
	 
	 //请求参数
	 $postfields= array('grant_type'     => $grant_type,
						 'client_id'     => $appKey,
						 'client_secret' => $appSecret,
						 'code'          => $code,
						 'redirect_uri'  => $redirect_uri
	 );
	 $url = 'https://oauth.taobao.com/token';	//print_r($postfields);
	 $token = json_decode(curl($url,$postfields));//print_r($token);
	$taobao_user_id = $token->taobao_user_id;
				load_class("user");
			$um = new UserModel();
	
		$sql = "select userId from qk_taobao_auth where user_id='$taobao_user_id'";
		$userId = $db->getOne($sql);
		if($userId && is_numeric($userId) && $db->getOne("select id from qk_user where id='".$userId."'")){
					$um->quickLogin($userId);
		}else{
			$access_token = $token->access_token;
			$refresh_token = $token->refresh_token;
			$taobao_user_nick = $token->taobao_user_nick;

			$params = array();
			$params['loginName'] = "TAOBAOLOGIN_".$taobao_user_id; 
			$params['nickname'] = $taobao_user_nick;
			$userId = $um->add($params,true);
			if($userId){
				$sql = "insert into qk_taobao_auth set userId='$userId',user_id='$taobao_user_id',access_token='$access_token',refresh_token='$refresh_token'";
				$sql .= ",updatetime=UNIX_TIMESTAMP(),posttime=UNIX_TIMESTAMP()";
				if($db->query($sql)){
					$um->quickLogin($userId);
				}
			}else{
				echo $um->msg;
			}
		}
 
	 //打印token
	 //echo "token返回结果：</br>";
	 //echo json_encode($token);

}else{
	$url = "https://oauth.taobao.com/authorize?response_type=code&client_id=".$appKey."&redirect_uri=$callback";
	header("Location:$url");
}


//token返回结果：</br>{"w2_expires_in":31536001,"taobao_user_id":"106673058","taobao_user_nick":"cgndg","w1_expires_in":31536001,"re_expires_in":0,"r2_expires_in":31536001,"expires_in":31536001,"token_type":"Bearer","refresh_token":"6200812fa390a7167df1ZZ9192f8af6fc9c008f6f31fa73106673058","access_token":"62029120c223b2ec6d8egi3a40096360dd4f6dba13651cc106673058","r1_expires_in":31536001}
?>