<?php
require __DIR__ . '/inc.php';

$trade_no=isset($_GET['trade_no'])?daddslashes($_GET['trade_no']):exit('No trade_no!');
$type=isset($_GET['type'])?$_GET['type']:'';

@header('Content-Type: application/json; charset=UTF-8');

$row=$DB->getRow("SELECT * FROM pre_pay WHERE trade_no='{$trade_no}' LIMIT 1");
if(!$row) exit(json_encode(array('code'=>-1,'msg'=>'订单不存在')));

if($row['domain'] && $row['domain']!=$_SERVER['HTTP_HOST'] && strpos($row['domain'],'.')!==false){
	$baseurl = 'http://'.$row['domain'].'/';
}else{
	$baseurl = '../';
}

if($row['tid'] != 0){
	$link = $baseurl.'user/index.php';
}else{
	$link = $baseurl.'user/recharge.php';
}

if($row['status']>=1){
	exit(json_encode(array('code'=>1,'msg'=>'付款成功','backurl'=>$link)));
}

// 支付宝：未付款时主动查询一次（解决本地/内网无法收到异步通知的问题）
if($type==='alipay'){
	$interface_id = isset($row['interface_id']) ? intval($row['interface_id']) : 0;
	if($interface_id > 0){
		$interface = $DB->getRow("SELECT config FROM pre_pay_interface WHERE id='{$interface_id}' LIMIT 1");
		if($interface){
			$interface_config = json_decode($interface['config'], true);
			if($interface_config){
				if(isset($interface_config['appid'])) $conf['alipay_appid'] = $interface_config['appid'];
				if(isset($interface_config['publickey'])) $conf['alipay_publickey'] = $interface_config['publickey'];
				if(isset($interface_config['privatekey'])) $conf['alipay_privatekey'] = $interface_config['privatekey'];
			}
		}
	}
	require_once(SYSTEM_ROOT.'alipay/model/builder/AlipayTradeQueryContentBuilder.php');
	require_once(SYSTEM_ROOT.'alipay/AlipayTradeService.php');
	try{
		$queryBuilder = new AlipayTradeQueryContentBuilder();
		$queryBuilder->setOutTradeNo($trade_no);
		$alipayService = new AlipayTradeService($config);
		$queryResponse = $alipayService->query($queryBuilder);
		if(!empty($queryResponse) && $queryResponse->code=='10000' && in_array($queryResponse->trade_status, array('TRADE_SUCCESS','TRADE_FINISHED'), true)){
			$api_trade_no = isset($queryResponse->trade_no) ? daddslashes($queryResponse->trade_no) : '';
			$DB->exec("UPDATE `pre_pay` SET `status`='1',`endtime`='$date',`api_trade_no`='$api_trade_no' WHERE `trade_no`='{$trade_no}'");
			processOrder($row);
			exit(json_encode(array('code'=>1,'msg'=>'付款成功','backurl'=>$link)));
		}
	}catch(Exception $e){}
}

exit(json_encode(array('code'=>-1,'msg'=>'未付款')));
