首页 >php教程 >PHP源码 >银联网页支付

银联网页支付

PHP中文网
PHP中文网原创
2016-05-26 08:19:241587浏览

银联WAP支付功能,仅限消费功能。

http://www.360us.net/article/25.html

<?php
namespace common\services;

class UnionPay
{
	/**
	 * 支付配置
	 * @var array
	 */
	public $config = [];
	
	/**
	 * 支付参数,提交到银联对应接口的所有参数
	 * @var array
	 */
	public $params = [];
	
	/**
	 * 自动提交表单模板
	 * @var string
	 */
	private $formTemplate = <<<&#39;HTML&#39;
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
	<title>支付</title>
</head>
<body>
	<p style="text-align:center">跳转中...</p>
	<form id="pay_form" name="pay_form" action="%s" method="post">
		%s
	</form>
    <script type="text/javascript">
	    document.onreadystatechange = function(){
            if(document.readyState == "complete") {
                document.pay_form.submit();
            }
        };
	</script>
</body>
</html>
HTML;
	
	/**
	 * 构建自动提交HTML表单
	 * @return string
	 */
	public function createPostForm()
	{
	    $this->params[&#39;signature&#39;] = $this->sign();
	    $input = &#39;&#39;;
	    foreach($this->params as $key => $item) {
	    	$input .= "\t\t<input type=\"hidden\" name=\"{$key}\" value=\"{$item}\">\n";
	    }
	    
	    return sprintf($this->formTemplate, $this->config[&#39;frontUrl&#39;], $input);
	}
	
	/**
	 * 验证签名
	 * 验签规则:
	 * 除signature域之外的所有项目都必须参加验签
	 * 根据key值按照字典排序,然后用&拼接key=value形式待验签字符串;
	 * 然后对待验签字符串使用sha1算法做摘要;
	 * 用银联公钥对摘要和签名信息做验签操作
	 * 
	 * @throws \Exception
	 * @return bool
	 */
	public function verifySign()
	{
		$publicKey = $this->getVerifyPublicKey();
		$verifyArr = $this->filterBeforSign();
		ksort($verifyArr);
		$verifyStr = $this->arrayToString($verifyArr);
		$verifySha1 = sha1($verifyStr);
		$signature = base64_decode($this->params[&#39;signature&#39;]);
		$result = openssl_verify($verifySha1, $signature, $publicKey);
		if($result === -1) {
			throw new \Exception(&#39;Verify Error:&#39;.openssl_error_string());
		}
		
		return $result === 1 ? true : false;
	}
	
	/**
	 * 取签名证书ID(SN)
	 * @return string
	 */
	public function getSignCertId()
	{
		return $this->getCertIdPfx($this->config[&#39;signCertPath&#39;]);
	}	
	
	/**
	 * 签名数据
	 * 签名规则:
	 * 除signature域之外的所有项目都必须参加签名
	 * 根据key值按照字典排序,然后用&拼接key=value形式待签名字符串;
	 * 然后对待签名字符串使用sha1算法做摘要;
	 * 用银联颁发的私钥对摘要做RSA签名操作
	 * 签名结果用base64编码后放在signature域
	 * 
	 * @throws \InvalidArgumentException
	 * @return multitype|string
	 */
	private function sign() {
		$signData = $this->filterBeforSign();
		ksort($signData);
		$signQueryString = $this->arrayToString($signData);
		
		if($this->params[&#39;signMethod&#39;] == 01) {
			//签名之前先用sha1处理
			//echo $signQueryString;exit;
			$datasha1 = sha1($signQueryString);
			$signed = $this->rsaSign($datasha1);
		} else {
			throw new \InvalidArgumentException(&#39;Nonsupport Sign Method&#39;);
		}
				
		return $signed;
		
	}
	
	/**
	 * 数组转换成字符串
	 * @param array $arr
	 * @return string
	 */
	private function arrayToString($arr)
	{
		$str = &#39;&#39;;
		foreach($arr as $key => $value) {
			$str .= $key.&#39;=&#39;.$value.&#39;&&#39;;
		}
		return substr($str, 0, strlen($str) - 1);
	}
	
	/**
	 * 过滤待签名数据
	 * signature域不参加签名
	 * 
	 * @return array
	 */
	private function filterBeforSign()
	{
		$tmp = $this->params;
		unset($tmp[&#39;signature&#39;]);
		return $tmp;
	}
	
	/**
	 * RSA签名数据,并base64编码
	 * @param string $data 待签名数据
	 * @return mixed
	 */
	private function rsaSign($data)
	{
		$privatekey = $this->getSignPrivateKey();
		$result = openssl_sign($data, $signature, $privatekey);
		if($result) {
			return base64_encode($signature);
		}
		return false;
	}
	
	/**
	 * 取.pfx格式证书ID(SN)
	 * @return string
	 */
	private function getCertIdPfx($path)
	{
		$pkcs12certdata = file_get_contents($path);
		openssl_pkcs12_read($pkcs12certdata, $certs, $this->config[&#39;signCertPwd&#39;]);
		$x509data = $certs[&#39;cert&#39;];
		openssl_x509_read($x509data);
		$certdata = openssl_x509_parse($x509data);
		return $certdata[&#39;serialNumber&#39;];
	}
	
	/**
	 * 取.cer格式证书ID(SN)
	 * @return string
	 */
	private function getCertIdCer($path)
	{
		$x509data = file_get_contents($path);
		openssl_x509_read($x509data);
		$certdata = openssl_x509_parse($x509data);
		return $certdata[&#39;serialNumber&#39;];
	}
	
	/**
	 * 取签名证书私钥
	 * @return resource
	 */
	private function getSignPrivateKey()
	{
		$pkcs12 = file_get_contents($this->config[&#39;signCertPath&#39;]);
		openssl_pkcs12_read($pkcs12, $certs, $this->config[&#39;signCertPwd&#39;]);
		return $certs[&#39;pkey&#39;];
	}
	
	/**
	 * 取验证签名证书
	 * @throws \InvalidArgumentException
	 * @return string
	 */
	private function getVerifyPublicKey()
	{
		//先判断配置的验签证书是否银联返回指定的证书是否一致
		if($this->getCertIdCer($this->config[&#39;verifyCertPath&#39;]) != $this->params[&#39;certId&#39;]) {
			throw new \InvalidArgumentException(&#39;Verify sign cert is incorrect&#39;);
		}
		return file_get_contents($this->config[&#39;verifyCertPath&#39;]);		
	}
}

   

2. [代码]配置示例    

           

   //银联支付设置
	&#39;unionpay&#39; => [
		//测试环境参数
	    &#39;frontUrl&#39; => &#39;https://101.231.204.80:5000/gateway/api/frontTransReq.do&#39;, //前台交易请求地址
	    //&#39;singleQueryUrl&#39; => &#39;https://101.231.204.80:5000/gateway/api/queryTrans.do&#39;, //单笔查询请求地址
	    &#39;signCertPath&#39; => __DIR__.&#39;/../keys/unionpay/test/sign/700000000000001_acp.pfx&#39;, //签名证书路径
	    &#39;signCertPwd&#39; => &#39;000000&#39;, //签名证书密码
	    &#39;verifyCertPath&#39; => __DIR__.&#39;/../keys/unionpay/test/verify/verify_sign_acp.cer&#39;, //验签证书路径
	    &#39;merId&#39; => &#39;xxxxxxx&#39;,
	    
		//正式环境参数
		//&#39;frontUrl&#39; => &#39;https://101.231.204.80:5000/gateway/api/frontTransReq.do&#39;, //前台交易请求地址
		//&#39;singleQueryUrl&#39; => &#39;https://101.231.204.80:5000/gateway/api/queryTrans.do&#39;, //单笔查询请求地址
		//&#39;signCertPath&#39; => __DIR__.&#39;/../keys/unionpay/test/sign/PM_700000000000001_acp.pfx&#39;, //签名证书路径
		//&#39;signCertPwd&#39; => &#39;000000&#39;, //签名证书密码
		//&#39;verifyCertPath&#39; => __DIR__.&#39;/../keys/unionpay/test/verify/verify_sign_acp.cer&#39;, //验签证书路径
	    //&#39;merId&#39; => &#39;xxxxxxxxx&#39;, //商户代码
	],

3. [代码]支付示例   

           

$unionPay = new UnionPay();
$unionPay->config = Yii::$app->params[&#39;unionpay&#39;];//上面的配置
		
$unionPay->params = [
	&#39;version&#39; => &#39;5.0.0&#39;, //版本号
	&#39;encoding&#39; => &#39;UTF-8&#39;, //编码方式
	&#39;certId&#39; => $unionPay->getSignCertId(), //证书ID
	&#39;signature&#39; => &#39;&#39;, //签名
	&#39;signMethod&#39; => &#39;01&#39;, //签名方式
	&#39;txnType&#39; => &#39;01&#39;, //交易类型
	&#39;txnSubType&#39; => &#39;01&#39;, //交易子类
	&#39;bizType&#39; => &#39;000201&#39;, //产品类型
	&#39;channelType&#39; => &#39;08&#39;,//渠道类型
	&#39;frontUrl&#39; => Url::toRoute([&#39;payment/unionpayreturn&#39;], true), //前台通知地址
	&#39;backUrl&#39; => Url::toRoute([&#39;payment/unionpaynotify&#39;], true), //后台通知地址
	//&#39;frontFailUrl&#39; => Url::toRoute([&#39;payment/unionpayfail&#39;], true), //失败交易前台跳转地址
	&#39;accessType&#39; => &#39;0&#39;, //接入类型
	&#39;merId&#39; => Yii::$app->params[&#39;unionpay&#39;][&#39;merId&#39;], //商户代码
	&#39;orderId&#39; => $orderNo, //商户订单号
	&#39;txnTime&#39; => date(&#39;YmdHis&#39;), //订单发送时间
	&#39;txnAmt&#39; => $sum * 100, //交易金额,单位分
	&#39;currencyCode&#39; => &#39;156&#39;, //交易币种
];
		
$html = $unionPay->createPostForm();

                   

4. [代码]异步通知示例 

$unionPay = new UnionPay();
$unionPay->config = Yii::$app->params[&#39;unionpay&#39;];
		
$unionPay->params = Yii::$app->request->post(); //银联提交的参数
if(empty($unionPay->params)) {
    return &#39;fail!&#39;;
}
if($unionPay->verifySign() && $unionPay->params[&#39;respCode&#39;] == &#39;00&#39;) {
    //.......
}

                   


                   

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn