作者 郭鑫
1 个管道 的构建 通过 耗费 1 秒

雇人修改

要显示太多修改。

为保证性能只显示 23 of 23+ 个文件。

  1 +<?php
  2 +// +----------------------------------------------------------------------
  3 +// | bronet [ 以客户为中心 以奋斗者为本 ]
  4 +// +----------------------------------------------------------------------
  5 +// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
  6 +// +----------------------------------------------------------------------
  7 +// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8 +// +----------------------------------------------------------------------
  9 +namespace app\portal\controller;
  10 +
  11 +use cmf\controller\HomeBaseController;
  12 +use think\Db;
  13 +
  14 +
  15 +
  16 +class SomepayController extends HomeBaseController
  17 +{
  18 + public function _initialize()
  19 + {
  20 + parent::_initialize();
  21 +// 微信
  22 + require_once EXTEND_PATH . "WxpayAPI/lib/WxPay.Api.php";
  23 + require_once EXTEND_PATH . "WxpayAPI/example/WxPay.JsApiPay.php";
  24 + require_once EXTEND_PATH . "WxpayAPI/lib/WxPay.Notify.php";
  25 + require_once EXTEND_PATH . 'WxpayAPI/example/log.php';
  26 + }
  27 +
  28 +// 微信支付
  29 + public function pay($openId , $price , $order_sn , $url,$content)
  30 + {
  31 + $price = intval($price * 100);
  32 + $tools = new \JsApiPay();
  33 + $input = new \WxPayUnifiedOrder();
  34 + $input->SetBody($content);
  35 + $input->SetAttach($content);
  36 + $input->SetOut_trade_no($order_sn);
  37 + $input->SetTotal_fee($price);
  38 + $input->SetTime_start(date("YmdHis"));
  39 + $input->SetTime_expire(date("YmdHis", time() + 600));
  40 + $input->SetGoods_tag($content);
  41 + $input->SetNotify_url($url);
  42 + $input->SetTrade_type("JSAPI");
  43 + $input->SetOpenid($openId);
  44 + $config = new \WxPayConfig();
  45 + $order = \WxPayApi::unifiedOrder($config, $input);
  46 + $jsApiParameters = $tools->GetJsApiParameters($order);
  47 + return json_decode($jsApiParameters);
  48 + }
  49 +
  50 +
  51 +
  52 +
  53 +
  54 + //微信回调
  55 + public function pay_notify()
  56 + {
  57 + $config = new \WxPayConfig();
  58 + $notify = new \WxPayNotify();
  59 + $notify->Handle($config, false);
  60 + $xml = file_get_contents("php://input");
  61 + $base = new \WxPayResults();
  62 + $data = $base->FromXml($xml);
  63 + //验签
  64 + if ($base->CheckSign($config)) {
  65 + if ($data["return_code"] == "SUCCESS") {
  66 + $a['c'] = json_decode($data);
  67 + Db::name('Test')->insertGetId($a);
  68 +// 支付成功
  69 +// Db::startTrans();
  70 +//// 更新主表状态
  71 +// $where_orderN['order_sn'] = $data['out_trade_no'];
  72 +// $where_orderN['status'] = 2;
  73 +// $order = Db::name('Order')->where($where_orderN)->find();
  74 +
  75 +
  76 + }
  77 + }
  78 + }
  79 +
  80 +
  81 +
  82 +
  83 +}
  1 +SDK
  2 +体验地址
  3 +http://paysdk.weixin.qq.com/
  4 +
  5 +快速搭建指南
  6 +①、安装配置nginx+phpfpm+php
  7 +②、建SDK解压到网站根目录
  8 +③、修改lib/WxPay.Config.php为自己申请的商户号的信息(配置详见说明)
  9 +⑤、下载证书替换cert下的文件
  10 +⑥、搭建完成
  11 +
  12 +SDK目录结构
  13 +|-- lib
  14 +|-- logs
  15 +`-- example
  16 +
  17 +
  18 +目录功能简介
  19 +lib
  20 +API接口封装代码
  21 +WxPay.Api.php 包括所有微信支付API接口的封装
  22 +WxPay.Config.Interface.php 商户配置 , 业务需要从这里继承(请注意保管自己的密钥/证书等)
  23 +WxPay.Data.php 输入参数封装
  24 +WxPay.Exception.php 异常类
  25 +WxPay.Notify.php 回调通知基类
  26 +
  27 +cert
  28 +证书存放路径,证书可以登录商户平台https://pay.weixin.qq.com/index.php/account/api_cert下载
  29 +注意:
  30 +1.证书文件不能放在web服务器虚拟目录,应放在有访问权限控制的目录中,防止被他人下载;
  31 +2.建议将证书文件名改为复杂且不容易猜测的文件名;
  32 +3.商户服务器要做好病毒和木马防护工作,不被非法侵入者窃取证书文件。
  33 +
  34 +example
  35 +样例程序代码路径
  36 +
  37 +example/phpqrcode
  38 +开源二维码php代码
  39 +
  40 +logs
  41 +日志文件
  42 +
  43 +※配置指南
  44 +MCHID = '1225312702';
  45 +这里填开户邮件中的商户号
  46 +
  47 +APPID = 'wx426b3015555a46be';
  48 +这里填开户邮件中的(公众账号APPID或者应用APPID)
  49 +
  50 +KEY = 'e10adc3949ba59abbe56e057f20f883e'
  51 +这里请使用商户平台登录账户和密码登录http://pay.weixin.qq.com 平台设置的“API密钥”,为了安全,请设置为32字符串。
  52 +
  53 +APPSECRET = '01c6d59a3f9024db6336662ac95c8e74'
  54 +改参数在JSAPI支付(open平台账户不能进行JSAPI支付)的时候需要用来获取用户openid,可使用APPID对应的公众平台登录http://mp.weixin.qq.com 的开发者中心获取AppSecret。
  55 +
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +require_once EXTEND_PATH . "WxpayAPI/lib/WxPay.Config.Interface.php";
  10 +
  11 +/**
  12 +*
  13 +* 该类需要业务自己继承, 该类只是作为deamon使用
  14 +* 实际部署时,请务必保管自己的商户密钥,证书等
  15 +*
  16 +*/
  17 +
  18 +class WxPayConfig extends WxPayConfigInterface
  19 +{
  20 + //=======【基本信息设置】=====================================
  21 + /**
  22 + * TODO: 修改这里配置为您自己申请的商户信息
  23 + * 微信公众号信息配置
  24 + *
  25 + * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
  26 + *
  27 + * MCHID:商户号(必须配置,开户邮件中可查看)
  28 + *
  29 + */
  30 + public function GetAppId()
  31 + {
  32 + return 'wx100c2e5f27e34b92';
  33 + }
  34 + public function GetMerchantId()
  35 + {
  36 + return '1511142881';
  37 + }
  38 +
  39 + //=======【支付相关配置:支付成功回调地址/签名方式】===================================
  40 + /**
  41 + * TODO:支付回调url
  42 + * 签名和验证签名方式, 支持md5和sha256方式
  43 + **/
  44 + public function GetNotifyUrl()
  45 + {
  46 + return "";
  47 + }
  48 + public function GetSignType()
  49 + {
  50 + return "MD5";
  51 + }
  52 +
  53 + //=======【curl代理设置】===================================
  54 + /**
  55 + * TODO:这里设置代理机器,只有需要代理的时候才设置,不需要代理,请设置为0.0.0.0和0
  56 + * 本例程通过curl使用HTTP POST方法,此处可修改代理服务器,
  57 + * 默认CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0,此时不开启代理(如有需要才设置)
  58 + * @var unknown_type
  59 + */
  60 + public function GetProxy(&$proxyHost, &$proxyPort)
  61 + {
  62 + $proxyHost = "0.0.0.0";
  63 + $proxyPort = 0;
  64 + }
  65 +
  66 +
  67 + //=======【上报信息配置】===================================
  68 + /**
  69 + * TODO:接口调用上报等级,默认紧错误上报(注意:上报超时间为【1s】,上报无论成败【永不抛出异常】,
  70 + * 不会影响接口调用流程),开启上报之后,方便微信监控请求调用的质量,建议至少
  71 + * 开启错误上报。
  72 + * 上报等级,0.关闭上报; 1.仅错误出错上报; 2.全量上报
  73 + * @var int
  74 + */
  75 + public function GetReportLevenl()
  76 + {
  77 + return 1;
  78 + }
  79 +
  80 +
  81 + //=======【商户密钥信息-需要业务方继承】===================================
  82 + /*
  83 + * KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置), 请妥善保管, 避免密钥泄露
  84 + * 设置地址:https://pay.weixin.qq.com/index.php/account/api_cert
  85 + *
  86 + * APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置, 登录公众平台,进入开发者中心可设置), 请妥善保管, 避免密钥泄露
  87 + * 获取地址:https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN
  88 + * @var string
  89 + */
  90 + public function GetKey()
  91 + {
  92 + return 'hfrT4YKO3teQqOkdSFTY9RGvtAErieV5';
  93 + }
  94 + public function GetAppSecret()
  95 + {
  96 + return '4de2264efb220ea89c1095580f4f4350';
  97 + }
  98 +
  99 +
  100 + //=======【证书路径设置-需要业务方继承】=====================================
  101 + /**
  102 + * TODO:设置商户证书路径
  103 + * 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要,可登录商户平台下载,
  104 + * API证书下载地址:https://pay.weixin.qq.com/index.php/account/api_cert,下载之前需要安装商户操作证书)
  105 + * 注意:
  106 + * 1.证书文件不能放在web服务器虚拟目录,应放在有访问权限控制的目录中,防止被他人下载;
  107 + * 2.建议将证书文件名改为复杂且不容易猜测的文件名;
  108 + * 3.商户服务器要做好病毒和木马防护工作,不被非法侵入者窃取证书文件。
  109 + * @var path
  110 + */
  111 + public function GetSSLCertPath(&$sslCertPath, &$sslKeyPath)
  112 + {
  113 + $sslCertPath = '../cert/apiclient_cert.pem';
  114 + $sslKeyPath = '../cert/apiclient_key.pem';
  115 + }
  116 +}
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +require_once EXTEND_PATH . "WxpayAPI/lib/WxPay.Api.php";
  10 +require_once "WxPay.Config.php";
  11 +/**
  12 + *
  13 + * JSAPI支付实现类
  14 + * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、
  15 + * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数
  16 + *
  17 + * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发
  18 + *
  19 + * @author widy
  20 + *
  21 + */
  22 +class JsApiPay
  23 +{
  24 + /**
  25 + *
  26 + * 网页授权接口微信服务器返回的数据,返回样例如下
  27 + * {
  28 + * "access_token":"ACCESS_TOKEN",
  29 + * "expires_in":7200,
  30 + * "refresh_token":"REFRESH_TOKEN",
  31 + * "openid":"OPENID",
  32 + * "scope":"SCOPE",
  33 + * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
  34 + * }
  35 + * 其中access_token可用于获取共享收货地址
  36 + * openid是微信支付jsapi支付接口必须的参数
  37 + * @var array
  38 + */
  39 + public $data = null;
  40 +
  41 + /**
  42 + *
  43 + * 通过跳转获取用户的openid,跳转流程如下:
  44 + * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
  45 + * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
  46 + *
  47 + * @return 用户的openid
  48 + */
  49 + public function GetOpenid()
  50 + {
  51 + //通过code获得openid
  52 + if (!isset($_GET['code'])){
  53 + //触发微信返回code码
  54 + $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
  55 + $url = $this->_CreateOauthUrlForCode($baseUrl);
  56 + Header("Location: $url");
  57 + exit();
  58 + } else {
  59 + //获取code码,以获取openid
  60 + $code = $_GET['code'];
  61 + $openid = $this->getOpenidFromMp($code);
  62 + return $openid;
  63 + }
  64 + }
  65 +
  66 + /**
  67 + *
  68 + * 获取jsapi支付的参数
  69 + * @param array $UnifiedOrderResult 统一支付接口返回的数据
  70 + * @throws WxPayException
  71 + *
  72 + * @return json数据,可直接填入js函数作为参数
  73 + */
  74 + public function GetJsApiParameters($UnifiedOrderResult)
  75 + {
  76 + if(!array_key_exists("appid", $UnifiedOrderResult)
  77 + || !array_key_exists("prepay_id", $UnifiedOrderResult)
  78 + || $UnifiedOrderResult['prepay_id'] == "")
  79 + {
  80 + throw new WxPayException("参数错误");
  81 + }
  82 +
  83 + $jsapi = new WxPayJsApiPay();
  84 + $jsapi->SetAppid($UnifiedOrderResult["appid"]);
  85 + $timeStamp = time();
  86 + $jsapi->SetTimeStamp("$timeStamp");
  87 + $jsapi->SetNonceStr(WxPayApi::getNonceStr());
  88 + $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
  89 +
  90 + $config = new WxPayConfig();
  91 + $jsapi->SetPaySign($jsapi->MakeSign($config));
  92 + $parameters = json_encode($jsapi->GetValues());
  93 + return $parameters;
  94 + }
  95 +
  96 + /**
  97 + *
  98 + * 通过code从工作平台获取openid机器access_token
  99 + * @param string $code 微信跳转回来带上的code
  100 + *
  101 + * @return openid
  102 + */
  103 + public function GetOpenidFromMp($code)
  104 + {
  105 + $url = $this->__CreateOauthUrlForOpenid($code);
  106 +
  107 + //初始化curl
  108 + $ch = curl_init();
  109 + $curlVersion = curl_version();
  110 + $config = new WxPayConfig();
  111 + $ua = "WXPaySDK/3.0.9 (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." "
  112 + .$config->GetMerchantId();
  113 +
  114 + //设置超时
  115 + curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
  116 + curl_setopt($ch, CURLOPT_URL, $url);
  117 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
  118 + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
  119 + curl_setopt($ch, CURLOPT_USERAGENT, $ua);
  120 + curl_setopt($ch, CURLOPT_HEADER, FALSE);
  121 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  122 +
  123 + $proxyHost = "0.0.0.0";
  124 + $proxyPort = 0;
  125 + $config->GetProxy($proxyHost, $proxyPort);
  126 + if($proxyHost != "0.0.0.0" && $proxyPort != 0){
  127 + curl_setopt($ch,CURLOPT_PROXY, $proxyHost);
  128 + curl_setopt($ch,CURLOPT_PROXYPORT, $proxyPort);
  129 + }
  130 + //运行curl,结果以jason形式返回
  131 + $res = curl_exec($ch);
  132 + curl_close($ch);
  133 + //取出openid
  134 + $data = json_decode($res,true);
  135 + $this->data = $data;
  136 + $openid = $data['openid'];
  137 + return $openid;
  138 + }
  139 +
  140 + /**
  141 + *
  142 + * 拼接签名字符串
  143 + * @param array $urlObj
  144 + *
  145 + * @return 返回已经拼接好的字符串
  146 + */
  147 + private function ToUrlParams($urlObj)
  148 + {
  149 + $buff = "";
  150 + foreach ($urlObj as $k => $v)
  151 + {
  152 + if($k != "sign"){
  153 + $buff .= $k . "=" . $v . "&";
  154 + }
  155 + }
  156 +
  157 + $buff = trim($buff, "&");
  158 + return $buff;
  159 + }
  160 +
  161 + /**
  162 + *
  163 + * 获取地址js参数
  164 + *
  165 + * @return 获取共享收货地址js函数需要的参数,json格式可以直接做参数使用
  166 + */
  167 + public function GetEditAddressParameters()
  168 + {
  169 + $config = new WxPayConfig();
  170 + $getData = $this->data;
  171 + $data = array();
  172 + $data["appid"] = $config->GetAppId();
  173 + $data["url"] = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  174 + $time = time();
  175 + $data["timestamp"] = "$time";
  176 + $data["noncestr"] = WxPayApi::getNonceStr();
  177 + $data["accesstoken"] = $getData["access_token"];
  178 + ksort($data);
  179 + $params = $this->ToUrlParams($data);
  180 + $addrSign = sha1($params);
  181 +
  182 + $afterData = array(
  183 + "addrSign" => $addrSign,
  184 + "signType" => "sha1",
  185 + "scope" => "jsapi_address",
  186 + "appId" => $config->GetAppId(),
  187 + "timeStamp" => $data["timestamp"],
  188 + "nonceStr" => $data["noncestr"]
  189 + );
  190 + $parameters = json_encode($afterData);
  191 + return $parameters;
  192 + }
  193 +
  194 + /**
  195 + *
  196 + * 构造获取code的url连接
  197 + * @param string $redirectUrl 微信服务器回跳的url,需要url编码
  198 + *
  199 + * @return 返回构造好的url
  200 + */
  201 + private function _CreateOauthUrlForCode($redirectUrl)
  202 + {
  203 + $config = new WxPayConfig();
  204 + $urlObj["appid"] = $config->GetAppId();
  205 + $urlObj["redirect_uri"] = "$redirectUrl";
  206 + $urlObj["response_type"] = "code";
  207 + $urlObj["scope"] = "snsapi_base";
  208 + $urlObj["state"] = "STATE"."#wechat_redirect";
  209 + $bizString = $this->ToUrlParams($urlObj);
  210 + return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
  211 + }
  212 +
  213 + /**
  214 + *
  215 + * 构造获取open和access_toke的url地址
  216 + * @param string $code,微信跳转带回的code
  217 + *
  218 + * @return 请求的url
  219 + */
  220 + private function __CreateOauthUrlForOpenid($code)
  221 + {
  222 + $config = new WxPayConfig();
  223 + $urlObj["appid"] = $config->GetAppId();
  224 + $urlObj["secret"] = $config->GetAppSecret();
  225 + $urlObj["code"] = $code;
  226 + $urlObj["grant_type"] = "authorization_code";
  227 + $bizString = $this->ToUrlParams($urlObj);
  228 + return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
  229 + }
  230 +}
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +require_once "../lib/WxPay.Api.php";
  10 +require_once "WxPay.Config.php";
  11 +/**
  12 + *
  13 + * 刷卡支付实现类
  14 + * 该类实现了一个刷卡支付的流程,流程如下:
  15 + * 1、提交刷卡支付
  16 + * 2、根据返回结果决定是否需要查询订单,如果查询之后订单还未变则需要返回查询(一般反复查10次)
  17 + * 3、如果反复查询10订单依然不变,则发起撤销订单
  18 + * 4、撤销订单需要循环撤销,一直撤销成功为止(注意循环次数,建议10次)
  19 + *
  20 + * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发,为了防止
  21 + * 查询时hold住后台php进程,商户查询和撤销逻辑可在前端调用
  22 + *
  23 + * @author widy
  24 + *
  25 + */
  26 +class MicroPay
  27 +{
  28 + /**
  29 + *
  30 + * 提交刷卡支付,并且确认结果,接口比较慢
  31 + * @param WxPayMicroPay $microPayInput
  32 + * @throws WxpayException
  33 + * @return 返回查询接口的结果
  34 + */
  35 + public function pay($microPayInput)
  36 + {
  37 + //①、提交被扫支付
  38 + $config = new WxPayConfig();
  39 + $result = WxPayApi::micropay($config, $microPayInput, 5);
  40 + //如果返回成功
  41 + if(!array_key_exists("return_code", $result)
  42 + || !array_key_exists("result_code", $result))
  43 + {
  44 + echo "接口调用失败,请确认是否输入是否有误!";
  45 + throw new WxPayException("接口调用失败!");
  46 + }
  47 +
  48 + //取订单号
  49 + $out_trade_no = $microPayInput->GetOut_trade_no();
  50 +
  51 + //②、接口调用成功,明确返回调用失败
  52 + if($result["return_code"] == "SUCCESS" &&
  53 + $result["result_code"] == "FAIL" &&
  54 + $result["err_code"] != "USERPAYING" &&
  55 + $result["err_code"] != "SYSTEMERROR")
  56 + {
  57 + return false;
  58 + }
  59 +
  60 + //③、确认支付是否成功
  61 + $queryTimes = 10;
  62 + while($queryTimes > 0)
  63 + {
  64 + $succResult = 0;
  65 + $queryResult = $this->query($out_trade_no, $succResult);
  66 + //如果需要等待1s后继续
  67 + if($succResult == 2){
  68 + sleep(2);
  69 + continue;
  70 + } else if($succResult == 1){//查询成功
  71 + return $queryResult;
  72 + } else {//订单交易失败
  73 + break;
  74 + }
  75 + }
  76 +
  77 + //④、次确认失败,则撤销订单
  78 + if(!$this->cancel($out_trade_no))
  79 + {
  80 + throw new WxpayException("撤销单失败!");
  81 + }
  82 +
  83 + return false;
  84 + }
  85 +
  86 + /**
  87 + *
  88 + * 查询订单情况
  89 + * @param string $out_trade_no 商户订单号
  90 + * @param int $succCode 查询订单结果
  91 + * @return 0 订单不成功,1表示订单成功,2表示继续等待
  92 + */
  93 + public function query($out_trade_no, &$succCode)
  94 + {
  95 + $queryOrderInput = new WxPayOrderQuery();
  96 + $queryOrderInput->SetOut_trade_no($out_trade_no);
  97 + $config = new WxPayConfig();
  98 + try{
  99 + $result = WxPayApi::orderQuery($config, $queryOrderInput);
  100 + } catch(Exception $e) {
  101 + Log::ERROR(json_encode($e));
  102 + }
  103 + if($result["return_code"] == "SUCCESS"
  104 + && $result["result_code"] == "SUCCESS")
  105 + {
  106 + //支付成功
  107 + if($result["trade_state"] == "SUCCESS"){
  108 + $succCode = 1;
  109 + return $result;
  110 + }
  111 + //用户支付中
  112 + else if($result["trade_state"] == "USERPAYING"){
  113 + $succCode = 2;
  114 + return false;
  115 + }
  116 + }
  117 +
  118 + //如果返回错误码为“此交易订单号不存在”则直接认定失败
  119 + if($result["err_code"] == "ORDERNOTEXIST")
  120 + {
  121 + $succCode = 0;
  122 + } else{
  123 + //如果是系统错误,则后续继续
  124 + $succCode = 2;
  125 + }
  126 + return false;
  127 + }
  128 +
  129 + /**
  130 + *
  131 + * 撤销订单,如果失败会重复调用10次
  132 + * @param string $out_trade_no
  133 + * @param 调用深度 $depth
  134 + */
  135 + public function cancel($out_trade_no, $depth = 0)
  136 + {
  137 + try {
  138 + if($depth > 10){
  139 + return false;
  140 + }
  141 +
  142 + $clostOrder = new WxPayReverse();
  143 + $clostOrder->SetOut_trade_no($out_trade_no);
  144 +
  145 + $config = new WxPayConfig();
  146 + $result = WxPayApi::reverse($config, $clostOrder);
  147 +
  148 +
  149 + //接口调用失败
  150 + if($result["return_code"] != "SUCCESS"){
  151 + return false;
  152 + }
  153 +
  154 + //如果结果为success且不需要重新调用撤销,则表示撤销成功
  155 + if($result["result_code"] != "SUCCESS"
  156 + && $result["recall"] == "N"){
  157 + return true;
  158 + } else if($result["recall"] == "Y") {
  159 + return $this->cancel($out_trade_no, ++$depth);
  160 + }
  161 + } catch(Exception $e) {
  162 + Log::ERROR(json_encode($e));
  163 + }
  164 + return false;
  165 + }
  166 +}
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +require_once "../lib/WxPay.Api.php";
  10 +require_once "WxPay.Config.php";
  11 +require_once 'log.php';
  12 +
  13 +/**
  14 + *
  15 + * 刷卡支付实现类
  16 + * @author widyhu
  17 + *
  18 + */
  19 +class NativePay
  20 +{
  21 + /**
  22 + *
  23 + * 生成扫描支付URL,模式一
  24 + * @param BizPayUrlInput $bizUrlInfo
  25 + */
  26 + public function GetPrePayUrl($productId)
  27 + {
  28 + $biz = new WxPayBizPayUrl();
  29 + $biz->SetProduct_id($productId);
  30 + try{
  31 + $config = new WxPayConfig();
  32 + $values = WxpayApi::bizpayurl($config, $biz);
  33 + } catch(Exception $e) {
  34 + Log::ERROR(json_encode($e));
  35 + }
  36 + $url = "weixin://wxpay/bizpayurl?" . $this->ToUrlParams($values);
  37 + return $url;
  38 + }
  39 +
  40 + /**
  41 + *
  42 + * 参数数组转换为url参数
  43 + * @param array $urlObj
  44 + */
  45 + private function ToUrlParams($urlObj)
  46 + {
  47 + $buff = "";
  48 + foreach ($urlObj as $k => $v)
  49 + {
  50 + $buff .= $k . "=" . $v . "&";
  51 + }
  52 +
  53 + $buff = trim($buff, "&");
  54 + return $buff;
  55 + }
  56 +
  57 + /**
  58 + *
  59 + * 生成直接支付url,支付url有效期为2小时,模式二
  60 + * @param UnifiedOrderInput $input
  61 + */
  62 + public function GetPayUrl($input)
  63 + {
  64 + if($input->GetTrade_type() == "NATIVE")
  65 + {
  66 + try{
  67 + $config = new WxPayConfig();
  68 + $result = WxPayApi::unifiedOrder($config, $input);
  69 + return $result;
  70 + } catch(Exception $e) {
  71 + Log::ERROR(json_encode($e));
  72 + }
  73 + }
  74 + return false;
  75 + }
  76 +}
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +require_once "../lib/WxPay.Api.php";
  10 +require_once "WxPay.Config.php";
  11 +require_once 'log.php';
  12 +
  13 +//初始化日志
  14 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  15 +$log = Log::Init($logHandler, 15);
  16 +
  17 +if((isset($_REQUEST["bill_date"]) && !preg_match("/^[0-9-]{6,64}$/i", $_REQUEST["bill_date"], $matches))
  18 + || (isset($_REQUEST["bill_type"]) && !preg_match("/^[A-Z]{1,64}$/i", $_REQUEST["bill_type"], $matches)))
  19 +{
  20 + header('HTTP/1.1 404 Not Found');
  21 + exit();
  22 +}
  23 +
  24 +if(isset($_REQUEST["bill_date"]) && $_REQUEST["bill_date"] != ""){
  25 +
  26 + $bill_date = $_REQUEST["bill_date"];
  27 + $bill_type = $_REQUEST["bill_type"];
  28 + $input = new WxPayDownloadBill();
  29 + $input->SetBill_date($bill_date);
  30 + $input->SetBill_type($bill_type);
  31 + $config = new WxPayConfig();
  32 + $file = WxPayApi::downloadBill($config, $input);
  33 + echo htmlspecialchars($file, ENT_QUOTES);
  34 + //TODO 对账单文件处理
  35 + exit(0);
  36 +}
  37 +?>
  38 +<html>
  39 +<head>
  40 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  41 + <meta name="viewport" content="width=device-width, initial-scale=1" />
  42 + <title>微信支付样例-查退款单</title>
  43 +</head>
  44 +<body>
  45 + <form action="#" method="post">
  46 + <div style="margin-left:2%;">对账日期:</div><br/>
  47 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="bill_date" /><br /><br />
  48 + <div style="margin-left:2%;">账单类型:</div><br/>
  49 + <select style="width:96%;height:35px;margin-left:2%;" name="bill_type">
  50 + <option value ="ALL">所有订单信息</option>
  51 + <option value ="SUCCESS">成功支付的订单</option>
  52 + <option value="REFUND">退款订单</option>
  53 + <option value="REVOKED">撤销的订单</option>
  54 + </select><br /><br />
  55 + <div align="center">
  56 + <input type="submit" value="下载订单" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
  57 + </div>
  58 + </form>
  59 +</body>
  60 +</html>
  1 +<html>
  2 +<head>
  3 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  4 + <meta name="viewport" content="width=device-width, initial-scale=1"/>
  5 + <title>微信支付样例</title>
  6 + <style type="text/css">
  7 + ul {
  8 + margin-left:10px;
  9 + margin-right:10px;
  10 + margin-top:10px;
  11 + padding: 0;
  12 + }
  13 + li {
  14 + width: 32%;
  15 + float: left;
  16 + margin: 0px;
  17 + margin-left:1%;
  18 + padding: 0px;
  19 + height: 100px;
  20 + display: inline;
  21 + line-height: 100px;
  22 + color: #fff;
  23 + font-size: x-large;
  24 + word-break:break-all;
  25 + word-wrap : break-word;
  26 + margin-bottom: 5px;
  27 + }
  28 + a {
  29 + -webkit-tap-highlight-color: rgba(0,0,0,0);
  30 + text-decoration:none;
  31 + color:#fff;
  32 + }
  33 + a:link{
  34 + -webkit-tap-highlight-color: rgba(0,0,0,0);
  35 + text-decoration:none;
  36 + color:#fff;
  37 + }
  38 + a:visited{
  39 + -webkit-tap-highlight-color: rgba(0,0,0,0);
  40 + text-decoration:none;
  41 + color:#fff;
  42 + }
  43 + a:hover{
  44 + -webkit-tap-highlight-color: rgba(0,0,0,0);
  45 + text-decoration:none;
  46 + color:#fff;
  47 + }
  48 + a:active{
  49 + -webkit-tap-highlight-color: rgba(0,0,0,0);
  50 + text-decoration:none;
  51 + color:#fff;
  52 + }
  53 + </style>
  54 +</head>
  55 +<body>
  56 + <div align="center">
  57 + <ul>
  58 + <li style="background-color:#FF7F24"><a href="http://<?php echo $_SERVER['SERVER_NAME']?>/jsapi.php">JSAPI支付</a></li>
  59 + <li style="background-color:#698B22"><a href="http://<?php echo $_SERVER['SERVER_NAME']?>/micropay.php">刷卡支付</a></li>
  60 + <li style="background-color:#8B6914"><a href="http://<?php echo $_SERVER['SERVER_NAME']?>/native.php">扫码支付</a></li>
  61 + <li style="background-color:#CDCD00"><a href="http://<?php echo $_SERVER['SERVER_NAME']?>/orderquery.php">订单查询</a></li>
  62 + <li style="background-color:#CD3278"><a href="http://<?php echo $_SERVER['SERVER_NAME']?>/refund.php">订单退款</a></li>
  63 + <li style="background-color:#848484"><a href="http://<?php echo $_SERVER['SERVER_NAME']?>/refundquery.php">退款查询</a></li>
  64 + <li style="background-color:#8EE5EE"><a href="http://<?php echo $_SERVER['SERVER_NAME']?>/download.php">下载订单</a></li>
  65 + </ul>
  66 + </div>
  67 +</body>
  68 +</html>
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +require_once "../lib/WxPay.Api.php";
  10 +require_once "WxPay.JsApiPay.php";
  11 +require_once "WxPay.Config.php";
  12 +require_once 'log.php';
  13 +
  14 +//初始化日志
  15 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  16 +$log = Log::Init($logHandler, 15);
  17 +
  18 +//打印输出数组信息
  19 +function printf_info($data)
  20 +{
  21 + foreach($data as $key=>$value){
  22 + echo "<font color='#00ff55;'>$key</font> : ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
  23 + }
  24 +}
  25 +
  26 +//①、获取用户openid
  27 +try{
  28 +
  29 + $tools = new JsApiPay();
  30 + $openId = $tools->GetOpenid();
  31 +
  32 + //②、统一下单
  33 + $input = new WxPayUnifiedOrder();
  34 + $input->SetBody("test");
  35 + $input->SetAttach("test");
  36 + $input->SetOut_trade_no("sdkphp".date("YmdHis"));
  37 + $input->SetTotal_fee("1");
  38 + $input->SetTime_start(date("YmdHis"));
  39 + $input->SetTime_expire(date("YmdHis", time() + 600));
  40 + $input->SetGoods_tag("test");
  41 + $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
  42 + $input->SetTrade_type("JSAPI");
  43 + $input->SetOpenid($openId);
  44 + $config = new WxPayConfig();
  45 + $order = WxPayApi::unifiedOrder($config, $input);
  46 + echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
  47 + printf_info($order);
  48 + $jsApiParameters = $tools->GetJsApiParameters($order);
  49 +
  50 + //获取共享收货地址js函数参数
  51 + $editAddress = $tools->GetEditAddressParameters();
  52 +} catch(Exception $e) {
  53 + Log::ERROR(json_encode($e));
  54 +}
  55 +//③、在支持成功回调通知中处理成功之后的事宜,见 notify.php
  56 +/**
  57 + * 注意:
  58 + * 1、当你的回调地址不可访问的时候,回调通知会失败,可以通过查询订单来确认支付是否成功
  59 + * 2、jsapi支付时需要填入用户openid,WxPay.JsApiPay.php中有获取openid流程 (文档可以参考微信公众平台“网页授权接口”,
  60 + * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html)
  61 + */
  62 +?>
  63 +
  64 +<html>
  65 +<head>
  66 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  67 + <meta name="viewport" content="width=device-width, initial-scale=1"/>
  68 + <title>微信支付样例-支付</title>
  69 + <script type="text/javascript">
  70 + //调用微信JS api 支付
  71 + function jsApiCall()
  72 + {
  73 + WeixinJSBridge.invoke(
  74 + 'getBrandWCPayRequest',
  75 + <?php echo $jsApiParameters; ?>,
  76 + function(res){
  77 + WeixinJSBridge.log(res.err_msg);
  78 + alert(res.err_code+res.err_desc+res.err_msg);
  79 + }
  80 + );
  81 + }
  82 +
  83 + function callpay()
  84 + {
  85 + if (typeof WeixinJSBridge == "undefined"){
  86 + if( document.addEventListener ){
  87 + document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
  88 + }else if (document.attachEvent){
  89 + document.attachEvent('WeixinJSBridgeReady', jsApiCall);
  90 + document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
  91 + }
  92 + }else{
  93 + jsApiCall();
  94 + }
  95 + }
  96 + </script>
  97 + <script type="text/javascript">
  98 + //获取共享地址
  99 + function editAddress()
  100 + {
  101 + WeixinJSBridge.invoke(
  102 + 'editAddress',
  103 + <?php echo $editAddress; ?>,
  104 + function(res){
  105 + var value1 = res.proviceFirstStageName;
  106 + var value2 = res.addressCitySecondStageName;
  107 + var value3 = res.addressCountiesThirdStageName;
  108 + var value4 = res.addressDetailInfo;
  109 + var tel = res.telNumber;
  110 +
  111 + alert(value1 + value2 + value3 + value4 + ":" + tel);
  112 + }
  113 + );
  114 + }
  115 +
  116 + window.onload = function(){
  117 + if (typeof WeixinJSBridge == "undefined"){
  118 + if( document.addEventListener ){
  119 + document.addEventListener('WeixinJSBridgeReady', editAddress, false);
  120 + }else if (document.attachEvent){
  121 + document.attachEvent('WeixinJSBridgeReady', editAddress);
  122 + document.attachEvent('onWeixinJSBridgeReady', editAddress);
  123 + }
  124 + }else{
  125 + editAddress();
  126 + }
  127 + };
  128 +
  129 + </script>
  130 +</head>
  131 +<body>
  132 + <br/>
  133 + <font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px">1分</span></b></font><br/><br/>
  134 + <div align="center">
  135 + <button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" >立即支付</button>
  136 + </div>
  137 +</body>
  138 +</html>
  1 +<?php
  2 +//以下为日志
  3 +
  4 +interface ILogHandler
  5 +{
  6 + public function write($msg);
  7 +
  8 +}
  9 +
  10 +class CLogFileHandler implements ILogHandler
  11 +{
  12 + private $handle = null;
  13 +
  14 + public function __construct($file = '')
  15 + {
  16 + $this->handle = fopen($file,'a');
  17 + }
  18 +
  19 + public function write($msg)
  20 + {
  21 + fwrite($this->handle, $msg, 4096);
  22 + }
  23 +
  24 + public function __destruct()
  25 + {
  26 + fclose($this->handle);
  27 + }
  28 +}
  29 +
  30 +class Log
  31 +{
  32 + private $handler = null;
  33 + private $level = 15;
  34 +
  35 + private static $instance = null;
  36 +
  37 + private function __construct(){}
  38 +
  39 + private function __clone(){}
  40 +
  41 + public static function Init($handler = null,$level = 15)
  42 + {
  43 + if(!self::$instance instanceof self)
  44 + {
  45 + self::$instance = new self();
  46 + self::$instance->__setHandle($handler);
  47 + self::$instance->__setLevel($level);
  48 + }
  49 + return self::$instance;
  50 + }
  51 +
  52 +
  53 + private function __setHandle($handler){
  54 + $this->handler = $handler;
  55 + }
  56 +
  57 + private function __setLevel($level)
  58 + {
  59 + $this->level = $level;
  60 + }
  61 +
  62 + public static function DEBUG($msg)
  63 + {
  64 + self::$instance->write(1, $msg);
  65 + }
  66 +
  67 + public static function WARN($msg)
  68 + {
  69 + self::$instance->write(4, $msg);
  70 + }
  71 +
  72 + public static function ERROR($msg)
  73 + {
  74 + $debugInfo = debug_backtrace();
  75 + $stack = "[";
  76 + foreach($debugInfo as $key => $val){
  77 + if(array_key_exists("file", $val)){
  78 + $stack .= ",file:" . $val["file"];
  79 + }
  80 + if(array_key_exists("line", $val)){
  81 + $stack .= ",line:" . $val["line"];
  82 + }
  83 + if(array_key_exists("function", $val)){
  84 + $stack .= ",function:" . $val["function"];
  85 + }
  86 + }
  87 + $stack .= "]";
  88 + self::$instance->write(8, $stack . $msg);
  89 + }
  90 +
  91 + public static function INFO($msg)
  92 + {
  93 + self::$instance->write(2, $msg);
  94 + }
  95 +
  96 + private function getLevelStr($level)
  97 + {
  98 + switch ($level)
  99 + {
  100 + case 1:
  101 + return 'debug';
  102 + break;
  103 + case 2:
  104 + return 'info';
  105 + break;
  106 + case 4:
  107 + return 'warn';
  108 + break;
  109 + case 8:
  110 + return 'error';
  111 + break;
  112 + default:
  113 +
  114 + }
  115 + }
  116 +
  117 + protected function write($level,$msg)
  118 + {
  119 + if(($level & $this->level) == $level )
  120 + {
  121 + $msg = '['.date('Y-m-d H:i:s').']['.$this->getLevelStr($level).'] '.$msg."\n";
  122 + $this->handler->write($msg);
  123 + }
  124 + }
  125 +}
  1 +<html>
  2 +<head>
  3 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  4 + <meta name="viewport" content="width=device-width, initial-scale=1" />
  5 + <title>微信支付样例-查退款单</title>
  6 +</head>
  7 +<?php
  8 +/**
  9 +*
  10 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  11 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  12 +* 请勿直接直接使用样例对外提供服务
  13 +*
  14 +**/
  15 +require_once "../lib/WxPay.Api.php";
  16 +require_once "WxPay.MicroPay.php";
  17 +require_once 'log.php';
  18 +
  19 +if((isset($_REQUEST["auth_code"]) && !preg_match("/^[0-9]{6,64}$/i", $_REQUEST["auth_code"], $matches)))
  20 +{
  21 + header('HTTP/1.1 404 Not Found');
  22 + exit();
  23 +}
  24 +
  25 +//初始化日志
  26 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  27 +$log = Log::Init($logHandler, 15);
  28 +
  29 +//打印输出数组信息
  30 +function printf_info($data)
  31 +{
  32 + foreach($data as $key=>$value){
  33 + echo "<font color='#00ff55;'>$key</font> : ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
  34 + }
  35 +}
  36 +
  37 +if(isset($_REQUEST["auth_code"]) && $_REQUEST["auth_code"] != ""){
  38 + try {
  39 + $auth_code = $_REQUEST["auth_code"];
  40 + $input = new WxPayMicroPay();
  41 + $input->SetAuth_code($auth_code);
  42 + $input->SetBody("刷卡测试样例-支付");
  43 + $input->SetTotal_fee("1");
  44 + $input->SetOut_trade_no("sdkphp".date("YmdHis"));
  45 +
  46 + $microPay = new MicroPay();
  47 + printf_info($microPay->pay($input));
  48 + } catch(Exception $e) {
  49 + Log::ERROR(json_encode($e));
  50 + }
  51 +}
  52 +
  53 +/**
  54 + * 注意:
  55 + * 1、提交被扫之后,返回系统繁忙、用户输入密码等错误信息时需要循环查单以确定是否支付成功
  56 + * 2、多次(一半10次)确认都未明确成功时需要调用撤单接口撤单,防止用户重复支付
  57 + */
  58 +
  59 +?>
  60 +<body>
  61 + <form action="#" method="post">
  62 + <div style="margin-left:2%;">商品描述:</div><br/>
  63 + <input type="text" style="width:96%;height:35px;margin-left:2%;" readonly value="刷卡测试样例-支付" name="auth_code" /><br /><br />
  64 + <div style="margin-left:2%;">支付金额:</div><br/>
  65 + <input type="text" style="width:96%;height:35px;margin-left:2%;" readonly value="1分" name="auth_code" /><br /><br />
  66 + <div style="margin-left:2%;">授权码:</div><br/>
  67 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="auth_code" /><br /><br />
  68 + <div align="center">
  69 + <input type="submit" value="提交刷卡" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
  70 + </div>
  71 + </form>
  72 +</body>
  73 +</html>
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +
  10 +require_once "../lib/WxPay.Api.php";
  11 +require_once "WxPay.NativePay.php";
  12 +require_once 'log.php';
  13 +
  14 +//初始化日志
  15 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  16 +$log = Log::Init($logHandler, 15);
  17 +
  18 +//模式一
  19 +//不再提供模式一支付方式
  20 +/**
  21 +
  22 + * 流程:
  23 + * 1、组装包含支付信息的url,生成二维码
  24 + * 2、用户扫描二维码,进行支付
  25 + * 3、确定支付之后,微信服务器会回调预先配置的回调地址,在【微信开放平台-微信支付-支付配置】中进行配置
  26 + * 4、在接到回调通知之后,用户进行统一下单支付,并返回支付信息以完成支付(见:native_notify.php)
  27 + * 5、支付完成之后,微信服务器会通知支付成功
  28 + * 6、在支付成功通知中需要查单确认是否真正支付成功(见:notify.php)
  29 + */
  30 +
  31 +$notify = new NativePay();
  32 +$url1 = $notify->GetPrePayUrl("123456789");
  33 +
  34 +//模式二
  35 +/**
  36 + * 流程:
  37 + * 1、调用统一下单,取得code_url,生成二维码
  38 + * 2、用户扫描二维码,进行支付
  39 + * 3、支付完成之后,微信服务器会通知支付成功
  40 + * 4、在支付成功通知中需要查单确认是否真正支付成功(见:notify.php)
  41 + */
  42 +$input = new WxPayUnifiedOrder();
  43 +$input->SetBody("test");
  44 +$input->SetAttach("test");
  45 +$input->SetOut_trade_no("sdkphp123456789".date("YmdHis"));
  46 +$input->SetTotal_fee("1");
  47 +$input->SetTime_start(date("YmdHis"));
  48 +$input->SetTime_expire(date("YmdHis", time() + 600));
  49 +$input->SetGoods_tag("test");
  50 +$input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
  51 +$input->SetTrade_type("NATIVE");
  52 +$input->SetProduct_id("123456789");
  53 +
  54 +$result = $notify->GetPayUrl($input);
  55 +$url2 = $result["code_url"];
  56 +?>
  57 +
  58 +<html>
  59 +<head>
  60 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  61 + <meta name="viewport" content="width=device-width, initial-scale=1" />
  62 + <title>微信支付样例-退款</title>
  63 +</head>
  64 +<body>
  65 + <div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">扫描支付模式一</div><br/>
  66 + <img alt="模式一扫码支付" src="qrcode.php?data=<?php echo urlencode($url1);?>" style="width:150px;height:150px;"/>
  67 + <br/><br/><br/>
  68 + <div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">扫描支付模式二</div><br/>
  69 + <img alt="模式二扫码支付" src="qrcode.php?data=<?php echo urlencode($url2);?>" style="width:150px;height:150px;"/>
  70 + <div style="color:#ff0000"><b>微信支付样例程序,仅做参考</b></div>
  71 +
  72 +</body>
  73 +</html>
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +
  10 +require_once "../lib/WxPay.Api.php";
  11 +require_once '../lib/WxPay.Notify.php';
  12 +require_once "WxPay.Config.php";
  13 +require_once 'log.php';
  14 +
  15 +//初始化日志
  16 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  17 +$log = Log::Init($logHandler, 15);
  18 +
  19 +class NativeNotifyCallBack extends WxPayNotify
  20 +{
  21 + public function unifiedorder($openId, $product_id)
  22 + {
  23 + //统一下单
  24 + $config = new WxPayConfig();
  25 + $input = new WxPayUnifiedOrder();
  26 + $input->SetBody("test");
  27 + $input->SetAttach("test");
  28 + $input->SetOut_trade_no($config->GetMerchantId().date("YmdHis"));
  29 + $input->SetTotal_fee("1");
  30 + $input->SetTime_start(date("YmdHis"));
  31 + $input->SetTime_expire(date("YmdHis", time() + 600));
  32 + $input->SetGoods_tag("test");
  33 + $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
  34 + $input->SetTrade_type("NATIVE");
  35 + $input->SetOpenid($openId);
  36 + $input->SetProduct_id($product_id);
  37 + try {
  38 + $result = WxPayApi::unifiedOrder($config, $input);
  39 + Log::DEBUG("unifiedorder:" . json_encode($result));
  40 + } catch(Exception $e) {
  41 + Log::ERROR(json_encode($e));
  42 + }
  43 + return $result;
  44 + }
  45 +
  46 + /**
  47 + *
  48 + * 回包前的回调方法
  49 + * 业务可以继承该方法,打印日志方便定位
  50 + * @param string $xmlData 返回的xml参数
  51 + *
  52 + **/
  53 + public function LogAfterProcess($xmlData)
  54 + {
  55 + Log::DEBUG("call back, return xml:" . $xmlData);
  56 + return;
  57 + }
  58 +
  59 + /**
  60 + * @param WxPayNotifyResults $objData 回调解释出的参数
  61 + * @param WxPayConfigInterface $config
  62 + * @param string $msg 如果回调处理失败,可以将错误信息输出到该方法
  63 + * @return true回调出来完成不需要继续回调,false回调处理未完成需要继续回调
  64 + */
  65 + public function NotifyProcess($objData, $config, &$msg)
  66 + {
  67 + $data = $objData->GetValues();
  68 + //echo "处理回调";
  69 + Log::DEBUG("call back:" . json_encode($data));
  70 + //TODO 1、进行参数校验
  71 + if(!array_key_exists("openid", $data) ||
  72 + !array_key_exists("product_id", $data))
  73 + {
  74 + $msg = "回调数据异常";
  75 + Log::DEBUG($msg . json_encode($data));
  76 + return false;
  77 + }
  78 +
  79 + //TODO 2、进行签名验证
  80 + try {
  81 + $checkResult = $objData->CheckSign($config);
  82 + if($checkResult == false){
  83 + //签名错误
  84 + Log::ERROR("签名错误...");
  85 + return false;
  86 + }
  87 + } catch(Exception $e) {
  88 + Log::ERROR(json_encode($e));
  89 + }
  90 +
  91 + $openid = $data["openid"];
  92 + $product_id = $data["product_id"];
  93 +
  94 + //TODO 3、处理业务逻辑
  95 + //统一下单
  96 + $result = $this->unifiedorder($openid, $product_id);
  97 + if(!array_key_exists("appid", $result) ||
  98 + !array_key_exists("mch_id", $result) ||
  99 + !array_key_exists("prepay_id", $result))
  100 + {
  101 + $msg = "统一下单失败";
  102 + Log::DEBUG($msg . json_encode($data));
  103 + return false;
  104 + }
  105 +
  106 + $this->SetData("appid", $result["appid"]);
  107 + $this->SetData("mch_id", $result["mch_id"]);
  108 + $this->SetData("nonce_str", WxPayApi::getNonceStr());
  109 + $this->SetData("prepay_id", $result["prepay_id"]);
  110 + $this->SetData("result_code", "SUCCESS");
  111 + $this->SetData("err_code_des", "OK");
  112 + return true;
  113 + }
  114 +}
  115 +
  116 +$config = new WxPayConfig();
  117 +Log::DEBUG("begin notify!");
  118 +$notify = new NativeNotifyCallBack();
  119 +$notify->Handle($config, true);
  120 +
  121 +
  122 +
  123 +
  124 +
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +
  10 +require_once "../lib/WxPay.Api.php";
  11 +require_once '../lib/WxPay.Notify.php';
  12 +require_once "WxPay.Config.php";
  13 +require_once 'log.php';
  14 +
  15 +//初始化日志
  16 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  17 +$log = Log::Init($logHandler, 15);
  18 +
  19 +class PayNotifyCallBack extends WxPayNotify
  20 +{
  21 + //查询订单
  22 + public function Queryorder($transaction_id)
  23 + {
  24 + $input = new WxPayOrderQuery();
  25 + $input->SetTransaction_id($transaction_id);
  26 +
  27 + $config = new WxPayConfig();
  28 + $result = WxPayApi::orderQuery($config, $input);
  29 + Log::DEBUG("query:" . json_encode($result));
  30 + if(array_key_exists("return_code", $result)
  31 + && array_key_exists("result_code", $result)
  32 + && $result["return_code"] == "SUCCESS"
  33 + && $result["result_code"] == "SUCCESS")
  34 + {
  35 + return true;
  36 + }
  37 + return false;
  38 + }
  39 +
  40 + /**
  41 + *
  42 + * 回包前的回调方法
  43 + * 业务可以继承该方法,打印日志方便定位
  44 + * @param string $xmlData 返回的xml参数
  45 + *
  46 + **/
  47 + public function LogAfterProcess($xmlData)
  48 + {
  49 + Log::DEBUG("call back, return xml:" . $xmlData);
  50 + return;
  51 + }
  52 +
  53 + //重写回调处理函数
  54 + /**
  55 + * @param WxPayNotifyResults $data 回调解释出的参数
  56 + * @param WxPayConfigInterface $config
  57 + * @param string $msg 如果回调处理失败,可以将错误信息输出到该方法
  58 + * @return true回调出来完成不需要继续回调,false回调处理未完成需要继续回调
  59 + */
  60 + public function NotifyProcess($objData, $config, &$msg)
  61 + {
  62 + $data = $objData->GetValues();
  63 + //TODO 1、进行参数校验
  64 + if(!array_key_exists("return_code", $data)
  65 + ||(array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
  66 + //TODO失败,不是支付成功的通知
  67 + //如果有需要可以做失败时候的一些清理处理,并且做一些监控
  68 + $msg = "异常异常";
  69 + return false;
  70 + }
  71 + if(!array_key_exists("transaction_id", $data)){
  72 + $msg = "输入参数不正确";
  73 + return false;
  74 + }
  75 +
  76 + //TODO 2、进行签名验证
  77 + try {
  78 + $checkResult = $objData->CheckSign($config);
  79 + if($checkResult == false){
  80 + //签名错误
  81 + Log::ERROR("签名错误...");
  82 + return false;
  83 + }
  84 + } catch(Exception $e) {
  85 + Log::ERROR(json_encode($e));
  86 + }
  87 +
  88 + //TODO 3、处理业务逻辑
  89 + Log::DEBUG("call back:" . json_encode($data));
  90 + $notfiyOutput = array();
  91 +
  92 +
  93 + //查询订单,判断订单真实性
  94 + if(!$this->Queryorder($data["transaction_id"])){
  95 + $msg = "订单查询失败";
  96 + return false;
  97 + }
  98 + return true;
  99 + }
  100 +}
  101 +
  102 +$config = new WxPayConfig();
  103 +Log::DEBUG("begin notify");
  104 +$notify = new PayNotifyCallBack();
  105 +$notify->Handle($config, false);
  1 +<html>
  2 +<head>
  3 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  4 + <meta name="viewport" content="width=device-width, initial-scale=1" />
  5 + <title>微信支付样例-订单查询</title>
  6 +</head>
  7 +<?php
  8 +/**
  9 +*
  10 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  11 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  12 +* 请勿直接直接使用样例对外提供服务
  13 +*
  14 +**/
  15 +require_once "../lib/WxPay.Api.php";
  16 +require_once 'log.php';
  17 +require_once "WxPay.Config.php";
  18 +
  19 +if((isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""
  20 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["transaction_id"], $matches))
  21 + || (isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""
  22 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["out_trade_no"], $matches))){
  23 + header('HTTP/1.1 404 Not Found');
  24 + exit();
  25 +}
  26 +
  27 +//初始化日志
  28 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  29 +$log = Log::Init($logHandler, 15);
  30 +
  31 +function printf_info($data)
  32 +{
  33 + foreach($data as $key=>$value){
  34 + echo "<font color='#f00;'>$key</font> : ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
  35 + }
  36 +}
  37 +
  38 +
  39 +if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
  40 + try {
  41 + $transaction_id = $_REQUEST["transaction_id"];
  42 + $input = new WxPayOrderQuery();
  43 + $input->SetTransaction_id($transaction_id);
  44 + $config = new WxPayConfig();
  45 + printf_info(WxPayApi::orderQuery($config, $input));
  46 + } catch(Exception $e) {
  47 + Log::ERROR(json_encode($e));
  48 + }
  49 + exit();
  50 +}
  51 +
  52 +if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
  53 + try{
  54 + $out_trade_no = $_REQUEST["out_trade_no"];
  55 + $input = new WxPayOrderQuery();
  56 + $input->SetOut_trade_no($out_trade_no);
  57 + $config = new WxPayConfig();
  58 + printf_info(WxPayApi::orderQuery($config, $input));
  59 + } catch(Exception $e) {
  60 + Log::ERROR(json_encode($e));
  61 + }
  62 + exit();
  63 +}
  64 +?>
  65 +<body>
  66 + <form action="#" method="post">
  67 + <div style="margin-left:2%;color:#f00">微信订单号和商户订单号选少填一个,微信订单号优先:</div><br/>
  68 + <div style="margin-left:2%;">微信订单号:</div><br/>
  69 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="transaction_id" /><br /><br />
  70 + <div style="margin-left:2%;">商户订单号:</div><br/>
  71 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_trade_no" /><br /><br />
  72 + <div align="center">
  73 + <input type="submit" value="查询" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
  74 + </div>
  75 + </form>
  76 +</body>
  77 +</html>
  1 +<?php
  2 +/**
  3 +*
  4 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  5 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  6 +* 请勿直接直接使用样例对外提供服务
  7 +*
  8 +**/
  9 +require_once 'phpqrcode/phpqrcode.php';
  10 +$url = urldecode($_GET["data"]);
  11 +if(substr($url, 0, 6) == "weixin"){
  12 + QRcode::png($url);
  13 +}else{
  14 + header('HTTP/1.1 404 Not Found');
  15 +}
  1 +<html>
  2 +<head>
  3 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  4 + <meta name="viewport" content="width=device-width, initial-scale=1" />
  5 + <title>微信支付样例-退款</title>
  6 +</head>
  7 +<?php
  8 +/**
  9 +*
  10 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  11 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  12 +* 请勿直接直接使用样例对外提供服务
  13 +*
  14 +**/
  15 +require_once "../lib/WxPay.Api.php";
  16 +require_once 'log.php';
  17 +require_once "WxPay.Config.php";
  18 +
  19 +if((isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""
  20 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["transaction_id"], $matches))
  21 + || (isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"]!=""
  22 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["out_trade_no"], $matches))
  23 + || (isset($_REQUEST["total_fee"]) && $_REQUEST["total_fee"] != ""
  24 + && !preg_match("/^[0-9]{0,10}$/i", $_REQUEST["total_fee"], $matches))
  25 + || (isset($_REQUEST["refund_fee"]) && $_REQUEST["refund_fee"] != ""
  26 + && !preg_match("/^[0-9]{0,10}$/i", $_REQUEST["refund_fee"], $matches)))
  27 +{
  28 + header('HTTP/1.1 404 Not Found');
  29 + exit();
  30 +}
  31 +//初始化日志
  32 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  33 +$log = Log::Init($logHandler, 15);
  34 +
  35 +function printf_info($data)
  36 +{
  37 + foreach($data as $key=>$value){
  38 + echo "<font color='#f00;'>$key</font> : ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
  39 + }
  40 +}
  41 +
  42 +if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
  43 + try{
  44 + $transaction_id = $_REQUEST["transaction_id"];
  45 + $total_fee = $_REQUEST["total_fee"];
  46 + $refund_fee = $_REQUEST["refund_fee"];
  47 + $input = new WxPayRefund();
  48 + $input->SetTransaction_id($transaction_id);
  49 + $input->SetTotal_fee($total_fee);
  50 + $input->SetRefund_fee($refund_fee);
  51 +
  52 + $config = new WxPayConfig();
  53 + $input->SetOut_refund_no("sdkphp".date("YmdHis"));
  54 + $input->SetOp_user_id($config->GetMerchantId());
  55 + printf_info(WxPayApi::refund($config, $input));
  56 + } catch(Exception $e) {
  57 + Log::ERROR(json_encode($e));
  58 + }
  59 + exit();
  60 +}
  61 +
  62 +//$_REQUEST["out_trade_no"]= "122531270220150304194108";
  63 +///$_REQUEST["total_fee"]= "1";
  64 +//$_REQUEST["refund_fee"] = "1";
  65 +if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
  66 + try{
  67 + $out_trade_no = $_REQUEST["out_trade_no"];
  68 + $total_fee = $_REQUEST["total_fee"];
  69 + $refund_fee = $_REQUEST["refund_fee"];
  70 + $input = new WxPayRefund();
  71 + $input->SetOut_trade_no($out_trade_no);
  72 + $input->SetTotal_fee($total_fee);
  73 + $input->SetRefund_fee($refund_fee);
  74 +
  75 + $config = new WxPayConfig();
  76 + $input->SetOut_refund_no("sdkphp".date("YmdHis"));
  77 + $input->SetOp_user_id($config->GetMerchantId());
  78 + printf_info(WxPayApi::refund($config, $input));
  79 + } catch(Exception $e) {
  80 + Log::ERROR(json_encode($e));
  81 + }
  82 + exit();
  83 +}
  84 +?>
  85 +<body>
  86 + <form action="#" method="post">
  87 + <div style="margin-left:2%;color:#f00">微信订单号和商户订单号选少填一个,微信订单号优先:</div><br/>
  88 + <div style="margin-left:2%;">微信订单号:</div><br/>
  89 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="transaction_id" /><br /><br />
  90 + <div style="margin-left:2%;">商户订单号:</div><br/>
  91 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_trade_no" /><br /><br />
  92 + <div style="margin-left:2%;">订单总金额(分):</div><br/>
  93 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="total_fee" /><br /><br />
  94 + <div style="margin-left:2%;">退款金额(分):</div><br/>
  95 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="refund_fee" /><br /><br />
  96 + <div align="center">
  97 + <input type="submit" value="提交退款" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
  98 + </div>
  99 + </form>
  100 +</body>
  101 +</html>
  1 +<html>
  2 +<head>
  3 + <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  4 + <meta name="viewport" content="width=device-width, initial-scale=1" />
  5 + <title>微信支付样例-查退款单</title>
  6 +</head>
  7 +<?php
  8 +/**
  9 +*
  10 +* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
  11 +* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
  12 +* 请勿直接直接使用样例对外提供服务
  13 +*
  14 +**/
  15 +require_once "../lib/WxPay.Api.php";
  16 +require_once 'log.php';
  17 +require_once "WxPay.Config.php";
  18 +
  19 +//初始化日志
  20 +$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
  21 +$log = Log::Init($logHandler, 15);
  22 +
  23 +$matches = array();
  24 +if( (isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""
  25 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["transaction_id"], $matches))
  26 + || (isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""
  27 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["out_trade_no"], $matches))
  28 + || (isset($_REQUEST["out_refund_no"]) && $_REQUEST["out_refund_no"] != ""
  29 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["out_refund_no"], $matches))
  30 + || (isset($_REQUEST["refund_id"]) && $_REQUEST["refund_id"] != ""
  31 + && !preg_match("/^[0-9a-zA-Z]{10,64}$/i", $_REQUEST["refund_id"], $matches)))
  32 +{
  33 + header('HTTP/1.1 404 Not Found');
  34 + exit();
  35 +}
  36 +
  37 +function printf_info($data)
  38 +{
  39 + foreach($data as $key=>$value){
  40 + echo "<font color='#f00;'>$key</font> : ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
  41 + }
  42 +}
  43 +
  44 +if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
  45 + try{
  46 + $transaction_id = $_REQUEST["transaction_id"];
  47 + $input = new WxPayRefundQuery();
  48 + $input->SetTransaction_id($transaction_id);
  49 + $config = new WxPayConfig();
  50 + printf_info(WxPayApi::refundQuery($config, $input));
  51 + } catch(Exception $e) {
  52 + Log::ERROR(json_encode($e));
  53 + }
  54 +}
  55 +
  56 +if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
  57 + try{
  58 + $out_trade_no = $_REQUEST["out_trade_no"];
  59 + $input = new WxPayRefundQuery();
  60 + $input->SetOut_trade_no($out_trade_no);
  61 + $config = new WxPayConfig();
  62 + printf_info(WxPayApi::refundQuery($input));
  63 + } catch(Exception $e) {
  64 + Log::ERROR(json_encode($e));
  65 + }
  66 + exit();
  67 +}
  68 +
  69 +if(isset($_REQUEST["out_refund_no"]) && $_REQUEST["out_refund_no"] != ""){
  70 + try{
  71 + $out_refund_no = $_REQUEST["out_refund_no"];
  72 + $input = new WxPayRefundQuery();
  73 + $input->SetOut_refund_no($out_refund_no);
  74 + $config = new WxPayConfig();
  75 + printf_info(WxPayApi::refundQuery($config, $input));
  76 + } catch(Exception $e) {
  77 + Log::ERROR(json_encode($e));
  78 + }
  79 + exit();
  80 +}
  81 +
  82 +if(isset($_REQUEST["refund_id"]) && $_REQUEST["refund_id"] != ""){
  83 + try{
  84 + $refund_id = $_REQUEST["refund_id"];
  85 + $input = new WxPayRefundQuery();
  86 + $input->SetRefund_id($refund_id);
  87 + $config = new WxPayConfig();
  88 + printf_info(WxPayApi::refundQuery($config, $input));
  89 + } catch(Exception $e) {
  90 + Log::ERROR(json_encode($e));
  91 + }
  92 + exit();
  93 +}
  94 +
  95 +?>
  96 +<body>
  97 + <form action="#" method="post">
  98 + <div style="margin-left:2%;color:#f00">微信订单号、商户订单号、微信订单号、微信退款单号选填至少一个,微信退款单号优先:</div><br/>
  99 + <div style="margin-left:2%;">微信订单号:</div><br/>
  100 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="transaction_id" /><br /><br />
  101 + <div style="margin-left:2%;">商户订单号:</div><br/>
  102 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_trade_no" /><br /><br />
  103 + <div style="margin-left:2%;">商户退款单号:</div><br/>
  104 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_refund_no" /><br /><br />
  105 + <div style="margin-left:2%;">微信退款单号:</div><br/>
  106 + <input type="text" style="width:96%;height:35px;margin-left:2%;" name="refund_id" /><br /><br />
  107 + <div align="center">
  108 + <input type="submit" value="查询" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" />
  109 + </div>
  110 + </form>
  111 +</body>
  112 +</html>
  1 +<?php
  2 +require_once "WxPay.Exception.php";
  3 +require_once "WxPay.Config.Interface.php";
  4 +require_once "WxPay.Data.php";
  5 +
  6 +/**
  7 + *
  8 + * 接口访问类,包含所有微信支付API列表的封装,类中方法为static方法,
  9 + * 每个接口有默认超时时间(除提交被扫支付为10s,上报超时时间为1s外,其他均为6s)
  10 + * @author widyhu
  11 + *
  12 + */
  13 +class WxPayApi
  14 +{
  15 + /**
  16 + *
  17 + * 统一下单,WxPayUnifiedOrder中out_trade_no、body、total_fee、trade_type必填
  18 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  19 + * @param WxPayConfigInterface $config 配置对象
  20 + * @param WxPayUnifiedOrder $inputObj
  21 + * @param int $timeOut
  22 + * @throws WxPayException
  23 + * @return 成功时返回,其他抛异常
  24 + */
  25 + public static function unifiedOrder($config, $inputObj, $timeOut = 6)
  26 + {
  27 + $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  28 + //检测必填参数
  29 + if(!$inputObj->IsOut_trade_noSet()) {
  30 + throw new WxPayException("缺少统一支付接口必填参数out_trade_no!");
  31 + }else if(!$inputObj->IsBodySet()){
  32 + throw new WxPayException("缺少统一支付接口必填参数body!");
  33 + }else if(!$inputObj->IsTotal_feeSet()) {
  34 + throw new WxPayException("缺少统一支付接口必填参数total_fee!");
  35 + }else if(!$inputObj->IsTrade_typeSet()) {
  36 + throw new WxPayException("缺少统一支付接口必填参数trade_type!");
  37 + }
  38 +
  39 + //关联参数
  40 + if($inputObj->GetTrade_type() == "JSAPI" && !$inputObj->IsOpenidSet()){
  41 + throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
  42 + }
  43 + if($inputObj->GetTrade_type() == "NATIVE" && !$inputObj->IsProduct_idSet()){
  44 + throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
  45 + }
  46 +
  47 + //异步通知url未设置,则使用配置文件中的url
  48 + if(!$inputObj->IsNotify_urlSet() && $config->GetNotifyUrl() != ""){
  49 + $inputObj->SetNotify_url($config->GetNotifyUrl());//异步通知url
  50 + }
  51 +
  52 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  53 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  54 + $inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
  55 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  56 +
  57 + //签名
  58 + $inputObj->SetSign($config);
  59 + $xml = $inputObj->ToXml();
  60 +
  61 + $startTimeStamp = self::getMillisecond();//请求开始时间
  62 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  63 + $result = WxPayResults::Init($config, $response);
  64 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  65 +
  66 + return $result;
  67 + }
  68 +
  69 + /**
  70 + *
  71 + * 查询订单,WxPayOrderQuery中out_trade_no、transaction_id至少填一个
  72 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  73 + * @param WxPayConfigInterface $config 配置对象
  74 + * @param WxPayOrderQuery $inputObj
  75 + * @param int $timeOut
  76 + * @throws WxPayException
  77 + * @return 成功时返回,其他抛异常
  78 + */
  79 + public static function orderQuery($config, $inputObj, $timeOut = 6)
  80 + {
  81 + $url = "https://api.mch.weixin.qq.com/pay/orderquery";
  82 + //检测必填参数
  83 + if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
  84 + throw new WxPayException("订单查询接口中,out_trade_no、transaction_id至少填一个!");
  85 + }
  86 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  87 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  88 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  89 +
  90 + $inputObj->SetSign($config);//签名
  91 + $xml = $inputObj->ToXml();
  92 +
  93 + $startTimeStamp = self::getMillisecond();//请求开始时间
  94 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  95 + $result = WxPayResults::Init($config, $response);
  96 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  97 +
  98 + return $result;
  99 + }
  100 +
  101 + /**
  102 + *
  103 + * 关闭订单,WxPayCloseOrder中out_trade_no必填
  104 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  105 + * @param WxPayConfigInterface $config 配置对象
  106 + * @param WxPayCloseOrder $inputObj
  107 + * @param int $timeOut
  108 + * @throws WxPayException
  109 + * @return 成功时返回,其他抛异常
  110 + */
  111 + public static function closeOrder($config, $inputObj, $timeOut = 6)
  112 + {
  113 + $url = "https://api.mch.weixin.qq.com/pay/closeorder";
  114 + //检测必填参数
  115 + if(!$inputObj->IsOut_trade_noSet()) {
  116 + throw new WxPayException("订单查询接口中,out_trade_no必填!");
  117 + }
  118 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  119 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  120 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  121 +
  122 + $inputObj->SetSign($config);//签名
  123 + $xml = $inputObj->ToXml();
  124 +
  125 + $startTimeStamp = self::getMillisecond();//请求开始时间
  126 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  127 + $result = WxPayResults::Init($config, $response);
  128 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  129 +
  130 + return $result;
  131 + }
  132 +
  133 + /**
  134 + *
  135 + * 申请退款,WxPayRefund中out_trade_no、transaction_id至少填一个且
  136 + * out_refund_no、total_fee、refund_fee、op_user_id为必填参数
  137 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  138 + * @param WxPayConfigInterface $config 配置对象
  139 + * @param WxPayRefund $inputObj
  140 + * @param int $timeOut
  141 + * @throws WxPayException
  142 + * @return 成功时返回,其他抛异常
  143 + */
  144 + public static function refund($config, $inputObj, $timeOut = 6)
  145 + {
  146 + $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
  147 + //检测必填参数
  148 + if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
  149 + throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!");
  150 + }else if(!$inputObj->IsOut_refund_noSet()){
  151 + throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!");
  152 + }else if(!$inputObj->IsTotal_feeSet()){
  153 + throw new WxPayException("退款申请接口中,缺少必填参数total_fee!");
  154 + }else if(!$inputObj->IsRefund_feeSet()){
  155 + throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!");
  156 + }else if(!$inputObj->IsOp_user_idSet()){
  157 + throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!");
  158 + }
  159 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  160 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  161 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  162 +
  163 + $inputObj->SetSign($config);//签名
  164 + $xml = $inputObj->ToXml();
  165 + $startTimeStamp = self::getMillisecond();//请求开始时间
  166 + $response = self::postXmlCurl($config, $xml, $url, true, $timeOut);
  167 + $result = WxPayResults::Init($config, $response);
  168 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  169 +
  170 + return $result;
  171 + }
  172 +
  173 + /**
  174 + *
  175 + * 查询退款
  176 + * 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,
  177 + * 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。
  178 + * WxPayRefundQuery中out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个
  179 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  180 + * @param WxPayConfigInterface $config 配置对象
  181 + * @param WxPayRefundQuery $inputObj
  182 + * @param int $timeOut
  183 + * @throws WxPayException
  184 + * @return 成功时返回,其他抛异常
  185 + */
  186 + public static function refundQuery($config, $inputObj, $timeOut = 6)
  187 + {
  188 + $url = "https://api.mch.weixin.qq.com/pay/refundquery";
  189 + //检测必填参数
  190 + if(!$inputObj->IsOut_refund_noSet() &&
  191 + !$inputObj->IsOut_trade_noSet() &&
  192 + !$inputObj->IsTransaction_idSet() &&
  193 + !$inputObj->IsRefund_idSet()) {
  194 + throw new WxPayException("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!");
  195 + }
  196 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  197 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  198 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  199 +
  200 + $inputObj->SetSign($config);//签名
  201 + $xml = $inputObj->ToXml();
  202 +
  203 + $startTimeStamp = self::getMillisecond();//请求开始时间
  204 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  205 + $result = WxPayResults::Init($config, $response);
  206 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  207 +
  208 + return $result;
  209 + }
  210 +
  211 + /**
  212 + * 下载对账单,WxPayDownloadBill中bill_date为必填参数
  213 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  214 + * @param WxPayConfigInterface $config 配置对象
  215 + * @param WxPayDownloadBill $inputObj
  216 + * @param int $timeOut
  217 + * @throws WxPayException
  218 + * @return 成功时返回,其他抛异常
  219 + */
  220 + public static function downloadBill($config, $inputObj, $timeOut = 6)
  221 + {
  222 + $url = "https://api.mch.weixin.qq.com/pay/downloadbill";
  223 + //检测必填参数
  224 + if(!$inputObj->IsBill_dateSet()) {
  225 + throw new WxPayException("对账单接口中,缺少必填参数bill_date!");
  226 + }
  227 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  228 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  229 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  230 +
  231 + $inputObj->SetSign($config);//签名
  232 + $xml = $inputObj->ToXml();
  233 +
  234 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  235 + if(substr($response, 0 , 5) == "<xml>"){
  236 + return "";
  237 + }
  238 + return $response;
  239 + }
  240 +
  241 + /**
  242 + * 提交被扫支付API
  243 + * 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台,
  244 + * 由商户收银台或者商户后台调用该接口发起支付。
  245 + * WxPayWxPayMicroPay中body、out_trade_no、total_fee、auth_code参数必填
  246 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  247 + * @param WxPayConfigInterface $config 配置对象
  248 + * @param WxPayWxPayMicroPay $inputObj
  249 + * @param int $timeOut
  250 + */
  251 + public static function micropay($config, $inputObj, $timeOut = 10)
  252 + {
  253 + $url = "https://api.mch.weixin.qq.com/pay/micropay";
  254 + //检测必填参数
  255 + if(!$inputObj->IsBodySet()) {
  256 + throw new WxPayException("提交被扫支付API接口中,缺少必填参数body!");
  257 + } else if(!$inputObj->IsOut_trade_noSet()) {
  258 + throw new WxPayException("提交被扫支付API接口中,缺少必填参数out_trade_no!");
  259 + } else if(!$inputObj->IsTotal_feeSet()) {
  260 + throw new WxPayException("提交被扫支付API接口中,缺少必填参数total_fee!");
  261 + } else if(!$inputObj->IsAuth_codeSet()) {
  262 + throw new WxPayException("提交被扫支付API接口中,缺少必填参数auth_code!");
  263 + }
  264 +
  265 + $inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
  266 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  267 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  268 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  269 +
  270 + $inputObj->SetSign($config);//签名
  271 + $xml = $inputObj->ToXml();
  272 +
  273 + $startTimeStamp = self::getMillisecond();//请求开始时间
  274 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  275 + $result = WxPayResults::Init($config, $response);
  276 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  277 +
  278 + return $result;
  279 + }
  280 +
  281 + /**
  282 + *
  283 + * 撤销订单API接口,WxPayReverse中参数out_trade_no和transaction_id必须填写一个
  284 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  285 + * @param WxPayConfigInterface $config 配置对象
  286 + * @param WxPayReverse $inputObj
  287 + * @param int $timeOut
  288 + * @throws WxPayException
  289 + */
  290 + public static function reverse($config, $inputObj, $timeOut = 6)
  291 + {
  292 + $url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
  293 + //检测必填参数
  294 + if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
  295 + throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!");
  296 + }
  297 +
  298 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  299 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  300 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  301 +
  302 + $inputObj->SetSign($config);//签名
  303 + $xml = $inputObj->ToXml();
  304 +
  305 + $startTimeStamp = self::getMillisecond();//请求开始时间
  306 + $response = self::postXmlCurl($config, $xml, $url, true, $timeOut);
  307 + $result = WxPayResults::Init($config, $response);
  308 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  309 +
  310 + return $result;
  311 + }
  312 +
  313 + /**
  314 + *
  315 + * 测速上报,该方法内部封装在report中,使用时请注意异常流程
  316 + * WxPayReport中interface_url、return_code、result_code、user_ip、execute_time_必填
  317 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  318 + * @param WxPayConfigInterface $config 配置对象
  319 + * @param WxPayReport $inputObj
  320 + * @param int $timeOut
  321 + * @throws WxPayException
  322 + * @return 成功时返回,其他抛异常
  323 + */
  324 + public static function report($config, $inputObj, $timeOut = 1)
  325 + {
  326 + $url = "https://api.mch.weixin.qq.com/payitil/report";
  327 + //检测必填参数
  328 + if(!$inputObj->IsInterface_urlSet()) {
  329 + throw new WxPayException("接口URL,缺少必填参数interface_url!");
  330 + } if(!$inputObj->IsReturn_codeSet()) {
  331 + throw new WxPayException("返回状态码,缺少必填参数return_code!");
  332 + } if(!$inputObj->IsResult_codeSet()) {
  333 + throw new WxPayException("业务结果,缺少必填参数result_code!");
  334 + } if(!$inputObj->IsUser_ipSet()) {
  335 + throw new WxPayException("访问接口IP,缺少必填参数user_ip!");
  336 + } if(!$inputObj->IsExecute_time_Set()) {
  337 + throw new WxPayException("接口耗时,缺少必填参数execute_time_!");
  338 + }
  339 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  340 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  341 + $inputObj->SetUser_ip($_SERVER['REMOTE_ADDR']);//终端ip
  342 + $inputObj->SetTime(date("YmdHis"));//商户上报时间
  343 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  344 +
  345 + $inputObj->SetSign($config);//签名
  346 + $xml = $inputObj->ToXml();
  347 +
  348 + $startTimeStamp = self::getMillisecond();//请求开始时间
  349 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  350 + return $response;
  351 + }
  352 +
  353 + /**
  354 + *
  355 + * 生成二维码规则,模式一生成支付二维码
  356 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  357 + * @param WxPayConfigInterface $config 配置对象
  358 + * @param WxPayBizPayUrl $inputObj
  359 + * @param int $timeOut
  360 + * @throws WxPayException
  361 + * @return 成功时返回,其他抛异常
  362 + */
  363 + public static function bizpayurl($config, $inputObj, $timeOut = 6)
  364 + {
  365 + if(!$inputObj->IsProduct_idSet()){
  366 + throw new WxPayException("生成二维码,缺少必填参数product_id!");
  367 + }
  368 +
  369 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  370 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  371 + $inputObj->SetTime_stamp(time());//时间戳
  372 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  373 +
  374 + $inputObj->SetSign($config);//签名
  375 +
  376 + return $inputObj->GetValues();
  377 + }
  378 +
  379 + /**
  380 + *
  381 + * 转换短链接
  382 + * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX),
  383 + * 减小二维码数据量,提升扫描速度和精确度。
  384 + * appid、mchid、spbill_create_ip、nonce_str不需要填入
  385 + * @param WxPayConfigInterface $config 配置对象
  386 + * @param WxPayShortUrl $inputObj
  387 + * @param int $timeOut
  388 + * @throws WxPayException
  389 + * @return 成功时返回,其他抛异常
  390 + */
  391 + public static function shorturl($config, $inputObj, $timeOut = 6)
  392 + {
  393 + $url = "https://api.mch.weixin.qq.com/tools/shorturl";
  394 + //检测必填参数
  395 + if(!$inputObj->IsLong_urlSet()) {
  396 + throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!");
  397 + }
  398 + $inputObj->SetAppid($config->GetAppId());//公众账号ID
  399 + $inputObj->SetMch_id($config->GetMerchantId());//商户号
  400 + $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  401 +
  402 + $inputObj->SetSign($config);//签名
  403 + $xml = $inputObj->ToXml();
  404 +
  405 + $startTimeStamp = self::getMillisecond();//请求开始时间
  406 + $response = self::postXmlCurl($config, $xml, $url, false, $timeOut);
  407 + $result = WxPayResults::Init($config, $response);
  408 + self::reportCostTime($config, $url, $startTimeStamp, $result);//上报请求花费时间
  409 +
  410 + return $result;
  411 + }
  412 +
  413 + /**
  414 + *
  415 + * 支付结果通用通知
  416 + * @param function $callback
  417 + * 直接回调函数使用方法: notify(you_function);
  418 + * 回调类成员函数方法:notify(array($this, you_function));
  419 + * $callback 原型为:function function_name($data){}
  420 + */
  421 + public static function notify($config, $callback, &$msg)
  422 + {
  423 + if (!isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
  424 + # 如果没有数据,直接返回失败
  425 + return false;
  426 + }
  427 +
  428 + //如果返回成功则验证签名
  429 + try {
  430 + //获取通知的数据
  431 + $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
  432 + $result = WxPayNotifyResults::Init($config, $xml);
  433 + } catch (WxPayException $e){
  434 + $msg = $e->errorMessage();
  435 + return false;
  436 + }
  437 +
  438 + return call_user_func($callback, $result);
  439 + }
  440 +
  441 + /**
  442 + *
  443 + * 产生随机字符串,不长于32位
  444 + * @param int $length
  445 + * @return 产生的随机字符串
  446 + */
  447 + public static function getNonceStr($length = 32)
  448 + {
  449 + $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  450 + $str ="";
  451 + for ( $i = 0; $i < $length; $i++ ) {
  452 + $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
  453 + }
  454 + return $str;
  455 + }
  456 +
  457 + /**
  458 + * 直接输出xml
  459 + * @param string $xml
  460 + */
  461 + public static function replyNotify($xml)
  462 + {
  463 + echo $xml;
  464 + }
  465 +
  466 + /**
  467 + *
  468 + * 上报数据, 上报的时候将屏蔽所有异常流程
  469 + * @param WxPayConfigInterface $config 配置对象
  470 + * @param string $usrl
  471 + * @param int $startTimeStamp
  472 + * @param array $data
  473 + */
  474 + private static function reportCostTime($config, $url, $startTimeStamp, $data)
  475 + {
  476 + //如果不需要上报数据
  477 + $reportLevenl = $config->GetReportLevenl();
  478 + if($reportLevenl == 0){
  479 + return;
  480 + }
  481 + //如果仅失败上报
  482 + if($reportLevenl == 1 &&
  483 + array_key_exists("return_code", $data) &&
  484 + $data["return_code"] == "SUCCESS" &&
  485 + array_key_exists("result_code", $data) &&
  486 + $data["result_code"] == "SUCCESS")
  487 + {
  488 + return;
  489 + }
  490 +
  491 + //上报逻辑
  492 + $endTimeStamp = self::getMillisecond();
  493 + $objInput = new WxPayReport();
  494 + $objInput->SetInterface_url($url);
  495 + $objInput->SetExecute_time_($endTimeStamp - $startTimeStamp);
  496 + //返回状态码
  497 + if(array_key_exists("return_code", $data)){
  498 + $objInput->SetReturn_code($data["return_code"]);
  499 + }
  500 + //返回信息
  501 + if(array_key_exists("return_msg", $data)){
  502 + $objInput->SetReturn_msg($data["return_msg"]);
  503 + }
  504 + //业务结果
  505 + if(array_key_exists("result_code", $data)){
  506 + $objInput->SetResult_code($data["result_code"]);
  507 + }
  508 + //错误代码
  509 + if(array_key_exists("err_code", $data)){
  510 + $objInput->SetErr_code($data["err_code"]);
  511 + }
  512 + //错误代码描述
  513 + if(array_key_exists("err_code_des", $data)){
  514 + $objInput->SetErr_code_des($data["err_code_des"]);
  515 + }
  516 + //商户订单号
  517 + if(array_key_exists("out_trade_no", $data)){
  518 + $objInput->SetOut_trade_no($data["out_trade_no"]);
  519 + }
  520 + //设备号
  521 + if(array_key_exists("device_info", $data)){
  522 + $objInput->SetDevice_info($data["device_info"]);
  523 + }
  524 +
  525 + try{
  526 + self::report($config, $objInput);
  527 + } catch (WxPayException $e){
  528 + //不做任何处理
  529 + }
  530 + }
  531 +
  532 + /**
  533 + * 以post方式提交xml到对应的接口url
  534 + *
  535 + * @param WxPayConfigInterface $config 配置对象
  536 + * @param string $xml 需要post的xml数据
  537 + * @param string $url url
  538 + * @param bool $useCert 是否需要证书,默认不需要
  539 + * @param int $second url执行超时时间,默认30s
  540 + * @throws WxPayException
  541 + */
  542 + private static function postXmlCurl($config, $xml, $url, $useCert = false, $second = 30)
  543 + {
  544 + $ch = curl_init();
  545 + $curlVersion = curl_version();
  546 + $ua = "WXPaySDK/3.0.9 (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." "
  547 + .$config->GetMerchantId();
  548 +
  549 + //设置超时
  550 + curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  551 +
  552 + $proxyHost = "0.0.0.0";
  553 + $proxyPort = 0;
  554 + $config->GetProxy($proxyHost, $proxyPort);
  555 + //如果有配置代理这里就设置代理
  556 + if($proxyHost != "0.0.0.0" && $proxyPort != 0){
  557 + curl_setopt($ch,CURLOPT_PROXY, $proxyHost);
  558 + curl_setopt($ch,CURLOPT_PROXYPORT, $proxyPort);
  559 + }
  560 + curl_setopt($ch,CURLOPT_URL, $url);
  561 + curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
  562 + curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
  563 + curl_setopt($ch,CURLOPT_USERAGENT, $ua);
  564 + //设置header
  565 + curl_setopt($ch, CURLOPT_HEADER, FALSE);
  566 + //要求结果为字符串且输出到屏幕上
  567 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  568 +
  569 + if($useCert == true){
  570 + //设置证书
  571 + //使用证书:cert 与 key 分别属于两个.pem文件
  572 + //证书文件请放入服务器的非web目录下
  573 + $sslCertPath = "";
  574 + $sslKeyPath = "";
  575 + $config->GetSSLCertPath($sslCertPath, $sslKeyPath);
  576 + curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  577 + curl_setopt($ch,CURLOPT_SSLCERT, $sslCertPath);
  578 + curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
  579 + curl_setopt($ch,CURLOPT_SSLKEY, $sslKeyPath);
  580 + }
  581 + //post提交方式
  582 + curl_setopt($ch, CURLOPT_POST, TRUE);
  583 + curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  584 + //运行curl
  585 + $data = curl_exec($ch);
  586 + //返回结果
  587 + if($data){
  588 + curl_close($ch);
  589 + return $data;
  590 + } else {
  591 + $error = curl_errno($ch);
  592 + curl_close($ch);
  593 + throw new WxPayException("curl出错,错误码:$error");
  594 + }
  595 + }
  596 +
  597 + /**
  598 + * 获取毫秒级别的时间戳
  599 + */
  600 + private static function getMillisecond()
  601 + {
  602 + //获取毫秒的时间戳
  603 + $time = explode ( " ", microtime () );
  604 + $time = $time[1] . ($time[0] * 1000);
  605 + $time2 = explode( ".", $time );
  606 + $time = $time2[0];
  607 + return $time;
  608 + }
  609 +}
  610 +
  1 +<?php
  2 +/**
  3 +* 配置账号信息
  4 +*/
  5 +
  6 +abstract class WxPayConfigInterface
  7 +{
  8 + //=======【基本信息设置】=====================================
  9 + /**
  10 + * TODO: 修改这里配置为您自己申请的商户信息
  11 + * 微信公众号信息配置
  12 + *
  13 + * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
  14 + *
  15 + * MCHID:商户号(必须配置,开户邮件中可查看)
  16 + *
  17 + */
  18 + public abstract function GetAppId();
  19 + public abstract function GetMerchantId();
  20 +
  21 +
  22 + //=======【支付相关配置:支付成功回调地址/签名方式】===================================
  23 + /**
  24 + * TODO:支付回调url
  25 + * 签名和验证签名方式, 支持md5和sha256方式
  26 + **/
  27 + public abstract function GetNotifyUrl();
  28 + public abstract function GetSignType();
  29 +
  30 + //=======【curl代理设置】===================================
  31 + /**
  32 + * TODO:这里设置代理机器,只有需要代理的时候才设置,不需要代理,请设置为0.0.0.0和0
  33 + * 本例程通过curl使用HTTP POST方法,此处可修改代理服务器,
  34 + * 默认CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0,此时不开启代理(如有需要才设置)
  35 + * @var unknown_type
  36 + */
  37 + public abstract function GetProxy(&$proxyHost, &$proxyPort);
  38 +
  39 +
  40 + //=======【上报信息配置】===================================
  41 + /**
  42 + * TODO:接口调用上报等级,默认紧错误上报(注意:上报超时间为【1s】,上报无论成败【永不抛出异常】,
  43 + * 不会影响接口调用流程),开启上报之后,方便微信监控请求调用的质量,建议至少
  44 + * 开启错误上报。
  45 + * 上报等级,0.关闭上报; 1.仅错误出错上报; 2.全量上报
  46 + * @var int
  47 + */
  48 + public abstract function GetReportLevenl();
  49 +
  50 +
  51 + //=======【商户密钥信息-需要业务方继承】===================================
  52 + /*
  53 + * KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置), 请妥善保管, 避免密钥泄露
  54 + * 设置地址:https://pay.weixin.qq.com/index.php/account/api_cert
  55 + *
  56 + * APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置, 登录公众平台,进入开发者中心可设置), 请妥善保管, 避免密钥泄露
  57 + * 获取地址:https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN
  58 + * @var string
  59 + */
  60 + public abstract function GetKey();
  61 + public abstract function GetAppSecret();
  62 +
  63 +
  64 + //=======【证书路径设置-需要业务方继承】=====================================
  65 + /**
  66 + * TODO:设置商户证书路径
  67 + * 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要,可登录商户平台下载,
  68 + * API证书下载地址:https://pay.weixin.qq.com/index.php/account/api_cert,下载之前需要安装商户操作证书)
  69 + * 注意:
  70 + * 1.证书文件不能放在web服务器虚拟目录,应放在有访问权限控制的目录中,防止被他人下载;
  71 + * 2.建议将证书文件名改为复杂且不容易猜测的文件名;
  72 + * 3.商户服务器要做好病毒和木马防护工作,不被非法侵入者窃取证书文件。
  73 + * @var path
  74 + */
  75 + public abstract function GetSSLCertPath(&$sslCertPath, &$sslKeyPath);
  76 +}