初始化代码

This commit is contained in:
2025-12-22 14:34:25 +08:00
parent c2c5ae2fdd
commit a77dbc743f
1510 changed files with 213008 additions and 0 deletions

76
weixinpay/doc/README Normal file
View File

@@ -0,0 +1,76 @@
SDK
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ַ
http://paysdk.weixin.qq.com/
<EFBFBD><EFBFBD><EFBFBD>ٴָ<EFBFBD><EFBFBD>
<EFBFBD>١<EFBFBD><EFBFBD><EFBFBD>װ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>nginx+phpfpm+php
<EFBFBD>ڡ<EFBFBD><EFBFBD><EFBFBD>SDK<EFBFBD><EFBFBD>ѹ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>վ<EFBFBD><EFBFBD>Ŀ¼
<EFBFBD>ۡ<EFBFBD><EFBFBD>޸<EFBFBD>lib/WxPay.Config.phpΪ<70>Լ<EFBFBD><D4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̻<EFBFBD><CCBB>ŵ<EFBFBD><C5B5><EFBFBD>Ϣ<EFBFBD><CFA2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˵<EFBFBD><CBB5><EFBFBD><EFBFBD>
<EFBFBD>ݡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤<EFBFBD><EFBFBD><EFBFBD>滻cert<EFBFBD>µ<EFBFBD><EFBFBD>ļ<EFBFBD>
<EFBFBD>ޡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
SDKĿ¼<EFBFBD>
|-- cert
| |-- apiclient_cert.pem
| `-- apiclient_key.pem
|-- index.php
|-- lib
| |-- WxPay.Api.php
| |-- WxPay.Config.php
| |-- WxPay.Data.php
| |-- WxPay.Exception.php
| `-- WxPay.Notify.php
|-- logs
| |-- 2015-03-06.log
| `-- 2015-03-11.log
`-- example
|-- WxPay.JsApiPay.php
|-- WxPay.MicroPay.php
|-- WxPay.NativePay.php
|-- download.php
|-- micropay.php
|-- native.php
|-- native_notify.php
|-- notify.php
|-- orderquery.php
|-- qrcode.php
|-- refund.php
|-- refundquery.php
|-- jsapi.php
|-- log.php
`-- phpqrcode
Ŀ¼<EFBFBD><EFBFBD><EFBFBD>ܼ<EFBFBD><EFBFBD><EFBFBD>
lib
API<EFBFBD>ӿڷ<EFBFBD>װ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
WxPay.Api.php <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>΢<EFBFBD><CEA2>֧<EFBFBD><D6A7>API<50>ӿڵķ<DAB5>װ
WxPay.Config.php <20>̻<EFBFBD><CCBB><EFBFBD><EFBFBD><EFBFBD>
WxPay.Data.php <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>װ
WxPay.Exception.php <20><EFBFBD><ECB3A3>
WxPay.Notify.php <20>ص<EFBFBD>֪ͨ<CDA8><D6AA><EFBFBD><EFBFBD>
cert
֤<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>·<EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ե<EFBFBD>¼<EFBFBD>̻<EFBFBD>ƽ̨https://pay.weixin.qq.com/index.php/account/api_cert<72><74><EFBFBD><EFBFBD>
example
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>·<EFBFBD><EFBFBD>
example/phpqrcode
<EFBFBD><EFBFBD>Դ<EFBFBD><EFBFBD>ά<EFBFBD><EFBFBD>php<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
logs
<EFBFBD><EFBFBD>־<EFBFBD>ļ<EFBFBD>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><EFBFBD>
MCHID = '1225312702';
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʼ<EFBFBD><EFBFBD>е<EFBFBD><EFBFBD>̻<EFBFBD><EFBFBD><EFBFBD>
APPID = 'wx426b3015555a46be';
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʼ<EFBFBD><EFBFBD>еģ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˺<EFBFBD>APPID<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӧ<EFBFBD><EFBFBD>APPID<EFBFBD><EFBFBD>
KEY = 'e10adc3949ba59abbe56e057f20f883e'
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD><EFBFBD><EFBFBD>̻<EFBFBD>ƽ̨<EFBFBD><EFBFBD>¼<EFBFBD>˻<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>¼http://pay.weixin.qq.com ƽ̨<C6BD><CCA8><EFBFBD>õġ<C3B5>API<50><49>Կ<EFBFBD><D4BF><EFBFBD><EFBFBD>Ϊ<EFBFBD>˰<EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ32<33>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD>
APPSECRET = '01c6d59a3f9024db6336662ac95c8e74'
<EFBFBD>IJ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>JSAPI֧<EFBFBD><EFBFBD><EFBFBD><EFBFBD>openƽ̨<EFBFBD>˻<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ܽ<EFBFBD><EFBFBD><EFBFBD>JSAPI֧<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȡ<EFBFBD>û<EFBFBD>openid<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD><EFBFBD>APPID<EFBFBD><EFBFBD>Ӧ<EFBFBD>Ĺ<EFBFBD><EFBFBD><EFBFBD>ƽ̨<EFBFBD><EFBFBD>¼http://mp.weixin.qq.com <20>Ŀ<EFBFBD><C4BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ļ<EFBFBD>ȡAppSecret<65><74>

BIN
weixinpay/doc/README.doc Normal file

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,147 @@
<?php
require_once "../lib/WxPay.Api.php";
/**
*
* 刷卡支付实现类
* 该类实现了一个刷卡支付的流程,流程如下:
* 1、提交刷卡支付
* 2、根据返回结果决定是否需要查询订单如果查询之后订单还未变则需要返回查询一般反复查10次
* 3、如果反复查询10订单依然不变则发起撤销订单
* 4、撤销订单需要循环撤销一直撤销成功为止注意循环次数建议10次
*
* 该类是微信支付提供的样例程序商户可根据自己的需求修改或者使用lib中的api自行开发为了防止
* 查询时hold住后台php进程商户查询和撤销逻辑可在前端调用
*
* @author widy
*
*/
class MicroPay
{
/**
*
* 提交刷卡支付,并且确认结果,接口比较慢
* @param WxPayMicroPay $microPayInput
* @throws WxpayException
* @return 返回查询接口的结果
*/
public function pay($microPayInput)
{
//①、提交被扫支付
$result = WxPayApi::micropay($microPayInput, 5);
//如果返回成功
if(!array_key_exists("return_code", $result)
|| !array_key_exists("out_trade_no", $result)
|| !array_key_exists("result_code", $result))
{
echo "接口调用失败,请确认是否输入是否有误!";
throw new WxPayException("接口调用失败!");
}
//签名验证
$out_trade_no = $microPayInput->GetOut_trade_no();
//②、接口调用成功,明确返回调用失败
if($result["return_code"] == "SUCCESS" &&
$result["result_code"] == "FAIL" &&
$result["err_code"] != "USERPAYING" &&
$result["err_code"] != "SYSTEMERROR")
{
return false;
}
//③、确认支付是否成功
$queryTimes = 10;
while($queryTimes > 0)
{
$succResult = 0;
$queryResult = $this->query($out_trade_no, $succResult);
//如果需要等待1s后继续
if($succResult == 2){
sleep(2);
continue;
} else if($succResult == 1){//查询成功
return $queryResult;
} else {//订单交易失败
return false;
}
}
//④、次确认失败,则撤销订单
if(!$this->cancel($out_trade_no))
{
throw new WxpayException("撤销单失败!");
}

View File

@@ -0,0 +1,56 @@
<?php
require_once "../lib/WxPay.Api.php";
/**
*
* 刷卡支付实现类
* @author widyhu
*
*/
class NativePay
{
/**
*
* 生成扫描支付URL,模式一
* @param BizPayUrlInput $bizUrlInfo
*/
public function GetPrePayUrl($productId)
{
$biz = new WxPayBizPayUrl();
$biz->SetProduct_id($productId);
$values = WxpayApi::bizpayurl($biz);
$url = "weixin://wxpay/bizpayurl?" . $this->ToUrlParams($values);
return $url;
}
/**
*
* 参数数组转换为url参数

View File

@@ -0,0 +1,40 @@
<?php
require_once "../lib/WxPay.Api.php";
//require_once "../lib/WxPay.MicroPay.php";
if(isset($_REQUEST["bill_date"]) && $_REQUEST["bill_date"] != ""){
$bill_date = $_REQUEST["bill_date"];
$bill_type = $_REQUEST["bill_type"];
$input = new WxPayDownloadBill();
$input->SetBill_date($bill_date);
$input->SetBill_type($bill_type);
$file = WxPayApi::downloadBill($input);
echo $file;
//TODO 对账单文件处理
exit(0);
}
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>

127
weixinpay/example/jsapi.php Normal file
View File

@@ -0,0 +1,127 @@
<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
//打印输出数组信息
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#00ff55;'>$key</font> : $value <br/>";
}
}
//①、获取用户openid
$tools = new JsApiPay();
$openId = $tools->GetOpenid();
//②、统一下单
$input = new WxPayUnifiedOrder();
$input->SetBody("test");
$input->SetAttach("test");
$input->SetOut_trade_no(WX_MCHID.date("YmdHis"));
$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);
$order = WxPayApi::unifiedOrder($input);
echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
printf_info($order);
$jsApiParameters = $tools->GetJsApiParameters($order);
//获取共享收货地址js函数参数
$editAddress = $tools->GetEditAddressParameters();
//③、在支持成功回调通知中处理成功之后的事宜,见 notify.php
/**
* 注意:
* 1、当你的回调地址不可访问的时候回调通知会失败可以通过查询订单来确认支付是否成功
* 2、jsapi支付时需要填入用户openidWxPay.JsApiPay.php中有获取openid流程 (文档可以参考微信公众平台“网页授权接口”,
* 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
*/
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>微信支付样例-支付</title>
<script type="text/javascript">
//调用微信JS api 支付
function jsApiCall()
{
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
<?php echo $jsApiParameters; ?>,

125
weixinpay/example/log.php Normal file
View File

@@ -0,0 +1,125 @@
<?php
//以下为日志
interface ILogHandler
{
public function write($msg);
}
class CLogFileHandler implements ILogHandler
{
private $handle = null;
public function __construct($file = '')
{
$this->handle = fopen($file,'a');
}
public function write($msg)
{
fwrite($this->handle, $msg, 4096);
}
public function __destruct()
{
fclose($this->handle);
}
}
class Log
{
private $handler = null;
private $level = 15;
private static $instance = null;
private function __construct(){}
private function __clone(){}
public static function Init($handler = null,$level = 15)
{
if(!self::$instance instanceof self)
{
self::$instance = new self();
self::$instance->__setHandle($handler);
self::$instance->__setLevel($level);
}
return self::$instance;
}
private function __setHandle($handler){
$this->handler = $handler;
}
private function __setLevel($level)
{
$this->level = $level;
}
public static function DEBUG($msg)
{

View File

@@ -0,0 +1,56 @@
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-查退款单</title>
</head>
<?php
require_once "../lib/WxPay.Api.php";
require_once "WxPay.MicroPay.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
//打印输出数组信息
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#00ff55;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["auth_code"]) && $_REQUEST["auth_code"] != ""){
$auth_code = $_REQUEST["auth_code"];
$input = new WxPayMicroPay();
$input->SetAuth_code($auth_code);
$input->SetBody("刷卡测试样例-支付");

View File

@@ -0,0 +1,59 @@
<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once "WxPay.NativePay.php";
require_once 'log.php';
//模式一
/**
* 流程:
* 1、组装包含支付信息的url生成二维码
* 2、用户扫描二维码进行支付
* 3、确定支付之后微信服务器会回调预先配置的回调地址在【微信开放平台-微信支付-支付配置】中进行配置
* 4、在接到回调通知之后用户进行统一下单支付并返回支付信息以完成支付native_notify.php
* 5、支付完成之后微信服务器会通知支付成功
* 6、在支付成功通知中需要查单确认是否真正支付成功notify.php
*/
$notify = new NativePay();
$url1 = $notify->GetPrePayUrl("123456789");
//模式二
/**
* 流程:
* 1、调用统一下单取得code_url生成二维码
* 2、用户扫描二维码进行支付
* 3、支付完成之后微信服务器会通知支付成功
* 4、在支付成功通知中需要查单确认是否真正支付成功notify.php
*/
$input = new WxPayUnifiedOrder();

View File

@@ -0,0 +1,72 @@
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
class NativeNotifyCallBack extends WxPayNotify
{
public function unifiedorder($openId, $product_id)
{
//统一下单
$input = new WxPayUnifiedOrder();
$input->SetBody("test");
$input->SetAttach("test");
$input->SetOut_trade_no(WX_MCHID.date("YmdHis"));
$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetTrade_type("NATIVE");
$input->SetOpenid($openId);
$input->SetProduct_id($product_id);
$result = WxPayApi::unifiedOrder($input);
Log::DEBUG("unifiedorder:" . json_encode($result));
return $result;
}
public function NotifyProcess($data, &$msg)
{

View File

@@ -0,0 +1,53 @@
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
class PayNotifyCallBack extends WxPayNotify
{
//查询订单
public function Queryorder($transaction_id)
{
$input = new WxPayOrderQuery();
$input->SetTransaction_id($transaction_id);
$result = WxPayApi::orderQuery($input);
Log::DEBUG("query:" . json_encode($result));
if(array_key_exists("return_code", $result)
&& array_key_exists("result_code", $result)
&& $result["return_code"] == "SUCCESS"
&& $result["result_code"] == "SUCCESS")
{
return true;

View File

@@ -0,0 +1,53 @@
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-订单查询</title>
</head>
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("./logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#f00;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
$transaction_id = $_REQUEST["transaction_id"];
$input = new WxPayOrderQuery();

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,5 @@
<?php
error_reporting(E_ERROR);
require_once 'phpqrcode/phpqrcode.php';

View File

@@ -0,0 +1,71 @@
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-退款</title>
</head>
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#f00;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
$transaction_id = $_REQUEST["transaction_id"];
$total_fee = $_REQUEST["total_fee"];
$refund_fee = $_REQUEST["refund_fee"];
$input = new WxPayRefund();
$input->SetTransaction_id($transaction_id);
$input->SetTotal_fee($total_fee);
$input->SetRefund_fee($refund_fee);
$input->SetOut_refund_no(WX_MCHID.date("YmdHis"));
$input->SetOp_user_id(WX_MCHID);
printf_info(WxPayApi::refund($input));
exit();
}

View File

@@ -0,0 +1,73 @@
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>微信支付样例-查退款单</title>
</head>
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once 'log.php';
//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#f00;'>$key</font> : $value <br/>";
}
}
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
$transaction_id = $_REQUEST["transaction_id"];
$input = new WxPayRefundQuery();
$input->SetTransaction_id($transaction_id);
printf_info(WxPayApi::refundQuery($input));
}
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
$out_trade_no = $_REQUEST["out_trade_no"];
$input = new WxPayRefundQuery();
$input->SetOut_trade_no($out_trade_no);
printf_info(WxPayApi::refundQuery($input));
exit();

BIN
weixinpay/image/bk.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,374 @@
<?php
class wechatAppPay
{
//接口API URL前缀
const API_URL_PREFIX = 'https://api.mch.weixin.qq.com';
//下单地址URL
const UNIFIEDORDER_URL = "/pay/unifiedorder";
//查询订单URL
const ORDERQUERY_URL = "/pay/orderquery";
//关闭订单URL
const CLOSEORDER_URL = "/pay/closeorder";
//公众账号ID
private $wxappid;
//商户号
private $mch_id;
//随机字符串
private $nonce_str;
//签名
private $sign;
//商品描述
private $body;
//商户订单号
private $out_trade_no;
//支付总金额
private $total_fee;
//终端IP
private $spbill_create_ip;
//支付结果回调通知地址
private $notify_url;
//交易类型
private $trade_type;
//支付密钥
private $key;
//证书路径
private $SSLCERT_PATH;
private $SSLKEY_PATH;
//所有参数
private $params = array();
public function __construct($wxappid, $mch_id, $notify_url, $key)
{
$this->appid = $wxappid;
$this->mch_id = $mch_id;
$this->notify_url = $notify_url;
$this->key = $key;
}
/**
* 下单方法
* @param $params 下单参数
*/
public function unifiedOrder($params)
{
$this->body = $params['body'];
$this->out_trade_no = $params['out_trade_no'];
$this->total_fee = $params['total_fee'];
$this->trade_type = $params['trade_type'];
$this->nonce_str = $this->genRandomString();
$this->spbill_create_ip = $_SERVER['REMOTE_ADDR'];
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->nonce_str;
$this->params['body'] = $this->body;
$this->params['out_trade_no'] = $this->out_trade_no;
$this->params['total_fee'] = $this->total_fee;
$this->params['spbill_create_ip'] = $this->spbill_create_ip;
$this->params['notify_url'] = $this->notify_url;
$this->params['trade_type'] = $this->trade_type;
//获取签名数据
$this->sign = $this->MakeSign($this->params);
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX . self::UNIFIEDORDER_URL);
if (!$response) {
return false;
}
$result = $this->xml_to_data($response);
if (!empty($result['result_code']) && !empty($result['err_code'])) {
$result['err_msg'] = $this->error_code($result['err_code']);
}
return $result;
}
/**
* 查询订单信息
* @param $out_trade_no 订单号
* @return array
*/
public function orderQuery($out_trade_no)
{
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->genRandomString();
$this->params['out_trade_no'] = $out_trade_no;
//获取签名数据
$this->sign = $this->MakeSign($this->params);
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX . self::ORDERQUERY_URL);
if (!$response) {
return false;
}
$result = $this->xml_to_data($response);
if (!empty($result['result_code']) && !empty($result['err_code'])) {
$result['err_msg'] = $this->error_code($result['err_code']);
}
return $result;
}
/**
* 关闭订单
* @param $out_trade_no 订单号
* @return array
*/
public function closeOrder($out_trade_no)
{
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->genRandomString();
$this->params['out_trade_no'] = $out_trade_no;
//获取签名数据
$this->sign = $this->MakeSign($this->params);
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX . self::CLOSEORDER_URL);
if (!$response) {
return false;
}
$result = $this->xml_to_data($response);
return $result;
}
/**
*
* 获取支付结果通知数据
* return array
*/
public function getNotifyData()
{
//获取通知的数据
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$data = array();
if (empty($xml)) {
return false;
}
$data = $this->xml_to_data($xml);
if (!empty($data['return_code'])) {
if ($data['return_code'] == 'FAIL') {
return false;
}
}
return $data;
}
/**
* 接收通知成功后应答输出XML数据
* @param string $xml
*/
public function replyNotify()
{
$data['return_code'] = 'SUCCESS';
$data['return_msg'] = 'OK';
$xml = $this->data_to_xml($data);
echo $xml;
die();
}
/**
* 生成APP端支付参数
* @param $prepayid 预支付id
*/
public function getAppPayParams($prepayid)
{
$data['appid'] = $this->appid;
$data['partnerid'] = $this->mch_id;
$data['prepayid'] = $prepayid;
$data['package'] = 'Sign=WXPay';
$data['noncestr'] = $this->genRandomString();
$data['timestamp'] = time();
$data['sign'] = $this->MakeSign($data);
return $data;
}
/**
* 生成签名
* @return 签名
*/
public function MakeSign($params)
{
//签名步骤一:按字典序排序数组参数
ksort($params);
$string = $this->ToUrlParams($params);
//签名步骤二在string后加入KEY
$string = $string . "&key=" . $this->key;
//签名步骤三MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
$result = strtoupper($string);
return $result;
}
/**
* 将参数拼接为url: key=value&key=value
* @param $params
* @return string
*/
public function ToUrlParams($params)
{
$string = '';
if (!empty($params)) {
$array = array();
foreach ($params as $key => $value) {
$array[] = $key . '=' . $value;
}
$string = implode("&", $array);
}
return $string;
}
/**
* 输出xml字符
* @param $params 参数名称
* return string 返回组装的xml
**/
public function data_to_xml($params)
{
if (!is_array($params) || count($params) <= 0) {
return false;
}
$xml = "<xml>";
foreach ($params as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
/**
* 将xml转为array
* @param string $xml
* return array
*/
public function xml_to_data($xml)
{
if (!$xml) {
return false;
}
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $data;
}
/**
* 获取毫秒级别的时间戳
*/
private static function getMillisecond()
{
//获取毫秒的时间戳
$time = explode(" ", microtime());
$time = $time[1] . ($time[0] * 1000);
$time2 = explode(".", $time);
$time = $time2[0];
return $time;
}
/**
* 产生一个指定长度的随机字符串,并返回给用户
* @param type $len 产生字符串的长度
* @return string 随机字符串
*/
private function genRandomString($len = 32)
{
$chars = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
"3", "4", "5", "6", "7", "8", "9"
);
$charsLen = count($chars) - 1;
// 将数组打乱
shuffle($chars);
$output = "";
for ($i = 0; $i < $len; $i++) {
$output .= $chars[mt_rand(0, $charsLen)];
}
return $output;
}
/**
* 以post方式提交xml到对应的接口url
*
* @param string $xml 需要post的xml数据
* @param string $url url
* @param bool $useCert 是否需要证书,默认不需要
* @param int $second url执行超时时间默认30s
* @throws WxPayException
*/
private function postXmlCurl($xml, $url, $useCert = false, $second = 30)
{
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if ($useCert == true) {
//设置证书
//使用证书cert 与 key 分别属于两个.pem文件
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
//curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
//curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行curl
$data = curl_exec($ch);
//返回结果
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
return false;
}
}
/**
* 错误代码
* @param $code 服务器输出的错误代码
* return string
*/
public function error_code($code)
{
$errList = array(
'NOAUTH' => '商户未开通此接口权限',
'NOTENOUGH' => '用户帐号余额不足',
'ORDERNOTEXIST' => '订单号不存在',
'ORDERPAID' => '商户订单已支付,无需重复操作',
'ORDERCLOSED' => '当前订单已关闭,无法支付',
'SYSTEMERROR' => '系统错误!系统超时',
'APPID_NOT_EXIST' => '参数中缺少APPID',
'MCHID_NOT_EXIST' => '参数中缺少MCHID',
'APPID_MCHID_NOT_MATCH' => 'appid和mch_id不匹配',
'LACK_PARAMS' => '缺少必要的请求参数',
'OUT_TRADE_NO_USED' => '同一笔交易不能多次提交',
'SIGNERROR' => '参数签名结果不正确',
'XML_FORMAT_ERROR' => 'XML格式错误',
'REQUIRE_POST_METHOD' => '未使用post传递参数 ',
'POST_DATA_EMPTY' => 'post数据不能为空',
'NOT_UTF8' => '未使用指定编码格式',
);
if (array_key_exists($code, $errList)) {
return $errList[$code];
}
}
}

View File

@@ -0,0 +1,93 @@
<?php
//商户付款
require_once 'WxPay.Data.php';
class WxMchPay extends WxPayDataBase {
public function MchPayOrder($openid, $money, $payId) {
$this->values['mch_appid'] = WX_APPID;
$this->values['mchid'] = WX_MCHID;
$this->values['nonce_str'] = self::getNonceStr();
$this->values['partner_trade_no'] = $payId . date('YmdHis', $_SERVER['REQUEST_TIME']);
$this->values['openid'] = $openid;
$this->values['check_name'] = 'NO_CHECK';
$this->values['amount'] = $money;
$this->values['desc'] = '提现';
$this->values['spbill_create_ip'] = gethostbyname($_SERVER['SERVER_NAME']);
$this->SetSign();
// p($this->values);
$api = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
$xml = $this->ToXml();
$response = self::postXmlCurl($xml, $api, true);
return $this->FromXml($response);
}
/**
* 以post方式提交xml到对应的接口url
*
* @param string $xml 需要post的xml数据
* @param string $url url
* @param bool $useCert 是否需要证书,默认不需要
* @param int $second url执行超时时间默认30s
* @throws WxPayException
*/
private static function postXmlCurl($xml, $url, $useCert = false, $second = 30) {
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//如果有配置代理这里就设置代理
if (WX_CURL_PROXY_HOST != "0.0.0.0" && WX_CURL_PROXY_PORT != 0) {
curl_setopt($ch, CURLOPT_PROXY, WX_CURL_PROXY_HOST);
curl_setopt($ch, CURLOPT_PROXYPORT, WX_CURL_PROXY_PORT);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//echo WX_SSLCERT_PATH;
//echo WX_SSLKEY_PATH;
// die;
if ($useCert == true) {
//设置证书
//使用证书cert 与 key 分别属于两个.pem文件
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERT,WX_SSLCERT_PATH);
curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLKEY, WX_SSLKEY_PATH);
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行curl
$data = curl_exec($ch);
//返回结果
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new WxPayException("curl出错错误码:$error");
}
}
public static function getNonceStr($length = 32) {
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
}

View File

@@ -0,0 +1,97 @@
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
use think\App;
use think\facade\Db;
require_once "WxPay.Api.php";
require_once 'WxPay.Notify.php';
class WxOrderNotify extends WxPayNotify
{
protected $app;
public function __construct ( App $app )
{
$this->app = $app;
}
//查询订单
public function Queryorder($transaction_id){
@file_put_contents('./weixinQuery.txt','in_query',FILE_APPEND);
$input = new WxPayOrderQuery();
$input->SetTransaction_id($transaction_id);
$result = WxPayApi::orderQuery($input);
if(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {
$arr = json_decode($result['attach'] , true);
switch ($arr['type']){
case 'Balance':
//余额卡
$order_model = new \app\farm\model\BalanceOrder();
break;
case 'Claim':
//认养
$order_model = new \app\farm\model\ClaimOrder();
break;
case 'Land':
//土地
$order_model = new \app\farm\model\LandOrder();
break;
case 'ClaimSend':
//配送订单
$order_model = new \app\farm\model\SendOrder();
break;
case 'Breed':
//养殖订单
$order_model = new \app\farm\model\BreedOrder();
break;
case 'SchoolShop':
//商城订单
$order_model = new \app\farm\model\ShopOrder();
break;
}
$order_model->orderResult($arr['out_trade_no'],$transaction_id);
}
return false;
}
//重写回调处理函数
public function NotifyProcess($data, &$msg)
{
$notfiyOutput = array();
if(!array_key_exists("transaction_id", $data)){
file_put_contents('./weixinQuery.txt','输入参数不正确',FILE_APPEND);
$msg = "输入参数不正确";
return false;
}
file_put_contents('./weixinQuery.txt','abc',FILE_APPEND);
//查询订单,判断订单真实性
if(!$this->Queryorder($data["transaction_id"],$data[''])){
$msg = "订单查询失败";
return false;
}
return true;
}
}

591
weixinpay/lib/WxPay.Api.php Normal file
View File

@@ -0,0 +1,591 @@
<?php
require_once "WxPay.Exception.php";
require_once "WxPay.Data.php";
/**
*
* 接口访问类包含所有微信支付API列表的封装类中方法为static方法
* 每个接口有默认超时时间除提交被扫支付为10s上报超时时间为1s外其他均为6s
* @author widyhu
*
*/
class WxPayApi
{
/**
*
* 统一下单WxPayUnifiedOrder中out_trade_no、body、total_fee、trade_type必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayUnifiedOrder $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function unifiedOrder($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet()) {
throw new WxPayException("缺少统一支付接口必填参数out_trade_no");
}else if(!$inputObj->IsBodySet()){
throw new WxPayException("缺少统一支付接口必填参数body");
}else if(!$inputObj->IsTotal_feeSet()) {
throw new WxPayException("缺少统一支付接口必填参数total_fee");
}else if(!$inputObj->IsTrade_typeSet()) {
throw new WxPayException("缺少统一支付接口必填参数trade_type");
}
//关联参数
if($inputObj->GetTrade_type() == "JSAPI" && !$inputObj->IsOpenidSet()){
throw new WxPayException("统一支付接口中缺少必填参数openidtrade_type为JSAPI时openid为必填参数");
}
if($inputObj->GetTrade_type() == "NATIVE" && !$inputObj->IsProduct_idSet()){
throw new WxPayException("统一支付接口中缺少必填参数product_idtrade_type为JSAPI时product_id为必填参数");
}
//异步通知url未设置则使用配置文件中的url
if(!$inputObj->IsNotify_urlSet()){
$inputObj->SetNotify_url(WX_NOTIFY_URL);//异步通知url
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
//$inputObj->SetSpbill_create_ip("1.1.1.1");
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
//签名
$inputObj->SetSign();
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 查询订单WxPayOrderQuery中out_trade_no、transaction_id至少填一个
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayOrderQuery $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function orderQuery($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/orderquery";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
throw new WxPayException("订单查询接口中out_trade_no、transaction_id至少填一个");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 关闭订单WxPayCloseOrder中out_trade_no必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayCloseOrder $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function closeOrder($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/closeorder";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet()) {
throw new WxPayException("订单查询接口中out_trade_no必填");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 申请退款WxPayRefund中out_trade_no、transaction_id至少填一个且
* out_refund_no、total_fee、refund_fee、op_user_id为必填参数
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayRefund $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function refund($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
throw new WxPayException("退款申请接口中out_trade_no、transaction_id至少填一个");
}else if(!$inputObj->IsOut_refund_noSet()){
throw new WxPayException("退款申请接口中缺少必填参数out_refund_no");
}else if(!$inputObj->IsTotal_feeSet()){
throw new WxPayException("退款申请接口中缺少必填参数total_fee");
}else if(!$inputObj->IsRefund_feeSet()){
throw new WxPayException("退款申请接口中缺少必填参数refund_fee");
}else if(!$inputObj->IsOp_user_idSet()){
throw new WxPayException("退款申请接口中缺少必填参数op_user_id");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, true, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 查询退款
* 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,
* 用零钱支付的退款20分钟内到账银行卡支付的退款3个工作日后重新查询退款状态。
* WxPayRefundQuery中out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayRefundQuery $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function refundQuery($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/refundquery";
//检测必填参数
if(!$inputObj->IsOut_refund_noSet() &&
!$inputObj->IsOut_trade_noSet() &&
!$inputObj->IsTransaction_idSet() &&
!$inputObj->IsRefund_idSet()) {
throw new WxPayException("退款查询接口中out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
* 下载对账单WxPayDownloadBill中bill_date为必填参数
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayDownloadBill $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function downloadBill($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/pay/downloadbill";
//检测必填参数
if(!$inputObj->IsBill_dateSet()) {
throw new WxPayException("对账单接口中缺少必填参数bill_date");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$response = self::postXmlCurl($xml, $url, false, $timeOut);
if(substr($response, 0 , 5) == "<xml>"){
return "";
}
return $response;
}
/**
* 提交被扫支付API
* 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台,
* 由商户收银台或者商户后台调用该接口发起支付。
* WxPayWxPayMicroPay中body、out_trade_no、total_fee、auth_code参数必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayWxPayMicroPay $inputObj
* @param int $timeOut
*/
public static function micropay($inputObj, $timeOut = 10)
{
$url = "https://api.mch.weixin.qq.com/pay/micropay";
//检测必填参数
if(!$inputObj->IsBodySet()) {
throw new WxPayException("提交被扫支付API接口中缺少必填参数body");
} else if(!$inputObj->IsOut_trade_noSet()) {
throw new WxPayException("提交被扫支付API接口中缺少必填参数out_trade_no");
} else if(!$inputObj->IsTotal_feeSet()) {
throw new WxPayException("提交被扫支付API接口中缺少必填参数total_fee");
} else if(!$inputObj->IsAuth_codeSet()) {
throw new WxPayException("提交被扫支付API接口中缺少必填参数auth_code");
}
$inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 撤销订单API接口WxPayReverse中参数out_trade_no和transaction_id必须填写一个
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayReverse $inputObj
* @param int $timeOut
* @throws WxPayException
*/
public static function reverse($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
//检测必填参数
if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
throw new WxPayException("撤销订单API接口中参数out_trade_no和transaction_id必须填写一个");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, true, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 测速上报该方法内部封装在report中使用时请注意异常流程
* WxPayReport中interface_url、return_code、result_code、user_ip、execute_time_必填
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayReport $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function report($inputObj, $timeOut = 1)
{
$url = "https://api.mch.weixin.qq.com/payitil/report";
//检测必填参数
if(!$inputObj->IsInterface_urlSet()) {
throw new WxPayException("接口URL缺少必填参数interface_url");
} if(!$inputObj->IsReturn_codeSet()) {
throw new WxPayException("返回状态码缺少必填参数return_code");
} if(!$inputObj->IsResult_codeSet()) {
throw new WxPayException("业务结果缺少必填参数result_code");
} if(!$inputObj->IsUser_ipSet()) {
throw new WxPayException("访问接口IP缺少必填参数user_ip");
} if(!$inputObj->IsExecute_time_Set()) {
throw new WxPayException("接口耗时缺少必填参数execute_time_");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetUser_ip($_SERVER['REMOTE_ADDR']);//终端ip
$inputObj->SetTime(date("YmdHis"));//商户上报时间
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
return $response;
}
/**
*
* 生成二维码规则,模式一生成支付二维码
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayBizPayUrl $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function bizpayurl($inputObj, $timeOut = 6)
{
if(!$inputObj->IsProduct_idSet()){
throw new WxPayException("生成二维码缺少必填参数product_id");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetTime_stamp(time());//时间戳
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
return $inputObj->GetValues();
}
/**
*
* 转换短链接
* 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX)
* 减小二维码数据量,提升扫描速度和精确度。
* appid、mchid、spbill_create_ip、nonce_str不需要填入
* @param WxPayShortUrl $inputObj
* @param int $timeOut
* @throws WxPayException
* @return 成功时返回,其他抛异常
*/
public static function shorturl($inputObj, $timeOut = 6)
{
$url = "https://api.mch.weixin.qq.com/tools/shorturl";
//检测必填参数
if(!$inputObj->IsLong_urlSet()) {
throw new WxPayException("需要转换的URL签名用原串传输需URL encode");
}
$inputObj->SetAppid(WX_APPID);//公众账号ID
$inputObj->SetMch_id(WX_MCHID);//商户号
$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
$inputObj->SetSign();//签名
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response = self::postXmlCurl($xml, $url, false, $timeOut);
$result = WxPayResults::Init($response);
self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
return $result;
}
/**
*
* 支付结果通用通知
* @param function $callback
* 直接回调函数使用方法: notify(you_function);
* 回调类成员函数方法:notify(array($this, you_function));
* $callback 原型为function function_name($data){}
*/
public static function notify($callback, &$msg)
{
//获取通知的数据
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
file_put_contents('./weixinQuery.txt','$xml---ori:---'.$xml,FILE_APPEND);
if(empty($xml)){
$xml = file_get_contents('php://input'); // 解决数据
}
file_put_contents('./weixinQuery.txt','$xml---now:---'.$xml,FILE_APPEND);
//如果返回成功则验证签名
try {
$result = WxPayResults::Init($xml);
//file_put_contents('./weixinQuery.txt','notify:---'.json_encode($result),FILE_APPEND);
} catch (WxPayException $e){
$msg = $e->errorMessage();
file_put_contents('./weixinQuery.txt','WxPayException:---'.$xml,$msg);
return false;
}
return call_user_func($callback, $result);
}
/**
*
* 产生随机字符串不长于32位
* @param int $length
* @return 产生的随机字符串
*/
public static function getNonceStr($length = 32)
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str ="";
for ( $i = 0; $i < $length; $i++ ) {
$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
return $str;
}
/**
* 直接输出xml
* @param string $xml
*/
public static function replyNotify($xml)
{
echo $xml;
}
/**
*
* 上报数据, 上报的时候将屏蔽所有异常流程
* @param string $usrl
* @param int $startTimeStamp
* @param array $data
*/
private static function reportCostTime($url, $startTimeStamp, $data)
{
//如果不需要上报数据
if(WX_REPORT_LEVENL == 0){
return;
}
//如果仅失败上报
if(WX_REPORT_LEVENL == 1 &&
array_key_exists("return_code", $data) &&
$data["return_code"] == "SUCCESS" &&
array_key_exists("result_code", $data) &&
$data["result_code"] == "SUCCESS")
{
return;
}
//上报逻辑
$endTimeStamp = self::getMillisecond();
$objInput = new WxPayReport();
$objInput->SetInterface_url($url);
$objInput->SetExecute_time_($endTimeStamp - $startTimeStamp);
//返回状态码
if(array_key_exists("return_code", $data)){
$objInput->SetReturn_code($data["return_code"]);
}
//返回信息
if(array_key_exists("return_msg", $data)){
$objInput->SetReturn_msg($data["return_msg"]);
}
//业务结果
if(array_key_exists("result_code", $data)){
$objInput->SetResult_code($data["result_code"]);
}
//错误代码
if(array_key_exists("err_code", $data)){
$objInput->SetErr_code($data["err_code"]);
}
//错误代码描述
if(array_key_exists("err_code_des", $data)){
$objInput->SetErr_code_des($data["err_code_des"]);
}
//商户订单号
if(array_key_exists("out_trade_no", $data)){
$objInput->SetOut_trade_no($data["out_trade_no"]);
}
//设备号
if(array_key_exists("device_info", $data)){
$objInput->SetDevice_info($data["device_info"]);
}
try{
self::report($objInput);
} catch (WxPayException $e){
//不做任何处理
}
}
/**
* 以post方式提交xml到对应的接口url
*
* @param string $xml 需要post的xml数据
* @param string $url url
* @param bool $useCert 是否需要证书,默认不需要
* @param int $second url执行超时时间默认30s
* @throws WxPayException
*/
private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
{
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//如果有配置代理这里就设置代理
if(WX_CURL_PROXY_HOST != "0.0.0.0"
&& WX_CURL_PROXY_PORT != 0){
curl_setopt($ch,CURLOPT_PROXY, WX_CURL_PROXY_HOST);
curl_setopt($ch,CURLOPT_PROXYPORT, WX_CURL_PROXY_PORT);
}
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if($useCert == true){
//设置证书
//使用证书cert 与 key 分别属于两个.pem文件
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT, WX_SSLCERT_PATH);
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY, WX_SSLKEY_PATH);
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行curl
$data = curl_exec($ch);
//返回结果
if($data){
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new WxPayException("curl出错错误码:$error");
}
}
/**
* 获取毫秒级别的时间戳
*/
private static function getMillisecond()
{
//获取毫秒的时间戳
$time = explode ( " ", microtime () );
$time = $time[1] . ($time[0] * 1000);
$time2 = explode( ".", $time );
$time = $time2[0];
return $time;
}
}

View File

@@ -0,0 +1,59 @@
<?php
/**
* 配置账号信息
*/
class WxPayConfig
{
//=======【基本信息设置】=====================================
//
/**
* TODO: 修改这里配置为您自己申请的商户信息
* 微信公众号信息配置
*
* APPID绑定支付的APPID必须配置开户邮件中可查看
*
* MCHID商户号必须配置开户邮件中可查看
*
* KEY商户支付密钥参考开户邮件设置必须配置登录商户平台自行设置
* 设置地址https://pay.weixin.qq.com/index.php/account/api_cert
*
* APPSECRET公众帐号secert仅JSAPI支付的时候需要配置 登录公众平台,进入开发者中心可设置),
* 获取地址https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN
* @var string
*/
const APPID = 'wx426b3015555a46be';
const MCHID = '1900009851';
const KEY = '8934e7d15453e97507ef794cf7b0519d';
const APPSECRET = '7813490da6f1265e4901ffb80afaa36f';
//=======【证书路径设置】=====================================
/**
* TODO设置商户证书路径
* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要,可登录商户平台下载,
* API证书下载地址https://pay.weixin.qq.com/index.php/account/api_cert下载之前需要安装商户操作证书
* @var path
*/
const SSLCERT_PATH = '../cert/apiclient_cert.pem';
const SSLKEY_PATH = '../cert/apiclient_key.pem';
//=======【curl代理设置】===================================
/**
* TODO这里设置代理机器只有需要代理的时候才设置不需要代理请设置为0.0.0.0和0
* 本例程通过curl使用HTTP POST方法此处可修改代理服务器
* 默认CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0此时不开启代理如有需要才设置
* @var unknown_type
*/
const CURL_PROXY_HOST = "0.0.0.0";//"10.152.18.220";
const CURL_PROXY_PORT = 0;//8080;
//=======【上报信息配置】===================================
/**
* TODO接口调用上报等级默认紧错误上报注意上报超时间为【1s】上报无论成败【永不抛出异常】
* 不会影响接口调用流程),开启上报之后,方便微信监控请求调用的质量,建议至少
* 开启错误上报。
* 上报等级0.关闭上报; 1.仅错误出错上报; 2.全量上报
* @var int
*/
const REPORT_LEVENL = 1;
}

2983
weixinpay/lib/WxPay.Data.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,13 @@
<?php
/**
*
* 微信支付API异常类
* @author widyhu
*
*/
class WxPayException extends Exception {
public function errorMessage()
{
return $this->getMessage();
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
*
* 回调基础类
* @author widyhu
*
*/
class WxPayNotify extends WxPayNotifyReply
{
/**
*
* 回调入口
* @param bool $needSign 是否需要签名输出
*/
final public function Handle($needSign = true)
{
file_put_contents('./weixinQuery.txt',1111111111111111111111111111111,FILE_APPEND);
$msg = "OK";
//当返回false的时候表示notify中调用NotifyCallBack回调失败获取签名校验失败此时直接回复失败
$result = WxpayApi::notify(array($this, 'NotifyCallBack'), $msg);
if($result == false){
file_put_contents('./weixinQuery.txt','false',FILE_APPEND);
$this->SetReturn_code("FAIL");
$this->SetReturn_msg($msg);
$this->ReplyNotify(false);
return;
} else {
file_put_contents('./weixinQuery.txt','true',FILE_APPEND);
//该分支在成功回调到NotifyCallBack方法处理完成之后流程
$this->SetReturn_code("SUCCESS");
$this->SetReturn_msg("OK");
}
$this->ReplyNotify($needSign);
}
/**
*
* 回调方法入口,子类可重写该方法
* 注意:
* 1、微信回调超时时间为2s建议用户使用异步处理流程确认成功之后立刻回复微信服务器
* 2、微信服务器在调用失败或者接到回包为非确认包的时候会发起重试需确保你的回调是可以重入
* @param array $data 回调解释出的参数
* @param string $msg 如果回调处理失败,可以将错误信息输出到该方法
* @return true回调出来完成不需要继续回调false回调处理未完成需要继续回调
*/
public function NotifyProcess($data, &$msg)
{
//TODO 用户基础该类之后需要重写该方法成功的时候返回true失败返回false
return true;
}
/**
*
* notify回调方法该方法中需要赋值需要输出的参数,不可重写
* @param array $data
* @return true回调出来完成不需要继续回调false回调处理未完成需要继续回调
*/
final public function NotifyCallBack($data)
{
$msg = "OK";
$aaa=json_encode($data);
file_put_contents('./weixinQuery.txt','NotifyCallBack:data---:'.$aaa,FILE_APPEND);
$result = $this->NotifyProcess($data, $msg);
if($result == true){
$this->SetReturn_code("SUCCESS");
$this->SetReturn_msg("OK");
} else {
$this->SetReturn_code("FAIL");
$this->SetReturn_msg($msg);
}
return $result;
}
/**
*
* 回复通知
* @param bool $needSign 是否需要签名输出
*/
final private function ReplyNotify($needSign = true)
{
//如果需要签名
if($needSign == true &&
$this->GetReturn_code($return_code) == "SUCCESS")
{
$this->SetSign();
}
WxpayApi::replyNotify($this->ToXml());
}
}