thinkphp5集成微信支付的方法
2024-09-01 21:42:23
在ThinkPHP5中集成微信支付,你需要遵循以下步骤:
- 注册微信支付商户
首先,你需要在微信支付官网注册成为微信支付商户,以获取必要的商户信息,如商户号、API密钥等。
- 安装微信支付SDK
在ThinkPHP5项目中,你可以使用Composer来安装微信支付SDK。在项目根目录下运行以下命令:
composer require "overtrue/wechat:~3.1 -D"
- 配置微信支付
在application
目录下的extra
文件夹中创建一个名为wechat.php
的配置文件,并填写微信支付相关参数:
<?php
return [
'app_id' => 'your_app_id',
'mch_id' => 'your_mch_id',
'key' => 'your_api_key',
'notify_url' => 'your_notify_url', // 支付结果通知地址
'trade_type' => 'JSAPI', // 交易类型,默认为JSAPI
'openid' => 'your_openid', // 用户的openid
];
- 创建支付控制器
在application/controller
目录下创建一个名为WechatPayController.php
的控制器文件,并编写支付相关方法:
<?php
namespace app\controller;
use think\Controller;
use overtrue\wechat\Payment;
class WechatPayController extends Controller
{
protected function _initialize()
{
$this->wechatPay = new Payment(config('wechat'));
}
public function pay()
{
$order = [
'body' => '商品描述',
'out_trade_no' => '商户订单号',
'total_fee' => 100, // 单位:分
'spbill_create_ip' => request()->ip(),
'notify_url' => config('wechat.notify_url'),
'trade_type' => config('wechat.trade_type'),
'openid' => config('wechat.openid'),
];
$result = $this->wechatPay->order->unifiedOrder($order);
return json($result);
}
public function notify()
{
$this->wechatPay->handleNotify(function ($message, \Closure $next) {
// 处理支付结果通知,例如更新订单状态等
// $message['out_trade_no'] 商户订单号
// $message['transaction_id'] 微信订单号
// $message['trade_state'] 交易状态
// $message['time_end'] 支付完成时间
// ... 更新订单状态等业务逻辑
return true; // 返回true表示处理成功,继续执行后续流程
});
}
}
- 配置路由
在application/route.php
文件中配置支付相关路由:
<?php
use think\Route;
Route::post('pay', 'WechatPayController/pay');
Route::post('notify', 'WechatPayController/notify');
- 前端调用支付接口
在前端页面中,你需要调用微信JSAPI支付接口。首先,引入微信JS库:
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
然后,调用支付接口:
function pay() {
// 获取后端返回的支付参数
fetch('/pay')
.then(response => response.json())
.then(data => {
// 调用微信支付接口
wx.chooseWXPay({
timestamp: data.timeStamp,
nonceStr: data.nonceStr,
package: data.package,
signType: data.signType,
paySign: data.paySign,
success: function (res) {
// 支付成功后的回调函数
alert('支付成功');
},
fail: function (res) {
// 支付失败后的回调函数
alert('支付失败');
}
});
});
}
至此,你已经成功在ThinkPHP5中集成了微信支付功能。用户可以通过前端页面发起支付请求,微信支付完成后,会自动调用后端的notify
接口处理支付结果。
还没有人发表评论