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 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Laravel - 변환된 유효성 검사 규칙으로 API 요청 제공동적 콘텐츠를 위해 API를 통해 Laravel CMS에 연결하는 모바일 앱(또는 웹사이트) 구축을 고려하십시오. 이제 앱은 CMS에서 번역된 콘텐츠를 받을 것으로 예상되는 다국어 앱이 될 수 있습니다. 일반적으로 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.