基於H5的微信支付開發詳解

  此次總結一下用戶在微信內打開網頁時,能夠調用微信支付完成下單功能的模塊開發,也就是在微信內的H5頁面經過jsApi接口實現支付功能。固然了,微信官網上的微信支付開發文檔也講解的很詳細,而且有實現代碼可供參考,有的朋友直接看文檔就能夠本身實現此支付接口的開發了。javascript

  1、前言php

  爲什麼我還寫一篇微信支付接口的博文呢?第一,咱們必須知道,所謂的工做經驗不少都是靠總結出來的,你只有總結了更多知識,積累了更多經驗,你才能在該行業中脫穎而出,我我的以爲現在的招聘,不少都須要工做經驗(1年、3年、5年....),其實,工做時間的長久不能衡量一我的技術水平的高低,有的人一年的工做經驗能拿3年工做經驗的程序猿的工資,有的3年工做經驗的卻有可能比別人只有一年工做經驗的還低,因此說,總結才能讓本身的知識體系,經驗深度更牛逼更穩固(雖然寫一篇博文挺花費時間的);第二,寫博文分享給你們仍是挺有成就感的,首先是能讓新手從我分享的博文中能學到東西,而且能快速將博文所講解的技術運用到實際中來,因此我寫的博文基本上能讓新人快速讀懂而且容易理解,另外,技術大神的話,看到博文有講解的不對之處,還能夠指出,而且能夠交流,何樂而不爲呢,咱們須要的就是分享和交流。html

  扯遠了,直接進入該主題的詳解。java

  如今的微信支付方式有N種,看下圖,有刷卡支付、公衆號支付、掃碼支付和APP支付,另外還有支付工具的開發,本博文選擇的是公衆號支付藉口而開發進行講解,其餘幾種支付接口開發基本上思路都是同樣的,只要你能看懂我這博文所講解的基本思路,你基本上也能獨自開發其餘幾個支付接口。redis

  2、思路詳解數據庫

  咱們能夠拿微信支付接口文檔裏的業務流程時序圖看看,以下圖,基本思路是這樣子:首先在後臺生成一個連接,展現給用戶讓用戶點擊(例如頁面上有微信支付的按鈕),用戶點擊按鈕後,網站後臺會根據訂單的相關信息生成一個支付訂單,此時會調用統一下單接口,對微信支付系統發起請求,而微信支付系統受到請求後,會根據請求過來的數據,生成一個 預支付交易會話標識(prepay_id,就是經過這個來識別該訂單的),咱們的網站收到微信支付系統的響應後,會獲得prepay_id,而後經過本身構造微信支付所須要的參數,接着將支付所需參數返回給客戶端,用戶此時可能會有一個訂單信息頁,會有一個按鈕,點擊支付,此時會調用JSAPI接口對微信支付系統發起 請求支付,微信支付系統檢查了請求的相關合法性以後,就會提示輸入密碼,用戶此時輸入密碼確認,微信支付系統會對其進行驗證,經過的話會返回支付結果,而後微信跳轉會H5頁面,這其中有一步是異步通知網站支付結果,咱們網站須要對此進行處理(好比說異步支付結果經過後,須要更新數據表或者訂單信息,例如標誌用戶已支付該訂單了,同時也須要更新訂單日誌,防止用戶重複提交訂單)。json

  3、代碼講解api

  本次開發環境用的是php5.6 + MySQL + Redis + Linux + Apache,所選用的框架的CI框架(這些環境不必定須要和個人一致,框架也能夠本身選擇,反正本身稍微修改下代碼就能移植過去了)。數組

  微信支付接口的開發代碼我已經提早寫好了,在這裏我對其進行分析講解,方便你們能輕鬆理解,固然,假如你有必定的基礎,直接看代碼就能理清全部流程了,而且個人代碼基本上都寫上了註釋(對於新手來講,這一點比微信文檔所提供的代碼好一點)。緩存

  一、構造一個連接展現給用戶

  這裏咱們提早須要知道一個點,那就是請求統一下單接口須要微信用戶的openid(詳情可看這https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1),而獲取openid須要先獲取code(詳情可看這微信登陸接口),因此咱們須要構造一個獲取code的URL:

Wxpay.php文件:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 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的代碼了,裏面基本上每個類每個方法甚至每一行代碼都會有解釋的了,這裏我就不對其展開一句句分析了:

  1 <?php
  2 defined('BASEPATH') OR exit('No direct script access allowed');
  3 
  4 class Wxpay_model extends CI_Model {
  5     public function __construct() {
  6         parent::__construct();
  7     }
  8     
  9     /**
 10      * 返回能夠得到微信code的URL (用以獲取openid)
 11      * @return [type] [description]
 12      */
 13     public function retWxPayUrl() {
 14         $jsApi = new JsApi_handle();
 15         return $jsApi->createOauthUrlForCode();
 16     }
 17  
 18     /**
 19      * 微信jsapi點擊支付
 20      * @param  [type] $data [description]
 21      * @return [type]       [description]
 22      */
 23     public function wxPayJsApi($data) {
 24         $jsApi = new JsApi_handle();
 25         //統一下單接口所需數據
 26         $payData = $this->returnData($data);
 27         //獲取code碼,用以獲取openid
 28         $code = $_GET['code'];
 29         $jsApi->setCode($code);
 30         //經過code獲取openid
 31         $openid = $jsApi->getOpenId();
 32         
 33         $unifiedOrderResult = null;
 34         if ($openid != null) {
 35             //取得統一下單接口返回的數據
 36             $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
 37             //獲取訂單接口狀態
 38             $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
 39             if ($returnMessage['resultCode']) {
 40                 $jsApi->setPrepayId($retuenMessage['resultField']);
 41                 //取得wxjsapi接口所須要的數據
 42                 $returnMessage['resultData'] = $jsApi->getParams();
 43             } 
 44 
 45             return $returnMessage;
 46         }
 47     }
 48 
 49     /**
 50      * 統一下單接口所須要的數據
 51      * @param  [type] $data [description]
 52      * @return [type]       [description]
 53      */
 54     public function returnData($data) {
 55         $payData['sn'] = $data['sn'];
 56         $payData['body'] = $data['goods_name'];
 57         $payData['out_trade_no'] = $data['order_no'];
 58         $payData['total_fee'] = $data['fee'];
 59         $payData['attach'] = $data['attach'];
 60 
 61         return $payData;
 62     }
 63 
 64     /**
 65      * 返回統一下單接口結果 (參考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
 66      * @param  [type] $payData    [description]
 67      * @param  [type] $trade_type [description]
 68      * @param  [type] $openid     [description]
 69      * @return [type]             [description]
 70      */
 71     public function getResult($payData, $trade_type, $openid = null) {
 72         $unifiedOrder = new UnifiedOrder_handle();
 73 
 74         if ($opneid != null) {
 75             $unifiedOrder->setParam('openid', $openid);
 76         }
 77         $unifiedOrder->setParam('body', $payData['body']);  //商品描述
 78         $unifiedOrder->setParam('out_trade_no', $payData['out_trade_no']); //商戶訂單號
 79         $unifiedOrder->setParam('total_fee', $payData['total_fee']);    //總金額
 80         $unifiedOrder->setParam('attach', $payData['attach']);  //附加數據
 81         $unifiedOrder->setParam('notify_url', base_url('/Wxpay/pay_callback'));//通知地址
 82         $unifiedOrder->setParam('trade_type', $trade_type); //交易類型
 83 
 84         //非必填參數,商戶可根據實際狀況選填
 85         //$unifiedOrder->setParam("sub_mch_id","XXXX");//子商戶號
 86         //$unifiedOrder->setParam("device_info","XXXX");//設備號
 87         //$unifiedOrder->setParam("time_start","XXXX");//交易起始時間
 88         //$unifiedOrder->setParam("time_expire","XXXX");//交易結束時間
 89         //$unifiedOrder->setParam("goods_tag","XXXX");//商品標記
 90         //$unifiedOrder->setParam("product_id","XXXX");//商品ID
 91         
 92         return $unifiedOrder->getResult();
 93     }
 94 
 95     /**
 96      * 返回微信訂單狀態
 97      */
 98     public function returnMessage($unifiedOrderResult,$field){
 99         $arrMessage=array("resultCode"=>0,"resultType"=>"獲取錯誤","resultMsg"=>"該字段爲空");
100         if($unifiedOrderResult==null){
101             $arrMessage["resultType"]="未獲取權限";
102             $arrMessage["resultMsg"]="請從新打開頁面";
103         }elseif ($unifiedOrderResult["return_code"] == "FAIL")
104         {
105             $arrMessage["resultType"]="網絡錯誤";
106             $arrMessage["resultMsg"]=$unifiedOrderResult['return_msg'];
107         }
108         elseif($unifiedOrderResult["result_code"] == "FAIL")
109         {
110             $arrMessage["resultType"]="訂單錯誤";
111             $arrMessage["resultMsg"]=$unifiedOrderResult['err_code_des'];
112         }
113         elseif($unifiedOrderResult[$field] != NULL)
114         {
115             $arrMessage["resultCode"]=1;
116             $arrMessage["resultType"]="生成訂單";
117             $arrMessage["resultMsg"]="OK";
118             $arrMessage["resultField"] = $unifiedOrderResult[$field];
119         }
120         return $arrMessage;
121     }
122 
123     /**
124      * 微信回調接口返回  驗證簽名並回應微信
125      * @param  [type] $xml [description]
126      * @return [type]      [description]
127      */
128     public function wxPayNotify($xml) {
129         $notify = new Wxpay_server();
130         $notify->saveData($xml);
131         //驗證簽名,並回復微信
132         //對後臺通知交互時,若是微信收到商戶的應答不是成功或者超時,微信認爲通知失敗
133         //微信會經過必定的策略(如30分鐘共8次),按期從新發起通知
134         if ($notify->checkSign() == false) {
135             $notify->setReturnParameter("return_code","FAIL");//返回狀態碼
136             $notify->setReturnParameter("return_msg","簽名失敗");//返回信息
137         } else {
138             $notify->checkSign=TRUE;
139             $notify->setReturnParameter("return_code","SUCCESS");//設置返回碼
140         }
141 
142         return $notify;
143     }
144 }
145 
146 /**
147 * JSAPI支付——H5網頁端調起支付接口
148 */
149 class JsApi_handle extends JsApi_common {
150     public $code;//code碼,用以獲取openid
151     public $openid;//用戶的openid
152     public $parameters;//jsapi參數,格式爲json
153     public $prepay_id;//使用統一支付接口獲得的預支付id
154     public $curl_timeout;//curl超時時間
155 
156     function __construct()
157     {
158         //設置curl超時時間
159         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
160     }
161 
162     /**
163      * 生成獲取code的URL
164      * @return [type] [description]
165      */
166     public function createOauthUrlForCode() {
167         //重定向URL
168         $redirectUrl = "http://www.itcen.cn/wxpay/confirm/".$orderId."?showwxpaytitle=1";
169         $urlParams['appid'] = WxPayConf::APPID;
170         $urlParams['redirect_uri'] = $redirectUrl;
171         $urlParams['response_type'] = 'code';
172         $urlParams['scope'] = 'snsapi_base';
173         $urlParams['state'] = "STATE"."#wechat_redirect";
174         //拼接字符串
175         $queryString = $this->ToUrlParams($urlParams, false);
176         return "https://open.weixin.qq.com/connect/oauth2/authorize?".$queryString;
177     }
178 
179     /**
180      * 設置code
181      * @param [type] $code [description]
182      */
183     public function setCode($code) {
184         $this->code = $code;
185     }
186 
187     /**
188      *  做用:設置prepay_id
189      */
190     public function setPrepayId($prepayId)
191     {
192         $this->prepay_id = $prepayId;
193     }
194 
195     /**
196      *  做用:獲取jsapi的參數
197      */
198     public function getParams()
199     {
200         $jsApiObj["appId"] = WxPayConf::APPID;
201         $timeStamp = time();
202         $jsApiObj["timeStamp"] = "$timeStamp";
203         $jsApiObj["nonceStr"] = $this->createNoncestr();
204         $jsApiObj["package"] = "prepay_id=$this->prepay_id";
205         $jsApiObj["signType"] = "MD5";
206         $jsApiObj["paySign"] = $this->getSign($jsApiObj);
207         $this->parameters = json_encode($jsApiObj);
208 
209         return $this->parameters;
210     }
211 
212     /**
213      * 經過curl 向微信提交code 用以獲取openid
214      * @return [type] [description]
215      */
216     public function getOpenId() {
217         //建立openid 的連接
218         $url = $this->createOauthUrlForOpenid();
219         //初始化
220         $ch = curl_init();
221         curl_setopt($ch, CURL_TIMEOUT, $this->curl_timeout);
222         curl_setopt($ch, CURL_URL, $url);
223         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
224         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
225         curl_setopt($ch, CURL_HEADER, FALSE);
226         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
227         //執行curl
228         $res = curl_exec($ch);
229         curl_close($ch);
230         //取出openid
231         $data = json_decode($res);
232         if (isset($data['openid'])) {
233             $this->openid = $data['openid'];
234         } else {
235             return null;
236         }
237 
238         return $this->openid;
239 
240     }
241 
242     /**
243      * 生成能夠獲取openid 的URL
244      * @return [type] [description]
245      */
246     public function createOauthUrlForOpenid() {
247         $urlParams['appid'] = WxPayConf::APPID;
248         $urlParams['secret'] = WxPayConf::APPSECRET;
249         $urlParams['code'] = $this->code;
250         $urlParams['grant_type'] = "authorization_code";
251         $queryString = $this->ToUrlParams($urlParams, false);
252         return "https://api.weixin.qq.com/sns/oauth2/access_token?".$queryString;
253     }
254 }
255 
256 /**
257  * 統一下單接口類
258  */
259 class UnifiedOrder_handle extends Wxpay_client_handle {
260     public function __construct() {
261         //設置接口連接
262         $this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
263         //設置curl超時時間
264         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
265     }
266 
267 }
268 
269 /**
270  * 響應型接口基類
271  */
272 class Wxpay_server_handle extends JsApi_common{
273     public $data; //接收到的數據,類型爲關聯數組
274     public $returnParams;   //返回參數,類型爲關聯數組
275 
276     /**
277      * 將微信請求的xml轉換成關聯數組
278      * @param  [type] $xml [description]
279      * @return [type]      [description]
280      */
281     public function saveData($xml) {
282         $this->data = $this->xmlToArray($xml); 
283     }
284 
285 
286     /**
287      * 驗證簽名
288      * @return [type] [description]
289      */
290     public function checkSign() {
291         $tmpData = $this->data;
292         unset($temData['sign']);
293         $sign = $this->getSign($tmpData);
294         if ($this->data['sign'] == $sign) {
295             return true;
296         }
297         return false;
298     }
299 
300 
301     /**
302      * 設置返回微信的xml數據
303      */
304     function setReturnParameter($parameter, $parameterValue)
305     {
306         $this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
307     }
308 
309     /**
310      * 將xml數據返回微信
311      */
312     function returnXml()
313     {
314         $returnXml = $this->createXml();
315         return $returnXml;
316     }
317 
318 }
319 
320 /**
321  * 請求型接口的基類
322  */
323 class Wxpay_client_handle extends JsApi_common{
324     public $params; //請求參數,類型爲關聯數組
325     public $response; //微信返回的響應
326     public $result; //返回參數,類型類關聯數組
327     public $url; //接口連接
328     public $curl_timeout; //curl超時時間
329 
330     /**
331      * 設置請求參數
332      * @param [type] $param      [description]
333      * @param [type] $paramValue [description]
334      */
335     public function setParam($param, $paramValue) {
336         $this->params[$this->tirmString($param)] = $this->trimString($paramValue);
337     }
338 
339     /**
340      * 獲取結果,默認不使用證書
341      * @return [type] [description]
342      */
343     public function getResult() {
344         $this->postxml(); 
345         $this->result = $this->xmlToArray($this->response);
346 
347         return $this->result;
348     }
349 
350     /**
351      * post請求xml
352      * @return [type] [description]
353      */
354     public function postxml() {
355         $xml = $this->createXml();
356         $this->response = $this->postXmlCurl($xml, $this->curl, $this->curl_timeout);
357 
358         return $this->response;
359     }
360 
361     public function createXml() {
362         $this->params['appid'] = WxPayConf::APPID; //公衆號ID
363         $this->params['mch_id'] = WxPayConf::MCHID; //商戶號
364         $this->params['nonce_str'] = $this->createNoncestr();   //隨機字符串
365         $this->params['sign'] = $this->getSign($this->params);  //簽名
366         
367         return $this->arrayToXml($this->params); 
368     }
369 
370     
371 
372 }
373 
374 /**
375  * 全部接口的基類
376  */
377 class JsApi_common {
378     function __construct() {
379 
380     }
381 
382     public function trimString($value) {
383         $ret = null;
384         if (null != $value) {
385             $ret = trim($value);
386             if (strlen($ret) == 0) {
387                 $ret = null;
388             }
389         } 
390         return $ret;
391     }
392 
393     /**
394      * 產生隨機字符串,不長於32位
395      * @param  integer $length [description]
396      * @return [type]          [description]
397      */
398     public function createNoncestr($length = 32) {
399         $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
400         $str = '';
401         for ($i = 0; $i < $length; $i++) {
402             $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
403         }
404 
405         return $str;
406     }
407 
408     /**
409      * 格式化參數 拼接字符串,簽名過程須要使用
410      * @param [type] $urlParams     [description]
411      * @param [type] $needUrlencode [description]
412      */
413     public function ToUrlParams($urlParams, $needUrlencode) {
414         $buff = "";
415         ksort($urlParams);
416 
417         foreach ($urlParams as $k => $v) {
418             if($needUrlencode) $v = urlencode($v);
419             $buff .= $k .'='. $v .'&';
420         }
421 
422         $reqString = '';
423         if (strlen($buff) > 0) {
424             $reqString = substr($buff, 0, strlen($buff) - 1);
425         }
426 
427         return $reqString;
428     }
429 
430     /**
431      * 生成簽名
432      * @param  [type] $params [description]
433      * @return [type]         [description]
434      */
435     public function getSign($obj) {
436         foreach ($obj as $k => $v) {
437             $params[$k] = $v;
438         }
439         //簽名步驟一:按字典序排序參數
440         ksort($params);
441         $str = $this->ToUrlParams($params, false);  
442         //簽名步驟二:在$str後加入key
443         $str = $str."$key=".WxPayConf::KEY;
444         //簽名步驟三:md5加密
445         $str = md5($str);
446         //簽名步驟四:全部字符轉爲大寫
447         $result = strtoupper($str);
448 
449         return $result;
450     }
451 
452     /**
453      * array轉xml
454      * @param  [type] $arr [description]
455      * @return [type]      [description]
456      */
457     public function arrayToXml($arr) {
458         $xml = "<xml>";
459         foreach ($arr as $k => $v) {
460             if (is_numeric($val)) {
461                 $xml .= "<".$key.">".$key."</".$key.">";
462             } else {
463                 $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">";
464             }
465         }
466         $xml .= "</xml>";
467         return $xml;
468     }
469 
470     /**
471      * 將xml轉爲array
472      * @param  [type] $xml [description]
473      * @return [type]      [description]
474      */
475     public function xmlToArray($xml) {
476         $arr = json_decode(json_encode(simplexml_load_string($xml, 'SinpleXMLElement', LIBXML_NOCDATA)), true);
477 
478         return $arr;
479     }
480 
481     /**
482      * 以post方式提交xml到對應的接口
483      * @param  [type]  $xml    [description]
484      * @param  [type]  $url    [description]
485      * @param  integer $second [description]
486      * @return [type]          [description]
487      */
488     public function postXmlCurl($xml, $url, $second = 30) {
489         //初始化curl
490         $ch = curl_init();
491         //設置超時
492         curl_setopt($ch, CURL_TIMEOUT, $second);
493         curl_setopt($ch, CURL_URL, $url);
494         //這裏設置代理,若是有的話
495         //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
496         //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
497         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
498         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
499         //設置header
500         curl_setopt($ch, CURL_HEADER, FALSE);
501         //要求結果爲字符串且輸出到屏幕上
502         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
503         //以post方式提交
504         curl_setopt($ch, CURL_POST, TRUE);
505         curl_setopt($ch, CURL_POSTFIELDS, $xml);
506         //執行curl
507         $res = curl_exec($ch);
508 
509         if ($res) {
510             curl_close($ch);
511             return $res;
512         } else {
513             $error = curl_errno($ch);
514             echo "curl出錯,錯誤碼:$error"."<br>";
515             echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>錯誤緣由查詢</a></br>";
516             curl_close($ch);
517             return false;
518         }
519     }
520 }
521 
522 /**
523  * 配置類
524  */
525 class WxPayConf {
526     //微信公衆號身份的惟一標識。
527     const APPID = 'wx654a22c6423213b7';
528     //受理商ID,身份標識
529     const MCHID = '10043241';
530     const MCHNAME = 'KellyCen的博客';
531     
532     //商戶支付密鑰Key。
533     const KEY = '0000000000000000000000000000000';
534     //JSAPI接口中獲取openid
535     const APPSECRET = '000000000000000000000000000';
536 
537     //證書路徑,注意應該填寫絕對路徑
538     const SSLCERT_PATH = '/home/WxPayCacert/apiclient_cert.pem';
539     const SSLKEY_PATH = '/home/WxPayCacert/apiclient_key.pem';
540     const SSLCA_PATH = '/home/WxPayCacert/rootca.pem';
541 
542     //本例程經過curl使用HTTP POST方法,此處可修改其超時時間,默認爲30秒
543     const CURL_TIMEOUT = 30;
544 }
Wxpay_model.php

   獲取到code的URL後,將其分配到頁面去,讓用戶去點擊,用戶進行點擊後,就會從微信服務器獲取到code,而後回調到redirect_uri所指的地址去。

  二、獲取到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 lang="zh-CN">  
<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>

  三、此時用戶只須要點擊支付,就能夠開始進入支付界面了,接着就是輸入密碼,確認,最後會提示支付成功,緊接着網站會提供一個支付成功跳轉頁面。相似微信文檔裏所提供的圖片這樣,這裏我就直接截取文檔裏的案例圖了:

  四、這裏還有一步,就是微信支付系統會異步通知網站後臺用戶的支付結果。在獲取統一下單數據時,咱們指定了一個通知地址,在model裏能夠找到

  支付成功後,微信支付系統會將支付結果異步發送到此地址上/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的微信支付接口開發詳解就講到這裏,若是你認真理清博文裏所講解的思路,本身基本上也能夠嘗試開發此接口了,同時只要會了這個,你也基本上能夠開發二維碼支付,刷卡支付等等的支付接口。

  這裏我附上這次開發中的完整代碼供你們閱讀:

  1 <?php
  2 defined('BASEPATH') OR exit('No direct script access allowed');
  3 
  4 class Wxpay extends MY_Controller {
  5     public function __construct() {
  6         parent::__construct();
  7         $this->load->model('wxpay_model');
  8         //$this->load->model('wxpay');
  9         
 10     }
 11  
 12     public function index() {
 13         //微信支付
 14         $this->smarty['wxPayUrl'] = $this->wxpay_model->retWxPayUrl();
 15         $this->displayView('wxpay/index.tpl');
 16     }
 17 
 18     /**
 19      * 手機端微信支付,此處是受權獲取到code時的回調地址
 20      * @param  [type] $orderId 訂單編號id
 21      * @return [type]          [description]
 22      */ 
 23     public function confirm($orderId) {
 24         //先確認用戶是否登陸
 25         $this->ensureLogin();
 26         //經過訂單編號獲取訂單數據
 27         $order = $this->wxpay_model->get($orderId);
 28         //驗證訂單是不是當前用戶
 29         $this->_verifyUser($order);
 30 
 31         //取得支付所須要的訂單數據
 32         $orderData = $this->returnOrderData[$orderId];
 33         //取得jsApi所須要的數據
 34         $wxJsApiData = $this->wxpay_model->wxPayJsApi($orderData);
 35         //將數據分配到模板去,在js裏使用
 36         $this->smartyData['wxJsApiData'] = json_encode($wxJsApiData, JSON_UNESCAPED_UNICODE);
 37         $this->smartyData['order'] = $orderData;
 38         $this->displayView('wxpay/confirm.tpl');
 39         
 40     }
 41     /**
 42      * 支付回調接口
 43      * @return [type] [description]
 44      */
 45     public function pay_callback() {
 46         $postData = '';
 47         if (file_get_contents("php://input")) {
 48             $postData = file_get_contents("php://input");
 49         } else {
 50             return;
 51         }
 52         $payInfo = array();
 53         $notify = $this->wxpay_model->wxPayNotify($postData);
 54 
 55         if ($notify->checkSign == TRUE) {
 56             if ($notify->data['return_code'] == 'FAIL') {
 57                 $payInfo['status'] = FALSE;
 58                 $payInfo['msg'] = '通訊出錯';
 59             } elseif ($notify->data['result_code'] == 'FAIL') {
 60                 $payInfo['status'] = FALSE;
 61                 $payInfo['msg'] = '業務出錯';
 62             } else {
 63                 $payInfo['status'] = TRUE;
 64                 $payInfo['msg'] = '支付成功';
 65                 $payInfo['sn']=substr($notify->data['out_trade_no'],8);
 66                 $payInfo['order_no'] = $notify->data['out_trade_no'];
 67                 $payInfo['platform_no']=$notify->data['transaction_id'];
 68                 $payInfo['attach']=$notify->data['attach'];
 69                 $payInfo['fee']=$notify->data['cash_fee'];
 70                 $payInfo['currency']=$notify->data['fee_type'];
 71                 $payInfo['user_sign']=$notify->data['openid'];
 72             }
 73         }
 74         $returnXml = $notify->returnXml();
 75 
 76         echo $returnXml;
 77 
 78         $this->load->library('RedisCache');
 79         if($payInfo['status']){
 80            //這裏要記錄到日誌處理(略)
 81             $this->model->order->onPaySuccess($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo);
 82             $this->redis->RedisCache->set('order:payNo:'.$payInfo['order_no'],'OK',5000);
 83         }else{
 84            //這裏要記錄到日誌處理(略)
 85             $this->model->order->onPayFailure($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo, '訂單支付失敗 ['.$payInfo['msg'].']');
 86         }
 87     }
 88 
 89     /**
 90      * 返回支付所須要的數據
 91      * @param  [type] $orderId 訂單號
 92      * @param  string $data    訂單數據,當$data數據存在時刷新$orderData緩存,由於訂單號不惟一
 93      * @return [type]          [description]
 94      */
 95     public function returnOrderData($orderId, $data = '') {
 96         //獲取訂單數據
 97         $order = $this->wxpay_model->get($orderId);
 98         if (0 === count($order)) return false;
 99         if (empty($data)) {
100             $this->load->library('RedisCache');
101             //取得緩存在redis的訂單數據
102             $orderData = $this->rediscache->getJson("order:orderData:".$orderId);
103             if (empty($orderData)) {
104                 //若是redis裏沒有,則直接讀數據庫取
105                 $this->load->model('order_model');
106                 $order = $this->order_model->get($orderId);
107                 if (0 === count($order)) {
108                     return false;
109                 }
110                 $data = $order;
111             } else {
112                 //若是redis裏面有的話,直接返回數據
113                 return $orderData;
114             }
115         }
116  
117         //支付前緩存所須要的數據
118         $orderData['id'] = $data['id'];
119         $orderData['fee'] = $data['fee'];
120 
121         //支付平臺須要的數據
122         $orderData['user_id'] = $data['user_id'];
123         $orderData['sn'] = $data['cn'];
124         //這是惟一編號
125         $orderData['order_no'] = substr(md5($data['sn'].$data['fee']), 8, 8).$data['sn'];
126         $orderData['fee'] = $data['fee'];
127         $orderData['time'] = $data['time'];
128         $orderData['goods_name'] = $data['goods_name'];
129         $orderData['attach'] = $data['attach'];
130 
131         //將數據緩存到redis裏面
132         $this->rediscache->set("order:orderData:".$orderId, $orderData, 3600*24);
133         //作個標識緩存到redis,用以判斷該訂單是否已經支付了
134         $this->rediscache->set("order:payNo:".$orderData['order_no'], "NO", 3600*24);
135 
136         return $orderData;
137     }
138 
139     private function _verifyUser($order) {
140         if (empty($order)) show_404();
141         if (0 === count($order)) show_404();
142         //判斷訂單表裏的用戶id是不是當前登陸者的id
143         if ($order['user_id'] == $this->uid) return;
144         show_error('只能查看本身的訂單');
145     }
146 
147 }
控制器:Wxpay.php
  1 <?php
  2 defined('BASEPATH') OR exit('No direct script access allowed');
  3 
  4 class Wxpay_model extends CI_Model {
  5     public function __construct() {
  6         parent::__construct();
  7     }
  8     
  9     /**
 10      * 返回能夠得到微信code的URL (用以獲取openid)
 11      * @return [type] [description]
 12      */
 13     public function retWxPayUrl() {
 14         $jsApi = new JsApi_handle();
 15         return $jsApi->createOauthUrlForCode();
 16     }
 17  
 18     /**
 19      * 微信jsapi點擊支付
 20      * @param  [type] $data [description]
 21      * @return [type]       [description]
 22      */
 23     public function wxPayJsApi($data) {
 24         $jsApi = new JsApi_handle();
 25         //統一下單接口所需數據
 26         $payData = $this->returnData($data);
 27         //獲取code碼,用以獲取openid
 28         $code = $_GET['code'];
 29         $jsApi->setCode($code);
 30         //經過code獲取openid
 31         $openid = $jsApi->getOpenId();
 32         
 33         $unifiedOrderResult = null;
 34         if ($openid != null) {
 35             //取得統一下單接口返回的數據
 36             $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
 37             //獲取訂單接口狀態
 38             $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
 39             if ($returnMessage['resultCode']) {
 40                 $jsApi->setPrepayId($retuenMessage['resultField']);
 41                 //取得wxjsapi接口所須要的數據
 42                 $returnMessage['resultData'] = $jsApi->getParams();
 43             } 
 44 
 45             return $returnMessage;
 46         }
 47     }
 48 
 49     /**
 50      * 統一下單接口所須要的數據
 51      * @param  [type] $data [description]
 52      * @return [type]       [description]
 53      */
 54     public function returnData($data) {
 55         $payData['sn'] = $data['sn'];
 56         $payData['body'] = $data['goods_name'];
 57         $payData['out_trade_no'] = $data['order_no'];
 58         $payData['total_fee'] = $data['fee'];
 59         $payData['attach'] = $data['attach'];
 60 
 61         return $payData;
 62     }
 63 
 64     /**
 65      * 返回統一下單接口結果 (參考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
 66      * @param  [type] $payData    [description]
 67      * @param  [type] $trade_type [description]
 68      * @param  [type] $openid     [description]
 69      * @return [type]             [description]
 70      */
 71     public function getResult($payData, $trade_type, $openid = null) {
 72         $unifiedOrder = new UnifiedOrder_handle();
 73 
 74         if ($opneid != null) {
 75             $unifiedOrder->setParam('openid', $openid);
 76         }
 77         $unifiedOrder->setParam('body', $payData['body']);  //商品描述
 78         $unifiedOrder->setParam('out_trade_no', $payData['out_trade_no']); //商戶訂單號
 79         $unifiedOrder->setParam('total_fee', $payData['total_fee']);    //總金額
 80         $unifiedOrder->setParam('attach', $payData['attach']);  //附加數據
 81         $unifiedOrder->setParam('notify_url', base_url('/Wxpay/pay_callback'));//通知地址
 82         $unifiedOrder->setParam('trade_type', $trade_type); //交易類型
 83 
 84         //非必填參數,商戶可根據實際狀況選填
 85         //$unifiedOrder->setParam("sub_mch_id","XXXX");//子商戶號
 86         //$unifiedOrder->setParam("device_info","XXXX");//設備號
 87         //$unifiedOrder->setParam("time_start","XXXX");//交易起始時間
 88         //$unifiedOrder->setParam("time_expire","XXXX");//交易結束時間
 89         //$unifiedOrder->setParam("goods_tag","XXXX");//商品標記
 90         //$unifiedOrder->setParam("product_id","XXXX");//商品ID
 91         
 92         return $unifiedOrder->getResult();
 93     }
 94 
 95     /**
 96      * 返回微信訂單狀態
 97      */
 98     public function returnMessage($unifiedOrderResult,$field){
 99         $arrMessage=array("resultCode"=>0,"resultType"=>"獲取錯誤","resultMsg"=>"該字段爲空");
100         if($unifiedOrderResult==null){
101             $arrMessage["resultType"]="未獲取權限";
102             $arrMessage["resultMsg"]="請從新打開頁面";
103         }elseif ($unifiedOrderResult["return_code"] == "FAIL")
104         {
105             $arrMessage["resultType"]="網絡錯誤";
106             $arrMessage["resultMsg"]=$unifiedOrderResult['return_msg'];
107         }
108         elseif($unifiedOrderResult["result_code"] == "FAIL")
109         {
110             $arrMessage["resultType"]="訂單錯誤";
111             $arrMessage["resultMsg"]=$unifiedOrderResult['err_code_des'];
112         }
113         elseif($unifiedOrderResult[$field] != NULL)
114         {
115             $arrMessage["resultCode"]=1;
116             $arrMessage["resultType"]="生成訂單";
117             $arrMessage["resultMsg"]="OK";
118             $arrMessage["resultField"] = $unifiedOrderResult[$field];
119         }
120         return $arrMessage;
121     }
122 
123     /**
124      * 微信回調接口返回  驗證簽名並回應微信
125      * @param  [type] $xml [description]
126      * @return [type]      [description]
127      */
128     public function wxPayNotify($xml) {
129         $notify = new Wxpay_server();
130         $notify->saveData($xml);
131         //驗證簽名,並回復微信
132         //對後臺通知交互時,若是微信收到商戶的應答不是成功或者超時,微信認爲通知失敗
133         //微信會經過必定的策略(如30分鐘共8次),按期從新發起通知
134         if ($notify->checkSign() == false) {
135             $notify->setReturnParameter("return_code","FAIL");//返回狀態碼
136             $notify->setReturnParameter("return_msg","簽名失敗");//返回信息
137         } else {
138             $notify->checkSign=TRUE;
139             $notify->setReturnParameter("return_code","SUCCESS");//設置返回碼
140         }
141 
142         return $notify;
143     }
144 }
145 
146 /**
147 * JSAPI支付——H5網頁端調起支付接口
148 */
149 class JsApi_handle extends JsApi_common {
150     public $code;//code碼,用以獲取openid
151     public $openid;//用戶的openid
152     public $parameters;//jsapi參數,格式爲json
153     public $prepay_id;//使用統一支付接口獲得的預支付id
154     public $curl_timeout;//curl超時時間
155 
156     function __construct()
157     {
158         //設置curl超時時間
159         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
160     }
161 
162     /**
163      * 生成獲取code的URL
164      * @return [type] [description]
165      */
166     public function createOauthUrlForCode() {
167         //重定向URL
168         $redirectUrl = "http://www.itcen.cn/wxpay/confirm/".$orderId."?showwxpaytitle=1";
169         $urlParams['appid'] = WxPayConf::APPID;
170         $urlParams['redirect_uri'] = $redirectUrl;
171         $urlParams['response_type'] = 'code';
172         $urlParams['scope'] = 'snsapi_base';
173         $urlParams['state'] = "STATE"."#wechat_redirect";
174         //拼接字符串
175         $queryString = $this->ToUrlParams($urlParams, false);
176         return "https://open.weixin.qq.com/connect/oauth2/authorize?".$queryString;
177     }
178 
179     /**
180      * 設置code
181      * @param [type] $code [description]
182      */
183     public function setCode($code) {
184         $this->code = $code;
185     }
186 
187     /**
188      *  做用:設置prepay_id
189      */
190     public function setPrepayId($prepayId)
191     {
192         $this->prepay_id = $prepayId;
193     }
194 
195     /**
196      *  做用:獲取jsapi的參數
197      */
198     public function getParams()
199     {
200         $jsApiObj["appId"] = WxPayConf::APPID;
201         $timeStamp = time();
202         $jsApiObj["timeStamp"] = "$timeStamp";
203         $jsApiObj["nonceStr"] = $this->createNoncestr();
204         $jsApiObj["package"] = "prepay_id=$this->prepay_id";
205         $jsApiObj["signType"] = "MD5";
206         $jsApiObj["paySign"] = $this->getSign($jsApiObj);
207         $this->parameters = json_encode($jsApiObj);
208 
209         return $this->parameters;
210     }
211 
212     /**
213      * 經過curl 向微信提交code 用以獲取openid
214      * @return [type] [description]
215      */
216     public function getOpenId() {
217         //建立openid 的連接
218         $url = $this->createOauthUrlForOpenid();
219         //初始化
220         $ch = curl_init();
221         curl_setopt($ch, CURL_TIMEOUT, $this->curl_timeout);
222         curl_setopt($ch, CURL_URL, $url);
223         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
224         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
225         curl_setopt($ch, CURL_HEADER, FALSE);
226         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
227         //執行curl
228         $res = curl_exec($ch);
229         curl_close($ch);
230         //取出openid
231         $data = json_decode($res);
232         if (isset($data['openid'])) {
233             $this->openid = $data['openid'];
234         } else {
235             return null;
236         }
237 
238         return $this->openid;
239 
240     }
241 
242     /**
243      * 生成能夠獲取openid 的URL
244      * @return [type] [description]
245      */
246     public function createOauthUrlForOpenid() {
247         $urlParams['appid'] = WxPayConf::APPID;
248         $urlParams['secret'] = WxPayConf::APPSECRET;
249         $urlParams['code'] = $this->code;
250         $urlParams['grant_type'] = "authorization_code";
251         $queryString = $this->ToUrlParams($urlParams, false);
252         return "https://api.weixin.qq.com/sns/oauth2/access_token?".$queryString;
253     }
254 }
255 
256 /**
257  * 統一下單接口類
258  */
259 class UnifiedOrder_handle extends Wxpay_client_handle {
260     public function __construct() {
261         //設置接口連接
262         $this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
263         //設置curl超時時間
264         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
265     }
266 
267 }
268 
269 /**
270  * 響應型接口基類
271  */
272 class Wxpay_server_handle extends JsApi_common{
273     public $data; //接收到的數據,類型爲關聯數組
274     public $returnParams;   //返回參數,類型爲關聯數組
275 
276     /**
277      * 將微信請求的xml轉換成關聯數組
278      * @param  [type] $xml [description]
279      * @return [type]      [description]
280      */
281     public function saveData($xml) {
282         $this->data = $this->xmlToArray($xml); 
283     }
284 
285 
286     /**
287      * 驗證簽名
288      * @return [type] [description]
289      */
290     public function checkSign() {
291         $tmpData = $this->data;
292         unset($temData['sign']);
293         $sign = $this->getSign($tmpData);
294         if ($this->data['sign'] == $sign) {
295             return true;
296         }
297         return false;
298     }
299 
300 
301     /**
302      * 設置返回微信的xml數據
303      */
304     function setReturnParameter($parameter, $parameterValue)
305     {
306         $this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
307     }
308 
309     /**
310      * 將xml數據返回微信
311      */
312     function returnXml()
313     {
314         $returnXml = $this->createXml();
315         return $returnXml;
316     }
317 
318 }
319 
320 /**
321  * 請求型接口的基類
322  */
323 class Wxpay_client_handle extends JsApi_common{
324     public $params; //請求參數,類型爲關聯數組
325     public $response; //微信返回的響應
326     public $result; //返回參數,類型類關聯數組
327     public $url; //接口連接
328     public $curl_timeout; //curl超時時間
329 
330     /**
331      * 設置請求參數
332      * @param [type] $param      [description]
333      * @param [type] $paramValue [description]
334      */
335     public function setParam($param, $paramValue) {
336         $this->params[$this->tirmString($param)] = $this->trimString($paramValue);
337     }
338 
339     /**
340      * 獲取結果,默認不使用證書
341      * @return [type] [description]
342      */
343     public function getResult() {
344         $this->postxml(); 
345         $this->result = $this->xmlToArray($this->response);
346 
347         return $this->result;
348     }
349 
350     /**
351      * post請求xml
352      * @return [type] [description]
353      */
354     public function postxml() {
355         $xml = $this->createXml();
356         $this->response = $this->postXmlCurl($xml, $this->curl, $this->curl_timeout);
357 
358         return $this->response;
359     }
360 
361     public function createXml() {
362         $this->params['appid'] = WxPayConf::APPID; //公衆號ID
363         $this->params['mch_id'] = WxPayConf::MCHID; //商戶號
364         $this->params['nonce_str'] = $this->createNoncestr();   //隨機字符串
365         $this->params['sign'] = $this->getSign($this->params);  //簽名
366         
367         return $this->arrayToXml($this->params); 
368     }
369 
370     
371 
372 }
373 
374 /**
375  * 全部接口的基類
376  */
377 class JsApi_common {
378     function __construct() {
379 
380     }
381 
382     public function trimString($value) {
383         $ret = null;
384         if (null != $value) {
385             $ret = trim($value);
386             if (strlen($ret) == 0) {
387                 $ret = null;
388             }
389         } 
390         return $ret;
391     }
392 
393     /**
394      * 產生隨機字符串,不長於32位
395      * @param  integer $length [description]
396      * @return [type]          [description]
397      */
398     public function createNoncestr($length = 32) {
399         $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
400         $str = '';
401         for ($i = 0; $i < $length; $i++) {
402             $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
403         }
404 
405         return $str;
406     }
407 
408     /**
409      * 格式化參數 拼接字符串,簽名過程須要使用
410      * @param [type] $urlParams     [description]
411      * @param [type] $needUrlencode [description]
412      */
413     public function ToUrlParams($urlParams, $needUrlencode) {
414         $buff = "";
415         ksort($urlParams);
416 
417         foreach ($urlParams as $k => $v) {
418             if($needUrlencode) $v = urlencode($v);
419             $buff .= $k .'='. $v .'&';
420         }
421 
422         $reqString = '';
423         if (strlen($buff) > 0) {
424             $reqString = substr($buff, 0, strlen($buff) - 1);
425         }
426 
427         return $reqString;
428     }
429 
430     /**
431      * 生成簽名
432      * @param  [type] $params [description]
433      * @return [type]         [description]
434      */
435     public function getSign($obj) {
436         foreach ($obj as $k => $v) {
437             $params[$k] = $v;
438         }
439         //簽名步驟一:按字典序排序參數
440         ksort($params);
441         $str = $this->ToUrlParams($params, false);  
442         //簽名步驟二:在$str後加入key
443         $str = $str."$key=".WxPayConf::KEY;
444         //簽名步驟三:md5加密
445         $str = md5($str);
446         //簽名步驟四:全部字符轉爲大寫
447         $result = strtoupper($str);
448 
449         return $result;
450     }
451 
452     /**
453      * array轉xml
454      * @param  [type] $arr [description]
455      * @return [type]      [description]
456      */
457     public function arrayToXml($arr) {
458         $xml = "<xml>";
459         foreach ($arr as $k => $v) {
460             if (is_numeric($val)) {
461                 $xml .= "<".$key.">".$key."</".$key.">";
462             } else {
463                 $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">";
464             }
465         }
466         $xml .= "</xml>";
467         return $xml;
468     }
469 
470     /**
471      * 將xml轉爲array
472      * @param  [type] $xml [description]
473      * @return [type]      [description]
474      */
475     public function xmlToArray($xml) {
476         $arr = json_decode(json_encode(simplexml_load_string($xml, 'SinpleXMLElement', LIBXML_NOCDATA)), true);
477 
478         return $arr;
479     }
480 
481     /**
482      * 以post方式提交xml到對應的接口
483      * @param  [type]  $xml    [description]
484      * @param  [type]  $url    [description]
485      * @param  integer $second [description]
486      * @return [type]          [description]
487      */
488     public function postXmlCurl($xml, $url, $second = 30) {
489         //初始化curl
490         $ch = curl_init();
491         //設置超時
492         curl_setopt($ch, CURL_TIMEOUT, $second);
493         curl_setopt($ch, CURL_URL, $url);
494         //這裏設置代理,若是有的話
495         //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
496         //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
497         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
498         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
499         //設置header
500         curl_setopt($ch, CURL_HEADER, FALSE);
501         //要求結果爲字符串且輸出到屏幕上
502         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
503         //以post方式提交
504         curl_setopt($ch, CURL_POST, TRUE);
505         curl_setopt($ch, CURL_POSTFIELDS, $xml);
506         //執行curl
507         $res = curl_exec($ch);
508 
509         if ($res) {
510             curl_close($ch);
511             return $res;
512         } else {
513             $error = curl_errno($ch);
514             echo "curl出錯,錯誤碼:$error"."<br>";
515             echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>錯誤緣由查詢</a></br>";
516             curl_close($ch);
517             return false;
518         }
519     }
520 }
521 
522 /**
523  * 配置類
524  */
525 class WxPayConf {
526     //微信公衆號身份的惟一標識。
527     const APPID = 'wx654a22c6423213b7';
528     //受理商ID,身份標識
529     const MCHID = '10043241';
530     const MCHNAME = 'KellyCen的博客';
531     
532     //商戶支付密鑰Key。
533     const KEY = '0000000000000000000000000000000';
534     //JSAPI接口中獲取openid
535     const APPSECRET = '000000000000000000000000000';
536 
537     //證書路徑,注意應該填寫絕對路徑
538     const SSLCERT_PATH = '/home/WxPayCacert/apiclient_cert.pem';
539     const SSLKEY_PATH = '/home/WxPayCacert/apiclient_key.pem';
540     const SSLCA_PATH = '/home/WxPayCacert/rootca.pem';
541 
542     //本例程經過curl使用HTTP POST方法,此處可修改其超時時間,默認爲30秒
543     const CURL_TIMEOUT = 30;
544 }
模型:Wxpay_model.php
 1 <!doctype html>  
 2 <html>  
 3 <head lang="zh-CN">  
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <!-- Make sure that we can test against real IE8 -->
 6 <meta http-equiv="X-UA-Compatible" content="IE=8" />
 7 <title></title>
 8 </head>
 9 <body>
10 
11 <a href="{$wxPayUrl}">微信支付</a>
12 </body>  
13 </html>
視圖:index.tpl
 1 <!doctype html>  
 2 <html>  
 3 <head lang="zh-CN">  
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <!-- Make sure that we can test against real IE8 -->
 6 <meta http-equiv="X-UA-Compatible" content="IE=8" />
 7 <title></title>
 8 </head>
 9 <body>
10 
11 <a href="javascript:callpay();" id="btnOrder">點擊支付</a>
12 </body>  
13 <script type="text/javascript">
14     //將數據付給js變量
15     var wxJsApiData = {$wxJsApiData};
16     function onBridgeReady()
17         {
18             //格式參考官方文檔 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
19             WeixinJSBridge.invoke(
20                 'getBrandWCPayRequest',
21                 $.parseJSON(wxJsApiData.resultData),
22                 function(res){
23                     if(res.err_msg == "get_brand_wcpay_request:ok" ){
24                         window.location.href="/wxpay/paysuccess/"+{$order.sn}; 
25                     }
26 
27                 } 
28             );
29         }
30         function callpay()
31         { 
32             if(!wxJsApiData.resultCode){
33                 alert(wxJsApiData.resultType+","+wxJsApiData.resultMsg+"!");
34                 return false;
35             }
36             if (typeof WeixinJSBridge == "undefined"){
37                 if( document.addEventListener ){
38                     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
39                 }else if (document.attachEvent){
40                     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
41                     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
42                 }
43             }else{
44                 onBridgeReady();
45             }
46         }
47 </script>
48 </html>
視圖:confirm.tpl

  裏面所用到的一些自定義函數能夠在我上一篇博文裏找找,那裏已經提供了代碼參考了。

 

  如今咱們的線上項目是微信支付,支付寶支付,網銀支付信用卡支付的功能都有,而且PC和WAP端都分別對應有。因此整一個支付系統模塊還算比較完整,後期有時間我會總結和分享下其餘的支付接口開發的博文,但願有興趣的博友能夠關注下哦!!

  本次分享和總結就到此。

  

 

 

  若是此博文中有哪裏講得讓人難以理解,歡迎留言交流,如有講解錯的地方歡迎指出。

  

  若是您以爲您能在此博文學到了新知識,請爲我頂一個,如文章中有解釋錯的地方,歡迎指出。

 

  互相學習,共同進步!

相關文章
相關標籤/搜索