unicodeveloper / laravel-paystack
用于与Paystack无缝工作的Laravel包
Requires
- php: ^7.2|^8.0|^8.1
- guzzlehttp/guzzle: ~6|~7|~8|~9
- illuminate/support: ~6|~7|~8|~9|^10.0|^11.0
Requires (Dev)
- mockery/mockery: ^1.3
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ^8.4|^9.0|^10.5
- scrutinizer/ocular: ~1.1
README
一个用于与Paystack无缝工作的Laravel包
安装
需要PHP 5.4+ 或 HHVM 3.3+ 以及 Composer。
要获取Laravel Paystack的最新版本,只需引入它
composer require unicodeveloper/laravel-paystack
或者将以下行添加到您的 composer.json
文件的 require 块中。
"unicodeveloper/laravel-paystack": "1.0.*"
然后运行 composer install
或 composer update
下载它,并更新自动加载器。
安装Laravel Paystack后,您需要注册服务提供者。打开 config/app.php
并将以下内容添加到 providers
键中。
'providers' => [ ... Unicodeveloper\Paystack\PaystackServiceProvider::class, ... ]
如果您使用的是 Laravel >= 5.5,则可以跳过此步骤并转到
配置
Unicodeveloper\Paystack\PaystackServiceProvider::class
同时,按照如下方式注册门面
'aliases' => [ ... 'Paystack' => Unicodeveloper\Paystack\Facades\Paystack::class, ... ]
配置
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="Unicodeveloper\Paystack\PaystackServiceProvider"
一个名为 paystack.php
的配置文件将带有一些合理的默认值放置在您的 config
目录中
<?php return [ /** * Public Key From Paystack Dashboard * */ 'publicKey' => getenv('PAYSTACK_PUBLIC_KEY'), /** * Secret Key From Paystack Dashboard * */ 'secretKey' => getenv('PAYSTACK_SECRET_KEY'), /** * Paystack Payment URL * */ 'paymentUrl' => getenv('PAYSTACK_PAYMENT_URL'), /** * Optional email address of the merchant * */ 'merchantEmail' => getenv('MERCHANT_EMAIL'), ];
通用支付流程
尽管有多个支付订单的方法,但大多数支付网关都期望您在结账过程中遵循以下流程
1. 客户被重定向到支付提供者
在客户完成结账流程并准备好支付后,客户必须被重定向到支付提供者的网站。
重定向是通过提交包含一些隐藏字段的表单来完成的。表单必须向支付提供者的网站发送 POST 请求。隐藏字段最少指定必须支付的金额、订单 ID 和一个散列值。
散列值是使用隐藏表单字段和一个非公开的秘密计算的。支付提供者使用的散列值用于验证请求是否有效。
2. 客户在支付提供者的网站上支付
客户到达支付提供者的网站并可以选择支付方式。支付订单所需的全部步骤都由支付提供者负责。
3. 客户被重定向回您的网站
支付订单后,客户被重定向回来。在重定向请求到商店网站时,会返回一些值。这些值通常是订单 ID、支付结果和一个散列值。
散列值是基于返回的一些字段和一个非公开的秘密计算的。此散列值用于验证请求是否有效且来自支付提供者。务必仔细检查此散列值。
用法
打开您的 .env 文件并添加您的公钥、密钥、商家电子邮件和支付 URL,如下所示
PAYSTACK_PUBLIC_KEY=xxxxxxxxxxxxx PAYSTACK_SECRET_KEY=xxxxxxxxxxxxx PAYSTACK_PAYMENT_URL=https://api.paystack.co MERCHANT_EMAIL=unicodeveloper@gmail.com
如果您使用的是像 heroku 这样的托管服务,请确保将上述详细信息添加到您的配置变量中。
设置路由和控制器方法,如下所示
注意:请确保您已在 Paystack 仪表板中将 /payment/callback
注册,网址如下 https://dashboard.paystack.co/#/settings/developer,如下所示
// Laravel 5.1.17 and above Route::post('/pay', 'PaymentController@redirectToGateway')->name('pay');
或者
Route::post('/pay', [ 'uses' => 'PaymentController@redirectToGateway', 'as' => 'pay' ]);
或者
// Laravel 8 & 9 Route::post('/pay', [App\Http\Controllers\PaymentController::class, 'redirectToGateway'])->name('pay');
Route::get('/payment/callback', 'PaymentController@handleGatewayCallback');
或者
// Laravel 5.0 Route::get('payment/callback', [ 'uses' => 'PaymentController@handleGatewayCallback' ]);
或者
// Laravel 8 & 9 Route::get('/payment/callback', [App\Http\Controllers\PaymentController::class, 'handleGatewayCallback']);
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Redirect; use Paystack; class PaymentController extends Controller { /** * Redirect the User to Paystack Payment Page * @return Url */ public function redirectToGateway() { try{ return Paystack::getAuthorizationUrl()->redirectNow(); }catch(\Exception $e) { return Redirect::back()->withMessage(['msg'=>'The paystack token has expired. Please refresh the page and try again.', 'type'=>'error']); } } /** * Obtain Paystack payment information * @return void */ public function handleGatewayCallback() { $paymentDetails = Paystack::getPaymentData(); dd($paymentDetails); // Now you have the payment details, // you can store the authorization_code in your db to allow for recurrent subscriptions // you can then redirect or do whatever you want } }
/** * In the case where you need to pass the data from your * controller instead of a form * Make sure to send: * required: email, amount, reference, orderID(probably) * optionally: currency, description, metadata * e.g: * */ $data = array( "amount" => 700 * 100, "reference" => '4g4g5485g8545jg8gj', "email" => 'user@mail.com', "currency" => "NGN", "orderID" => 23456, ); return Paystack::getAuthorizationUrl($data)->redirectNow();
让我在这里简要解释一下该包提供的流畅方法。
/** * This fluent method does all the dirty work of sending a POST request with the form data * to Paystack Api, then it gets the authorization Url and redirects the user to Paystack * Payment Page. We've abstracted all of it, so you don't have to worry about that. * Just eat your cookies while coding! */ Paystack::getAuthorizationUrl()->redirectNow(); /** * Alternatively, use the helper. */ paystack()->getAuthorizationUrl()->redirectNow(); /** * This fluent method does all the dirty work of verifying that the just concluded transaction was actually valid, * It verifies the transaction reference with Paystack Api and then grabs the data returned from Paystack. * In that data, we have a lot of good stuff, especially the `authorization_code` that you can save in your db * to allow for easy recurrent subscription. */ Paystack::getPaymentData(); /** * Alternatively, use the helper. */ paystack()->getPaymentData(); /** * This method gets all the customers that have performed transactions on your platform with Paystack * @returns array */ Paystack::getAllCustomers(); /** * Alternatively, use the helper. */ paystack()->getAllCustomers(); /** * This method gets all the plans that you have registered on Paystack * @returns array */ Paystack::getAllPlans(); /** * Alternatively, use the helper. */ paystack()->getAllPlans(); /** * This method gets all the transactions that have occurred * @returns array */ Paystack::getAllTransactions(); /** * Alternatively, use the helper. */ paystack()->getAllTransactions(); /** * This method generates a unique super secure cryptographic hash token to use as transaction reference * @returns string */ Paystack::genTranxRef(); /** * Alternatively, use the helper. */ paystack()->genTranxRef(); /** * This method creates a subaccount to be used for split payments * @return array */ Paystack::createSubAccount(); /** * Alternatively, use the helper. */ paystack()->createSubAccount(); /** * This method fetches the details of a subaccount * @return array */ Paystack::fetchSubAccount(); /** * Alternatively, use the helper. */ paystack()->fetchSubAccount(); /** * This method lists the subaccounts associated with your paystack account * @return array */ Paystack::listSubAccounts(); /** * Alternatively, use the helper. */ paystack()->listSubAccounts(); /** * This method Updates a subaccount to be used for split payments * @return array */ Paystack::updateSubAccount(); /** * Alternatively, use the helper. */ paystack()->updateSubAccount();
一个示例表单将如下所示
<?php // more details https://paystack.com/docs/payments/multi-split-payments/#dynamic-splits $split = [ "type" => "percentage", "currency" => "KES", "subaccounts" => [ [ "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 10 ], [ "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 30 ], ], "bearer_type" => "all", "main_account_share" => 70 ]; ?>
<form method="POST" action="{{ route('pay') }}" accept-charset="UTF-8" class="form-horizontal" role="form"> <div class="row" style="margin-bottom:40px;"> <div class="col-md-8 col-md-offset-2"> <p> <div> Lagos Eyo Print Tee Shirt ₦ 2,950 </div> </p> <input type="hidden" name="email" value="otemuyiwa@gmail.com"> {{-- required --}} <input type="hidden" name="orderID" value="345"> <input type="hidden" name="amount" value="800"> {{-- required in kobo --}} <input type="hidden" name="quantity" value="3"> <input type="hidden" name="currency" value="NGN"> <input type="hidden" name="metadata" value="{{ json_encode($array = ['key_name' => 'value',]) }}" > {{-- For other necessary things you want to add to your payload. it is optional though --}} <input type="hidden" name="reference" value="{{ Paystack::genTranxRef() }}"> {{-- required --}} <input type="hidden" name="split_code" value="SPL_EgunGUnBeCareful"> {{-- to support transaction split. more details https://paystack.com/docs/payments/multi-split-payments/#using-transaction-splits-with-payments --}} <input type="hidden" name="split" value="{{ json_encode($split) }}"> {{-- to support dynamic transaction split. More details https://paystack.com/docs/payments/multi-split-payments/#dynamic-splits --}} {{ csrf_field() }} {{-- works only when using laravel 5.1, 5.2 --}} <input type="hidden" name="_token" value="{{ csrf_token() }}"> {{-- employ this in place of csrf_field only in laravel 5.0 --}} <p> <button class="btn btn-success btn-lg btn-block" type="submit" value="Pay Now!"> <i class="fa fa-plus-circle fa-lg"></i> Pay Now! </button> </p> </div> </div> </form>
当点击提交按钮时,客户会被重定向到Paystack网站。
因此现在我们已经将客户重定向到了Paystack。客户在那里执行了一些操作(希望他们已经支付了订单)然后现在被重定向回我们的商店网站。
Paystack会将客户重定向到Paystack仪表板Web Hooks部分的回调URL中指定的路由URL。
我们必须验证重定向到我们网站的请求是否是有效的(我们不希望冒充者错误地放置未付款的订单)。
在处理来自支付提供者的请求的控制器中,我们有
Paystack::getPaymentData()
- 这个函数调用验证方法并确保这是一笔有效交易,否则它会抛出异常。
您可以使用这些详细信息进行测试
Card Number: 4123450131001381
Expiry Date: any date in the future
CVV: 883
待办事项
- 重新收费客户
- 添加全面的测试
- 实现事务仪表板以查看您Laravel应用程序中的所有交易
贡献
请随意分叉此包,并通过提交拉取请求来增强功能进行贡献。
我如何感谢您?
为什么不给GitHub仓库加星?我非常喜欢关注!为什么不把此仓库的链接分享到Twitter或HackerNews?传播一下!
别忘了在Twitter上关注我!
谢谢!Prosper Otemuyiwa。
许可协议
MIT许可协议(MIT)。请参阅许可文件以获取更多信息。