A-A+

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

2015年11月10日 资讯 暂无评论 阅读 1,058 次

这次总结一下用户在微信内打开网页时,可以调用微信支 付完成下单功能的模块开发,也就是在微信内的H5页面通过jsApi接口实现支付功能。当然了,微信官网上的微信支付开发文档也讲解的很详细,并且有实现 代码可供参考,有的朋友直接看文档就可以自己实现此支付接口的开发了。

一、前言

为何我还写一篇微信支付接口的博文呢?第一,我们 必须知道,所谓的工作经验很多都是靠总结出来的,你只有总结了更多知识,积累了更多经验,你才能在该行业中脱颖而出,我个人觉得如今的招聘,很多都需要工 作经验(1年、3年、5年....),其实,工作时间的长久不能衡量一个人技术水平的高低,有的人一年的工作经验能拿3年工作经验的程序猿的工资,有的3 年工作经验的却有可能比别人只有一年工作经验的还低,所以说,总结才能让自己的知识体系,经验深度更牛逼更稳固(虽然写一篇博文挺花费时间的);第二,写 博文分享给大家还是挺有成就感的,首先是能让新手从我分享的博文中能学到东西,并且能快速将博文所讲解的技术运用到实际中来,所以我写的博文基本上能让新 人快速读懂并且容易理解,另外,技术大神的话,看到博文有讲解的不对之处,还可以指出,并且可以交流,何乐而不为呢,我们需要的就是分享和交流。

扯远了,直接进入该主题的详解。

现在的微信支付方式有N种,看下图,有刷卡支付、 公众号支付、扫码支付和APP支付,另外还有支付工具的开发,本博文选择的是公众号支付借口而开发进行讲解,其他几种支付接口开发基本上思路都是一样的, 只要你能看懂我这博文所讲解的基本思路,你基本上也能独自开发其他几个支付接口。

HTML5教程 HTML5技术 微信支付 微信支付接口开发 微信支付api

二、思路详解

我们可以拿微信支付接口文档里的业务流程时序图看 看,如下图,基本思路是这样子:首先在后台生成一个链接,展示给用户让用户点击(例如页面上有微信支付的按钮),用户点击按钮后,网站后台会根据订单的相 关信息生成一个支付订单,此时会调用统一下单接口,对微信支付系统发起请求,而微信支付系统受到请求后,会根据请求过来的数据,生成一个 预支付交易会话标识(prepay_id,就是通过这个来识别该订单的),我们的网站收到微信支付系统的响应后,会得到prepay_id,然后通过自己 构造微信支付所需要的参数,接着将支付所需参数返回给客户端,用户此时可能会有一个订单信息页,会有一个按钮,点击支付,此时会调用JSAPI接口对微信 支付系统发起 请求支付,微信支付系统检查了请求的相关合法性之后,就会提示输入密码,用户此时输入密码确认,微信支付系统会对其进行验证,通过的话会返回支付结果,然 后微信跳转会H5页面,这其中有一步是异步通知网站支付结果,我们网站需要对此进行处理(比如说异步支付结果通过后,需要更新数据表或者订单信息,例如标 志用户已支付该订单了,同时也需要更新订单日志,防止用户重复提交订单)。

HTML5教程 HTML5技术 微信支付 微信支付接口开发 微信支付api

三、代码讲解

本次开发环境用的是php5.6 + MySQL + Redis + Linux + Apache,所选用的框架的CI框架(这些环境不一定需要和我的一致,框架也可以自己选择,反正自己稍微修改下代码就能移植过去了)。

微信支付接口的开发代码我已经提前写好了,在这里我对其进行分析讲解,方便大家能轻松理解,当然,假如你有一定的基础,直接看代码就能理清所有流程了,并且我的代码基本上都写上了注释(对于新手来说,这一点比微信文档所提供的代码好一点)。

1、构造一个链接展示给用户

这里我们提前需要知道一个点,那就是请求统一下单接口需要微信用户的openid(详情可看这https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1),而获取openid需要先获取code(详情可看这微信登录接口),所以我们需要构造一个获取code的URL:

  1. Wxpay.php文件:
  2. <?php
  3. defined('BASEPATH') OR exit('No direct script access allowed');
  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.     public function index() {
  11.         //微信支付
  12.         $this->smarty['wxPayUrl'] = $this->wxpay_model->retWxPayUrl();
  13.         $this->displayView('wxpay/index.tpl');
  14.     }
  15. }

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

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

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3. class Wxpay_model extends CI_Model {
  4.     public function __construct() {
  5.         parent::__construct();
  6.     }
  7.     /**
  8.      * 返回可以获得微信code的URL (用以获取openid)
  9.      * @return [type] [description]
  10.      */
  11.     public function retWxPayUrl() {
  12.         $jsApi = new JsApi_handle();
  13.         return $jsApi->createOauthUrlForCode();
  14.     }
  15.     /**
  16.      * 微信jsapi点击支付
  17.      * @param  [type] $data [description]
  18.      * @return [type]       [description]
  19.      */
  20.     public function wxPayJsApi($data) {
  21.         $jsApi = new JsApi_handle();
  22.         //统一下单接口所需数据
  23.         $payData = $this->returnData($data);
  24.         //获取code码,用以获取openid
  25.         $code = $_GET['code'];
  26.         $jsApi->setCode($code);
  27.         //通过code获取openid
  28.         $openid = $jsApi->getOpenId();
  29.         $unifiedOrderResult = null;
  30.         if ($openid != null) {
  31.             //取得统一下单接口返回的数据
  32.             $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
  33.             //获取订单接口状态
  34.             $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
  35.             if ($returnMessage['resultCode']) {
  36.                 $jsApi->setPrepayId($retuenMessage['resultField']);
  37.                 //取得wxjsapi接口所需要的数据
  38.                 $returnMessage['resultData'] = $jsApi->getParams();
  39.             }
  40.             return $returnMessage;
  41.         }
  42.     }
  43.     /**
  44.      * 统一下单接口所需要的数据
  45.      * @param  [type] $data [description]
  46.      * @return [type]       [description]
  47.      */
  48.     public function returnData($data) {
  49.         $payData['sn'] = $data['sn'];
  50.         $payData['body'] = $data['goods_name'];
  51.         $payData['out_trade_no'] = $data['order_no'];
  52.         $payData['total_fee'] = $data['fee'];
  53.         $payData['attach'] = $data['attach'];
  54.         return $payData;
  55.     }
  56.     /**
  57.      * 返回统一下单接口结果 (参考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
  58.      * @param  [type] $payData    [description]
  59.      * @param  [type] $trade_type [description]
  60.      * @param  [type] $openid     [description]
  61.      * @return [type]             [description]
  62.      */
  63.     public function getResult($payData, $trade_type, $openid = null) {
  64.         $unifiedOrder = new UnifiedOrder_handle();
  65.         if ($opneid != null) {
  66.             $unifiedOrder->setParam('openid', $openid);
  67.         }
  68.         $unifiedOrder->setParam('body', $payData['body']);  //商品描述
  69.         $unifiedOrder->setParam('out_trade_no', $payData['out_trade_no']); //商户订单号
  70.         $unifiedOrder->setParam('total_fee', $payData['total_fee']);    //总金额
  71.         $unifiedOrder->setParam('attach', $payData['attach']);  //附加数据
  72.         $unifiedOrder->setParam('notify_url', base_url('/Wxpay/pay_callback'));//通知地址
  73.         $unifiedOrder->setParam('trade_type', $trade_type); //交易类型
  74.         //非必填参数,商户可根据实际情况选填
  75.         //$unifiedOrder->setParam("sub_mch_id","XXXX");//子商户号
  76.         //$unifiedOrder->setParam("device_info","XXXX");//设备号
  77.         //$unifiedOrder->setParam("time_start","XXXX");//交易起始时间
  78.         //$unifiedOrder->setParam("time_expire","XXXX");//交易结束时间
  79.         //$unifiedOrder->setParam("goods_tag","XXXX");//商品标记
  80.         //$unifiedOrder->setParam("product_id","XXXX");//商品ID
  81.         return $unifiedOrder->getResult();
  82.     }
  83.     /**
  84.      * 返回微信订单状态
  85.      */
  86.     public function returnMessage($unifiedOrderResult,$field){
  87.         $arrMessage=array("resultCode"=>0,"resultType"=>"获取错误","resultMsg"=>"该字段为空");
  88.         if($unifiedOrderResult==null){
  89.             $arrMessage["resultType"]="未获取权限";
  90.             $arrMessage["resultMsg"]="请重新打开页面";
  91.         }elseif ($unifiedOrderResult["return_code"] == "FAIL")
  92.         {
  93.             $arrMessage["resultType"]="网络错误";
  94.             $arrMessage["resultMsg"]=$unifiedOrderResult['return_msg'];
  95.         }
  96.         elseif($unifiedOrderResult["result_code"] == "FAIL")
  97.         {
  98.             $arrMessage["resultType"]="订单错误";
  99.             $arrMessage["resultMsg"]=$unifiedOrderResult['err_code_des'];
  100.         }
  101.         elseif($unifiedOrderResult[$field] != NULL)
  102.         {
  103.             $arrMessage["resultCode"]=1;
  104.             $arrMessage["resultType"]="生成订单";
  105.             $arrMessage["resultMsg"]="OK";
  106.             $arrMessage["resultField"] = $unifiedOrderResult[$field];
  107.         }
  108.         return $arrMessage;
  109.     }
  110.     /**
  111.      * 微信回调接口返回  验证签名并回应微信
  112.      * @param  [type] $xml [description]
  113.      * @return [type]      [description]
  114.      */
  115.     public function wxPayNotify($xml) {
  116.         $notify = new Wxpay_server();
  117.         $notify->saveData($xml);
  118.         //验证签名,并回复微信
  119.         //对后台通知交互时,如果微信收到商户的应答不是成功或者超时,微信认为通知失败
  120.         //微信会通过一定的策略(如30分钟共8次),定期重新发起通知
  121.         if ($notify->checkSign() == false) {
  122.             $notify->setReturnParameter("return_code","FAIL");//返回状态码
  123.             $notify->setReturnParameter("return_msg","签名失败");//返回信息
  124.         } else {
  125.             $notify->checkSign=TRUE;
  126.             $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
  127.         }
  128.         return $notify;
  129.     }
  130. }
  131. /**
  132. * JSAPI支付——H5网页端调起支付接口
  133. */
  134. class JsApi_handle extends JsApi_common {
  135.     public $code;//code码,用以获取openid
  136.     public $openid;//用户的openid
  137.     public $parameters;//jsapi参数,格式为json
  138.     public $prepay_id;//使用统一支付接口得到的预支付id
  139.     public $curl_timeout;//curl超时时间
  140.     function __construct()
  141.     {
  142.         //设置curl超时时间
  143.         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
  144.     }
  145.     /**
  146.      * 生成获取code的URL
  147.      * @return [type] [description]
  148.      */
  149.     public function createOauthUrlForCode() {
  150.         //重定向URL
  151.         $redirectUrl = "http://www.itcen.cn/wxpay/confirm/".$orderId."?showwxpaytitle=1";
  152.         $urlParams['appid'] = WxPayConf::APPID;
  153.         $urlParams['redirect_uri'] = $redirectUrl;
  154.         $urlParams['response_type'] = 'code';
  155.         $urlParams['scope'] = 'snsapi_base';
  156.         $urlParams['state'] = "STATE"."#wechat_redirect";
  157.         //拼接字符串
  158.         $queryString = $this->ToUrlParams($urlParams, false);
  159.         return "https://open.weixin.qq.com/connect/oauth2/authorize?".$queryString;
  160.     }
  161.     /**
  162.      * 设置code
  163.      * @param [type] $code [description]
  164.      */
  165.     public function setCode($code) {
  166.         $this->code = $code;
  167.     }
  168.     /**
  169.      *  作用:设置prepay_id
  170.      */
  171.     public function setPrepayId($prepayId)
  172.     {
  173.         $this->prepay_id = $prepayId;
  174.     }
  175.     /**
  176.      *  作用:获取jsapi的参数
  177.      */
  178.     public function getParams()
  179.     {
  180.         $jsApiObj["appId"] = WxPayConf::APPID;
  181.         $timeStamp = time();
  182.         $jsApiObj["timeStamp"] = "$timeStamp";
  183.         $jsApiObj["nonceStr"] = $this->createNoncestr();
  184.         $jsApiObj["package"] = "prepay_id=$this->prepay_id";
  185.         $jsApiObj["signType"] = "MD5";
  186.         $jsApiObj["paySign"] = $this->getSign($jsApiObj);
  187.         $this->parameters = json_encode($jsApiObj);
  188.         return $this->parameters;
  189.     }
  190.     /**
  191.      * 通过curl 向微信提交code 用以获取openid
  192.      * @return [type] [description]
  193.      */
  194.     public function getOpenId() {
  195.         //创建openid 的链接
  196.         $url = $this->createOauthUrlForOpenid();
  197.         //初始化
  198.         $ch = curl_init();
  199.         curl_setopt($ch, CURL_TIMEOUT, $this->curl_timeout);
  200.         curl_setopt($ch, CURL_URL, $url);
  201.         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
  202.         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
  203.         curl_setopt($ch, CURL_HEADER, FALSE);
  204.         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
  205.         //执行curl
  206.         $res = curl_exec($ch);
  207.         curl_close($ch);
  208.         //取出openid
  209.         $data = json_decode($res);
  210.         if (isset($data['openid'])) {
  211.             $this->openid = $data['openid'];
  212.         } else {
  213.             return null;
  214.         }
  215.         return $this->openid;
  216.     }
  217.     /**
  218.      * 生成可以获取openid 的URL
  219.      * @return [type] [description]
  220.      */
  221.     public function createOauthUrlForOpenid() {
  222.         $urlParams['appid'] = WxPayConf::APPID;
  223.         $urlParams['secret'] = WxPayConf::APPSECRET;
  224.         $urlParams['code'] = $this->code;
  225.         $urlParams['grant_type'] = "authorization_code";
  226.         $queryString = $this->ToUrlParams($urlParams, false);
  227.         return "https://api.weixin.qq.com/sns/oauth2/access_token?".$queryString;
  228.     }
  229. }
  230. /**
  231.  * 统一下单接口类
  232.  */
  233. class UnifiedOrder_handle extends Wxpay_client_handle {
  234.     public function __construct() {
  235.         //设置接口链接
  236.         $this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  237.         //设置curl超时时间
  238.         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
  239.     }
  240. }
  241. /**
  242.  * 响应型接口基类
  243.  */
  244. class Wxpay_server_handle extends JsApi_common{
  245.     public $data; //接收到的数据,类型为关联数组
  246.     public $returnParams;   //返回参数,类型为关联数组
  247.     /**
  248.      * 将微信请求的xml转换成关联数组
  249.      * @param  [type] $xml [description]
  250.      * @return [type]      [description]
  251.      */
  252.     public function saveData($xml) {
  253.         $this->data = $this->xmlToArray($xml);
  254.     }
  255.     /**
  256.      * 验证签名
  257.      * @return [type] [description]
  258.      */
  259.     public function checkSign() {
  260.         $tmpData = $this->data;
  261.         unset($temData['sign']);
  262.         $sign = $this->getSign($tmpData);
  263.         if ($this->data['sign'] == $sign) {
  264.             return true;
  265.         }
  266.         return false;
  267.     }
  268.     /**
  269.      * 设置返回微信的xml数据
  270.      */
  271.     function setReturnParameter($parameter, $parameterValue)
  272.     {
  273.         $this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
  274.     }
  275.     /**
  276.      * 将xml数据返回微信
  277.      */
  278.     function returnXml()
  279.     {
  280.         $returnXml = $this->createXml();
  281.         return $returnXml;
  282.     }
  283. }
  284. /**
  285.  * 请求型接口的基类
  286.  */
  287. class Wxpay_client_handle extends JsApi_common{
  288.     public $params; //请求参数,类型为关联数组
  289.     public $response; //微信返回的响应
  290.     public $result; //返回参数,类型类关联数组
  291.     public $url; //接口链接
  292.     public $curl_timeout; //curl超时时间
  293.     /**
  294.      * 设置请求参数
  295.      * @param [type] $param      [description]
  296.      * @param [type] $paramValue [description]
  297.      */
  298.     public function setParam($param, $paramValue) {
  299.         $this->params[$this->tirmString($param)] = $this->trimString($paramValue);
  300.     }
  301.     /**
  302.      * 获取结果,默认不使用证书
  303.      * @return [type] [description]
  304.      */
  305.     public function getResult() {
  306.         $this->postxml();
  307.         $this->result = $this->xmlToArray($this->response);
  308.         return $this->result;
  309.     }
  310.     /**
  311.      * post请求xml
  312.      * @return [type] [description]
  313.      */
  314.     public function postxml() {
  315.         $xml = $this->createXml();
  316.         $this->response = $this->postXmlCurl($xml, $this->curl, $this->curl_timeout);
  317.         return $this->response;
  318.     }
  319.     public function createXml() {
  320.         $this->params['appid'] = WxPayConf::APPID; //公众号ID
  321.         $this->params['mch_id'] = WxPayConf::MCHID; //商户号
  322.         $this->params['nonce_str'] = $this->createNoncestr();   //随机字符串
  323.         $this->params['sign'] = $this->getSign($this->params);  //签名
  324.         return $this->arrayToXml($this->params);
  325.     }
  326. }
  327. /**
  328.  * 所有接口的基类
  329.  */
  330. class JsApi_common {
  331.     function __construct() {
  332.     }
  333.     public function trimString($value) {
  334.         $ret = null;
  335.         if (null != $value) {
  336.             $ret = trim($value);
  337.             if (strlen($ret) == 0) {
  338.                 $ret = null;
  339.             }
  340.         }
  341.         return $ret;
  342.     }
  343.     /**
  344.      * 产生随机字符串,不长于32位
  345.      * @param  integer $length [description]
  346.      * @return [type]          [description]
  347.      */
  348.     public function createNoncestr($length = 32) {
  349.         $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  350.         $str = '';
  351.         for ($i = 0; $i < $length; $i++) {
  352.             $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  353.         }
  354.         return $str;
  355.     }
  356.     /**
  357.      * 格式化参数 拼接字符串,签名过程需要使用
  358.      * @param [type] $urlParams     [description]
  359.      * @param [type] $needUrlencode [description]
  360.      */
  361.     public function ToUrlParams($urlParams, $needUrlencode) {
  362.         $buff = "";
  363.         ksort($urlParams);
  364.         foreach ($urlParams as $k => $v) {
  365.             if($needUrlencode) $v = urlencode($v);
  366.             $buff .= $k .'='. $v .'&';
  367.         }
  368.         $reqString = '';
  369.         if (strlen($buff) > 0) {
  370.             $reqString = substr($buff, 0, strlen($buff) - 1);
  371.         }
  372.         return $reqString;
  373.     }
  374.     /**
  375.      * 生成签名
  376.      * @param  [type] $params [description]
  377.      * @return [type]         [description]
  378.      */
  379.     public function getSign($obj) {
  380.         foreach ($obj as $k => $v) {
  381.             $params[$k] = $v;
  382.         }
  383.         //签名步骤一:按字典序排序参数
  384.         ksort($params);
  385.         $str = $this->ToUrlParams($params, false);
  386.         //签名步骤二:在$str后加入key
  387.         $str = $str."$key=".WxPayConf::KEY;
  388.         //签名步骤三:md5加密
  389.         $str = md5($str);
  390.         //签名步骤四:所有字符转为大写
  391.         $result = strtoupper($str);
  392.         return $result;
  393.     }
  394.     /**
  395.      * array转xml
  396.      * @param  [type] $arr [description]
  397.      * @return [type]      [description]
  398.      */
  399.     public function arrayToXml($arr) {
  400.         $xml = "<xml>";
  401.         foreach ($arr as $k => $v) {
  402.             if (is_numeric($val)) {
  403.                 $xml .= "<".$key.">".$key."</".$key.">";
  404.             } else {
  405.                 $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">";
  406.             }
  407.         }
  408.         $xml .= "</xml>";
  409.         return $xml;
  410.     }
  411.     /**
  412.      * 将xml转为array
  413.      * @param  [type] $xml [description]
  414.      * @return [type]      [description]
  415.      */
  416.     public function xmlToArray($xml) {
  417.         $arr = json_decode(json_encode(simplexml_load_string($xml, 'SinpleXMLElement', LIBXML_NOCDATA)), true);
  418.         return $arr;
  419.     }
  420.     /**
  421.      * 以post方式提交xml到对应的接口
  422.      * @param  [type]  $xml    [description]
  423.      * @param  [type]  $url    [description]
  424.      * @param  integer $second [description]
  425.      * @return [type]          [description]
  426.      */
  427.     public function postXmlCurl($xml, $url, $second = 30) {
  428.         //初始化curl
  429.         $ch = curl_init();
  430.         //设置超时
  431.         curl_setopt($ch, CURL_TIMEOUT, $second);
  432.         curl_setopt($ch, CURL_URL, $url);
  433.         //这里设置代理,如果有的话
  434.         //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
  435.         //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
  436.         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
  437.         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
  438.         //设置header
  439.         curl_setopt($ch, CURL_HEADER, FALSE);
  440.         //要求结果为字符串且输出到屏幕上
  441.         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
  442.         //以post方式提交
  443.         curl_setopt($ch, CURL_POST, TRUE);
  444.         curl_setopt($ch, CURL_POSTFIELDS, $xml);
  445.         //执行curl
  446.         $res = curl_exec($ch);
  447.         if ($res) {
  448.             curl_close($ch);
  449.             return $res;
  450.         } else {
  451.             $error = curl_errno($ch);
  452.             echo "curl出错,错误码:$error"."<br>";
  453.             echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
  454.             curl_close($ch);
  455.             return false;
  456.         }
  457.     }
  458. }
  459. /**
  460.  * 配置类
  461.  */
  462. class WxPayConf {
  463.     //微信公众号身份的唯一标识。
  464.     const APPID = 'wx654a22c6423213b7';
  465.     //受理商ID,身份标识
  466.     const MCHID = '10043241';
  467.     const MCHNAME = 'KellyCen的博客';
  468.     //商户支付密钥Key。
  469.     const KEY = '0000000000000000000000000000000';
  470.     //JSAPI接口中获取openid
  471.     const APPSECRET = '000000000000000000000000000';
  472.     //证书路径,注意应该填写绝对路径
  473.     const SSLCERT_PATH = '/home/WxPayCacert/apiclient_cert.pem';
  474.     const SSLKEY_PATH = '/home/WxPayCacert/apiclient_key.pem';
  475.     const SSLCA_PATH = '/home/WxPayCacert/rootca.pem';
  476.     //本例程通过curl使用HTTP POST方法,此处可修改其超时时间,默认为30秒
  477.     const CURL_TIMEOUT = 30;
  478. }
  479. Wxpay_model.php

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

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

  1. /**
  2.      * 手机端微信支付,此处是授权获取到code时的回调地址
  3.      * @param  [type] $orderId 订单编号id
  4.      * @return [type]          [description]
  5.      */
  6.     public function confirm($orderId) {
  7.         //先确认用户是否登录
  8.         $this->ensureLogin();
  9.         //通过订单编号获取订单数据
  10.         $order = $this->wxpay_model->get($orderId);
  11.         //验证订单是否是当前用户
  12.         $this->_verifyUser($order);
  13.         //取得支付所需要的订单数据
  14.         $orderData = $this->returnOrderData[$orderId];
  15.         //取得jsApi所需要的数据
  16.         $wxJsApiData = $this->wxpay_model->wxPayJsApi($orderData);
  17.         //将数据分配到模板去,在js里使用
  18.         $this->smartyData['wxJsApiData'] = json_encode($wxJsApiData, JSON_UNESCAPED_UNICODE);
  19.         $this->smartyData['order'] = $orderData;
  20.         $this->displayView('wxpay/confirm.tpl');
  21.     }

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

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

  1. /**
  2.      * 微信jsapi点击支付
  3.      * @param  [type] $data [description]
  4.      * @return [type]       [description]
  5.      */
  6.     public function wxPayJsApi($data) {
  7.         $jsApi = new JsApi_handle();
  8.         //统一下单接口所需数据
  9.         $payData = $this->returnData($data);
  10.         //获取code码,用以获取openid
  11.         $code = $_GET['code'];
  12.         $jsApi->setCode($code);
  13.         //通过code获取openid
  14.         $openid = $jsApi->getOpenId();
  15.         $unifiedOrderResult = null;
  16.         if ($openid != null) {
  17.             //取得统一下单接口返回的数据
  18.             $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
  19.             //获取订单接口状态
  20.             $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
  21.             if ($returnMessage['resultCode']) {
  22.                 $jsApi->setPrepayId($retuenMessage['resultField']);
  23.                 //取得wxjsapi接口所需要的数据
  24.                 $returnMessage['resultData'] = $jsApi->getParams();
  25.             }
  26.             return $returnMessage;
  27.         }
  28.     }

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

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

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

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

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

  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. <a href="javascript:callpay();" id="btnOrder">点击支付</a>
  11. </body>
  12. <script type="text/javascript">
  13.     //将数据付给js变量
  14.     var wxJsApiData = {$wxJsApiData};
  15.     function onBridgeReady()
  16.         {
  17.             //格式参考官方文档 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
  18.             WeixinJSBridge.invoke(
  19.                 'getBrandWCPayRequest',
  20.                 $.parseJSON(wxJsApiData.resultData),
  21.                 function(res){
  22.                     if(res.err_msg == "get_brand_wcpay_request:ok" ){
  23.                         window.location.href="/wxpay/paysuccess/"+{$order.sn};
  24.                     }
  25.                 }
  26.             );
  27.         }
  28.         function callpay()
  29.         {
  30.             if(!wxJsApiData.resultCode){
  31.                 alert(wxJsApiData.resultType+","+wxJsApiData.resultMsg+"!");
  32.                 return false;
  33.             }
  34.             if (typeof WeixinJSBridge == "undefined"){
  35.                 if( document.addEventListener ){
  36.                     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
  37.                 }else if (document.attachEvent){
  38.                     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
  39.                     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
  40.                 }
  41.             }else{
  42.                 onBridgeReady();
  43.             }
  44.         }
  45. </script>
  46. </html>

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

HTML5教程 HTML5技术 微信支付 微信支付接口开发 微信支付api

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

HTML5教程 HTML5技术 微信支付 微信支付接口开发 微信支付api

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

  1. /**
  2.      * 支付回调接口
  3.      * @return [type] [description]
  4.      */
  5.     public function pay_callback() {
  6.         $postData = '';
  7.         if (file_get_contents("php://input")) {
  8.             $postData = file_get_contents("php://input");
  9.         } else {
  10.             return;
  11.         }
  12.         $payInfo = array();
  13.         $notify = $this->wxpay_model->wxPayNotify($postData);
  14.         if ($notify->checkSign == TRUE) {
  15.             if ($notify->data['return_code'] == 'FAIL') {
  16.                 $payInfo['status'] = FALSE;
  17.                 $payInfo['msg'] = '通信出错';
  18.             } elseif ($notify->data['result_code'] == 'FAIL') {
  19.                 $payInfo['status'] = FALSE;
  20.                 $payInfo['msg'] = '业务出错';
  21.             } else {
  22.                 $payInfo['status'] = TRUE;
  23.                 $payInfo['msg'] = '支付成功';
  24.                 $payInfo['sn']=substr($notify->data['out_trade_no'],8);
  25.                 $payInfo['order_no'] = $notify->data['out_trade_no'];
  26.                 $payInfo['platform_no']=$notify->data['transaction_id'];
  27.                 $payInfo['attach']=$notify->data['attach'];
  28.                 $payInfo['fee']=$notify->data['cash_fee'];
  29.                 $payInfo['currency']=$notify->data['fee_type'];
  30.                 $payInfo['user_sign']=$notify->data['openid'];
  31.             }
  32.         }
  33.         $returnXml = $notify->returnXml();
  34.         echo $returnXml;
  35.         $this->load->library('RedisCache');
  36.         if($payInfo['status']){
  37.            //这里要记录到日志处理(略)
  38.             $this->model->order->onPaySuccess($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo);
  39.             $this->redis->RedisCache->set('order:payNo:'.$payInfo['order_no'],'OK',5000);
  40.         }else{
  41.            //这里要记录到日志处理(略)
  42.             $this->model->order->onPayFailure($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],'', $payInfo['user_sign'], $payInfo, '订单支付失败 ['.$payInfo['msg'].']');
  43.         }
  44.     }

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

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

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

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

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

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

控制器:Wxpay.php

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3. class Wxpay extends MY_Controller {
  4.     public function __construct() {
  5.         parent::__construct();
  6.         $this->load->model('wxpay_model');
  7.         //$this->load->model('wxpay');
  8.     }
  9.     public function index() {
  10.         //微信支付
  11.         $this->smarty['wxPayUrl'] = $this->wxpay_model->retWxPayUrl();
  12.         $this->displayView('wxpay/index.tpl');
  13.     }
  14.     /**
  15.      * 手机端微信支付,此处是授权获取到code时的回调地址
  16.      * @param  [type] $orderId 订单编号id
  17.      * @return [type]          [description]
  18.      */
  19.     public function confirm($orderId) {
  20.         //先确认用户是否登录
  21.         $this->ensureLogin();
  22.         //通过订单编号获取订单数据
  23.         $order = $this->wxpay_model->get($orderId);
  24.         //验证订单是否是当前用户
  25.         $this->_verifyUser($order);
  26.         //取得支付所需要的订单数据
  27.         $orderData = $this->returnOrderData[$orderId];
  28.         //取得jsApi所需要的数据
  29.         $wxJsApiData = $this->wxpay_model->wxPayJsApi($orderData);
  30.         //将数据分配到模板去,在js里使用
  31.         $this->smartyData['wxJsApiData'] = json_encode($wxJsApiData, JSON_UNESCAPED_UNICODE);
  32.         $this->smartyData['order'] = $orderData;
  33.         $this->displayView('wxpay/confirm.tpl');
  34.     }
  35.     /**
  36.      * 支付回调接口
  37.      * @return [type] [description]
  38.      */
  39.     public function pay_callback() {
  40.         $postData = '';
  41.         if (file_get_contents("php://input")) {
  42.             $postData = file_get_contents("php://input");
  43.         } else {
  44.             return;
  45.         }
  46.         $payInfo = array();
  47.         $notify = $this->wxpay_model->wxPayNotify($postData);
  48.         if ($notify->checkSign == TRUE) {
  49.             if ($notify->data['return_code'] == 'FAIL') {
  50.                 $payInfo['status'] = FALSE;
  51.                 $payInfo['msg'] = '通信出错';
  52.             } elseif ($notify->data['result_code'] == 'FAIL') {
  53.                 $payInfo['status'] = FALSE;
  54.                 $payInfo['msg'] = '业务出错';
  55.             } else {
  56.                 $payInfo['status'] = TRUE;
  57.                 $payInfo['msg'] = '支付成功';
  58.                 $payInfo['sn']=substr($notify->data['out_trade_no'],8);
  59.                 $payInfo['order_no'] = $notify->data['out_trade_no'];
  60.                 $payInfo['platform_no']=$notify->data['transaction_id'];
  61.                 $payInfo['attach']=$notify->data['attach'];
  62.                 $payInfo['fee']=$notify->data['cash_fee'];
  63.                 $payInfo['currency']=$notify->data['fee_type'];
  64.                 $payInfo['user_sign']=$notify->data['openid'];
  65.             }
  66.         }
  67.         $returnXml = $notify->returnXml();
  68.         echo $returnXml;
  69.         $this->load->library('RedisCache');
  70.         if($payInfo['status']){
  71.            //这里要记录到日志处理(略)
  72.             $this->model->order->onPaySuccess($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],''$payInfo['user_sign'], $payInfo);
  73.             $this->redis->RedisCache->set('order:payNo:'.$payInfo['order_no'],'OK',5000);
  74.         }else{
  75.            //这里要记录到日志处理(略)
  76.             $this->model->order->onPayFailure($payInfo['sn'], $payInfo['order_no'], $payInfo['platform_no'],''$payInfo['user_sign'], $payInfo'订单支付失败 ['.$payInfo['msg'].']');
  77.         }
  78.     }
  79.     /**
  80.      * 返回支付所需要的数据
  81.      * @param  [type] $orderId 订单号
  82.      * @param  string $data    订单数据,当$data数据存在时刷新$orderData缓存,因为订单号不唯一
  83.      * @return [type]          [description]
  84.      */
  85.     public function returnOrderData($orderId$data = '') {
  86.         //获取订单数据
  87.         $order = $this->wxpay_model->get($orderId);
  88.         if (0 === count($order)) return false;
  89.         if (emptyempty($data)) {
  90.             $this->load->library('RedisCache');
  91.             //取得缓存在redis的订单数据
  92.             $orderData = $this->rediscache->getJson("order:orderData:".$orderId);
  93.             if (emptyempty($orderData)) {
  94.                 //如果redis里没有,则直接读数据库取
  95.                 $this->load->model('order_model');
  96.                 $order = $this->order_model->get($orderId);
  97.                 if (0 === count($order)) {
  98.                     return false;
  99.                 }
  100.                 $data = $order;
  101.             } else {
  102.                 //如果redis里面有的话,直接返回数据
  103.                 return $orderData;
  104.             }
  105.         }
  106.         //支付前缓存所需要的数据
  107.         $orderData['id'] = $data['id'];
  108.         $orderData['fee'] = $data['fee'];
  109.         //支付平台需要的数据
  110.         $orderData['user_id'] = $data['user_id'];
  111.         $orderData['sn'] = $data['cn'];
  112.         //这是唯一编号
  113.         $orderData['order_no'] = substr(md5($data['sn'].$data['fee']), 8, 8).$data['sn'];
  114.         $orderData['fee'] = $data['fee'];
  115.         $orderData['time'] = $data['time'];
  116.         $orderData['goods_name'] = $data['goods_name'];
  117.         $orderData['attach'] = $data['attach'];
  118.         //将数据缓存到redis里面
  119.         $this->rediscache->set("order:orderData:".$orderId$orderData, 3600*24);
  120.         //做个标识缓存到redis,用以判断该订单是否已经支付了
  121.         $this->rediscache->set("order:payNo:".$orderData['order_no'], "NO", 3600*24);
  122.         return $orderData;
  123.     }
  124.     private function _verifyUser($order) {
  125.         if (emptyempty($order)) show_404();
  126.         if (0 === count($order)) show_404();
  127.         //判断订单表里的用户id是否是当前登录者的id
  128.         if ($order['user_id'] == $this->uid) return;
  129.         show_error('只能查看自己的订单');
  130.     }
  131. }
  132. 控制器:Wxpay.php

模型:Wxpay_model.php

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3. class Wxpay_model extends CI_Model {
  4.     public function __construct() {
  5.         parent::__construct();
  6.     }
  7.     /**
  8.      * 返回可以获得微信code的URL (用以获取openid)
  9.      * @return [type] [description]
  10.      */
  11.     public function retWxPayUrl() {
  12.         $jsApi = new JsApi_handle();
  13.         return $jsApi->createOauthUrlForCode();
  14.     }
  15.     /**
  16.      * 微信jsapi点击支付
  17.      * @param  [type] $data [description]
  18.      * @return [type]       [description]
  19.      */
  20.     public function wxPayJsApi($data) {
  21.         $jsApi = new JsApi_handle();
  22.         //统一下单接口所需数据
  23.         $payData = $this->returnData($data);
  24.         //获取code码,用以获取openid
  25.         $code = $_GET['code'];
  26.         $jsApi->setCode($code);
  27.         //通过code获取openid
  28.         $openid = $jsApi->getOpenId();
  29.         $unifiedOrderResult = null;
  30.         if ($openid != null) {
  31.             //取得统一下单接口返回的数据
  32.             $unifiedOrderResult = $this->getResult($payData, 'JSAPI', $openid);
  33.             //获取订单接口状态
  34.             $returnMessage = $this->returnMessage($unifiedOrder, 'prepay_id');
  35.             if ($returnMessage['resultCode']) {
  36.                 $jsApi->setPrepayId($retuenMessage['resultField']);
  37.                 //取得wxjsapi接口所需要的数据
  38.                 $returnMessage['resultData'] = $jsApi->getParams();
  39.             }
  40.             return $returnMessage;
  41.         }
  42.     }
  43.     /**
  44.      * 统一下单接口所需要的数据
  45.      * @param  [type] $data [description]
  46.      * @return [type]       [description]
  47.      */
  48.     public function returnData($data) {
  49.         $payData['sn'] = $data['sn'];
  50.         $payData['body'] = $data['goods_name'];
  51.         $payData['out_trade_no'] = $data['order_no'];
  52.         $payData['total_fee'] = $data['fee'];
  53.         $payData['attach'] = $data['attach'];
  54.         return $payData;
  55.     }
  56.     /**
  57.      * 返回统一下单接口结果 (参考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
  58.      * @param  [type] $payData    [description]
  59.      * @param  [type] $trade_type [description]
  60.      * @param  [type] $openid     [description]
  61.      * @return [type]             [description]
  62.      */
  63.     public function getResult($payData, $trade_type, $openid = null) {
  64.         $unifiedOrder = new UnifiedOrder_handle();
  65.         if ($opneid != null) {
  66.             $unifiedOrder->setParam('openid', $openid);
  67.         }
  68.         $unifiedOrder->setParam('body', $payData['body']);  //商品描述
  69.         $unifiedOrder->setParam('out_trade_no', $payData['out_trade_no']); //商户订单号
  70.         $unifiedOrder->setParam('total_fee', $payData['total_fee']);    //总金额
  71.         $unifiedOrder->setParam('attach', $payData['attach']);  //附加数据
  72.         $unifiedOrder->setParam('notify_url', base_url('/Wxpay/pay_callback'));//通知地址
  73.         $unifiedOrder->setParam('trade_type', $trade_type); //交易类型
  74.         //非必填参数,商户可根据实际情况选填
  75.         //$unifiedOrder->setParam("sub_mch_id","XXXX");//子商户号
  76.         //$unifiedOrder->setParam("device_info","XXXX");//设备号
  77.         //$unifiedOrder->setParam("time_start","XXXX");//交易起始时间
  78.         //$unifiedOrder->setParam("time_expire","XXXX");//交易结束时间
  79.         //$unifiedOrder->setParam("goods_tag","XXXX");//商品标记
  80.         //$unifiedOrder->setParam("product_id","XXXX");//商品ID
  81.         return $unifiedOrder->getResult();
  82.     }
  83.     /**
  84.      * 返回微信订单状态
  85.      */
  86.     public function returnMessage($unifiedOrderResult,$field){
  87.         $arrMessage=array("resultCode"=>0,"resultType"=>"获取错误","resultMsg"=>"该字段为空");
  88.         if($unifiedOrderResult==null){
  89.             $arrMessage["resultType"]="未获取权限";
  90.             $arrMessage["resultMsg"]="请重新打开页面";
  91.         }elseif ($unifiedOrderResult["return_code"] == "FAIL")
  92.         {
  93.             $arrMessage["resultType"]="网络错误";
  94.             $arrMessage["resultMsg"]=$unifiedOrderResult['return_msg'];
  95.         }
  96.         elseif($unifiedOrderResult["result_code"] == "FAIL")
  97.         {
  98.             $arrMessage["resultType"]="订单错误";
  99.             $arrMessage["resultMsg"]=$unifiedOrderResult['err_code_des'];
  100.         }
  101.         elseif($unifiedOrderResult[$field] != NULL)
  102.         {
  103.             $arrMessage["resultCode"]=1;
  104.             $arrMessage["resultType"]="生成订单";
  105.             $arrMessage["resultMsg"]="OK";
  106.             $arrMessage["resultField"] = $unifiedOrderResult[$field];
  107.         }
  108.         return $arrMessage;
  109.     }
  110.     /**
  111.      * 微信回调接口返回  验证签名并回应微信
  112.      * @param  [type] $xml [description]
  113.      * @return [type]      [description]
  114.      */
  115.     public function wxPayNotify($xml) {
  116.         $notify = new Wxpay_server();
  117.         $notify->saveData($xml);
  118.         //验证签名,并回复微信
  119.         //对后台通知交互时,如果微信收到商户的应答不是成功或者超时,微信认为通知失败
  120.         //微信会通过一定的策略(如30分钟共8次),定期重新发起通知
  121.         if ($notify->checkSign() == false) {
  122.             $notify->setReturnParameter("return_code","FAIL");//返回状态码
  123.             $notify->setReturnParameter("return_msg","签名失败");//返回信息
  124.         } else {
  125.             $notify->checkSign=TRUE;
  126.             $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
  127.         }
  128.         return $notify;
  129.     }
  130. }
  131. /**
  132. * JSAPI支付——H5网页端调起支付接口
  133. */
  134. class JsApi_handle extends JsApi_common {
  135.     public $code;//code码,用以获取openid
  136.     public $openid;//用户的openid
  137.     public $parameters;//jsapi参数,格式为json
  138.     public $prepay_id;//使用统一支付接口得到的预支付id
  139.     public $curl_timeout;//curl超时时间
  140.     function __construct()
  141.     {
  142.         //设置curl超时时间
  143.         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
  144.     }
  145.     /**
  146.      * 生成获取code的URL
  147.      * @return [type] [description]
  148.      */
  149.     public function createOauthUrlForCode() {
  150.         //重定向URL
  151.         $redirectUrl = "http://www.itcen.cn/wxpay/confirm/".$orderId."?showwxpaytitle=1";
  152.         $urlParams['appid'] = WxPayConf::APPID;
  153.         $urlParams['redirect_uri'] = $redirectUrl;
  154.         $urlParams['response_type'] = 'code';
  155.         $urlParams['scope'] = 'snsapi_base';
  156.         $urlParams['state'] = "STATE"."#wechat_redirect";
  157.         //拼接字符串
  158.         $queryString = $this->ToUrlParams($urlParams, false);
  159.         return "https://open.weixin.qq.com/connect/oauth2/authorize?".$queryString;
  160.     }
  161.     /**
  162.      * 设置code
  163.      * @param [type] $code [description]
  164.      */
  165.     public function setCode($code) {
  166.         $this->code = $code;
  167.     }
  168.     /**
  169.      *  作用:设置prepay_id
  170.      */
  171.     public function setPrepayId($prepayId)
  172.     {
  173.         $this->prepay_id = $prepayId;
  174.     }
  175.     /**
  176.      *  作用:获取jsapi的参数
  177.      */
  178.     public function getParams()
  179.     {
  180.         $jsApiObj["appId"] = WxPayConf::APPID;
  181.         $timeStamp = time();
  182.         $jsApiObj["timeStamp"] = "$timeStamp";
  183.         $jsApiObj["nonceStr"] = $this->createNoncestr();
  184.         $jsApiObj["package"] = "prepay_id=$this->prepay_id";
  185.         $jsApiObj["signType"] = "MD5";
  186.         $jsApiObj["paySign"] = $this->getSign($jsApiObj);
  187.         $this->parameters = json_encode($jsApiObj);
  188.         return $this->parameters;
  189.     }
  190.     /**
  191.      * 通过curl 向微信提交code 用以获取openid
  192.      * @return [type] [description]
  193.      */
  194.     public function getOpenId() {
  195.         //创建openid 的链接
  196.         $url = $this->createOauthUrlForOpenid();
  197.         //初始化
  198.         $ch = curl_init();
  199.         curl_setopt($ch, CURL_TIMEOUT, $this->curl_timeout);
  200.         curl_setopt($ch, CURL_URL, $url);
  201.         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
  202.         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
  203.         curl_setopt($ch, CURL_HEADER, FALSE);
  204.         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
  205.         //执行curl
  206.         $res = curl_exec($ch);
  207.         curl_close($ch);
  208.         //取出openid
  209.         $data = json_decode($res);
  210.         if (isset($data['openid'])) {
  211.             $this->openid = $data['openid'];
  212.         } else {
  213.             return null;
  214.         }
  215.         return $this->openid;
  216.     }
  217.     /**
  218.      * 生成可以获取openid 的URL
  219.      * @return [type] [description]
  220.      */
  221.     public function createOauthUrlForOpenid() {
  222.         $urlParams['appid'] = WxPayConf::APPID;
  223.         $urlParams['secret'] = WxPayConf::APPSECRET;
  224.         $urlParams['code'] = $this->code;
  225.         $urlParams['grant_type'] = "authorization_code";
  226.         $queryString = $this->ToUrlParams($urlParams, false);
  227.         return "https://api.weixin.qq.com/sns/oauth2/access_token?".$queryString;
  228.     }
  229. }
  230. /**
  231.  * 统一下单接口类
  232.  */
  233. class UnifiedOrder_handle extends Wxpay_client_handle {
  234.     public function __construct() {
  235.         //设置接口链接
  236.         $this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  237.         //设置curl超时时间
  238.         $this->curl_timeout = WxPayConf::CURL_TIMEOUT;
  239.     }
  240. }
  241. /**
  242.  * 响应型接口基类
  243.  */
  244. class Wxpay_server_handle extends JsApi_common{
  245.     public $data; //接收到的数据,类型为关联数组
  246.     public $returnParams;   //返回参数,类型为关联数组
  247.     /**
  248.      * 将微信请求的xml转换成关联数组
  249.      * @param  [type] $xml [description]
  250.      * @return [type]      [description]
  251.      */
  252.     public function saveData($xml) {
  253.         $this->data = $this->xmlToArray($xml);
  254.     }
  255.     /**
  256.      * 验证签名
  257.      * @return [type] [description]
  258.      */
  259.     public function checkSign() {
  260.         $tmpData = $this->data;
  261.         unset($temData['sign']);
  262.         $sign = $this->getSign($tmpData);
  263.         if ($this->data['sign'] == $sign) {
  264.             return true;
  265.         }
  266.         return false;
  267.     }
  268.     /**
  269.      * 设置返回微信的xml数据
  270.      */
  271.     function setReturnParameter($parameter, $parameterValue)
  272.     {
  273.         $this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
  274.     }
  275.     /**
  276.      * 将xml数据返回微信
  277.      */
  278.     function returnXml()
  279.     {
  280.         $returnXml = $this->createXml();
  281.         return $returnXml;
  282.     }
  283. }
  284. /**
  285.  * 请求型接口的基类
  286.  */
  287. class Wxpay_client_handle extends JsApi_common{
  288.     public $params; //请求参数,类型为关联数组
  289.     public $response; //微信返回的响应
  290.     public $result; //返回参数,类型类关联数组
  291.     public $url; //接口链接
  292.     public $curl_timeout; //curl超时时间
  293.     /**
  294.      * 设置请求参数
  295.      * @param [type] $param      [description]
  296.      * @param [type] $paramValue [description]
  297.      */
  298.     public function setParam($param, $paramValue) {
  299.         $this->params[$this->tirmString($param)] = $this->trimString($paramValue);
  300.     }
  301.     /**
  302.      * 获取结果,默认不使用证书
  303.      * @return [type] [description]
  304.      */
  305.     public function getResult() {
  306.         $this->postxml();
  307.         $this->result = $this->xmlToArray($this->response);
  308.         return $this->result;
  309.     }
  310.     /**
  311.      * post请求xml
  312.      * @return [type] [description]
  313.      */
  314.     public function postxml() {
  315.         $xml = $this->createXml();
  316.         $this->response = $this->postXmlCurl($xml, $this->curl, $this->curl_timeout);
  317.         return $this->response;
  318.     }
  319.     public function createXml() {
  320.         $this->params['appid'] = WxPayConf::APPID; //公众号ID
  321.         $this->params['mch_id'] = WxPayConf::MCHID; //商户号
  322.         $this->params['nonce_str'] = $this->createNoncestr();   //随机字符串
  323.         $this->params['sign'] = $this->getSign($this->params);  //签名
  324.         return $this->arrayToXml($this->params);
  325.     }
  326. }
  327. /**
  328.  * 所有接口的基类
  329.  */
  330. class JsApi_common {
  331.     function __construct() {
  332.     }
  333.     public function trimString($value) {
  334.         $ret = null;
  335.         if (null != $value) {
  336.             $ret = trim($value);
  337.             if (strlen($ret) == 0) {
  338.                 $ret = null;
  339.             }
  340.         }
  341.         return $ret;
  342.     }
  343.     /**
  344.      * 产生随机字符串,不长于32位
  345.      * @param  integer $length [description]
  346.      * @return [type]          [description]
  347.      */
  348.     public function createNoncestr($length = 32) {
  349.         $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  350.         $str = '';
  351.         for ($i = 0; $i < $length; $i++) {
  352.             $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  353.         }
  354.         return $str;
  355.     }
  356.     /**
  357.      * 格式化参数 拼接字符串,签名过程需要使用
  358.      * @param [type] $urlParams     [description]
  359.      * @param [type] $needUrlencode [description]
  360.      */
  361.     public function ToUrlParams($urlParams, $needUrlencode) {
  362.         $buff = "";
  363.         ksort($urlParams);
  364.         foreach ($urlParams as $k => $v) {
  365.             if($needUrlencode) $v = urlencode($v);
  366.             $buff .= $k .'='. $v .'&';
  367.         }
  368.         $reqString = '';
  369.         if (strlen($buff) > 0) {
  370.             $reqString = substr($buff, 0, strlen($buff) - 1);
  371.         }
  372.         return $reqString;
  373.     }
  374.     /**
  375.      * 生成签名
  376.      * @param  [type] $params [description]
  377.      * @return [type]         [description]
  378.      */
  379.     public function getSign($obj) {
  380.         foreach ($obj as $k => $v) {
  381.             $params[$k] = $v;
  382.         }
  383.         //签名步骤一:按字典序排序参数
  384.         ksort($params);
  385.         $str = $this->ToUrlParams($params, false);
  386.         //签名步骤二:在$str后加入key
  387.         $str = $str."$key=".WxPayConf::KEY;
  388.         //签名步骤三:md5加密
  389.         $str = md5($str);
  390.         //签名步骤四:所有字符转为大写
  391.         $result = strtoupper($str);
  392.         return $result;
  393.     }
  394.     /**
  395.      * array转xml
  396.      * @param  [type] $arr [description]
  397.      * @return [type]      [description]
  398.      */
  399.     public function arrayToXml($arr) {
  400.         $xml = "<xml>";
  401.         foreach ($arr as $k => $v) {
  402.             if (is_numeric($val)) {
  403.                 $xml .= "<".$key.">".$key."</".$key.">";
  404.             } else {
  405.                 $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">";
  406.             }
  407.         }
  408.         $xml .= "</xml>";
  409.         return $xml;
  410.     }
  411.     /**
  412.      * 将xml转为array
  413.      * @param  [type] $xml [description]
  414.      * @return [type]      [description]
  415.      */
  416.     public function xmlToArray($xml) {
  417.         $arr = json_decode(json_encode(simplexml_load_string($xml, 'SinpleXMLElement', LIBXML_NOCDATA)), true);
  418.         return $arr;
  419.     }
  420.     /**
  421.      * 以post方式提交xml到对应的接口
  422.      * @param  [type]  $xml    [description]
  423.      * @param  [type]  $url    [description]
  424.      * @param  integer $second [description]
  425.      * @return [type]          [description]
  426.      */
  427.     public function postXmlCurl($xml, $url, $second = 30) {
  428.         //初始化curl
  429.         $ch = curl_init();
  430.         //设置超时
  431.         curl_setopt($ch, CURL_TIMEOUT, $second);
  432.         curl_setopt($ch, CURL_URL, $url);
  433.         //这里设置代理,如果有的话
  434.         //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
  435.         //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
  436.         curl_setopt($ch, CURL_SSL_VERIFYHOST, FALSE);
  437.         curl_setopt($ch, CURL_SSL_VERIFYPEER, FALSE);
  438.         //设置header
  439.         curl_setopt($ch, CURL_HEADER, FALSE);
  440.         //要求结果为字符串且输出到屏幕上
  441.         curl_setopt($ch, CURL_RETURNTRANSFER, TRUE);
  442.         //以post方式提交
  443.         curl_setopt($ch, CURL_POST, TRUE);
  444.         curl_setopt($ch, CURL_POSTFIELDS, $xml);
  445.         //执行curl
  446.         $res = curl_exec($ch);
  447.         if ($res) {
  448.             curl_close($ch);
  449.             return $res;
  450.         } else {
  451.             $error = curl_errno($ch);
  452.             echo "curl出错,错误码:$error"."<br>";
  453.             echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
  454.             curl_close($ch);
  455.             return false;
  456.         }
  457.     }
  458. }
  459. /**
  460.  * 配置类
  461.  */
  462. class WxPayConf {
  463.     //微信公众号身份的唯一标识。
  464.     const APPID = 'wx654a22c6423213b7';
  465.     //受理商ID,身份标识
  466.     const MCHID = '10043241';
  467.     const MCHNAME = 'KellyCen的博客';
  468.     //商户支付密钥Key。
  469.     const KEY = '0000000000000000000000000000000';
  470.     //JSAPI接口中获取openid
  471.     const APPSECRET = '000000000000000000000000000';
  472.     //证书路径,注意应该填写绝对路径
  473.     const SSLCERT_PATH = '/home/WxPayCacert/apiclient_cert.pem';
  474.     const SSLKEY_PATH = '/home/WxPayCacert/apiclient_key.pem';
  475.     const SSLCA_PATH = '/home/WxPayCacert/rootca.pem';
  476.     //本例程通过curl使用HTTP POST方法,此处可修改其超时时间,默认为30秒
  477.     const CURL_TIMEOUT = 30;
  478. }
  479. 模型:Wxpay_model.php

视图: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. <a href="{$wxPayUrl}">微信支付</a>
  11. </body>
  12. </html>
  13. 视图:index.tpl

 视图:confirm.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. <a href="javascript:callpay();" id="btnOrder">点击支付</a>
  11. </body>
  12. <script type="text/javascript">
  13.     //将数据付给js变量
  14.     var wxJsApiData = {$wxJsApiData};
  15.     function onBridgeReady()
  16.         {
  17.             //格式参考官方文档 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
  18.             WeixinJSBridge.invoke(
  19.                 'getBrandWCPayRequest',
  20.                 $.parseJSON(wxJsApiData.resultData),
  21.                 function(res){
  22.                     if(res.err_msg == "get_brand_wcpay_request:ok" ){
  23.                         window.location.href="/wxpay/paysuccess/"+{$order.sn};
  24.                     }
  25.                 }
  26.             );
  27.         }
  28.         function callpay()
  29.         {
  30.             if(!wxJsApiData.resultCode){
  31.                 alert(wxJsApiData.resultType+","+wxJsApiData.resultMsg+"!");
  32.                 return false;
  33.             }
  34.             if (typeof WeixinJSBridge == "undefined"){
  35.                 if( document.addEventListener ){
  36.                     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
  37.                 }else if (document.attachEvent){
  38.                     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
  39.                     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
  40.                 }
  41.             }else{
  42.                 onBridgeReady();
  43.             }
  44.         }
  45. </script>
  46. </html>
  47. 视图:confirm.tpl

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

现在我们的线上项目是微信支付,支付宝支付,网银支付信用卡支付的功能都有,并且PC和WAP端都分别对应有。所以整一个支付系统模块还算比较完整,后期有时间我会总结和分享下其他的支付接口开发的博文,希望有兴趣的博友可以关注下哦!!

标签:

给我留言