一、前言
为何我还写一篇微信支付接口的博文呢?第一,我们必须知道,所谓的工作经验很多都是靠总结出来的,你只有总结了更多知识,积累了更多经验,你才能在该行业中脱颖而出,我个人觉得如今的招聘,很多都需要工作经验(1年、3年、5年....),其实,工作时间的长久不能衡量一个人技术水平的高低,有的人一年的工作经验能拿3年工作经验的程序猿的工资,有的3年工作经验的却有可能比别人只有一年工作经验的还低,所以说,总结才能让自己的知识体系,经验深度更牛逼更稳固(虽然写一篇博文挺花费时间的);第二,写博文分享给大家还是挺有成就感的,首先是能让新手从我分享的博文中能学到东西,并且能快速将博文所讲解的技术运用到实际中来,所以我写的博文基本上能让新人快速读懂并且容易理解,另外,技术大神的话,看到博文有讲解的不对之处,还可以指出,并且可以交流,何乐而不为呢,我们需要的就是分享和交流。
扯远了,直接进入该主题的详解。
现在的微信支付方式有n种,看下图,有刷卡支付、公众号支付、扫码支付和app支付,另外还有支付工具的开发,本博文选择的是公众号支付借口而开发进行讲解,其他几种支付接口开发基本上思路都是一样的,只要你能看懂我这博文所讲解的基本思路,你基本上也能独自开发其他几个支付接口。
二、思路详解
我们可以拿微信支付接口文档里的业务流程时序图看看,如下图,基本思路是这样子:首先在后台生成一个链接,展示给用户让用户点击(例如页面上有微信支付的按钮),用户点击按钮后,网站后台会根据订单的相关信息生成一个支付订单,此时会调用统一下单接口,对微信支付系统发起请求,而微信支付系统受到请求后,会根据请求过来的数据,生成一个 预支付交易会话标识(prepay_id,就是通过这个来识别该订单的),我们的网站收到微信支付系统的响应后,会得到prepay_id,然后通过自己构造微信支付所需要的参数,接着将支付所需参数返回给客户端,用户此时可能会有一个订单信息页,会有一个按钮,点击支付,此时会调用jsapi接口对微信支付系统发起 请求支付,微信支付系统检查了请求的相关合法性之后,就会提示输入密码,用户此时输入密码确认,微信支付系统会对其进行验证,通过的话会返回支付结果,然后微信跳转会h5页面,这其中有一步是异步通知网站支付结果,我们网站需要对此进行处理(比如说异步支付结果通过后,需要更新数据表或者订单信息,例如标志用户已支付该订单了,同时也需要更新订单日志,防止用户重复提交订单)。
三、代码讲解
本次开发环境用的是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:
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的代码了,里面基本上每一个类每一个方法甚至每一行代码都会有解释的了,这里我就不对其展开一句句分析了:
<?php defined('basepath') or exit('no direct script access allowed'); class wxpay_model extends ci_model { public function __construct() { parent::__construct(); } /** * 返回可以获得微信code的url (用以获取openid) * @return [type] [description] */ public function retwxpayurl() { $jsapi = new jsapi_handle(); return $jsapi->createoauthurlforcode(); } /** * 微信jsapi点击支付 * @param [type] $data [description] * @return [type] [description] */ public function wxpayjsapi($data) { $jsapi = new jsapi_handle(); //统一下单接口所需数据 $paydata = $this->returndata($data); //获取code码,用以获取openid $code = $_get['code']; $jsapi->setcode($code); //通过code获取openid $openid = $jsapi->getopenid(); $unifiedorderresult = null; if ($openid != null) { //取得统一下单接口返回的数据 $unifiedorderresult = $this->getresult($paydata, 'jsapi', $openid); //获取订单接口状态 $returnmessage = $this->returnmessage($unifiedorder, 'prepay_id'); if ($returnmessage['resultcode']) { $jsapi->setprepayid($retuenmessage['resultfield']); //取得wxjsapi接口所需要的数据 $returnmessage['resultdata'] = $jsapi->getparams(); } return $returnmessage; } } /** * 统一下单接口所需要的数据 * @param [type] $data [description] * @return [type] [description] */ public function returndata($data) { $paydata['sn'] = $data['sn']; $paydata['body'] = $data['goods_name']; $paydata['out_trade_no'] = $data['order_no']; $paydata['total_fee'] = $data['fee']; $paydata['attach'] = $data['attach']; return $paydata; } /** * 返回统一下单接口结果 (参考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1) * @param [type] $paydata [description] * @param [type] $trade_type [description] * @param [type] $openid [description] * @return [type] [description] */ public function getresult($paydata, $trade_type, $openid = null) { $unifiedorder = new unifiedorder_handle(); if ($opneid != null) { $unifiedorder->setparam('openid', $openid); } $unifiedorder->setparam('body', $paydata['body']); //商品描述 $unifiedorder->setparam('out_trade_no', $paydata['out_trade_no']); //商户订单号 $unifiedorder->setparam('total_fee', $paydata['total_fee']); //总金额 $unifiedorder->setparam('attach', $paydata['attach']); //附加数据 $unifiedorder->setparam('notify_url', base_url('/wxpay/pay_callback'));//通知地址 $unifiedorder->setparam('trade_type', $trade_type); //交易类型 //非必填参数,商户可根据实际情况选填 //$unifiedorder->setparam(sub_mch_id,xxxx);//子商户号 //$unifiedorder->setparam(device_info,xxxx);//设备号 //$unifiedorder->setparam(time_start,xxxx);//交易起始时间 //$unifiedorder->setparam(time_expire,xxxx);//交易结束时间 //$unifiedorder->setparam(goods_tag,xxxx);//商品标记 //$unifiedorder->setparam(product_id,xxxx);//商品id return $unifiedorder->getresult(); } /** * 返回微信订单状态 */ public function returnmessage($unifiedorderresult,$field){ $arrmessage=array(resultcode=>0,resulttype=>获取错误,resultmsg=>该字段为空); if($unifiedorderresult==null){ $arrmessage[resulttype]=未获取权限; $arrmessage[resultmsg]=请重新打开页面; }elseif ($unifiedorderresult[return_code] == fail) { $arrmessage[resulttype]=网络错误; $arrmessage[resultmsg]=$unifiedorderresult['return_msg']; } elseif($unifiedorderresult[result_code] == fail) { $arrmessage[resulttype]=订单错误; $arrmessage[resultmsg]=$unifiedorderresult['err_code_des']; } elseif($unifiedorderresult[$field] != null) { $arrmessage[resultcode]=1; $arrmessage[resulttype]=生成订单; $arrmessage[resultmsg]=ok; $arrmessage[resultfield] = $unifiedorderresult[$field]; } return $arrmessage; } /** * 微信回调接口返回 验证签名并回应微信 * @param [type] $xml [description] * @return [type] [description] */ public function wxpaynotify($xml) { $notify = new wxpay_server(); $notify->savedata($xml); //验证签名,并回复微信 //对后台通知交互时,如果微信收到商户的应答不是成功或者超时,微信认为通知失败 //微信会通过一定的策略(如30分钟共8次),定期重新发起通知 if ($notify->checksign() == false) { $notify->setreturnparameter(return_code,fail);//返回状态码 $notify->setreturnparameter(return_msg,签名失败);//返回信息 } else { $notify->checksign=true; $notify->setreturnparameter(return_code,success);//设置返回码 } return $notify; } } /** * jsapi支付——h5网页端调起支付接口 */ class jsapi_handle extends jsapi_common { public $code;//code码,用以获取openid public $openid;//用户的openid public $parameters;//jsapi参数,格式为json public $prepay_id;//使用统一支付接口得到的预支付id public $curl_timeout;//curl超时时间 function __construct() { //设置curl超时时间 $this->curl_timeout = wxpayconf::curl_timeout; } /** * 生成获取code的url * @return [type] [description] */ public function createoauthurlforcode() { //重定向url $redirecturl = http://www.itcen.cn/wxpay/confirm/.$orderid.?showwxpaytitle=1; $urlparams['appid'] = wxpayconf::appid; $urlparams['redirect_uri'] = $redirecturl; $urlparams['response_type'] = 'code'; $urlparams['scope'] = 'snsapi_base'; $urlparams['state'] = state.#wechat_redirect; //拼接字符串 $querystring = $this->tourlparams($urlparams, false); return https://open.weixin.qq.com/connect/oauth2/authorize?.$querystring; } /** * 设置code * @param [type] $code [description] */ public function setcode($code) { $this->code = $code; } /** * 作用:设置prepay_id */ public function setprepayid($prepayid) { $this->prepay_id = $prepayid; } /** * 作用:获取jsapi的参数 */ public function getparams() { $jsapiobj[appid] = wxpayconf::appid; $timestamp = time(); $jsapiobj[timestamp] = $timestamp; $jsapiobj[noncestr] = $this->createnoncestr(); $jsapiobj[package] = prepay_id=$this->prepay_id; $jsapiobj[signtype] = md5; $jsapiobj[paysign] = $this->getsign($jsapiobj); $this->parameters = json_encode($jsapiobj); return $this->parameters; } /** * 通过curl 向微信提交code 用以获取openid * @return [type] [description] */ public function getopenid() { //创建openid 的链接 $url = $this->createoauthurlforopenid(); //初始化 $ch = curl_init(); curl_setopt($ch, curl_timeout, $this->curl_timeout); curl_setopt($ch, curl_url, $url); curl_setopt($ch, curl_ssl_verifypeer, false); curl_setopt($ch, curl_ssl_verifyhost, false); curl_setopt($ch, curl_header, false); curl_setopt($ch, curl_returntransfer, true); //执行curl $res = curl_exec($ch); curl_close($ch); //取出openid $data = json_decode($res); if (isset($data['openid'])) { $this->openid = $data['openid']; } else { return null; } return $this->openid; } /** * 生成可以获取openid 的url * @return [type] [description] */ public function createoauthurlforopenid() { $urlparams['appid'] = wxpayconf::appid; $urlparams['secret'] = wxpayconf::appsecret; $urlparams['code'] = $this->code; $urlparams['grant_type'] = authorization_code; $querystring = $this->tourlparams($urlparams, false); return https://api.weixin.qq.com/sns/oauth2/access_token?.$querystring; } } /** * 统一下单接口类 */ class unifiedorder_handle extends wxpay_client_handle { public function __construct() { //设置接口链接 $this->url = https://api.mch.weixin.qq.com/pay/unifiedorder; //设置curl超时时间 $this->curl_timeout = wxpayconf::curl_timeout; } } /** * 响应型接口基类 */ class wxpay_server_handle extends jsapi_common{ public $data; //接收到的数据,类型为关联数组 public $returnparams; //返回参数,类型为关联数组 /** * 将微信请求的xml转换成关联数组 * @param [type] $xml [description] * @return [type] [description] */ public function savedata($xml) { $this->data = $this->xmltoarray($xml); } /** * 验证签名 * @return [type] [description] */ public function checksign() { $tmpdata = $this->data; unset($temdata['sign']); $sign = $this->getsign($tmpdata); if ($this->data['sign'] == $sign) { return true; } return false; } /** * 设置返回微信的xml数据 */ function setreturnparameter($parameter, $parametervalue) { $this->returnparameters[$this->trimstring($parameter)] = $this->trimstring($parametervalue); } /** * 将xml数据返回微信 */ function returnxml() { $returnxml = $this->createxml(); return $returnxml; } } /** * 请求型接口的基类 */ class wxpay_client_handle extends jsapi_common{ public $params; //请求参数,类型为关联数组 public $response; //微信返回的响应 public $result; //返回参数,类型类关联数组 public $url; //接口链接 public $curl_timeout; //curl超时时间 /** * 设置请求参数 * @param [type] $param [description] * @param [type] $paramvalue [description] */ public function setparam($param, $paramvalue) { $this->params[$this->tirmstring($param)] = $this->trimstring($paramvalue); } /** * 获取结果,默认不使用证书 * @return [type] [description] */ public function getresult() { $this->postxml(); $this->result = $this->xmltoarray($this->response); return $this->result; } /** * post请求xml * @return [type] [description] */ public function postxml() { $xml = $this->createxml(); $this->response = $this->postxmlcurl($xml, $this->curl, $this->curl_timeout); return $this->response; } public function createxml() { $this->params['appid'] = wxpayconf::appid; //公众号id $this->params['mch_id'] = wxpayconf::mchid; //商户号 $this->params['nonce_str'] = $this->createnoncestr(); //随机字符串 $this->params['sign'] = $this->getsign($this->params); //签名 return $this->arraytoxml($this->params); } } /** * 所有接口的基类 */ class jsapi_common { function __construct() { } public function trimstring($value) { $ret = null; if (null != $value) { $ret = trim($value); if (strlen($ret) == 0) { $ret = null; } } return $ret; } /** * 产生随机字符串,不长于32位 * @param integer $length [description] * @return [type] [description] */ public function createnoncestr($length = 32) { $chars = abcdefghijklmnopqrstuvwxyz0123456789; $str = ''; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } /** * 格式化参数 拼接字符串,签名过程需要使用 * @param [type] $urlparams [description] * @param [type] $needurlencode [description] */ public function tourlparams($urlparams, $needurlencode) { $buff = ""; ksort($urlparams); foreach ($urlparams as $k => $v) { if($needurlencode) $v = urlencode($v); $buff .= $k .'='. $v .'&'; } $reqstring = ''; if (strlen($buff) > 0) { $reqstring = substr($buff, 0, strlen($buff) - 1); } return $reqstring; } /** * 生成签名 * @param [type] $params [description] * @return [type] [description] */ public function getsign($obj) { foreach ($obj as $k => $v) { $params[$k] = $v; } //签名步骤一:按字典序排序参数 ksort($params); $str = $this->tourlparams($params, false); //签名步骤二:在$str后加入key $str = $str.$key=.wxpayconf::key; //签名步骤三:md5加密 $str = md5($str); //签名步骤四:所有字符转为大写 $result = strtoupper($str); return $result; } /** * array转xml * @param [type] $arr [description] * @return [type] [description] */ public function arraytoxml($arr) { $xml = <xml>; foreach ($arr as $k => $v) { if (is_numeric($val)) { $xml .= <".$key.">.$key.</".$key.">; } else { $xml .= <".$key."><![cdata[".$val."]]></".$key.">; } } $xml .= </xml>; return $xml; } /** * 将xml转为array * @param [type] $xml [description] * @return [type] [description] */ public function xmltoarray($xml) { $arr = json_decode(json_encode(simplexml_load_string($xml, 'sinplexmlelement', libxml_nocdata)), true); return $arr; } /** * 以post方式提交xml到对应的接口 * @param [type] $xml [description] * @param [type] $url [description] * @param integer $second [description] * @return [type] [description] */ public function postxmlcurl($xml, $url, $second = 30) { //初始化curl $ch = curl_init(); //设置超时 curl_setopt($ch, curl_timeout, $second); curl_setopt($ch, curl_url, $url); //这里设置代理,如果有的话 //curl_setopt($ch,curlopt_proxy, '8.8.8.8'); //curl_setopt($ch,curlopt_proxyport, 8080); curl_setopt($ch, curl_ssl_verifyhost, false); curl_setopt($ch, curl_ssl_verifypeer, false); //设置header curl_setopt($ch, curl_header, false); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, curl_returntransfer, true); //以post方式提交 curl_setopt($ch, curl_post, true); curl_setopt($ch, curl_postfields, $xml); //执行curl $res = curl_exec($ch); if ($res) { curl_close($ch); return $res; } else { $error = curl_errno($ch); echo curl出错,错误码:$error.<br>; echo <a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>; curl_close($ch); return false; } } } /** * 配置类 */ class wxpayconf { //微信公众号身份的唯一标识。 const appid = 'wx654a22c6423213b7'; //受理商id,身份标识 const mchid = '10043241'; const mchname = 'kellycen的博客'; //商户支付密钥key。 const key = '0000000000000000000000000000000'; //jsapi接口中获取openid const appsecret = '000000000000000000000000000'; //证书路径,注意应该填写绝对路径 const sslcert_path = '/home/wxpaycacert/apiclient_cert.pem'; const sslkey_path = '/home/wxpaycacert/apiclient_key.pem'; const sslca_path = '/home/wxpaycacert/rootca.pem'; //本例程通过curl使用http post方法,此处可修改其超时时间,默认为30秒 const curl_timeout = 30; } wxpay_model.php
wxpay_model.php
获取到code的url后,将其分配到页面去,让用户去点击,用户进行点击后,就会从微信服务器获取到code,然后回调到redirect_uri所指的地址去。
2、获取到code后,会回调到redirect_uri所指向的地址去,这里是到了/wxpay/confirm/,看看这个confirm方法是打算干嘛的:
/** * 手机端微信支付,此处是授权获取到code时的回调地址 * @param [type] $orderid 订单编号id * @return [type] [description] */ public function confirm($orderid) { //先确认用户是否登录 $this->ensurelogin(); //通过订单编号获取订单数据 $order = $this->wxpay_model->get($orderid); //验证订单是否是当前用户 $this->_verifyuser($order); //取得支付所需要的订单数据 $orderdata = $this->returnorderdata[$orderid]; //取得jsapi所需要的数据 $wxjsapidata = $this->wxpay_model->wxpayjsapi($orderdata); //将数据分配到模板去,在js里使用 $this->smartydata['wxjsapidata'] = json_encode($wxjsapidata, json_unescaped_unicode); $this->smartydata['order'] = $orderdata; $this->displayview('wxpay/confirm.tpl'); }
这一步开始去取jsapi支付接口所需要的数据了,这一步算是最主要的一步,这里还会调用统一下单接口获取到prepay_id,我们跳到
$this->wxpay_model->wxpayjsapi($orderdata) 看看:
/** * 微信jsapi点击支付 * @param [type] $data [description] * @return [type] [description] */ public function wxpayjsapi($data) { $jsapi = new jsapi_handle(); //统一下单接口所需数据 $paydata = $this->returndata($data); //获取code码,用以获取openid $code = $_get['code']; $jsapi->setcode($code); //通过code获取openid $openid = $jsapi->getopenid(); $unifiedorderresult = null; if ($openid != null) { //取得统一下单接口返回的数据 $unifiedorderresult = $this->getresult($paydata, 'jsapi', $openid); //获取订单接口状态 $returnmessage = $this->returnmessage($unifiedorder, 'prepay_id'); if ($returnmessage['resultcode']) { $jsapi->setprepayid($retuenmessage['resultfield']); //取得wxjsapi接口所需要的数据 $returnmessage['resultdata'] = $jsapi->getparams(); } return $returnmessage; } }
这里首先是取得下单接口所需要的数据;
接着获取到code码,通过code码获取到openid;
然后调用统一下单接口,取得下单接口的响应数据,即prepay_id;
最后取得微信支付jsapi所需要的数据。
这就是上面这个方法所要做的事情,取到数据后,会将数据分配到模板里,然后根据官方文档所给的参考格式将其放在js里,如下面的代码:
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <!-- make sure that we can test against real ie8 --> <meta http-equiv="x-ua-compatible" content="ie=8" /> <title></title> </head> <body> <a href="javascript:callpay();" id="btnorder">点击支付</a> </body> <script type="text/javascript"> //将数据付给js变量 var wxjsapidata = {$wxjsapidata}; function onbridgeready() { //格式参考官方文档 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6 weixinjsbridge.invoke( 'getbrandwcpayrequest', $.parsejson(wxjsapidata.resultdata), function(res){ if(res.err_msg == get_brand_wcpay_request:ok ){ window.location.href=/wxpay/paysuccess/+{$order.sn}; } } ); } function callpay() { if(!wxjsapidata.resultcode){ alert(wxjsapidata.resulttype+,+wxjsapidata.resultmsg+!); return false; } if (typeof weixinjsbridge == undefined){ if( document.addeventlistener ){ document.addeventlistener('weixinjsbridgeready', onbridgeready, false); }else if (document.attachevent){ document.attachevent('weixinjsbridgeready', onbridgeready); document.attachevent('onweixinjsbridgeready', onbridgeready); } }else{ onbridgeready(); } } </script> </html>
3、此时用户只需要点击支付,就可以开始进入支付界面了,接着就是输入密码,确认,最后会提示支付成功,紧接着网站会提供一个支付成功跳转页面。类似微信文档里所提供的图片这样,这里我就直接截取文档里的案例图了:
4、这里还有一步,就是微信支付系统会异步通知网站后台用户的支付结果。在获取统一下单数据时,我们指定了一个通知地址,在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的微信支付接口开发详解就讲到这里,如果你认真理清博文里所讲解的思路,自己基本上也可以尝试开发此接口了,同时只要会了这个,你也基本上可以开发二维码支付,刷卡支付等等的支付接口。
这里我附上此次开发中的完整代码供大家阅读:
<?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'); } /** * 手机端微信支付,此处是授权获取到code时的回调地址 * @param [type] $orderid 订单编号id * @return [type] [description] */ public function confirm($orderid) { //先确认用户是否登录 $this->ensurelogin(); //通过订单编号获取订单数据 $order = $this->wxpay_model->get($orderid); //验证订单是否是当前用户 $this->_verifyuser($order); //取得支付所需要的订单数据 $orderdata = $this->returnorderdata[$orderid]; //取得jsapi所需要的数据 $wxjsapidata = $this->wxpay_model->wxpayjsapi($orderdata); //将数据分配到模板去,在js里使用 $this->smartydata['wxjsapidata'] = json_encode($wxjsapidata, json_unescaped_unicode); $this->smartydata['order'] = $orderdata; $this->displayview('wxpay/confirm.tpl'); } /** * 支付回调接口 * @return [type] [description] */ public function pay_callback() { $postdata = ''; if (file_get_contents(php://input)) { $postdata = file_get_contents(php://input); } else { return; } $payinfo = array(); $notify = $this->wxpay_model->wxpaynotify($postdata); if ($notify->checksign == true) { if ($notify->data['return_code'] == 'fail') { $payinfo['status'] = false; $payinfo['msg'] = '通信出错'; } elseif ($notify->data['result_code'] == 'fail') { $payinfo['status'] = false; $payinfo['msg'] = '业务出错'; } else { $payinfo['status'] = true; $payinfo['msg'] = '支付成功'; $payinfo['sn']=substr($notify->data['out_trade_no'],8); $payinfo['order_no'] = $notify->data['out_trade_no']; $payinfo['platform_no']=$notify->data['transaction_id']; $payinfo['attach']=$notify->data['attach']; $payinfo['fee']=$notify->data['cash_fee']; $payinfo['currency']=$notify->data['fee_type']; $payinfo['user_sign']=$notify->data['openid']; } } $returnxml = $notify->returnxml(); echo $returnxml; $this->load->library('rediscache'); if($payinfo['status']){ //这里要记录到日志处理(略) $this->model->order->onpaysuccess($payinfo['sn'], $payinfo['order_no'], $payinfo['platform_no'],'', $payinfo['user_sign'], $payinfo); $this->redis->rediscache->set('order:payno:'.$payinfo['order_no'],'ok',5000); }else{ //这里要记录到日志处理(略) $this->model->order->onpayfailure($payinfo['sn'], $payinfo['order_no'], $payinfo['platform_no'],'', $payinfo['user_sign'], $payinfo, '订单支付失败 ['.$payinfo['msg'].']'); } } /** * 返回支付所需要的数据 * @param [type] $orderid 订单号 * @param string $data 订单数据,当$data数据存在时刷新$orderdata缓存,因为订单号不唯一 * @return [type] [description] */ public function returnorderdata($orderid, $data = '') { //获取订单数据 $order = $this->wxpay_model->get($orderid); if (0 === count($order)) return false; if (empty($data)) { $this->load->library('rediscache'); //取得缓存在redis的订单数据 $orderdata = $this->rediscache->getjson(order:orderdata:.$orderid); if (empty($orderdata)) { //如果redis里没有,则直接读数据库取 $this->load->model('order_model'); $order = $this->order_model->get($orderid); if (0 === count($order)) { return false; } $data = $order; } else { //如果redis里面有的话,直接返回数据 return $orderdata; } } //支付前缓存所需要的数据 $orderdata['id'] = $data['id']; $orderdata['fee'] = $data['fee']; //支付平台需要的数据 $orderdata['user_id'] = $data['user_id']; $orderdata['sn'] = $data['cn']; //这是唯一编号 $orderdata['order_no'] = substr(md5($data['sn'].$data['fee']), 8, 8).$data['sn']; $orderdata['fee'] = $data['fee']; $orderdata['time'] = $data['time']; $orderdata['goods_name'] = $data['goods_name']; $orderdata['attach'] = $data['attach']; //将数据缓存到redis里面 $this->rediscache->set(order:orderdata:.$orderid, $orderdata, 3600*24); //做个标识缓存到redis,用以判断该订单是否已经支付了 $this->rediscache->set(order:payno:.$orderdata['order_no'], no, 3600*24); return $orderdata; } private function _verifyuser($order) { if (empty($order)) show_404(); if (0 === count($order)) show_404(); //判断订单表里的用户id是否是当前登录者的id if ($order['user_id'] == $this->uid) return; show_error('只能查看自己的订单'); } } 控制器:wxpay.php
控制器:wxpay.php
<?php defined('basepath') or exit('no direct script access allowed'); class wxpay_model extends ci_model { public function __construct() { parent::__construct(); } /** * 返回可以获得微信code的url (用以获取openid) * @return [type] [description] */ public function retwxpayurl() { $jsapi = new jsapi_handle(); return $jsapi->createoauthurlforcode(); } /** * 微信jsapi点击支付 * @param [type] $data [description] * @return [type] [description] */ public function wxpayjsapi($data) { $jsapi = new jsapi_handle(); //统一下单接口所需数据 $paydata = $this->returndata($data); //获取code码,用以获取openid $code = $_get['code']; $jsapi->setcode($code); //通过code获取openid $openid = $jsapi->getopenid(); $unifiedorderresult = null; if ($openid != null) { //取得统一下单接口返回的数据 $unifiedorderresult = $this->getresult($paydata, 'jsapi', $openid); //获取订单接口状态 $returnmessage = $this->returnmessage($unifiedorder, 'prepay_id'); if ($returnmessage['resultcode']) { $jsapi->setprepayid($retuenmessage['resultfield']); //取得wxjsapi接口所需要的数据 $returnmessage['resultdata'] = $jsapi->getparams(); } return $returnmessage; } } /** * 统一下单接口所需要的数据 * @param [type] $data [description] * @return [type] [description] */ public function returndata($data) { $paydata['sn'] = $data['sn']; $paydata['body'] = $data['goods_name']; $paydata['out_trade_no'] = $data['order_no']; $paydata['total_fee'] = $data['fee']; $paydata['attach'] = $data['attach']; return $paydata; } /** * 返回统一下单接口结果 (参考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1) * @param [type] $paydata [description] * @param [type] $trade_type [description] * @param [type] $openid [description] * @return [type] [description] */ public function getresult($paydata, $trade_type, $openid = null) { $unifiedorder = new unifiedorder_handle(); if ($opneid != null) { $unifiedorder->setparam('openid', $openid); } $unifiedorder->setparam('body', $paydata['body']); //商品描述 $unifiedorder->setparam('out_trade_no', $paydata['out_trade_no']); //商户订单号 $unifiedorder->setparam('total_fee', $paydata['total_fee']); //总金额 $unifiedorder->setparam('attach', $paydata['attach']); //附加数据 $unifiedorder->setparam('notify_url', base_url('/wxpay/pay_callback'));//通知地址 $unifiedorder->setparam('trade_type', $trade_type); //交易类型 //非必填参数,商户可根据实际情况选填 //$unifiedorder->setparam(sub_mch_id,xxxx);//子商户号 //$unifiedorder->setparam(device_info,xxxx);//设备号 //$unifiedorder->setparam(time_start,xxxx);//交易起始时间 //$unifiedorder->setparam(time_expire,xxxx);//交易结束时间 //$unifiedorder->setparam(goods_tag,xxxx);//商品标记 //$unifiedorder->setparam(product_id,xxxx);//商品id return $unifiedorder->getresult(); } /** * 返回微信订单状态 */ public function returnmessage($unifiedorderresult,$field){ $arrmessage=array(resultcode=>0,resulttype=>获取错误,resultmsg=>该字段为空); if($unifiedorderresult==null){ $arrmessage[resulttype]=未获取权限; $arrmessage[resultmsg]=请重新打开页面; }elseif ($unifiedorderresult[return_code] == fail) { $arrmessage[resulttype]=网络错误; $arrmessage[resultmsg]=$unifiedorderresult['return_msg']; } elseif($unifiedorderresult[result_code] == fail) { $arrmessage[resulttype]=订单错误; $arrmessage[resultmsg]=$unifiedorderresult['err_code_des']; } elseif($unifiedorderresult[$field] != null) { $arrmessage[resultcode]=1; $arrmessage[resulttype]=生成订单; $arrmessage[resultmsg]=ok; $arrmessage[resultfield] = $unifiedorderresult[$field]; } return $arrmessage; } /** * 微信回调接口返回 验证签名并回应微信 * @param [type] $xml [description] * @return [type] [description] */ public function wxpaynotify($xml) { $notify = new wxpay_server(); $notify->savedata($xml); //验证签名,并回复微信 //对后台通知交互时,如果微信收到商户的应答不是成功或者超时,微信认为通知失败 //微信会通过一定的策略(如30分钟共8次),定期重新发起通知 if ($notify->checksign() == false) { $notify->setreturnparameter(return_code,fail);//返回状态码 $notify->setreturnparameter(return_msg,签名失败);//返回信息 } else { $notify->checksign=true; $notify->setreturnparameter(return_code,success);//设置返回码 } return $notify; } } /** * jsapi支付——h5网页端调起支付接口 */ class jsapi_handle extends jsapi_common { public $code;//code码,用以获取openid public $openid;//用户的openid public $parameters;//jsapi参数,格式为json public $prepay_id;//使用统一支付接口得到的预支付id public $curl_timeout;//curl超时时间 function __construct() { //设置curl超时时间 $this->curl_timeout = wxpayconf::curl_timeout; } /** * 生成获取code的url * @return [type] [description] */ public function createoauthurlforcode() { //重定向url $redirecturl = http://www.itcen.cn/wxpay/confirm/.$orderid.?showwxpaytitle=1; $urlparams['appid'] = wxpayconf::appid; $urlparams['redirect_uri'] = $redirecturl; $urlparams['response_type'] = 'code'; $urlparams['scope'] = 'snsapi_base'; $urlparams['state'] = state.#wechat_redirect; //拼接字符串 $querystring = $this->tourlparams($urlparams, false); return https://open.weixin.qq.com/connect/oauth2/authorize?.$querystring; } /** * 设置code * @param [type] $code [description] */ public function setcode($code) { $this->code = $code; } /** * 作用:设置prepay_id */ public function setprepayid($prepayid) { $this->prepay_id = $prepayid; } /** * 作用:获取jsapi的参数 */ public function getparams() { $jsapiobj[appid] = wxpayconf::appid; $timestamp = time(); $jsapiobj[timestamp] = $timestamp; $jsapiobj[noncestr] = $this->createnoncestr(); $jsapiobj[package] = prepay_id=$this->prepay_id; $jsapiobj[signtype] = md5; $jsapiobj[paysign] = $this->getsign($jsapiobj); $this->parameters = json_encode($jsapiobj); return $this->parameters; } /** * 通过curl 向微信提交code 用以获取openid * @return [type] [description] */ public function getopenid() { //创建openid 的链接 $url = $this->createoauthurlforopenid(); //初始化 $ch = curl_init(); curl_setopt($ch, curl_timeout, $this->curl_timeout); curl_setopt($ch, curl_url, $url); curl_setopt($ch, curl_ssl_verifypeer, false); curl_setopt($ch, curl_ssl_verifyhost, false); curl_setopt($ch, curl_header, false); curl_setopt($ch, curl_returntransfer, true); //执行curl $res = curl_exec($ch); curl_close($ch); //取出openid $data = json_decode($res); if (isset($data['openid'])) { $this->openid = $data['openid']; } else { return null; } return $this->openid; } /** * 生成可以获取openid 的url * @return [type] [description] */ public function createoauthurlforopenid() { $urlparams['appid'] = wxpayconf::appid; $urlparams['secret'] = wxpayconf::appsecret; $urlparams['code'] = $this->code; $urlparams['grant_type'] = authorization_code; $querystring = $this->tourlparams($urlparams, false); return https://api.weixin.qq.com/sns/oauth2/access_token?.$querystring; } } /** * 统一下单接口类 */ class unifiedorder_handle extends wxpay_client_handle { public function __construct() { //设置接口链接 $this->url = https://api.mch.weixin.qq.com/pay/unifiedorder; //设置curl超时时间 $this->curl_timeout = wxpayconf::curl_timeout; } } /** * 响应型接口基类 */ class wxpay_server_handle extends jsapi_common{ public $data; //接收到的数据,类型为关联数组 public $returnparams; //返回参数,类型为关联数组 /** * 将微信请求的xml转换成关联数组 * @param [type] $xml [description] * @return [type] [description] */ public function savedata($xml) { $this->data = $this->xmltoarray($xml); } /** * 验证签名 * @return [type] [description] */ public function checksign() { $tmpdata = $this->data; unset($temdata['sign']); $sign = $this->getsign($tmpdata); if ($this->data['sign'] == $sign) { return true; } return false; } /** * 设置返回微信的xml数据 */ function setreturnparameter($parameter, $parametervalue) { $this->returnparameters[$this->trimstring($parameter)] = $this->trimstring($parametervalue); } /** * 将xml数据返回微信 */ function returnxml() { $returnxml = $this->createxml(); return $returnxml; } } /** * 请求型接口的基类 */ class wxpay_client_handle extends jsapi_common{ public $params; //请求参数,类型为关联数组 public $response; //微信返回的响应 public $result; //返回参数,类型类关联数组 public $url; //接口链接 public $curl_timeout; //curl超时时间 /** * 设置请求参数 * @param [type] $param [description] * @param [type] $paramvalue [description] */ public function setparam($param, $paramvalue) { $this->params[$this->tirmstring($param)] = $this->trimstring($paramvalue); } /** * 获取结果,默认不使用证书 * @return [type] [description] */ public function getresult() { $this->postxml(); $this->result = $this->xmltoarray($this->response); return $this->result; } /** * post请求xml * @return [type] [description] */ public function postxml() { $xml = $this->createxml(); $this->response = $this->postxmlcurl($xml, $this->curl, $this->curl_timeout); return $this->response; } public function createxml() { $this->params['appid'] = wxpayconf::appid; //公众号id $this->params['mch_id'] = wxpayconf::mchid; //商户号 $this->params['nonce_str'] = $this->createnoncestr(); //随机字符串 $this->params['sign'] = $this->getsign($this->params); //签名 return $this->arraytoxml($this->params); } } /** * 所有接口的基类 */ class jsapi_common { function __construct() { } public function trimstring($value) { $ret = null; if (null != $value) { $ret = trim($value); if (strlen($ret) == 0) { $ret = null; } } return $ret; } /** * 产生随机字符串,不长于32位 * @param integer $length [description] * @return [type] [description] */ public function createnoncestr($length = 32) { $chars = abcdefghijklmnopqrstuvwxyz0123456789; $str = ''; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } /** * 格式化参数 拼接字符串,签名过程需要使用 * @param [type] $urlparams [description] * @param [type] $needurlencode [description] */ public function tourlparams($urlparams, $needurlencode) { $buff = ""; ksort($urlparams); foreach ($urlparams as $k => $v) { if($needurlencode) $v = urlencode($v); $buff .= $k .'='. $v .'&'; } $reqstring = ''; if (strlen($buff) > 0) { $reqstring = substr($buff, 0, strlen($buff) - 1); } return $reqstring; } /** * 生成签名 * @param [type] $params [description] * @return [type] [description] */ public function getsign($obj) { foreach ($obj as $k => $v) { $params[$k] = $v; } //签名步骤一:按字典序排序参数 ksort($params); $str = $this->tourlparams($params, false); //签名步骤二:在$str后加入key $str = $str.$key=.wxpayconf::key; //签名步骤三:md5加密 $str = md5($str); //签名步骤四:所有字符转为大写 $result = strtoupper($str); return $result; } /** * array转xml * @param [type] $arr [description] * @return [type] [description] */ public function arraytoxml($arr) { $xml = <xml>; foreach ($arr as $k => $v) { if (is_numeric($val)) { $xml .= <".$key.">.$key.</".$key.">; } else { $xml .= <".$key."><![cdata[".$val."]]></".$key.">; } } $xml .= </xml>; return $xml; } /** * 将xml转为array * @param [type] $xml [description] * @return [type] [description] */ public function xmltoarray($xml) { $arr = json_decode(json_encode(simplexml_load_string($xml, 'sinplexmlelement', libxml_nocdata)), true); return $arr; } /** * 以post方式提交xml到对应的接口 * @param [type] $xml [description] * @param [type] $url [description] * @param integer $second [description] * @return [type] [description] */ public function postxmlcurl($xml, $url, $second = 30) { //初始化curl $ch = curl_init(); //设置超时 curl_setopt($ch, curl_timeout, $second); curl_setopt($ch, curl_url, $url); //这里设置代理,如果有的话 //curl_setopt($ch,curlopt_proxy, '8.8.8.8'); //curl_setopt($ch,curlopt_proxyport, 8080); curl_setopt($ch, curl_ssl_verifyhost, false); curl_setopt($ch, curl_ssl_verifypeer, false); //设置header curl_setopt($ch, curl_header, false); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, curl_returntransfer, true); //以post方式提交 curl_setopt($ch, curl_post, true); curl_setopt($ch, curl_postfields, $xml); //执行curl $res = curl_exec($ch); if ($res) { curl_close($ch); return $res; } else { $error = curl_errno($ch); echo curl出错,错误码:$error.<br>; echo <a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>; curl_close($ch); return false; } } } /** * 配置类 */ class wxpayconf { //微信公众号身份的唯一标识。 const appid = 'wx654a22c6423213b7'; //受理商id,身份标识 const mchid = '10043241'; const mchname = 'kellycen的博客'; //商户支付密钥key。 const key = '0000000000000000000000000000000'; //jsapi接口中获取openid const appsecret = '000000000000000000000000000'; //证书路径,注意应该填写绝对路径 const sslcert_path = '/home/wxpaycacert/apiclient_cert.pem'; const sslkey_path = '/home/wxpaycacert/apiclient_key.pem'; const sslca_path = '/home/wxpaycacert/rootca.pem'; //本例程通过curl使用http post方法,此处可修改其超时时间,默认为30秒 const curl_timeout = 30; } 模型:wxpay_model.php
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <!-- make sure that we can test against real ie8 --> <meta http-equiv="x-ua-compatible" content="ie=8" /> <title></title> </head> <body> <a href="{$wxpayurl}">微信支付</a> </body> </html> 视图:index.tpl
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- make sure that we can test against real ie8 -->
<meta http-equiv="x-ua-compatible" content="ie=8" />
<title></title>
</head>
<body>
<a href="javascript:callpay();" id="btnorder">点击支付</a>
</body>
<script type="text/javascript">
//将数据付给js变量
var wxjsapidata = {$wxjsapidata};
function onbridgeready()
{
//格式参考官方文档 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
weixinjsbridge.invoke(
'getbrandwcpayrequest',
$.parsejson(wxjsapidata.resultdata),
function(res){
if(res.err_msg == get_brand_wcpay_request:ok ){
window.location.href=/wxpay/paysuccess/+{$order.sn};
}
}
);
}
function callpay()
{
if(!wxjsapidata.resultcode){
alert(wxjsapidata.resulttype+,+wxjsapidata.resultmsg+!);
return false;
}
if (typeof weixinjsbridge == undefined){
if( document.addeventlistener ){
document.addeventlistener('weixinjsbridgeready', onbridgeready, false);
}else if (document.attachevent){
document.attachevent('weixinjsbridgeready', onbridgeready);
document.attachevent('onweixinjsbridgeready', onbridgeready);
}
}else{
onbridgeready();
}
}
</script>
</html>
视图:confirm.tpl
里面所用到的一些自定义函数可以在我上一篇博文里找找,那里已经提供了代码参考了。
更多基于h5的微信支付开发详解 。
