PHP開發之微信H5支付

最近由於業務所需,對接了微信H5支付,然而微信支付對這塊並沒有現成的demo可用,所以就必須自己老老實實對照開發文檔去寫咯!但這對於剛接觸的童鞋來說,坑多多少少還是有的,所以尋思着把自己的經驗分享出來,畢竟現成的用的還是多巴適的嘛!
好了,官方文檔的那一套就不多說了,詳情見官方文檔
在這裏,我主要分成了三個文件:WxPay.Config.php(支付配置文件)、Weixin.class.php(支付類)以及PayMentController.class.php(支付文件)。

首先,WxPay.Config.php配置文件主要包含了商戶appId、商戶號、商家key、異步回調URL、支付場景信息,如下:
class WxPayConfig
{
    public static $appid = '微信支付的公衆號appid';
    public static $mchid = '微信支付分配的商戶號';
    public static $key = '微信商戶自己設置的安全key';
    public static $notify_url = '商戶側接收微信支付異步通知的URL';
    public static $scene_info = '{"h5_info":{"type":"Wap","wap_url":" 發起微信H5支付H5的URL","wap_name":"支付"}}'; 
}
然後,封裝Weixin.class.php支付類,主要調用統一下單Api,這裏不多說了,直接上代碼:
<?php
require_once "lib/WxPay.Config.php";
class Weixin
{
         /**
     * 微信H5下單付款
     *     @order 付款信息
          *     @bodys 付款內容
     * */
         function getCode($order,$bodys){
                   $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信傳參地址
                   //1.獲取調用統一下單接口所需必備參數
        $appid =WxPayConfig::$appid;//微信公衆號appid
        $mch_id = WxPayConfig::$mchid;//微信支付商戶號
        $key = WxPayConfig::$key;//自己設置的微信商家key
        $out_trade_no = $order['order_sn'];//平臺內部訂單號
        $nonce_str=MD5($out_trade_no);//隨機字符串
        $body = $bodys;//付款內容
        $total_fee = $order['order_amount']*100;//付款金額,單位爲分
        $spbill_create_ip = getIP(); //獲得用戶設備IP
        $attach = 'weixinh5';//附加數據(自定義,在支付通知中原樣返回)
        $notify_url = WxPayConfig::$notify_url; //異步回調地址,需外網可以直接訪問
        $trade_type = 'MWEB';//交易類型,微信H5支付時固定爲MWEB
        $scene_info =WxPayConfig::$scene_info;//場景信息
                   //2.將參數按照key=value的格式,並按照參數名ASCII字典序排序生成字符串
        $signA ="appid=$appid&attach=$attach&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
        //3.拼接字符串
                   $strSignTmp = $signA."&key=$key";
                   //4.MD5加密後轉換成大寫
        $sign = strtoupper(MD5($strSignTmp));
                   //5.拼接成所需XML格式
        $post_data = "<xml> 
                       <appid>$appid</appid> 
                       <attach>$attach</attach> 
                       <body>$body</body> 
                       <mch_id>$mch_id</mch_id> 
                       <nonce_str>$nonce_str</nonce_str> 
                       <notify_url>$notify_url</notify_url> 
                       <out_trade_no>$out_trade_no</out_trade_no> 
                       <spbill_create_ip>$spbill_create_ip</spbill_create_ip> 
                       <total_fee>$total_fee</total_fee> 
                       <trade_type>$trade_type</trade_type>
                       <scene_info>$scene_info</scene_info>
                       <sign>$sign</sign> 
                   </xml>";
                   //6.以POST方式向微信傳參,並取得微信返回的支付參數
        $dataxml = httpRequest($url,'POST',$post_data);
        $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //將微信返回的XML轉換成數組
        return $objectxml;
    }
}
最後,PayMentController.class.php支付文件,支付文件接收前端發起支付的請求並處理後,調用Weixin.class.php支付類並接受結果後返回給前端(此處分享已經去掉接口驗證等系列代碼邏輯):
public function getPay(){
         //1.引入支付類文件
         include_once "plugins/Payment/weixin/Weixin.class.php";
         $payment = new \Weixin();
         $order_id = I('order_id');
         //2.判斷參數是否爲空
         if (!empty($order_id)){
                   //3.根據訂單id查詢訂單是否存在
                   $order = M('Order')->where(array('id'=>$order_id))->find();
                   if ($order){//訂單存在
                            //4.判斷該筆訂單是否已經支付,如已支付則返回支付失敗並給出相應提示
                            if ($order['pay_status'] == '1'){
                                     exit(json_encode(array('status'=>'205','msg'=>'該訂單已支付,請勿重複提交!')));
                            }
                            $bodys = '訂單:'.$order['order_sn'] . '支付';
                            //5.調用支付類中封裝的支付方法並對應傳參
                            $result = $payment->getCode($order,$bodys);
                            //6.當return_code和result_code均爲SUCCESS,代表下單成功,將支付參數返回
                            if($result['return_code'] == 'SUCCESS'){
                                     if($result['result_code'] == 'SUCCESS'){
                                               exit(json_encode(array('status'=>'0','msg'=>'下單成功,請支付!','result'=>$result['mweb_url'])));
                                     }elseif($result['result_code'] == 'FAIL'){
                                               exit(json_encode(array('status'=>'-201','msg'=>$result['err_code_des'])));
                                     }
                            }else{
               exit(json_encode(array('status'=>'-1','msg'=>'未知錯誤,請稍後重試!')));
                                    }
                   }else{
                            //報錯:數據不存在
                            exit(json_encode(array('status'=>'-200','msg'=>'訂單不存在,請覈實後再提交!')));
                   }
         }else{
                   //報錯:缺少參數
                   exit(json_encode(array('status'=>'-204','msg'=>'參數缺失,請覈實!')));
         }
}

前端在接收到支付URL後執行即可喚醒微信支付。

附一:獲取用戶終端設備ip方法
    function getIP(){           
        if (getenv("HTTP_CLIENT_IP"))
             $ip = getenv("HTTP_CLIENT_IP");
        else if(getenv("HTTP_X_FORWARDED_FOR"))
                $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if(getenv("REMOTE_ADDR"))
             $ip = getenv("REMOTE_ADDR");
        else $ip = "Unknow";
        return $ip;
}

######附二:CURL請求方法

    /**
     * CURL請求
     * @param $url 請求url地址
     * @param $method 請求方法 get post
     * @param null $postfields post數據數組
     * @param array $headers 請求header信息
     * @param bool|false $debug  調試開啓 默認false
     * @return mixed
     */
    function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在發起連接前等待的時間,如果設置爲0,則無限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 設置cURL允許執行的最長秒數 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //設置請求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if($ssl){
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https請求 不驗證證書和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不從證書中檢查SSL加密算法是否存在
        }
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的數量,這個選項是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
}

好了,一點點菜鳥心得,有不當之處歡迎留言指證交流,一起成長,喵,就是這樣!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章