ホームページ  >  記事  >  WeChat アプレット  >  H5に基づくWeChat決済開発の詳細な説明

H5に基づくWeChat決済開発の詳細な説明

高洛峰
高洛峰オリジナル
2017-02-13 13:23:521839ブラウズ

今回は、ユーザーがWeChatでWebページを開くと、WeChat Payを呼び出して注文機能のモジュール開発を完了できます。つまり、支払い機能はH5ページのjsApiインターフェイスを介して実装されます。 WeChatで。もちろん、WeChat 公式 Web サイトの WeChat 決済開発ドキュメントにも詳しく説明されており、参考用の実装コードが記載されており、ドキュメントを読むだけでこの決済インターフェイスの開発を自分で実装できる人もいます。

1. はじめに

なぜ私がWeChatの支払いインターフェースについてブログ記事を書くのか?まず、いわゆる職務経験の多くは要約に基づいていることを知っておく必要があります。より多くの知識を要約し、より多くの経験を蓄積することでのみ、今日の採用活動の多くは要約に基づいていると個人的に感じています。実務経験が必要です (1 年、3 年、5 年など)。実際には、勤務期間の長さではその人の技術レベルを測ることはできません。1 年の実務経験でプログラマーになれる人もいます。実務経験が 3 年ある人の給与は、1 年しかない人よりも低い場合があります。したがって、要約することで、知識体系と経験の深さをより強力かつ安定させることができます。ブログ投稿を書くのに時間がかかります); 次に、ブログ投稿を書いてみんなと共有することは非常に充実しています。第一に、初心者は私が共有するブログ投稿から何かを学び、ブログ投稿で説明されているテクニックをすぐに実践することができます。したがって、私が書いているブログ記事は、基本的に初心者でもすぐに読むことができます。また、技術専門家であれば、ブログ記事で説明されている間違いを指摘して、コミュニケーションをとることができます。必要なのは共有とコミュニケーションです。

早速、このテーマの詳しい説明に入っていきましょう。

現在、WeChat の支払い方法には、カード支払い、公式アカウント支払い、APP 支払いがあります。説明すると、他のいくつかの支払いインターフェースの開発アイデアは、私のブログ投稿で説明した基本的なアイデアを理解できれば、基本的には自分で開発できます。 。

基于H5的微信支付开发详解

2. アイデアの詳細な説明

以下に示すように、WeChat 支払いインターフェイス ドキュメントのビジネス プロセス シーケンス図を見てみましょう。基本的なアイデアは次のとおりです。まず、バックグラウンドでリンクを生成します。ユーザーがクリックできるようにそれを表示します (たとえば、ページに WeChat 支払いボタンがあります)。ユーザーがボタンをクリックすると、注文の関連情報に基づいて Web サイトの背景が支払い注文を生成します。今回は、統合注文インターフェイスが呼び出されて WeChat 支払いシステムへのリクエストが開始され、WeChat 支払いシステムがそのリクエストを受け取ります。最後に、前払いトランザクション セッション ID (注文を識別するための prepay_id) が生成されます。当社の Web サイトが WeChat 支払いシステムから応答を受信すると、prepay_id が取得され、支払いに必要なパラメータがクライアントに返されます。このとき、WeChat 支払いシステムへの支払いリクエストを開始するために JSAPI インターフェイスが呼び出され、リクエストの正当性が確認されます。ユーザーが確認のためにパスワードを入力すると、WeChat 支払いシステムがそれを検証し、支払い結果が返され、WeChat は非同期的に支払いを Web サイトに通知します。当社の Web サイトが処理する必要がある結果 (たとえば、非同期の支払い結果が渡された後、ユーザーが注文に対して支払いを行ったことをマークするなど、データ テーブルまたは注文情報を更新する必要があります。また、注文ログも更新する必要があります)ユーザーが繰り返し注文を送信できないようにします)。

基于H5的微信支付开发详解

3. コードの説明

この開発環境は、php5.6 + MySQL + Redis + Linux + Apache を使用します。選択したフレームワークの CI フレームワーク (これらの環境は必ずしも私の環境と一致している必要はありません。フレームワークはまた、自分で選択することもできますが、コードを少し変更するだけで移植できます)。

WeChatの決済インターフェースの開発コードを事前に書きましたので、ここで誰でも簡単に理解できるように分析して説明します。 もちろん、ある程度の基礎があれば、それを見ればすべてのプロセスが明確になります。コードを直接記述します。また、私のコードは基本的にコメントを使用して記述されています (初心者にとって、これは WeChat ドキュメントで提供されるコードよりも少し優れています)。

1. ユーザーに表示するリンクを構築します

ここで、事前に知っておく必要がある点が 1 つあります。それは、統一された注文インターフェイスをリクエストするには、WeChat ユーザーの openid が必要であるということです (詳細については、こちらを参照してください https:// pay.weixin.qq.com/wiki /doc/api/jsapi.php?chapter=9_1)、openid を取得するには、まずコードを取得する必要があります (詳細については WeChat ログイン インターフェイスを参照)。そのため、次のように構築する必要があります。コードを取得するための URL:

Wxpay.php文件:
<?php
defined(&#39;BASEPATH&#39;) OR exit(&#39;No direct script access allowed&#39;);

class Wxpay extends MY_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('wxpay_model');
        //$this->load->model('wxpay');
        
    }
 
    public function index() {
        //微信支付
        $this->smarty['wxPayUrl'] = $this->wxpay_model->retWxPayUrl();
        $this->displayView('wxpay/index.tpl');
    }
}

  在这先看看model里所写的几个类:model里有几个类:微信支付类、统一下单接口类、响应型接口基类、请求型接口基类、所有接口基类、配置类。为何要分那么多类而不在一个类里实现所有的方法的,因为,这样看起来代码逻辑清晰,哪个类该干嘛就干嘛。

  这里我直接附上model的代码了,里面基本上每一个类每一个方法甚至每一行代码都会有解释的了,这里我就不对其展开一句句分析了:

  <?php
defined(&#39;BASEPATH&#39;) OR exit(&#39;No direct script access allowed&#39;);

class Wxpay_model extends CI_Model {
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * 返回可以获得微信code的URL (用以获取openid)
     * @return [type] [description]
     */
    public function retWxPayUrl() {
        $jsApi = new JsApi_handle();
        return $jsApi->createOauthUrlForCode();
    }
 
    /**
     * 微信jsapi点击支付
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function wxPayJsApi($data) {
        $jsApi = new JsApi_handle();
        //统一下单接口所需数据
        $payData = $this->returnData($data);
        //获取code码,用以获取openid
        $code = $_GET['code'];
        $jsApi->setCode($code);
        //通过code获取openid
        $openid = $jsApi->getOpenId();
        
        $unifiedOrderResult = null;
        if ($openid != null) {
            //取得统一下单接口返回的数据
            $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
            //获取订单接口状态
            $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
            if ($returnMessage['resultCode']) {
                $jsApi->setPrepayId($retuenMessage['resultField']);
                //取得wxjsapi接口所需要的数据
                $returnMessage['resultData'] = $jsApi->getParams();
            } 

            return $returnMessage;
        }
    }

    /**
     * 统一下单接口所需要的数据
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function returnData($data) {
        $payData['sn'] = $data['sn'];
        $payData['body'] = $data['goods_name'];
        $payData['out_trade_no'] = $data['order_no'];
        $payData['total_fee'] = $data['fee'];
        $payData['attach'] = $data['attach'];

        return $payData;
    }

    /**
     * 返回统一下单接口结果 (参考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
     * @param  [type] $payData    [description]
     * @param  [type] $trade_type [description]
     * @param  [type] $openid     [description]
     * @return [type]             [description]
     */
    public function getResult($payData, $trade_type, $openid = null) {
        $unifiedOrder = new UnifiedOrder_handle();

        if ($opneid != null) {
            $unifiedOrder->setParam('openid', $openid);
        }
        $unifiedOrder->setParam('body', $payData['body']);  //商品描述
        $unifiedOrder->setParam('out_trade_no', $payData['out_trade_no']); //商户订单号
        $unifiedOrder->setParam('total_fee', $payData['total_fee']);    //总金额
        $unifiedOrder->setParam('attach', $payData['attach']);  //附加数据
        $unifiedOrder->setParam('notify_url', base_url('/Wxpay/pay_callback'));//通知地址
        $unifiedOrder->setParam('trade_type', $trade_type); //交易类型

        //非必填参数,商户可根据实际情况选填
        //$unifiedOrder->setParam("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParam("device_info","XXXX");//设备号
        //$unifiedOrder->setParam("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParam("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParam("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParam("product_id","XXXX");//商品ID
        
        return $unifiedOrder->getResult();
    }

    /**
     * 返回微信订单状态
     */
    public function returnMessage($unifiedOrderResult,$field){
        $arrMessage=array("resultCode"=>0,"resultType"=>"获取错误","resultMsg"=>"该字段为空");
        if($unifiedOrderResult==null){
            $arrMessage["resultType"]="未获取权限";
            $arrMessage["resultMsg"]="请重新打开页面";
        }elseif ($unifiedOrderResult["return_code"] == "FAIL")
        {
            $arrMessage["resultType"]="网络错误";
            $arrMessage["resultMsg"]=$unifiedOrderResult['return_msg'];
        }
        elseif($unifiedOrderResult["result_code"] == "FAIL")
        {
            $arrMessage["resultType"]="订单错误";
            $arrMessage["resultMsg"]=$unifiedOrderResult['err_code_des'];
        }
        elseif($unifiedOrderResult[$field] != NULL)
        {
            $arrMessage["resultCode"]=1;
            $arrMessage["resultType"]="生成订单";
            $arrMessage["resultMsg"]="OK";
            $arrMessage["resultField"] = $unifiedOrderResult[$field];
        }
        return $arrMessage;
    }

    /**
     * 微信回调接口返回  验证签名并回应微信
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    public function wxPayNotify($xml) {
        $notify = new Wxpay_server();
        $notify->saveData($xml);
        //验证签名,并回复微信
        //对后台通知交互时,如果微信收到商户的应答不是成功或者超时,微信认为通知失败
        //微信会通过一定的策略(如30分钟共8次),定期重新发起通知
        if ($notify->checkSign() == false) {
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        } else {
            $notify->checkSign=TRUE;
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }

        return $notify;
    }
}

/**
* JSAPI支付——H5网页端调起支付接口
*/
class JsApi_handle extends JsApi_common {
    public $code;//code码,用以获取openid
    public $openid;//用户的openid
    public $parameters;//jsapi参数,格式为json
    public $prepay_id;//使用统一支付接口得到的预支付id
    public $curl_timeout;//curl超时时间

    function __construct()
    {
        //设置curl超时时间
        $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
    }

    /**
     * 生成获取code的URL
     * @return [type] [description]
     */
    public function createOauthUrlForCode() {
        //重定向URL
        $redirectUrl = "http://www.itcen.cn/wxpay/confirm/".$orderId."?showwxpaytitle=1";
        $urlParams['appid'] = WxPayConf::APPID;
        $urlParams['redirect_uri'] = $redirectUrl;
        $urlParams['response_type'] = 'code';
        $urlParams['scope'] = 'snsapi_base';
        $urlParams['state'] = "STATE"."#wechat_redirect";
        //拼接字符串
        $queryString = $this->ToUrlParams($urlParams, false);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$queryString;
    }

    /**
     * 设置code
     * @param [type] $code [description]
     */
    public function setCode($code) {
        $this->code = $code;
    }

    /**
     *  作用:设置prepay_id
     */
    public function setPrepayId($prepayId)
    {
        $this->prepay_id = $prepayId;
    }

    /**
     *  作用:获取jsapi的参数
     */
    public function getParams()
    {
        $jsApiObj["appId"] = WxPayConf::APPID;
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=$this->prepay_id";
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);
        $this->parameters = json_encode($jsApiObj);

        return $this->parameters;
    }

    /**
     * 通过curl 向微信提交code 用以获取openid
     * @return [type] [description]
     */
    public function getOpenId() {
        //创建openid 的链接
        $url = $this->createOauthUrlForOpenid();
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURL_TIMEOUT, $this->curl_timeout);
        curl_setopt($ch, CURL_URL, $url);
        curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURL_HEADER, FALSE);
        curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
        //执行curl
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res);
        if (isset($data['openid'])) {
            $this->openid = $data['openid'];
        } else {
            return null;
        }

        return $this->openid;

    }

    /**
     * 生成可以获取openid 的URL
     * @return [type] [description]
     */
    public function createOauthUrlForOpenid() {
        $urlParams['appid'] = WxPayConf::APPID;
        $urlParams['secret'] = WxPayConf::APPSECRET;
        $urlParams['code'] = $this->code;
        $urlParams['grant_type'] = "authorization_code";
        $queryString = $this->ToUrlParams($urlParams, false);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$queryString;
    }
}

/**
 * 统一下单接口类
 */
class UnifiedOrder_handle extends Wxpay_client_handle {
    public function __construct() {
        //设置接口链接
        $this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        //设置curl超时时间
        $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
    }

}

/**
 * 响应型接口基类
 */
class Wxpay_server_handle extends JsApi_common{
    public $data; //接收到的数据,类型为关联数组
    public $returnParams;   //返回参数,类型为关联数组

    /**
     * 将微信请求的xml转换成关联数组
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    public function saveData($xml) {
        $this->data = $this->xmlToArray($xml); 
    }


    /**
     * 验证签名
     * @return [type] [description]
     */
    public function checkSign() {
        $tmpData = $this->data;
        unset($temData['sign']);
        $sign = $this->getSign($tmpData);
        if ($this->data['sign'] == $sign) {
            return true;
        }
        return false;
    }


    /**
     * 设置返回微信的xml数据
     */
    function setReturnParameter($parameter, $parameterValue)
    {
        $this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
    }

    /**
     * 将xml数据返回微信
     */
    function returnXml()
    {
        $returnXml = $this->createXml();
        return $returnXml;
    }

}

/**
 * 请求型接口的基类
 */
class Wxpay_client_handle extends JsApi_common{
    public $params; //请求参数,类型为关联数组
    public $response; //微信返回的响应
    public $result; //返回参数,类型类关联数组
    public $url; //接口链接
    public $curl_timeout; //curl超时时间

    /**
     * 设置请求参数
     * @param [type] $param      [description]
     * @param [type] $paramValue [description]
     */
    public function setParam($param, $paramValue) {
        $this->params[$this->tirmString($param)] = $this->trimString($paramValue);
    }

    /**
     * 获取结果,默认不使用证书
     * @return [type] [description]
     */
    public function getResult() {
        $this->postxml(); 
        $this->result = $this->xmlToArray($this->response);

        return $this->result;
    }

    /**
     * post请求xml
     * @return [type] [description]
     */
    public function postxml() {
        $xml = $this->createXml();
        $this->response = $this->postXmlCurl($xml, $this->curl, $this->curl_timeout);

        return $this->response;
    }

    public function createXml() {
        $this->params['appid'] = WxPayConf::APPID; //公众号ID
        $this->params['mch_id'] = WxPayConf::MCHID; //商户号
        $this->params['nonce_str'] = $this->createNoncestr();   //随机字符串
        $this->params['sign'] = $this->getSign($this->params);  //签名
        
        return $this->arrayToXml($this->params); 
    }

    

}

/**
 * 所有接口的基类
 */
class JsApi_common {
    function __construct() {

    }

    public function trimString($value) {
        $ret = null;
        if (null != $value) {
            $ret = trim($value);
            if (strlen($ret) == 0) {
                $ret = null;
            }
        } 
        return $ret;
    }

    /**
     * 产生随机字符串,不长于32位
     * @param  integer $length [description]
     * @return [type]          [description]
     */
    public function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $str;
    }

    /**
     * 格式化参数 拼接字符串,签名过程需要使用
     * @param [type] $urlParams     [description]
     * @param [type] $needUrlencode [description]
     */
    public function ToUrlParams($urlParams, $needUrlencode) {
        $buff = "";
        ksort($urlParams);

        foreach ($urlParams as $k => $v) {
            if($needUrlencode) $v = urlencode($v);
            $buff .= $k .'='. $v .'&';
        }

        $reqString = '';
        if (strlen($buff) > 0) {
            $reqString = substr($buff, 0, strlen($buff) - 1);
        }

        return $reqString;
    }

    /**
     * 生成签名
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getSign($obj) {
        foreach ($obj as $k => $v) {
            $params[$k] = $v;
        }
        //签名步骤一:按字典序排序参数
        ksort($params);
        $str = $this->ToUrlParams($params, false);  
        //签名步骤二:在$str后加入key
        $str = $str."$key=".WxPayConf::KEY;
        //签名步骤三:md5加密
        $str = md5($str);
        //签名步骤四:所有字符转为大写
        $result = strtoupper($str);

        return $result;
    }

    /**
     * array转xml
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    public function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $k => $v) {
            if (is_numeric($val)) {
                $xml .= "<".$key.">".$key."</".$key.">";
            } else {
                $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    /**
     * 将xml转为array
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    public function xmlToArray($xml) {
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SinpleXMLElement', LIBXML_NOCDATA)), true);

        return $arr;
    }

    /**
     * 以post方式提交xml到对应的接口
     * @param  [type]  $xml    [description]
     * @param  [type]  $url    [description]
     * @param  integer $second [description]
     * @return [type]          [description]
     */
    public function postXmlCurl($xml, $url, $second = 30) {
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURL_TIMEOUT, $second);
        curl_setopt($ch, CURL_URL, $url);
        //这里设置代理,如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
        //设置header
        curl_setopt($ch, CURL_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
        //以post方式提交
        curl_setopt($ch, CURL_POST, TRUE);
        curl_setopt($ch, CURL_POSTFIELDS, $xml);
        //执行curl
        $res = curl_exec($ch);

        if ($res) {
            curl_close($ch);
            return $res;
        } else {
            $error = curl_errno($ch);
            echo "curl出错,错误码:$error"."<br>";
            echo "<a href=&#39;http://curl.haxx.se/libcurl/c/libcurl-errors.html&#39;>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }
}

/**
 * 配置类
 */
class WxPayConf {
    //微信公众号身份的唯一标识。
    const APPID = 'wx654a22c6423213b7';
    //受理商ID,身份标识
    const MCHID = '10043241';
    const MCHNAME = 'KellyCen的博客';
    
    //商户支付密钥Key。
    const KEY = '0000000000000000000000000000000';
    //JSAPI接口中获取openid
    const APPSECRET = '000000000000000000000000000';

    //证书路径,注意应该填写绝对路径
    const SSLCERT_PATH = '/home/WxPayCacert/apiclient_cert.pem';
    const SSLKEY_PATH = '/home/WxPayCacert/apiclient_key.pem';
    const SSLCA_PATH = '/home/WxPayCacert/rootca.pem';

    //本例程通过curl使用HTTP POST方法,此处可修改其超时时间,默认为30秒
    const CURL_TIMEOUT = 30;
}

Wxpay_model.php

Wxpay_model.php

   获取到code的URL后,将其分配到页面去,让用户去点击,用户进行点击后,就会从微信服务器获取到code,然后回调到redirect_uri所指的地址去。

  2、获取到code后,会回调到redirect_uri所指向的地址去,这里是到了/Wxpay/confirm/,看看这个confirm方法是打算干嘛的:

/**
     * 手机端微信支付,此处是授权获取到code时的回调地址
     * @param  [type] $orderId 订单编号id
     * @return [type]          [description]
     */ 
    public function confirm($orderId) {
        //先确认用户是否登录
        $this->ensureLogin();
        //通过订单编号获取订单数据
        $order = $this->wxpay_model->get($orderId);
        //验证订单是否是当前用户
        $this->_verifyUser($order);

        //取得支付所需要的订单数据
        $orderData = $this->returnOrderData[$orderId];
        //取得jsApi所需要的数据
        $wxJsApiData = $this->wxpay_model->wxPayJsApi($orderData);
        //将数据分配到模板去,在js里使用
        $this->smartyData['wxJsApiData'] = json_encode($wxJsApiData, JSON_UNESCAPED_UNICODE);
        $this->smartyData['order'] = $orderData;
        $this->displayView('wxpay/confirm.tpl');
        
    }

  这一步开始去取JSAPI支付接口所需要的数据了,这一步算是最主要的一步,这里还会调用统一下单接口获取到prepay_id,我们跳到

  $this->wxpay_model->wxPayJsApi($orderData) 看看:

/**
     * 微信jsapi点击支付
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function wxPayJsApi($data) {
        $jsApi = new JsApi_handle();
        //统一下单接口所需数据
        $payData = $this->returnData($data);
        //获取code码,用以获取openid
        $code = $_GET['code'];
        $jsApi->setCode($code);
        //通过code获取openid
        $openid = $jsApi->getOpenId();
        
        $unifiedOrderResult = null;
        if ($openid != null) {
            //取得统一下单接口返回的数据
            $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
            //获取订单接口状态
            $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
            if ($returnMessage['resultCode']) {
                $jsApi->setPrepayId($retuenMessage['resultField']);
                //取得wxjsapi接口所需要的数据
                $returnMessage['resultData'] = $jsApi->getParams();
            } 

            return $returnMessage;
        }
    }

  这里首先是取得下单接口所需要的数据;

  接着获取到code码,通过code码获取到openid;

  然后调用统一下单接口,取得下单接口的响应数据,即prepay_id;

  最后取得微信支付JSAPI所需要的数据。

  这就是上面这个方法所要做的事情,取到数据后,会将数据分配到模板里,然后根据官方文档所给的参考格式将其放在js里,如下面的代码:

<!doctype html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Make sure that we can test against real IE8 -->
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<title></title>
</head>
<body>

<a href="javascript:callpay();" id="btnOrder">点击支付</a>
</body>  
<script type="text/javascript">
    //将数据付给js变量
    var wxJsApiData = {$wxJsApiData};
    function onBridgeReady()
        {
            //格式参考官方文档 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest',
                $.parseJSON(wxJsApiData.resultData),
                function(res){
                    if(res.err_msg == "get_brand_wcpay_request:ok" ){
                        window.location.href="/wxpay/paysuccess/"+{$order.sn}; 
                    }

                } 
            );
        }
        function callpay()
        { 
            if(!wxJsApiData.resultCode){
                alert(wxJsApiData.resultType+","+wxJsApiData.resultMsg+"!");
                return false;
            }
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            }else{
                onBridgeReady();
            }
        }
</script>
</html>

  3、此时用户只需要点击支付,就可以开始进入支付界面了,接着就是输入密码,确认,最后会提示支付成功,紧接着网站会提供一个支付成功跳转页面。类似微信文档里所提供的图片这样,这里我就直接截取文档里的案例图了:

基于H5的微信支付开发详解

  4、这里还有一步,就是微信支付系统会异步通知网站后台用户的支付结果。在获取统一下单数据时,我们指定了一个通知地址,在model里可以找到

基于H5的微信支付开发详解

  支付成功后,微信支付系统会将支付结果异步发送到此地址上/Wxpay/pay_callback/ ,我们来看一下这个方法

/**
     * 支付回调接口
     * @return [type] [description]
     */
    public function pay_callback() {
        $postData = '';
        if (file_get_contents("php://input")) {
            $postData = file_get_contents("php://input");
        } else {
            return;
        }
        $payInfo = array();
        $notify = $this->wxpay_model->wxPayNotify($postData);

        if ($notify->checkSign == TRUE) {
            if ($notify->data['return_code'] == 'FAIL') {
                $payInfo['status'] = FALSE;
                $payInfo['msg'] = '通信出错';
            } elseif ($notify->data['result_code'] == 'FAIL') {
                $payInfo['status'] = FALSE;
                $payInfo['msg'] = '业务出错';
            } else {
                $payInfo['status'] = TRUE;
                $payInfo['msg'] = '支付成功';
                $payInfo['sn']=substr($notify->data['out_trade_no'],8);
                $payInfo['order_no'] = $notify->data['out_trade_no'];
                $payInfo['platform_no']=$notify->data['transaction_id'];
                $payInfo['attach']=$notify->data['attach'];
                $payInfo['fee']=$notify->data['cash_fee'];
                $payInfo['currency']=$notify->data['fee_type'];
                $payInfo['user_sign']=$notify->data['openid'];
            }
        }
        $returnXml = $notify->returnXml();

        echo $returnXml;

        $this->load->library('RedisCache');
        if($payInfo['status']){
           //这里要记录到日志处理(略)
            $this->model->order->onPaySuccess($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo);
            $this->redis->RedisCache->set('order:payNo:'.$payInfo['order_no'],'OK',5000);
        }else{
           //这里要记录到日志处理(略)
            $this->model->order->onPayFailure($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo, '订单支付失败 ['.$payInfo['msg'].']');
        }
    }

  这方法就是对支付是否成功,对网站的支付相关逻辑进行后续处理,例如假如支付失败,就需要记录日志里说明此次交易失败,或者是做某一些逻辑处理,而支付成功又该如何做处理,等等。

  这里我们就分析下这个方法 $this->wxpay_model->wxPayNotify($postData); 对异步返回的数据进行安全性校验,例如验证签名,看看model里的这个方法:

/**
     * 微信回调接口返回  验证签名并回应微信
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    public function wxPayNotify($xml) {
        $notify = new Wxpay_server();
        $notify->saveData($xml);
        //验证签名,并回复微信
        //对后台通知交互时,如果微信收到商户的应答不是成功或者超时,微信认为通知失败
        //微信会通过一定的策略(如30分钟共8次),定期重新发起通知
        if ($notify->checkSign() == false) {
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        } else {
            $notify->checkSign=TRUE;
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }

        return $notify;
    }

  如果验证通过,则就开始进行交易成功或者失败时所要做的逻辑处理了,这逻辑处理的代码我就不写了,因为每一个网站的处理方式都不一样,我这里是这样处理的,我把思路写下,方便不懂的朋友可以按着我的思路去完善后续的处理:首先是查看数据库里的订单日志表,看这笔交易之前是否已经交易过了,交易过就不用再更新数据表了,如果没交易过,就会将之前存在redis的订单数据给取出来,再将这些数据插入到订单日志表里,差不多就这样处理。

 

  好了,基于H5的微信支付接口开发详解就讲到这里,如果你认真理清博文里所讲解的思路,自己基本上也可以尝试开发此接口了,同时只要会了这个,你也基本上可以开发二维码支付,刷卡支付等等的支付接口。

  这里我附上此次开发中的完整代码供大家阅读:

 load->model('wxpay_model');
        //$this->load->model('wxpay');
        
    }
 
    public function index() {
        //微信支付
        $this->smarty['wxPayUrl'] = $this->wxpay_model->retWxPayUrl();
        $this->displayView('wxpay/index.tpl');
    }

    /**
     * 手机端微信支付,此处是授权获取到code时的回调地址
     * @param  [type] $orderId 订单编号id
     * @return [type]          [description]
     */ 
    public function confirm($orderId) {
        //先确认用户是否登录
        $this->ensureLogin();
        //通过订单编号获取订单数据
        $order = $this->wxpay_model->get($orderId);
        //验证订单是否是当前用户
        $this->_verifyUser($order);

        //取得支付所需要的订单数据
        $orderData = $this->returnOrderData[$orderId];
        //取得jsApi所需要的数据
        $wxJsApiData = $this->wxpay_model->wxPayJsApi($orderData);
        //将数据分配到模板去,在js里使用
        $this->smartyData['wxJsApiData'] = json_encode($wxJsApiData, JSON_UNESCAPED_UNICODE);
        $this->smartyData['order'] = $orderData;
        $this->displayView('wxpay/confirm.tpl');
        
    }
    /**
     * 支付回调接口
     * @return [type] [description]
     */
    public function pay_callback() {
        $postData = '';
        if (file_get_contents("php://input")) {
            $postData = file_get_contents("php://input");
        } else {
            return;
        }
        $payInfo = array();
        $notify = $this->wxpay_model->wxPayNotify($postData);

        if ($notify->checkSign == TRUE) {
            if ($notify->data['return_code'] == 'FAIL') {
                $payInfo['status'] = FALSE;
                $payInfo['msg'] = '通信出错';
            } elseif ($notify->data['result_code'] == 'FAIL') {
                $payInfo['status'] = FALSE;
                $payInfo['msg'] = '业务出错';
            } else {
                $payInfo['status'] = TRUE;
                $payInfo['msg'] = '支付成功';
                $payInfo['sn']=substr($notify->data['out_trade_no'],8);
                $payInfo['order_no'] = $notify->data['out_trade_no'];
                $payInfo['platform_no']=$notify->data['transaction_id'];
                $payInfo['attach']=$notify->data['attach'];
                $payInfo['fee']=$notify->data['cash_fee'];
                $payInfo['currency']=$notify->data['fee_type'];
                $payInfo['user_sign']=$notify->data['openid'];
            }
        }
        $returnXml = $notify->returnXml();

        echo $returnXml;

        $this->load->library('RedisCache');
        if($payInfo['status']){
           //这里要记录到日志处理(略)
            $this->model->order->onPaySuccess($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo);
            $this->redis->RedisCache->set('order:payNo:'.$payInfo['order_no'],'OK',5000);
        }else{
           //这里要记录到日志处理(略)
            $this->model->order->onPayFailure($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo, '订单支付失败 ['.$payInfo['msg'].']');
        }
    }

    /**
     * 返回支付所需要的数据
     * @param  [type] $orderId 订单号
     * @param  string $data    订单数据,当$data数据存在时刷新$orderData缓存,因为订单号不唯一
     * @return [type]          [description]
     */
    public function returnOrderData($orderId, $data = '') {
        //获取订单数据
        $order = $this->wxpay_model->get($orderId);
        if (0 === count($order)) return false;
        if (empty($data)) {
            $this->load->library('RedisCache');
            //取得缓存在redis的订单数据
            $orderData = $this->rediscache->getJson("order:orderData:".$orderId);
            if (empty($orderData)) {
                //如果redis里没有,则直接读数据库取
                $this->load->model('order_model');
                $order = $this->order_model->get($orderId);
                if (0 === count($order)) {
                    return false;
                }
                $data = $order;
            } else {
                //如果redis里面有的话,直接返回数据
                return $orderData;
            }
        }
 
        //支付前缓存所需要的数据
        $orderData['id'] = $data['id'];
        $orderData['fee'] = $data['fee'];

        //支付平台需要的数据
        $orderData['user_id'] = $data['user_id'];
        $orderData['sn'] = $data['cn'];
        //这是唯一编号
        $orderData['order_no'] = substr(md5($data['sn'].$data['fee']), 8, 8).$data['sn'];
        $orderData['fee'] = $data['fee'];
        $orderData['time'] = $data['time'];
        $orderData['goods_name'] = $data['goods_name'];
        $orderData['attach'] = $data['attach'];

        //将数据缓存到redis里面
        $this->rediscache->set("order:orderData:".$orderId, $orderData, 3600*24);
        //做个标识缓存到redis,用以判断该订单是否已经支付了
        $this->rediscache->set("order:payNo:".$orderData['order_no'], "NO", 3600*24);

        return $orderData;
    }

    private function _verifyUser($order) {
        if (empty($order)) show_404();
        if (0 === count($order)) show_404();
        //判断订单表里的用户id是否是当前登录者的id
        if ($order['user_id'] == $this->uid) return;
        show_error('只能查看自己的订单');
    }

}

控制器:Wxpay.php

控制器:Wxpay.php

 createOauthUrlForCode();
    }
 
    /**
     * 微信jsapi点击支付
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function wxPayJsApi($data) {
        $jsApi = new JsApi_handle();
        //统一下单接口所需数据
        $payData = $this->returnData($data);
        //获取code码,用以获取openid
        $code = $_GET['code'];
        $jsApi->setCode($code);
        //通过code获取openid
        $openid = $jsApi->getOpenId();
        
        $unifiedOrderResult = null;
        if ($openid != null) {
            //取得统一下单接口返回的数据
            $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
            //获取订单接口状态
            $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
            if ($returnMessage['resultCode']) {
                $jsApi->setPrepayId($retuenMessage['resultField']);
                //取得wxjsapi接口所需要的数据
                $returnMessage['resultData'] = $jsApi->getParams();
            } 

            return $returnMessage;
        }
    }

    /**
     * 统一下单接口所需要的数据
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function returnData($data) {
        $payData['sn'] = $data['sn'];
        $payData['body'] = $data['goods_name'];
        $payData['out_trade_no'] = $data['order_no'];
        $payData['total_fee'] = $data['fee'];
        $payData['attach'] = $data['attach'];

        return $payData;
    }

    /**
     * 返回统一下单接口结果 (参考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
     * @param  [type] $payData    [description]
     * @param  [type] $trade_type [description]
     * @param  [type] $openid     [description]
     * @return [type]             [description]
     */
    public function getResult($payData, $trade_type, $openid = null) {
        $unifiedOrder = new UnifiedOrder_handle();

        if ($opneid != null) {
            $unifiedOrder->setParam('openid', $openid);
        }
        $unifiedOrder->setParam('body', $payData['body']);  //商品描述
        $unifiedOrder->setParam('out_trade_no', $payData['out_trade_no']); //商户订单号
        $unifiedOrder->setParam('total_fee', $payData['total_fee']);    //总金额
        $unifiedOrder->setParam('attach', $payData['attach']);  //附加数据
        $unifiedOrder->setParam('notify_url', base_url('/Wxpay/pay_callback'));//通知地址
        $unifiedOrder->setParam('trade_type', $trade_type); //交易类型

        //非必填参数,商户可根据实际情况选填
        //$unifiedOrder->setParam("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParam("device_info","XXXX");//设备号
        //$unifiedOrder->setParam("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParam("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParam("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParam("product_id","XXXX");//商品ID
        
        return $unifiedOrder->getResult();
    }

    /**
     * 返回微信订单状态
     */
    public function returnMessage($unifiedOrderResult,$field){
        $arrMessage=array("resultCode"=>0,"resultType"=>"获取错误","resultMsg"=>"该字段为空");
        if($unifiedOrderResult==null){
            $arrMessage["resultType"]="未获取权限";
            $arrMessage["resultMsg"]="请重新打开页面";
        }elseif ($unifiedOrderResult["return_code"] == "FAIL")
        {
            $arrMessage["resultType"]="网络错误";
            $arrMessage["resultMsg"]=$unifiedOrderResult['return_msg'];
        }
        elseif($unifiedOrderResult["result_code"] == "FAIL")
        {
            $arrMessage["resultType"]="订单错误";
            $arrMessage["resultMsg"]=$unifiedOrderResult['err_code_des'];
        }
        elseif($unifiedOrderResult[$field] != NULL)
        {
            $arrMessage["resultCode"]=1;
            $arrMessage["resultType"]="生成订单";
            $arrMessage["resultMsg"]="OK";
            $arrMessage["resultField"] = $unifiedOrderResult[$field];
        }
        return $arrMessage;
    }

    /**
     * 微信回调接口返回  验证签名并回应微信
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    public function wxPayNotify($xml) {
        $notify = new Wxpay_server();
        $notify->saveData($xml);
        //验证签名,并回复微信
        //对后台通知交互时,如果微信收到商户的应答不是成功或者超时,微信认为通知失败
        //微信会通过一定的策略(如30分钟共8次),定期重新发起通知
        if ($notify->checkSign() == false) {
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        } else {
            $notify->checkSign=TRUE;
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }

        return $notify;
    }
}

/**
* JSAPI支付——H5网页端调起支付接口
*/
class JsApi_handle extends JsApi_common {
    public $code;//code码,用以获取openid
    public $openid;//用户的openid
    public $parameters;//jsapi参数,格式为json
    public $prepay_id;//使用统一支付接口得到的预支付id
    public $curl_timeout;//curl超时时间

    function __construct()
    {
        //设置curl超时时间
        $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
    }

    /**
     * 生成获取code的URL
     * @return [type] [description]
     */
    public function createOauthUrlForCode() {
        //重定向URL
        $redirectUrl = "http://www.itcen.cn/wxpay/confirm/".$orderId."?showwxpaytitle=1";
        $urlParams['appid'] = WxPayConf::APPID;
        $urlParams['redirect_uri'] = $redirectUrl;
        $urlParams['response_type'] = 'code';
        $urlParams['scope'] = 'snsapi_base';
        $urlParams['state'] = "STATE"."#wechat_redirect";
        //拼接字符串
        $queryString = $this->ToUrlParams($urlParams, false);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$queryString;
    }

    /**
     * 设置code
     * @param [type] $code [description]
     */
    public function setCode($code) {
        $this->code = $code;
    }

    /**
     *  作用:设置prepay_id
     */
    public function setPrepayId($prepayId)
    {
        $this->prepay_id = $prepayId;
    }

    /**
     *  作用:获取jsapi的参数
     */
    public function getParams()
    {
        $jsApiObj["appId"] = WxPayConf::APPID;
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=$this->prepay_id";
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);
        $this->parameters = json_encode($jsApiObj);

        return $this->parameters;
    }

    /**
     * 通过curl 向微信提交code 用以获取openid
     * @return [type] [description]
     */
    public function getOpenId() {
        //创建openid 的链接
        $url = $this->createOauthUrlForOpenid();
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURL_TIMEOUT, $this->curl_timeout);
        curl_setopt($ch, CURL_URL, $url);
        curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURL_HEADER, FALSE);
        curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
        //执行curl
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res);
        if (isset($data['openid'])) {
            $this->openid = $data['openid'];
        } else {
            return null;
        }

        return $this->openid;

    }

    /**
     * 生成可以获取openid 的URL
     * @return [type] [description]
     */
    public function createOauthUrlForOpenid() {
        $urlParams['appid'] = WxPayConf::APPID;
        $urlParams['secret'] = WxPayConf::APPSECRET;
        $urlParams['code'] = $this->code;
        $urlParams['grant_type'] = "authorization_code";
        $queryString = $this->ToUrlParams($urlParams, false);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$queryString;
    }
}

/**
 * 统一下单接口类
 */
class UnifiedOrder_handle extends Wxpay_client_handle {
    public function __construct() {
        //设置接口链接
        $this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        //设置curl超时时间
        $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
    }

}

/**
 * 响应型接口基类
 */
class Wxpay_server_handle extends JsApi_common{
    public $data; //接收到的数据,类型为关联数组
    public $returnParams;   //返回参数,类型为关联数组

    /**
     * 将微信请求的xml转换成关联数组
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    public function saveData($xml) {
        $this->data = $this->xmlToArray($xml); 
    }


    /**
     * 验证签名
     * @return [type] [description]
     */
    public function checkSign() {
        $tmpData = $this->data;
        unset($temData['sign']);
        $sign = $this->getSign($tmpData);
        if ($this->data['sign'] == $sign) {
            return true;
        }
        return false;
    }


    /**
     * 设置返回微信的xml数据
     */
    function setReturnParameter($parameter, $parameterValue)
    {
        $this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
    }

    /**
     * 将xml数据返回微信
     */
    function returnXml()
    {
        $returnXml = $this->createXml();
        return $returnXml;
    }

}

/**
 * 请求型接口的基类
 */
class Wxpay_client_handle extends JsApi_common{
    public $params; //请求参数,类型为关联数组
    public $response; //微信返回的响应
    public $result; //返回参数,类型类关联数组
    public $url; //接口链接
    public $curl_timeout; //curl超时时间

    /**
     * 设置请求参数
     * @param [type] $param      [description]
     * @param [type] $paramValue [description]
     */
    public function setParam($param, $paramValue) {
        $this->params[$this->tirmString($param)] = $this->trimString($paramValue);
    }

    /**
     * 获取结果,默认不使用证书
     * @return [type] [description]
     */
    public function getResult() {
        $this->postxml(); 
        $this->result = $this->xmlToArray($this->response);

        return $this->result;
    }

    /**
     * post请求xml
     * @return [type] [description]
     */
    public function postxml() {
        $xml = $this->createXml();
        $this->response = $this->postXmlCurl($xml, $this->curl, $this->curl_timeout);

        return $this->response;
    }

    public function createXml() {
        $this->params['appid'] = WxPayConf::APPID; //公众号ID
        $this->params['mch_id'] = WxPayConf::MCHID; //商户号
        $this->params['nonce_str'] = $this->createNoncestr();   //随机字符串
        $this->params['sign'] = $this->getSign($this->params);  //签名
        
        return $this->arrayToXml($this->params); 
    }

    

}

/**
 * 所有接口的基类
 */
class JsApi_common {
    function __construct() {

    }

    public function trimString($value) {
        $ret = null;
        if (null != $value) {
            $ret = trim($value);
            if (strlen($ret) == 0) {
                $ret = null;
            }
        } 
        return $ret;
    }

    /**
     * 产生随机字符串,不长于32位
     * @param  integer $length [description]
     * @return [type]          [description]
     */
    public function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $str;
    }

    /**
     * 格式化参数 拼接字符串,签名过程需要使用
     * @param [type] $urlParams     [description]
     * @param [type] $needUrlencode [description]
     */
    public function ToUrlParams($urlParams, $needUrlencode) {
        $buff = "";
        ksort($urlParams);

        foreach ($urlParams as $k => $v) {
            if($needUrlencode) $v = urlencode($v);
            $buff .= $k .'='. $v .'&';
        }

        $reqString = '';
        if (strlen($buff) > 0) {
            $reqString = substr($buff, 0, strlen($buff) - 1);
        }

        return $reqString;
    }

    /**
     * 生成签名
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getSign($obj) {
        foreach ($obj as $k => $v) {
            $params[$k] = $v;
        }
        //签名步骤一:按字典序排序参数
        ksort($params);
        $str = $this->ToUrlParams($params, false);  
        //签名步骤二:在$str后加入key
        $str = $str."$key=".WxPayConf::KEY;
        //签名步骤三:md5加密
        $str = md5($str);
        //签名步骤四:所有字符转为大写
        $result = strtoupper($str);

        return $result;
    }

    /**
     * array转xml
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    public function arrayToXml($arr) {
        $xml = "";
        foreach ($arr as $k => $v) {
            if (is_numeric($val)) {
                $xml .= "<".$key.">".$key."";
            } else {
                $xml .= "<".$key.">";
            }
        }
        $xml .= "";
        return $xml;
    }

    /**
     * 将xml转为array
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    public function xmlToArray($xml) {
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SinpleXMLElement', LIBXML_NOCDATA)), true);

        return $arr;
    }

    /**
     * 以post方式提交xml到对应的接口
     * @param  [type]  $xml    [description]
     * @param  [type]  $url    [description]
     * @param  integer $second [description]
     * @return [type]          [description]
     */
    public function postXmlCurl($xml, $url, $second = 30) {
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURL_TIMEOUT, $second);
        curl_setopt($ch, CURL_URL, $url);
        //这里设置代理,如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
        //设置header
        curl_setopt($ch, CURL_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
        //以post方式提交
        curl_setopt($ch, CURL_POST, TRUE);
        curl_setopt($ch, CURL_POSTFIELDS, $xml);
        //执行curl
        $res = curl_exec($ch);

        if ($res) {
            curl_close($ch);
            return $res;
        } else {
            $error = curl_errno($ch);
            echo "curl出错,错误码:$error"."
";             echo "错误原因查询
";             curl_close($ch);             return false;         }     } } /**  * 配置类  */ class WxPayConf {     //微信公众号身份的唯一标识。     const APPID = 'wx654a22c6423213b7';     //受理商ID,身份标识     const MCHID = '10043241';     const MCHNAME = 'KellyCen的博客';          //商户支付密钥Key。     const KEY = '0000000000000000000000000000000';     //JSAPI接口中获取openid     const APPSECRET = '000000000000000000000000000';     //证书路径,注意应该填写绝对路径     const SSLCERT_PATH = '/home/WxPayCacert/apiclient_cert.pem';     const SSLKEY_PATH = '/home/WxPayCacert/apiclient_key.pem';     const SSLCA_PATH = '/home/WxPayCacert/rootca.pem';     //本例程通过curl使用HTTP POST方法,此处可修改其超时时间,默认为30秒     const CURL_TIMEOUT = 30; } 模型:Wxpay_model.php

 <!doctype html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Make sure that we can test against real IE8 -->
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<title></title>
</head>
<body>

<a href="{$wxPayUrl}">微信支付</a>
</body>  
</html>

视图:index.tpl

 
 
 
 







点击支付
 



视图:confirm.tpl

里面所用到的一些自定义函数可以在我上一篇博文里找找,那里已经提供了代码参考了。 

更多基于H5的微信支付开发详解 相关文章请关注PHP中文网!

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。