引言随着互联网的快速发展,移动支付已经成为现代商业活动中不可或缺的一部分。微信支付作为中国领先的移动支付平台,为商家提供了便捷的收款解决方案。本文将详细讲解如何使用PHP轻松对接微信支付,帮助您开启便...
随着互联网的快速发展,移动支付已经成为现代商业活动中不可或缺的一部分。微信支付作为中国领先的移动支付平台,为商家提供了便捷的收款解决方案。本文将详细讲解如何使用PHP轻松对接微信支付,帮助您开启便捷收款之旅。
在开始对接微信支付之前,您需要完成以下准备工作:
通过Composer安装微信支付SDK,以下为安装命令:
composer require wechatpay/wechatpay-guzzle在您的PHP项目中,创建一个配置文件(例如:wechatpay.php)并配置以下参数:
<?php
return [ 'app_id' => '您的公众号AppID', 'mch_id' => '您的商户号', 'api_key' => '您的API密钥', 'merchant_cert_path' => '/path/to/apiclient_cert.pem', 'merchant_key_path' => '/path/to/apiclient_key.pem', 'notify_url' => '您的异步通知URL',
];以下为发起支付请求的示例代码:
<?php
require 'wechatpay.php';
use WeChatPayGuzzleMiddlewareWeChatPayMiddleware;
use WeChatPayGuzzleMiddlewareUtilAesUtil;
$wechatPay = new WeChatPayGuzzleMiddlewareWeChatPayMiddleware( config('wechatpay.app_id'), config('wechatpay.mch_id'), config('wechatpay.api_key'), config('wechatpay.merchant_cert_path'), config('wechatpay.merchant_key_path')
);
$httpClient = new GuzzleHttpClient();
$httpClient->addMiddleware($wechatPay);
// 发起支付请求
$response = $httpClient->post( 'https://api.mch.weixin.qq.com/v3/pay/transactions/native', [ 'json' => [ 'description' => '商品描述', 'out_trade_no' => '订单号', 'amount' => [ 'total' => 1, // 金额(分) 'currency' => 'CNY', ], 'spbill_create_ip' => '127.0.0.1', 'notify_url' => config('wechatpay.notify_url'), ], ]
);
// 获取支付二维码
$codeUrl = json_decode($response->getBody())->code_url;
echo "<img src='{$codeUrl}' alt='支付二维码'/>";在您的异步通知URL上,接收微信支付的通知并处理订单。以下为处理通知的示例代码:
<?php
require 'wechatpay.php';
use WeChatPayGuzzleMiddlewareWeChatPayMiddleware;
use WeChatPayGuzzleMiddlewareUtilAesUtil;
$wechatPay = new WeChatPayGuzzleMiddlewareWeChatPayMiddleware( config('wechatpay.app_id'), config('wechatpay.mch_id'), config('wechatpay.api_key'), config('wechatpay.merchant_cert_path'), config('wechatpay.merchant_key_path')
);
$httpClient = new GuzzleHttpClient();
$httpClient->addMiddleware($wechatPay);
// 验证签名
$wechatPay->verifyNotify( file_get_contents('php://input')
);
// 处理订单逻辑
// ...通过以上步骤,您已经可以轻松使用PHP对接微信支付。在实际应用中,您可以根据需求调整代码,实现更多功能。祝您在微信支付的道路上越走越远!