php 은 련 홈 페이지 결제 실현 방법

본 고 는 php 은 련 홈 페이지 결제 실현 방법 을 실례 로 서술 하 였 다.모두 에 게 참고 하도록 공유 하 다.구체 적 인 분석 은 다음 과 같다.
여기에 소 개 된 은 련 WAP 결제 기능 은 소비 기능 만 가능 하 다.
1.PHP 코드 는 다음 과 같 습 니 다:

namespace common\services;
class UnionPay
{
    /**
     *
     * @var array
     */
    public $config = [];
    /**
     * ,
     * @var array
     */
    public $params = [];
    /**
     *
     * @var string
     */
    private $formTemplate = <<<'HTML'
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title> </title>
</head>
<body>
    <div style="text-align:center"> ...</div>
    <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['signature'] = $this->sign();
        $input = '';
        foreach($this->params as $key => $item) {
            $input .= "\t\t<input type=\"hidden\" name=\"{$key}\" value=\"{$item}\">
";
        }
        return sprintf($this->formTemplate, $this->config['frontUrl'], $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['signature']);
        $result = openssl_verify($verifySha1, $signature, $publicKey);
        if($result === -1) {
            throw new \Exception('Verify Error:'.openssl_error_string());
        }
        return $result === 1 ? true : false;
}
/**
* ID(SN)
* @return string
*/
public function getSignCertId()
{
        return $this->getCertIdPfx($this->config['signCertPath']);
}  
/**
*
* :
* 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['signMethod'] == 01) {
            // sha1
            //echo $signQueryString;exit;
            $datasha1 = sha1($signQueryString);
            $signed = $this->rsaSign($datasha1);
        } else {
            throw new \InvalidArgumentException('Nonsupport Sign Method');
        }
        return $signed;
}
/**
*
* @param array $arr
* @return string
*/
private function arrayToString($arr)
{
        $str = '';
        foreach($arr as $key => $value) {
            $str .= $key.'='.$value.'&';
        }
        return substr($str, 0, strlen($str) - 1);
}
/**
*
* signature
*
* @return array
*/
private function filterBeforSign()
{
        $tmp = $this->params;
        unset($tmp['signature']);
        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['signCertPwd']);
        $x509data = $certs['cert'];
        openssl_x509_read($x509data);
        $certdata = openssl_x509_parse($x509data);
        return $certdata['serialNumber'];
}
/**
* .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['serialNumber'];
}
/**
*
* @return resource
*/
private function getSignPrivateKey()
{
        $pkcs12 = file_get_contents($this->config['signCertPath']);
        openssl_pkcs12_read($pkcs12, $certs, $this->config['signCertPwd']);
        return $certs['pkey'];
}
/**
*
* @throws \InvalidArgumentException
* @return string
*/
private function getVerifyPublicKey()
{
        //
        if($this->getCertIdCer($this->config['verifyCertPath']) != $this->params['certId']) {
            throw new \InvalidArgumentException('Verify sign cert is incorrect');
        }
        return file_get_contents($this->config['verifyCertPath']);      
    }
}
2.예제 설정    
//      
 'unionpay' => [
     //
     'frontUrl' => 'https://101.231.204.80:5000/gateway/api/frontTransReq.do', //
     //'singleQueryUrl' => 'https://101.231.204.80:5000/gateway/api/queryTrans.do', //
     'signCertPath' => __DIR__.'/../keys/unionpay/test/sign/700000000000001_acp.pfx', //
     'signCertPwd' => '000000', //
     'verifyCertPath' => __DIR__.'/../keys/unionpay/test/verify/verify_sign_acp.cer', //
     'merId' => 'xxxxxxx',
     //
     //'frontUrl' => 'https://101.231.204.80:5000/gateway/api/frontTransReq.do', //
     //'singleQueryUrl' => 'https://101.231.204.80:5000/gateway/api/queryTrans.do', //
     //'signCertPath' => __DIR__.'/../keys/unionpay/test/sign/PM_700000000000001_acp.pfx', //
     //'signCertPwd' => '000000', //
     //'verifyCertPath' => __DIR__.'/../keys/unionpay/test/verify/verify_sign_acp.cer', //
     //'merId' => 'xxxxxxxxx', //
 ],
3.지불 예시    
$unionPay = new UnionPay();
$unionPay->config = Yii::$app->params['unionpay'];//
$unionPay->params = [
    'version' => '5.0.0', //
    'encoding' => 'UTF-8', //
    'certId' => $unionPay->getSignCertId(), // ID
    'signature' => '', //
    'signMethod' => '01', //
    'txnType' => '01', //
    'txnSubType' => '01', //
    'bizType' => '000201', //
    'channelType' => '08',//
    'frontUrl' => Url::toRoute(['payment/unionpayreturn'], true), //
    'backUrl' => Url::toRoute(['payment/unionpaynotify'], true), //
    //'frontFailUrl' => Url::toRoute(['payment/unionpayfail'], true), //
    'accessType' => '0', //
    'merId' => Yii::$app->params['unionpay']['merId'], //
    'orderId' => $orderNo, //
    'txnTime' => date('YmdHis'), //
    'txnAmt' => $sum * 100, // ,
    'currencyCode' => '156', //
];
$html = $unionPay->createPostForm();
4.비동기 알림 예시
$unionPay = new UnionPay();
$unionPay->config = Yii::$app->params['unionpay'];
$unionPay->params = Yii::$app->request->post(); //
if(empty($unionPay->params)) {
    return 'fail!';
}
if($unionPay->verifySign() && $unionPay->params['respCode'] == '00') {
    //.......
}
본 논문 에서 말 한 것 이 여러분 의 phop 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기