<?php
 /**
 *      [XCECP] (C) Colorful Network Inc.
 *      This is NOT a freeware, use is subject to license terms
 */
if(!defined("IN_QKWEB")){exit("Access Denied");}
class Pay{
	public $payfor="";
	public $msg;
	function paymentInfo($paymentId){
			global $db;
			$sql = "select * from `qk_payment` where id='$paymentId'";
			$res = $db->getRow($sql);
			return $res;
	}

	function getConfig($paymentId){
		$info = $this->paymentInfo($paymentId);
		$config = $info['config'];
		$config = unserialize($config);
		if(!$config || !is_array($config)){ saveLog('支付接口'.$paymentId.'未配置');exit('支付方式未配置'); }
		foreach($config as $item){
			$config[$item['name']] = $item['value'];
		}
		return $config;
	}

	function order($paymentId,$amount,$orderId=0,$loginName=false,$bank=''){
		global $db;
			$typeId = $db->getOne("select typeId from `qk_payment` where id='$paymentId'");
			$className = $db->getOne("select className from qk_paytype where id='$typeId'");
			$className = ucfirst(strtolower($className));
			if($className){
				$outTradeNo = date("YmdHis").rand(1000,9999);
				$userId = $_SESSION['userId'];
				if($loginName){
					$tmpUserId = $db->getOne("select id from `qk_user` where loginName='$loginName'");
					if(isset($tmpUserId) && $tmpUserId){$userId = $tmpUserId;}
				}else{
					$loginName = $db->getOne("select loginName from `qk_user` where id='$userId'");
				}
				$sql = "insert into qk_onlinepay set userId='$userId',outTradeNo='$outTradeNo',amount='$amount',paymentId='$paymentId',iStatus=11,orderId='$orderId',posttime=UNIX_TIMESTAMP()";
				$db->query($sql);
				require(ROOT_PATH."plugins/pay/".$className.".class.php");
				$pay = new $className();
				if($orderId){
					$_POST['subject'] = '为订单：'.$orderId.'付款';
				}else{
					$_POST['subject'] = $GLOBALS['siteConf']['siteName'].' 充值款';
				}
				$pay->pay($paymentId,$amount,$outTradeNo,$bank);
			}else{
				Msg::show('未定义支付方式处理类');
			}
	}

 	public static function html($url,$param,$method='post',$auto=true,$title='正在为您跳转到银行页面，请稍候...'){
		$html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>'.$title.'</title><style type="text/css">body {margin:0;padding:0;}p {position:absolute;left:50%;top:45%;width:320px;height:30px;margin:-35px 0 0 -160px;padding:20px;font:bold 14px/30px "宋体", Arial;background:#f9fafc url('.$GLOBALS['baseUrl'].'static/images/loading.gif) no-repeat 20px 26px;text-indent:22px;border:1px solid #c5d0dc;} #waiting {font-family:Arial;}.none{display:none}</style></head><body><p id="loadingDiv" onclick="pay()">'.$title.'</p><div id="pay_div" class="none"><form id="pay_form" action="'.$url.'" method="'.$method.'">';
		foreach($param as $key=>$val){$html .= '<input type="hidden" name="'.$key.'" value="'.$val.'">';}
		$html .= '<input type="submit" value="确认支付"></form></div>';
		if($auto===true){
			$html .= '  <script type="text/javascript">
			  function loaded() {
				 var s = window.name;
				if (typeof s === "undefined" || /^newWindow/.test(s)) {
				  setTimeout(loaded, 100);
				} else {
				  var div = document.createElement("div");
				  div.style.display = "none";
				  div.innerHTML = s;
				  document.body.appendChild(div);
				  try {
					document.forms[0].submit();
				  } catch (e) {setTimeout(loaded, 100);}
				}
			  }
			  loaded();
			</script>';
		}else{
			$html .= '  <script type="text/javascript">
				function pay(){ document.forms[0].submit(); }
			</script>';
		}
		$html.='</body></html>';	
		return $html;
	}

	function create($payform,$title=''){
		$html = "<html><head><title>".$title."</title></head><body>";
		$html .= $payform;
		$html .= "</body></html>";
		echo $html;
	}

	function payResult($outTradeNo,$payAmount,$remark='',$tradeNo=''){
		global $db;
				load_class("pay");
					$pm = new PayModel();
					$payInfo = $pm->getInfo(array("outTradeNo"=>$outTradeNo));
					if($payInfo){
						if($payInfo['amount']==$payAmount){
							if($payInfo['iStatus']==11){
								$sql = "update qk_onlinepay set iStatus=14,transactionId='$tradeNo' where id='".$payInfo['id']."'";
								$db->query($sql);	//在线支付订单完成
								$userId = $payInfo['userId'];
								$sql = "insert into qk_finance set userId='$userId',typeId=1,amount='".$payInfo['amount']."',about='在线充值入款',remark='".$remark."',iStatus=1";
								$sql .= ",outTradeNo='$outTradeNo',effectiveTime=UNIX_TIMESTAMP(),posttime=UNIX_TIMESTAMP()";
								$db->query($sql);	//向账户财务记录中充值
								$orderId = $payInfo['orderId'];
									if($orderId){
										load_class("order");
										$om = new OrderModel();
										$orderInfo = $om->getInfo(array("id"=>$orderId));
										if($orderInfo['payStatusId']==4){
											if($payInfo['amount']>=$orderInfo['amountNow']){
												$sql = "insert into qk_finance set userId='$userId',typeId=2,amount='-".$payInfo['amount']."',about='为订单".$orderId."支付',remark='',iStatus=1";
												$sql .= ",orderId='$orderId',effectiveTime=UNIX_TIMESTAMP(),posttime=UNIX_TIMESTAMP()";
												$db->query($sql);	//向账户财务记录中扣费
												$sql = "update qk_order set payStatusId=22 where id='".$orderInfo['id']."'";
												$db->query($sql);
												$ret = true;
												$this->payfor="order";
												return true;
											}else{
												saveLog('支付金额'.$payAmount.'小于交易订单 '.$orderId.' 需支付金额'.$orderInfo['amount'].'：'.$tmp);
											}
										}else{
											saveLog('订单 '.$orderId.' 不处于待支付状态');
										}
									}else{
										return true;
									}
							}else{
								saveLog('支付订单 '.$outTradeNo.' 已经处理');
							}
						}else{
							saveLog('支付订单 '.$outTradeNo.' 金额 '.$payInfo['amount'].' 与实际支付金额'.$payAmount.'不同： '.$tmp);
						}
					}else{
						saveLog('系统中不存在该订单：'.$tmp);
					}
		return false;
	}
	
	function query($id){
		load_class("onlinepay");
		$om = new OnlinepayModel();
		$payInfo = $om->getInfo($id);
		if($payInfo['query']){
			$param = array();
			$param['outTradeNo'] = $payInfo['outTradeNo'];
			$className = $payInfo['paymentInterface']['className'];
			$payConfig = $this->getConfig($payInfo['paymentId']);
			require_once(ROOT_PATH."plugins/pay/".$className.".class.php");$pay = new $className($payConfig); 
			if($pay->action && $pay->action['query']===true){
				$res = $pay->query($param);
				$this->msg=$pay->msg;
				return $res;
			}
			$this->msg='该接口不支持查询操作';
		}else{
			$this->msg='该接口不支持查询操作';
		}
		return false;
	}
}
?>