<?php
/**
 * 封装银联支付接口
 *
 * @author sun
 */
class ChinaPay {
	//版本类型
	public $versoinType = '';

    //身份验证接口172.17.1.184 221.231.141.174
    //const P_CHINAPAY_URL = '';

	public $chinapyUrl = '';

	public $chinapaySubmitUrl = '';

    //支付请求地址(生产)
    const REQ_URL_PAY = 'https://payment.ChinaPay.com/pay/TransGet';
    //查询请求地址(生产)
    const REQ_URL_QRY = 'http://console.chinapay.com/QueryWeb/processQuery.jsp';
    //退款请求地址(生产)
    const REQ_URL_REF = 'https://bak.chinapay.com/refund/SingleRefund.jsp';
    
    //生产环境
    public  $env_chinapay = 2;

	public function __construct($data = array())
	{
		if(!empty($data['chinapayVersion']) && $data['chinapayVersion'] == 'new')
		{
			//$this->chinapyUrl = 'http://202.102.83.150:8011/zsb_pay/paydata.php';
			$this->chinapyUrl = 'http://192.168.2.3/zsb_pay/paydata.php';
			$this->chinapaySubmitUrl = 'https://payment.chinapay.com/CTITS/service/rest/page/nref/000000000017/0/0/0/0/0';
			$this->versoinType = 'new';
		}
		else
		{
			//$this->chinapyUrl = 'http://221.231.141.174/chinapay/paydata.php';
			$this->chinapyUrl = 'http://172.17.1.184/chinapay/paydata.php';
			$this->versoinType = 'old';
		}
	}
    
    /**
     * 数字签名
     * @param  array $para 签名参数
     */
    public function build_my_sign($para) 
    {
		if(empty($para))
		{
			return '';
		}
		
		if($this->versoinType == 'new')
		{
			//参数组建
			$url_parse = '';
			foreach($para as $key => $value)
			{	
				if(!empty($url_parse))
				{
					$url_parse .= '&'.$key.'='.$value;	
				}
				else
				{
					$url_parse = $key.'='.$value;
				}
			}
			
			return curl_get_contents($this->chinapyUrl . '?action=getSign&'.$url_parse);
		}
		else
		{
			return curl_get_contents($this->chinapyUrl . '?param=sign&env=' 
					. $this->env_chinapay . '&MerId=' . $para['MerId'] . '&OrdId='
					. $para['OrdId'] . '&OrdAmt=' . $para['OrdAmt'] . '&BgRetUrl=' 
					. $para['BgRetUrl'] . '&PageRetUrl=' . $para['PageRetUrl'] 
					. '&ShareData=' . $para['ShareData'] . '&gateid=' 
					. $para['GateId']);
		}
    }
    
    /**
     * 导入私钥
     * @return array 
     */
    public function get_private_key() 
    {
        return curl_get_contents($this->chinapyUrl . '?param=const&env=' 
                . $this->env_chinapay);
    }
    
    /**
     * 验证签名
     * @param array $para
     */
    public function verify($para = array(),$flag = 'page') 
    {
		if($this->versoinType == 'new')
		{
			if(empty($para))
			{
				return '';
			}

			//参数组建
			$url_parse = '';
			foreach($para as $key => $value)
			{	
				if(!empty($url_parse))
				{
					$url_parse .= '&'.$key.'='.$value;	
				}
				else
				{
					$url_parse = $key.'='.$value;
				}
			}
			
			return curl_get_contents($this->chinapyUrl . '?action=checkSign&'.$url_parse);
		}
		else
		{
			return curl_get_contents($this->chinapyUrl . '?param=verify&env='
					. $this->env_chinapay . '&MerId=' . $_REQUEST['MerId']. '&OrdId=' 
					. $_REQUEST['OrdId'].'&OrdAmt=' . $_REQUEST['OrdAmt'] . '&GateId=' 
					. $_REQUEST['GateId'] .'&ShareData=' . $_REQUEST['ShareData'] 
					. '&PayStat=' . $_REQUEST['PayStat'] . '&PayTime=' 
					. urlencode($_REQUEST['PayTime']) . '&ChkValue=' . $_REQUEST['ChkValue'] . '');
		}
    }
    
    
    /**
     * 格式化所需要提交支付的参数
     * @param array $para_temp 参数
     */
    public function build_request_para($para_temp) 
    {
        $para = array();
		
		if($this->versoinType == 'new')
		{
			//接口版本号，境内支付为 20140728，必填
			$para['Version'] = "20140728";

			//接入类型 0：商户身份接入（默认） 1：机构身份接入
			$para['AccessType'] = '0';

			//商户名
			$para['MerId'] = $para_temp['MerId'];

			//订单ID为交易号 
			$para['MerOrderNo'] = $para_temp['transaction_id'];

			//交易日期
			$para['TranDate'] = date('Ymd');
			
			//交易时间
			$para['TranTime'] = date('His');
			
			//交易金额，单位:分
			$para['OrderAmt'] = $para_temp['price']*100; 

			//交易类型 0001个人网银支付 0002企业网银支付
			$para['TranType'] = '0001';

			//业务类型
			$para['BusiType'] = '0001';

			//交易币种  默认为人民币：CNY
			$para['CurryNo'] = 'CNY';

			//支付机构号  银行代码
			$para['BankInstNo'] = $para_temp['bank_gate_id'];

			//商户前台通知地址
			$para['MerPageUrl'] = $para_temp['page_ret_url'];

			//商户后台通知地址
			$para['MerBgUrl'] = $para_temp['bg_ret_url'];

			//订单描述
			$para['CommodityMsg'] = $para_temp['ord_desc'];
			
			//签名
			$para['Signature'] = $this->build_my_sign($para);
		}
		else
		{
			//导入私钥文件
			$const_str = $this->get_private_key();
			$arrconst = explode("<=>", $const_str);
			//商户名
			$para['MerId'] = $arrconst['0'];
			//交易号 $transaction_id
			$para['OrdId'] = $para_temp['transaction_id'];
			//订单金额，定长12位，以分为单位，不足左补0，必填  $price
			$amt = $para_temp['price'];
			$para['OrdAmt'] = sprintf("%012d", $amt*100);
			//货币代码，3位，境内商户固定为156，表示人民币，必填
			$para['CuryId'] = "156";
			//订单日期，本例采用当前日期，必填
			$para['TransDate'] = date('Ymd', time());
			//交易类型，0001 表示支付交易，0002 表示退款交易
			$para['ShareType'] = "0001";
			//接口版本号，境内支付为 20070129，必填
			$para['Version'] = "20100401";
			// 页面返回地址(您服务器上可访问的URL)，最长80位，当用户完成支付后，银行页面会自动跳转到该页面，并POST订单结果信息，可选
			$para['BgRetUrl'] = $para_temp['bg_ret_url'];
			// 后台返回地址(您服务器上可访问的URL)，最长80位，当用户完成支付后，我方服务器会POST订单结果信息到该页面，必填
			$para['PageRetUrl'] = $para_temp['page_ret_url'];
			//支付网关号，4位  $gateId   0000为跳转到公共接口的标志
			$para['GateId'] = $para_temp['bank_gate_id'] == '0000' ? '' : $para_temp['bank_gate_id'];
			$para['OrdDesc'] = $para_temp['ord_desc'];
			$para['ShareData'] = "{$arrconst['2']}^" . $amt * 100;
			$para['ChkValue'] = $this->build_my_sign($para);

			$this->chinapaySubmitUrl = end($arrconst);
		}

        return $para;
    }
    
    /**
     * 建立请求，以表单HTML形式构造（默认）
     * @param $para_temp 请求参数数组
     * @param $method 提交方式。两个值可选：post、get
     * @return 提交表单HTML文本
     */
    private function build_request_form($para_temp, $method) 
    {
		//待请求参数数组
		$para = $this->build_request_para($para_temp);
		$sHtml = "<form  name='pay_form' action='". $this->chinapaySubmitUrl."' method='".$method."'>";
		while(list($key, $val) = each($para)) {
            $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
        }
        $sHtml = $sHtml."</form>";
		$sHtml = $sHtml."<script>document.forms['pay_form'].submit();</script>";
		return $sHtml;
    }
    
    //支付接口
    public function dopay($para_temp, $method) {
        return $this->build_request_form($para_temp, $method);
    }
    
    //异步执行
    public function notify($data = array()) {
        return $this->verify($data,'notify');
    }
    
    //成功返回
    public function success($data = array()) {
        return $this->verify($data);
    }
}
