escolalms / przelewy24-php
Przelewy24 PHP 库
Requires
- php: ^8.1
- guzzlehttp/guzzle: ^7.6
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.34
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2024-09-22 11:23:10 UTC
README
为 Przelewy24 提供的 PHP 包装器。
如果你正在使用 Laravel,请查看 mnastalski/przelewy24-laravel。
Przelewy24 的 API 文档可在 https://developers.przelewy24.pl/ 查找。
要求
- PHP >=8.1
对于较低的 PHP 版本,请查看 0.x 版本。
安装
composer require escolalms/przelewy24-php
使用
创建实例
use Przelewy24\Przelewy24; $przelewy24 = new Przelewy24( merchantId: 12345, reportsKey: 'f0ae...', crc: 'aef0...', isLive: false, );
将 isLive
设置为 false
将使用 sandbox environment。将其设置为 true
以使用生产/实时模式。
创建交易
$transaction = $przelewy24->transactions()->register( // Required parameters: sessionId: 'unique order identifier from your application', amount: 125, description: 'transaction description', email: 'buyer email address', urlReturn: 'url to return to after transaction', // Optional parameters: urlStatus: 'url to which the transaction status webhook will be sent', // client: 'Mateusz Nastalski', // currency: \Przelewy24\Enums\Currency::EUR, // language: Language::ENGLISH, // ... );
请注意,amount
以整数形式传递,因此如果实际金额为 1.25 PLN
,则需要传递 125
作为值。
有关可用参数的完整列表,请查看 TransactionRequests::register() 的签名。
返回交易的令牌
$transaction->token();
返回支付网关的 URL
$transaction->gatewayUrl();
监听交易状态 webhook
要将 webhook 的有效载荷解析为,请将整个 POST 请求的数据作为数组传递给 handleWebhook()
// $requestData = $request->request->all(); // $requestData = $request->post(); // $requestData = json_decode(file_get_contents('php://input'), true); $webhook = $przelewy24->handleWebhook($requestData);
handleWebhook()
返回 TransactionStatusNotification::class
,该类具有许多有用的方法,您可以使用它们来检查交易数据,以及验证 webhook 的签名。
$webhook->amount(); $webhook->currency(); $webhook->orderId(); ... $webhook->isSignValid(...);
如果您想确保传入请求的 IP 地址属于 Przelewy24,那么有效 IP 地址列表可在 \Przelewy24\Constants\IpAddresses::V4
常量中找到。还有一个接受 IP 地址字符串并返回布尔值的辅助方法:\Przelewy24\Constants\IpAddresses::isValid($ip)
。
验证交易
$przelewy24->transactions()->verify( sessionId: 'unique order identifier from your application', orderId: $webhook->orderId(), amount: 125, );
类似于注册交易,amount
也是以整数形式传递的。
错误处理
如果 Przelewy24 的 API 返回错误响应,则会抛出 ApiResponseException::class
(它扩展了 Przelewy24Exception::class
)。因此,您可以使用 try/catch
块来处理任何错误。
use Przelewy24\Exceptions\Przelewy24Exception; try { $przelewy24->transactions()->verify([ // ... ]); } catch (Przelewy24Exception $e) { // Handle the error... }