<?php
class Weibopay extends Pay{
	private $info;
	private $path;
	function __construct(){
		$path = str_replace("/Weibopay.class.php","/",str_replace("\\","/",__FILE__));
		$this->path = $path;
	}

	function pay($paymentId,$amount,$tradeNo,$loginName="",$name=""){
		$payConfig = $this->getConfig($paymentId);
		if(!$payConfig){Msg::show('该支付接口未配置');}
		$privateKey = "-----BEGIN PRIVATE KEY-----\n";
		for($i=0;$i<strlen($payConfig['privateKey']);$i++){
			$privateKey .= $payConfig['privateKey']{$i};
			if(($i+1)%64==0){ $privateKey.="\n"; }
		}
		$privateKey .= "\n-----END PRIVATE KEY-----";
		$bankCode = getgpc('bankCode');
		if(!preg_match("/^([A-Z]+)$/",$bankCode)){$bankCode='';}
		$param['inputCharset']='1';	//2 //1代表UTF-8; 2代表GBK; 3代表GB2312
		$param['bgUrl']="http://".$_SERVER['HTTP_HOST']."/pay/payNotify/weibopay";	//256
		//$param['cancelUrl']= 'http://pay.ueidc.com/cancel.php';	//256
		$param['version']= 'v2.3';	//10
		$param['language']='1';	 //2
		$param['signType']= $payConfig['signType'];	//1代表MD5加密签名方式	 4代表PKI签名方式
		$param['merchantAcctId']= $payConfig['merchantAcctId'];	//30
		$param['orderId']= $tradeNo;//'20030270';// //50 字母 数字 - _ 以字母或数字开头
		$param['orderAmount']= $amount*100;	 //以分为单位 10元=1000
		$param['orderTime']= date('YmdHis',time());//'20121017165834';	//date('YmdHis',time());
		$param['productName']= $name?$name:'炫彩网络服务';	//256
		$param['productNum']= '1';	//8
		$param['productId']= 'xcecp';	//20
		$param['payType']= '10';	//2	固定值 10 银行卡网银支付
		$param['bankId']= $bankCode;	//8	银行代码	TESTBANK	 SDTBNK	CITIC
		$param['redoFlag']= '0';
		$param['pid']= $payConfig['memberId'];
		$p = '';
		foreach($param as $key=>$val){
			if($val!==''){
				$p .= '&'.$key.'='.$val;
			}
		}
		$p =substr($p,1);saveLog("向支付平台 [".$info['name']."] 发送数据：".$p);
		if($param['signType']=='4'){
					if(!($pkeyid = @openssl_get_privatekey($privateKey))){
						exit('私钥加载失败');
					}
					if(openssl_sign($p, $signature, $pkeyid, OPENSSL_ALGO_SHA1)){
						openssl_free_key($pkeyid);
						$param['signMsg']= base64_encode($signature);
					}else{
						exit('加密失败');
					}
		}else{
			$param['signMsg']=md5($p.'&key='.$secret);
		}
		$html_text= '<form action="https://gate.pay.sina.com.cn/acquire-order-channel/gateway/receiveOrderLoading.htm" id="weibopayForm">';
		foreach($param as $key=>$val){$html_text .= '<input type="hidden" name="'.$key.'" value="'.$val.'" size="50" /> ';}
		$html_text.='<input type="submit" value="正在转向到支付平台，如不能自动转向请点击"></form>';
		$html_text.='<script>document.getElementById("weibopayForm").submit();</script>';
		parent::create($html_text,'正在加载支付页面..');
	}
	
	function payNotify(){
		$pay_params=array();
		$pay_params["merchantAcctId"]=@$_REQUEST["merchantAcctId"];
		$pay_params["version"]=@$_REQUEST["version"];
		$pay_params["language"]=@$_REQUEST["language"];
		$pay_params["signType"]=@$_REQUEST["signType"];
		$pay_params["payType"]=@$_REQUEST["payType"];
		$pay_params["bankId"]=@$_REQUEST["bankId"];
		$pay_params["orderId"]=@$_REQUEST["orderId"];
		$pay_params["orderTime"]=@$_REQUEST["orderTime"];
		$pay_params["orderAmount"]=@$_REQUEST["orderAmount"];
		$pay_params["dealId"]=@$_REQUEST["dealId"];
		$pay_params["bankDealId"]=@$_REQUEST["bankDealId"];
		$pay_params["dealTime"]=@$_REQUEST["dealTime"];
		$pay_params["payAmount"]=@$_REQUEST["payAmount"];
		$pay_params["fee"]=@$_REQUEST["fee"];
		$pay_params["ext1"]=@$_REQUEST["ext1"];
		$pay_params["ext2"]=@$_REQUEST["ext2"];
		$pay_params["payResult"]=@$_REQUEST["payResult"];
		$pay_params["payIp"]=@$_REQUEST["payIp"];
		$pay_params["errCode"]=@$_REQUEST["errCode"];
		$pay_params["signMsg"]=@$_REQUEST["signMsg"];
		$log = '';foreach($_REQUEST as $key=>$val){$log .= $key.'='.$val.'&';}if($log){saveLog('服务器端：微博钱包通知数据：'.$log);}
		$paymentId = $GLOBALS['db']->getOne("select paymentId from qk_onlinepay where outTradeNo='".$pay_params["orderId"]."'");
		$payConfig = $this->getConfig($paymentId);
		if($this->checkSignMsg($pay_params)){
			$resultShow = "http://".$_SERVER['HTTP_HOST']."/pay/result/status/failed";
			$result = '1';
			if($pay_params["payResult"]==10){//成功
					if($url=$this->payResult($pay_params["orderId"],$pay_params["orderAmount"]/100,$remark,$pay_params["dealId"])){
						 saveLog('服务器端：支付结果本地校验成功');
						 if(preg_match("/^http:\/\//",$url)){
							$resultShow = $url;
						 }else{
							$resultShow = "http://".$_SERVER['HTTP_HOST']."/pay/result/status/success";
						 }
						$result = '1';
					}else{
						 saveLog('服务器端：支付结果本地校验失败');
					}
			 }else{	
				 saveLog('服务器端：返回的支付结果非交易成功');
			 }
			echo '<result>'.$result.'</result><redirecturl><![CDATA['.$resultShow.']]></redirecturl>';
		}else{
				saveLog('服务器端：签名错误！');
			die("签名错误！");
		}
	}

	function checkSignMsg($pay_params=array())
	{
		$params_str = "";
		$signMsg = "";
		$return = false;
		foreach($pay_params as $key=>$val){if($key!="signMsg" && !is_null($val) && @$val!=""){$params_str .= $key."=".$val."&";}}
		switch ($pay_params['signType'])
		{
			case '4':
				$fp = fopen(dirname(__File__) . '/weihuimas.crt', "r");
		        $cert = fread($fp, 8192);
		        fclose($fp);
		        $pubkeyid = openssl_get_publickey($cert);
		        $ok = openssl_verify($params_str, base64_decode($signMsg), $pubkeyid, OPENSSL_ALGO_SHA1);
		        $return = $ok == 1 ? false : true;
		        openssl_free_key($pubkeyid);
				break;
			case '1':
			default:
				$params_str .= "key=" . $this->pay_config['md5_key'];
				$signMsg = strtolower(md5($params_str));
				$return = ($signMsg == strtolower($pay_params['signMsg']))?true:false;
				break;
		}
		return $return;
	}

}
?>