ThinkPHP5.0 實現 app微信支付功能

相對於以前隨筆寫的《ThinkPHP5.0實現app支付寶支付功能》來講,php對接app微信支付功能就相對簡單的多了,最近有加個人朋友問到app微信支付,因此我把app微信支付的demo展現出來供你們參考一下,但願對作這個功能的人員給予參考和幫助,php

首先仍是到支付頁面:html

微信支付的步驟大體和支付寶支付的步驟差很少,這裏我講的詳細一點。前端

第一步:創建一個支付控制器pay.php,是由上個頁面選擇好支付方式以後確認支付後須要通過的控制器(這裏選擇的是微信支付),代碼 以下:node

<?php
namespace app\mobile\controller;
use think\Controller;

class Pay extends Controller
{
    public function pay_order()
    {
        $res = new OrderGoods();
        //獲取訂單號
        $where['id'] = input('post.order_sn');
        $reoderSn = input('post.order_sn');
        //查詢訂單信息
        $order_info = $res->where($where)->find();
        //獲取支付方式
        $pay_type = input('post.pay_type');//微信支付 或者支付寶支付
        //獲取支付金額
        $money = input('post.totle_sum');
        //判斷支付方式
        switch ($pay_type) {
            case 'ali';//若是支付方式爲支付寶支付

                break;
            case 'wx';
                $type['pay_type'] = 'wx';//更新支付方式爲微信
                $res->where($where)->update($type);
                
                $wx = new Wxpay();//實例化微信支付控制器
               
                $body = '訂單號' . $order_info;//支付說明
                
                $out_trade_no = $reoderSn;//訂單號
                
                $total_fee = $money * 100;//支付金額(乘以100)
                
                $notify_url = '';//回調地址

                $order = $wx->getPrePayOrder($body, $out_trade_no, $total_fee, $notify_url);//調用微信支付的方法
                
                if ($order['prepay_id']){//判斷返回參數中是否有prepay_id
                    
                    $order1 = $wx->getOrder($order['prepay_id']);//執行二次簽名返回參數
                    
                    echo json_encode(array('status' => 1, 'prepay_order' => no_null($order1)));
                } else {
                    echo json_encode(array('status' => 0, 'msg' => $order['err_code_des']));
                }
                break;
        }
    }
}

而後建立微信支付控制器了。命名爲wx.php,用於執行微信支付,代碼以下:json

<?php
namespace app\mobile\controller;
use think\Controller;
use think\Db;
class WxPay extends Controller{
    /*
    配置參數
    */
    private $config = array(
        'appid' => "",//"wxcf1dded808489e2c",    /*微信開放平臺上的應用id*/
        'mch_id' => "",//"1440493402",   /*微信申請成功以後郵件中的商戶id*/
        'api_key' => ""    /*在微信商戶平臺上本身設定的api密鑰 32位*/
    );


    //獲取預支付訂單
    public function getPrePayOrder($body, $out_trade_no, $total_fee, $notify_url){
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        $onoce_str = $this->getRandChar(32);

        $data["appid"] = $this->config["appid"];
        $data["body"] = $body;
        $data["mch_id"] = $this->config['mch_id'];
        $data["nonce_str"] = $onoce_str;
        $data["notify_url"] = $notify_url;
        $data["out_trade_no"] = $out_trade_no;
        $data["spbill_create_ip"] = $this->get_client_ip();
        $data["total_fee"] = $total_fee;
        $data["trade_type"] = "APP";
        $s = $this->getSign($data, false);
        $data["sign"] = $s;

        $xml = $this->arrayToXml($data);
        $response = $this->postXmlCurl($xml, $url);

        //將微信返回的結果xml轉成數組
//        return $this->xmlstr_to_array($response);
        return xmlToArray($response);
    }

    //執行第二次簽名,才能返回給客戶端使用
    public function getOrder($prepayId){
        $data["appid"] = $this->config["appid"];
        $data["noncestr"] = $this->getRandChar(32);;
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config['mch_id'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->getSign($data, false);
        $data["sign"] = $s;

        return $data;
    }

    /*
        生成簽名
    */
    function getSign($Obj)
    {
        foreach ($Obj as $k => $v)
        {
            $Parameters[strtolower($k)] = $v;
        }
        //簽名步驟一:按字典序排序參數
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo "【string】 =".$String."</br>";
        //簽名步驟二:在string後加入KEY
        $String = $String."&key=".$this->config['api_key'];
//        echo "<textarea style='width: 50%; height: 150px;'>$String</textarea> <br />";
        //簽名步驟三:MD5加密
        $result_ = strtoupper(md5($String));
        return $result_;
    }

    //獲取指定長度的隨機字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介於min和max兩個數之間的一個隨機整數
        }

        return $str;
    }

    //數組轉xml
    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    //post https請求,CURLOPT_POSTFIELDS xml格式
    function postXmlCurl($xml,$url,$second=30)
    {
        //初始化curl
        $ch = curl_init();
        //超時時間
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        //這裏設置代理,若是有的話
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //設置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求結果爲字符串且輸出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //運行curl
        $data = curl_exec($ch);
        //返回結果
        if($data)
        {
            curl_close($ch);
            return $data;
        }
        else
        {
            $error = curl_errno($ch);
            echo "curl出錯,錯誤碼:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>錯誤緣由查詢</a></br>";
            curl_close($ch);
            return false;
        }
    }

    /*
        獲取當前服務器的IP
    */
    function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }

    //將數組轉成uri字符串
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

    /**
    xml轉成數組
     */
//    function xmlstr_to_array($xmlstr) {
//        $doc = new DOMDocument();
//        $doc->loadXML($xmlstr);
//        return $this->domnode_to_array($doc->documentElement);
//    }
    function domnode_to_array($node) {
        $output = array();
        switch ($node->nodeType) {
            case XML_CDATA_SECTION_NODE:
            case XML_TEXT_NODE:
                $output = trim($node->textContent);
                break;
            case XML_ELEMENT_NODE:
                for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
                    $child = $node->childNodes->item($i);
                    $v = $this->domnode_to_array($child);
                    if(isset($child->tagName)) {
                        $t = $child->tagName;
                        if(!isset($output[$t])) {
                            $output[$t] = array();
                        }
                        $output[$t][] = $v;
                    }
                    elseif($v) {
                        $output = (string) $v;
                    }
                }
                if(is_array($output)) {
                    if($node->attributes->length) {
                        $a = array();
                        foreach($node->attributes as $attrName => $attrNode) {
                            $a[$attrName] = (string) $attrNode->value;
                        }
                        $output['@attributes'] = $a;
                    }
                    foreach ($output as $t => $v) {
                        if(is_array($v) && count($v)==1 && $t!='@attributes') {
                            $output[$t] = $v[0];
                        }
                    }
                }
                break;
        }
        return $output;
    }
}

微信支付控制器裏面基本不用動,只須要改幾個參數就好了。很簡單。api

回調控制器和方法我這裏就不寫了,很簡單的,不懂得能夠私信。數組

流程已經沒了,執行一下程序,看一下返回給前端的參數示例:服務器

把這些參數經過和前端交互給到前端就好了,接下來就是前端拿着參數去進行支付,支付成功系統會自動調用你寫的回調地址改寫你所須要的代碼邏輯。微信

 至於微信控制器wx.php存放的位置參考以前的那個app支付寶支付文章就好了,同樣的。但願以上說明對須要作這個的有所幫助。app

本文屬原創內容,爲了尊重他人勞動,轉載請註明本文地址:

http://www.cnblogs.com/luokakale/p/8391580.html

相關文章
相關標籤/搜索