<?php
global $db;
$path = str_replace("/alipay.inc.php","/",str_replace("\\","/",__FILE__));
require_once($path."alipay.config.php");
require_once($path."lib/alipay_service.class.php");

$act = getgpc("act");
if($act=="callback"){
	require_once($path."lib/alipay_notify.class.php");
	$alipayNotify = new AlipayNotify($aliapy_config);
	$verify_result = $alipayNotify->verifyReturn();
	if($verify_result) {//验证成功
		$user_id	= $_GET['user_id'];	//支付宝用户id
		load_class("user");
		$um = new UserModel();
		$token		= $_GET['token'];	
		$sql = "select userId from qk_alipay_auth where user_id='$user_id'";
		$userId = $db->getOne($sql);
		if($userId && is_numeric($userId) && $db->getOne("select id from qk_user where id='".$userId."'")){
				$sql = "update qk_alipay_auth set token='$token',updatetime=UNIX_TIMESTAMP() where user_id='$user_id'";
				$db->query($sql);
				saveLog("支付宝账号登录 TOKEN：$token  user_id：$user_id",0,0,$userId);
				if(!$um->quickLogin($userId)){
					$db->query("delete from qk_alipay_auth where user_id='$user_id'");
					createAlipayUser();
				}
		}else{
			createAlipayUser();
		}
	}
	else {
		exit("Alipay Login Error (0)");
	}

}else{
	$parameter = array(
		"service"			=> "alipay.auth.authorize",
		"target_service"	=> 'user.auth.quick.login',
		
		"partner"			=> trim($aliapy_config['partner']),
		"_input_charset"	=> trim(strtolower($aliapy_config['input_charset'])),
        "return_url"		=> trim($aliapy_config['return_url']),

        "anti_phishing_key"	=> $anti_phishing_key,
			"exter_invoke_ip"	=> $exter_invoke_ip
	);

	//构造快捷登录接口
	$alipayService = new AlipayService($aliapy_config);
	$html_text = $alipayService->alipay_auth_authorize($parameter);
	echo $html_text;
}

function createAlipayUser(){
	global $db;
			load_class("user");
		$um = new UserModel();
	$user_id = $_GET['user_id'];
	$token		= $_GET['token'];	
			$real_name = $_GET['real_name'];
			$email = $_GET['email'];

			//执行商户的业务程序
				$params = array();
				$params['loginName'] = "ALIPAYLOGIN_".$user_id; 
				$params['nickname'] = $real_name;
				$params['email'] = $email;
				$userId = $um->add($params,true);
				if($userId){
					$sql = "insert into qk_alipay_auth set userId='$userId',user_id='$user_id',token='$token'";
					$sql .= ",updatetime=UNIX_TIMESTAMP(),posttime=UNIX_TIMESTAMP()";
					if($db->query($sql)){
						$um->quickLogin($userId);
					}
				}else{
					Msg::show('自动创建用户失败('.$um->msg.')');
				}
}
?>