php 알 리 페 이 핸드폰 홈 페이지 결제 클래스 실례

18106 단어 php알 리 페 이
이 글 은 phop 알 리 페 이 모 바 일 홈 페이지 결제 류 를 실례 로 서술 하 였 다.모두 에 게 참고 하도록 공유 하 다.구체 적 인 분석 은 다음 과 같다.
여기 주의:
① 이 종 류 는 Yii 프레임 에 사 용 된 것 으로 프레임 을 제거 하지 않 았 다.
② 본 류 는 어떠한 수정 도 하지 않 고 사용 할 수 없다.
1.PHP 코드 부분 은 다음 과 같 습 니 다.    

namespace weixin\components;
use Yii;
/**
 *
 *
 * @example
 *    
 *     $params = []; //
 *     $alipay = new Alipay();
 *     $alipay->key = ''; //
 *     $this->alipay->alipay_config = $params;
 *     $alipay->buildRequest();
 *    
 *    
 *     $this->alipay->key = ''; //
 *     $this->alipay->alipay_config = $data; //
 *     $this->alipay->verifyNotify();
 *
 * @package Alipay
 * @author Dyllen
 * @since Version 0.2
 */
class Alipay {
    /**
     *
     *
     * @access public
     * @var string
     */
    public $key;
    
    /**
     * ,
     *
     * @access public
     * @var array
     */
    public $alipay_config=[];
    
    /**
     * HTTPS , cURL
     * cacert.pem
     *
     * @access public
     * @var string
     */
    public $credential;
    
    public $notify_data = null;
    
    /**
     *
     */
    const ALIPAY_GATEWAY = 'https://mapi.alipay.com/gateway.do?';
    
    /**
     * HTTPS
     */
    const HTTPS_VERIFY_URL = 'https://mapi.alipay.com/gateway.do?service=notify_verify&';
    
    /**
     * HTTP
     */
    const HTTP_VERIFY_URL = 'http://notify.alipay.com/trade/notify_query.do?';
    
    /**
     *
     * @var string
     */
    const ALIPAY_PAGE_GATEWAY = 'http://wappaygw.alipay.com/service/rest.htm?';
    
    
    /**
     * url
     *
     * @access public
     * @return void
     */
    public function buildRequest() {
        $this->alipay_config['sign'] = $this->signData();
        return self::ALIPAY_GATEWAY . $this->createQueryString('', true);       
    }
    
    /**
     *
     * @return string
     */
    public function buildPageUrl()
    {
        $this->alipay_config['sign'] = $this->signData();
        $url = self::ALIPAY_PAGE_GATEWAY. $this->createQueryString('');
        $response = $this->getHttpResponseGET($url);
        $res = $this->parseResponse(trim($response));
        //
        $this->alipay_config['service'] = 'alipay.wap.auth.authAndExecute';
        $this->alipay_config['req_data'] = '<auth_and_execute_req><request_token>'.$res['request_token'].'</request_token></auth_and_execute_req>';
        
        $this->alipay_config['sign'] = $this->signData();
        return self::ALIPAY_PAGE_GATEWAY. $this->createQueryString('', true);
    }
    
    /**
     *
     *
     * @access public
     * @return boolean
     */
    public function verifyNotify() {
        $param_tmp = $this->filter(); //
        if(!isset($this->alipay_config['notify_data'])) {
            return false;
        }
        $this->notify_data = $this->xmlToArray($this->alipay_config['notify_data']);
        $this->alipay_config['notify_id'] = $this->notify_data['notify_id'];
        $responseTxt = 'true';
        if( !empty( $this->alipay_config['notify_id'] ) ) {
            $responseTxt = $this->getResponse();
        }
        unset($this->alipay_config['notify_id']);
        $txt = 'service=';
        $txt .= $this->alipay_config['service'];
        $txt .= '&v='.$this->alipay_config['v'];
        $txt .= '&sec_id='.$this->alipay_config['sec_id'];
        $txt .= '&notify_data='.$this->alipay_config['notify_data'];
        $txt .= $this->key;     
        $sign = md5($txt);
 
        if ( preg_match("/true$/i",$responseTxt) && ($sign == $this->alipay_config['sign']) ) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     *
     * @param string $content
     * @throws \Exception
     * @return array
     */
    private function parseResponse($content) {
        parse_str($content, $arr);
        $data = isset($arr['res_data']) ? $arr['res_data'] : $arr['res_error'];
        $res_data = simplexml_load_string($data);
        if(strlen($res_data->request_token) == 0 || strlen($res_data->msg) > 0) {
            throw new \Exception('code:'.$res_data->code.','.$res_data->msg);
        }
        $arr['request_token'] = $res_data->request_token->__toString();
        return $arr;
    }
    
    /**
     * simpleXML
     * @param string $xml
     * @return multitype:NULL
     */
    private function xmlToArray($xml)
    {
        $xml_obj = simplexml_load_string($xml, 'SimpleXMLIterator');
        $arr = [];
        $xml_obj->rewind(); //
        while (1) {
            if( ! is_object($xml_obj->current()) )
            {
                break;
            }
            $arr[$xml_obj->key()] = $xml_obj->current()->__toString();
            $xml_obj->next(); //
        }
        return $arr;
    }
    
    /**
     *
     * :
     *     sign sign_type ,
     *    
     *     & , URL , url encoding
     *     MD5 : , md5 , 32
     *    
     * @return string
     */
    private function signData() {
        $param_tmp = $this->getSignString(); //
        
        if( !isset($this->key) ) {
            return FALSE;
        }
        
        $sign = '';
        
        //
        switch ($this->alipay_config['sec_id']) {
            case '001': //rsa
                $sign = $this->rsaSign($param_tmp);
                break;
            case 'DES':
                break;
            default:
                $sign = $this->md5Sign($param_tmp);
        }
        
        return $sign;
    }
    
    /**
     * MD5
     *
     * @access private
     * @param string $data
     * @return string
     */
    private function md5Sign( $data ) {
        return md5($data . $this->key);
    }
    
    /**
     * RSA
     *
     * @param string $data
     * @return string
     */
    private function rsaSign( $data ) {
        return false;
    }
    
    /**
     *
     *
     * @access private
     * @return string
     */
    private function getSignString() {
        $param_tmp = $this->filter(); //
        
        //
        ksort($param_tmp);
        reset($param_tmp);
        
        //
        return $this->createQueryString($param_tmp);
    }
    
    /**
     * , sing、sing_type
     *
     * @access private
     * @return array
     */
    private function filter() {
        $para_filter = array();
        foreach($this->alipay_config as $key => $value){
            if($key == "sign" || $key == "sign_type" || empty($value)) continue;
            else $para_filter[$key] = $value;
        }
        return $para_filter;
    }
    
    /**
     * & , URL
     *
     * @access private
     * @param array $data
     * @param boolean $is_encode urlencode
     * @return string
     */
    private function createQueryString($data=NULL, $is_encode=false ) {
        $arr = empty($data) ? $this->alipay_config : $data;
        $arg = '';
        foreach( $arr as $key => $value ) {
            if($is_encode) {
                $key = urlencode($key);
                $value = urlencode($value);
            }
            $arg .= $key . '=' . $value . '&';
        }
        $arg = substr($arg, 0, strlen($arg)-1); // &
        // ,
        if(get_magic_quotes_gpc()) {$arg = stripslashes($arg);}
        
        return $arg;
    }
    
    /**
     * ATN , URL
     *
     * :
     * invalid , partner key
     * true
     * false
     *
     * @access private
     * @return ATN
     */
    private function getResponse() {
        //
        $config = Yii::$app->params['alipay'];
        
        $transport = strtolower(trim($config['transport']));
        $partner = trim($config['partner']);
        $veryfy_url = '';
        if($transport == 'https') {
            $veryfy_url = self::HTTPS_VERIFY_URL;
        }
        else {
            $veryfy_url = self::HTTP_VERIFY_URL;
        }
        $veryfy_url = $veryfy_url."partner=" . $partner . "&notify_id=" . $this->alipay_config['notify_id'];
        $responseTxt = $this->getHttpResponseGET($veryfy_url);
    
        return $responseTxt;
    }
    
    /**
     * , cURL
     *
     * @access private
     * @return string
     */
    private function getCr() {
        if( ! empty($this->credential) ) {
            return $this->credential;
        }
        return __DIR__ . DIRECTORY_SEPARATOR .'cacert.pem';
    }
    
    /**
     * ,POST
     * :
     * 1. Crul php.ini , php_curl.dll ";"
     * 2. cacert.pem SSL , :getcwd().'\\cacert.pem'
     *
     * @param $url URL
     * @param $cacert_url
     * @param $para
     * @param $input_charset 。 :
     * return
     */
    private function getHttpResponsePOST($url, $para, $input_charset = '') {
    
        if (trim($input_charset) != '') {
            $url = $url."_input_charset=".$input_charset;
        }
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//
        curl_setopt($curl, CURLOPT_CAINFO,$this->getCr());//
        curl_setopt($curl, CURLOPT_HEADER, 0 ); // HTTP
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//
        curl_setopt($curl, CURLOPT_POST,true); // post
        curl_setopt($curl, CURLOPT_POSTFIELDS,$para);// post
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );// curl , ,
        curl_close($curl);
    
        return $responseText;
    }
    
    /**
     * ,GET
     * :
     * 1. Crul php.ini , php_curl.dll ";"
     * 2. cacert.pem SSL , :getcwd().'\\cacert.pem'
     *
     * @param $url URL
     * @param $cacert_url
     * return
     */
    private function getHttpResponseGET($url) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0 ); // HTTP
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//
        curl_setopt($curl, CURLOPT_CAINFO,$this->getCr());//
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );exit;// curl , ,
        curl_close($curl);
    
        return $responseText;
    }
}
2.사용 방법:
//        
$sum = 0.01; //
$req_data = '<direct_trade_create_req><subject> </subject>';
$req_data .= '<out_trade_no>'.$orderNo.'</out_trade_no>';
$req_data .= '<total_fee>'.$sum.'</total_fee>';
$req_data .= '<call_back_url>'.Url::toRoute(['payment/return'], true).'</call_back_url>';
$req_data .= '<notify_url>'.Url::toRoute(['payment/notify'], true).'</notify_url>';
$req_data .= '<seller_account_name>'.Yii::$app->params['alipay']['seller_email'].'</seller_account_name>';
$req_data .= '</direct_trade_create_req>';
$params = [
    'service' => 'alipay.wap.trade.create.direct',
    'format' => 'xml',
    'v' => '2.0',
    'partner' => Yii::$app->params['alipay']['partner'], // ID
    'req_id' => date('Ymdhis'),
    'sec_id' => Yii::$app->params['alipay']['sign_type'],
    'req_data' => $req_data,
];
 
$alipay = new Alipay();
$alipay->key = Yii::$app->params['alipay']['key'];
$alipay->alipay_config = $params;
$url = $alipay->buildPageUrl();
$this->redirect($url);
3.예제 설정:
//       
'alipay' => [
        'key' => 'XXXXX',  // , 32
        'transport' => 'https',         //
        'seller_email' => 'XXXX', // ,
        'service' => 'create_direct_pay_by_user', //
        'partner' => 'XXXX', // ID
        '_input_charset' => 'utf-8', //
        'sign_type' => 'MD5', // , , MD5
        //
        'notify_url' => '', //
        'return_url' => '', //
],
본 논문 에서 말 한 것 이 여러분 의 phop 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기