prevailexcel / laravel-marasoftpay
Marasoft Pay的Laravel SDK
Requires
- guzzlehttp/guzzle: ^7.0.1
This package is auto-updated.
Last update: 2024-08-30 11:55:10 UTC
README
一个用于无缝处理MarasoftPay支付的Laravel包。
从个人或全球范围内的个人或企业收集款项,并使用多种货币结算,确保支付过程既经济又方便。此包还允许您接收来自Marasoft Pay的所有类型webhooks,该包会对其进行验证并为您处理有效负载。您可以在几分钟内开始收款。
Bank Transfers
USSD
Cards
Virtual Bank Accounts
Mobile Money
安装
需要PHP 5.4+或HHVM 3.3+,以及Composer。
要获取Laravel Marasoft Pay的最新版本,只需要求它
composer require prevailexcel/laravel-marasoftpay
或者将以下行添加到您的composer.json文件的require块中。
"prevailexcel/laravel-marasoftpay": "1.0.*"
然后您需要运行composer install或composer update来下载它并更新自动加载器。
一旦安装了Laravel Marasoft Pay,您需要注册服务提供者。打开config/app.php并将以下内容添加到providers键中。
如果您使用
Laravel >= 5.5,则可以跳过此步骤并转到配置
'providers' => [ ... PrevailExcel\MarasoftPay\MarasoftPayServiceProvider::class, ... ]
此外,还需要以如下方式注册外观
'aliases' => [ ... 'MarasoftPay' => PrevailExcel\MarasoftPay\Facades\MarasoftPay::class, ... ]
配置
您可以使用此命令发布配置文件
php artisan vendor:publish --provider="PrevailExcel\MarasoftPay\MarasoftPayServiceProvider"
一个名为marasoftpay.php的配置文件,其中包含一些合理的默认值,将被放置在您的config目录中
<?php return [ /** * Public Key From MARASOFTPAY Dashboard * */ 'publicKey' => getenv('MARASOFTPAY_PUBLIC_KEY'), /** * Encryption Key From MARASOFTPAY Dashboard * */ 'encryptionKey' => getenv('MARASOFTPAY_ENCRYPTION_KEY'), /** * You enviroment can either be live or stage. * Make sure to add the appropriate API key after changing the enviroment in .env * */ 'env' => env('MARASOFTPAY_ENV', 'test'), // OR "LIVE" /** * Your secret hash is a unique key which is part of the data sent with your webhooks * It serves as a form of verification to prove that the webhook is coming from Marasoft Pay. * */ 'hash' => env('MARASOFTPAY_HASH', 'MarasoftPay'), // OR "LIVE" /** * Should user bear charge? * */ 'user_bear_charge' => "yes", // or "no" /** * MARASOFTPAY Base URL * */ 'baseUrl' => env('MARASOFTPAY_LIVE_URL', "https://api.marasoftpay.live"), ];
一般支付流程
尽管有多种支付订单的方式,但大多数支付网关都希望您在结账过程中遵循以下流程
1. 客户被重定向到支付提供者网站
当客户完成结账过程并准备支付时,客户必须被重定向到支付提供者的网站。
重定向是通过提交包含一些隐藏字段的表单来完成的。表单必须向支付提供者的网站发送POST请求。隐藏字段至少指定了必须支付的金额、订单ID和一个哈希值。
哈希值是使用隐藏表单字段和非公开的秘密计算得出的。支付提供者使用的哈希值用于验证请求是否有效。
2. 客户在支付提供者网站上支付
客户到达支付提供者的网站,并可以选择支付方式。支付订单所需的所有步骤都由支付提供者处理。
3. 客户被重定向回您的网站
支付订单后,客户被重定向回。在重定向请求到商店网站时,会返回一些值。这些值通常是订单ID、支付结果和一个哈希值。
哈希值是使用返回的一些字段和非公开的秘密计算得出的。此哈希值用于验证请求是否有效且来自支付提供者。这一点至关重要,必须仔细检查此哈希值。
用法
打开您的.env文件,并添加所有必要的密钥,如下所示
MARASOFTPAY_PUBLIC_KEY=MSFT_****_**************************************** MARASOFTPAY_ENCRYPTION_KEY=MSFT_Enc****************************************** MARASOFTPAY_ENV=test MARASOFTPAY_HASH=yoursecret
如果您使用像heroku这样的托管服务,请确保将上述详细信息添加到您的配置变量中。 记住,当您在生产环境中时,将MARASOFTPAY_ENV更改为'live'并更新密钥。
接下来,您需要设置您的路由。
为了开始,您应该有3条路由。
- 用于发起支付
- 设置回调 - Route::callback。
- 设置webhook并处理事件响应 - Route::webhook。
// Laravel 5.1.17 and above Route::post('/pay', 'PaymentController@createPayment')->name('pay'); Route::callback(PaymentController::class, 'handleGatewayCallback'); Route::webhook(WebhookController::class, 'handleWebhook');
或者
// Laravel 8 & 9 Route::post('/pay', [PaymentController::class, 'createPayment'])->name('pay'); Route::callback(PaymentController::class, 'handleGatewayCallback'); Route::webhook(WebhookController::class, 'handleWebhook');
让我们设置我们的控制器
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Redirect; use PrevailExcel\MarasoftPay\Facades\MarasoftPay; class PaymentController extends Controller { /** * Redirect the User to Marasoft Pay Payment Page * @return Url */ public function redirectToGateway() { try{ return MarasoftPay::getLink()->redirectNow(); }catch(\Exception $e) { return Redirect::back()->withMessage(['msg'=> $e->getMessage(), 'type'=>'error']); } } /** * Obtain Marasoft Pay payment information * @return void */ public function handleGatewayCallback() { $paymentDetails = marasoftpay()->getPaymentData(); dd($paymentDetails); // Now you have the payment details, // you can store the reference ID in your db. // you can then redirect or do whatever you want } }
/** * In the case where you need to pass the data from your * controller or via your client or app instead of a form * */ $data = [ 'name' => "Prevail Ambrose", 'email_address' => "example@gmail.com", 'phone_number' => "08100000000", 'amount' => "9000", 'description' => "Gold Color" ]; // if monolithic, do return MarasoftPay::getLink($data)->redirectNow(); // if API, do return MarasoftPay::getLink($data, true);
"User Bear Charge" 默认在
config/marasoftpay.php中设置为 true。如果您想要承担费用,您可以将其更改为 false。您也可以通过直接传递'user_bear_charge' => 'no'来手动覆盖特定方法。
现在让我们使用银行转账来支付。
在这里,您可以获取一个动态账户 payWithBankTransfer($amount) 用于一次性支付,或者您可以获取一个预留账户 getReservedAccount($data) 或周期性支付。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use PrevailExcel\MarasoftPay\Facades\MarasoftPay; class PaymentController extends Controller { /** * You collect data from your blade form * and this returns the Account details for payment */ public function createPayment() { try { // You can use the global helper marasoftpay()->method() or the Facade MarasoftPay::method(). // Dynamic Account Payment return MarasoftPay::payWithBankTransfer("100000"); // Reserved Account Payment $data = [ 'first_name' => "Prevail", 'last_name' => "Ambrose", 'phone_number' => "08052344545", 'tag' => "whatever", 'bvn' => "2522222222" ]; return MarasoftPay::getReservedAccount($data); } catch (\Exception $e) { return redirect()->back()->withMessage(['msg' => $e->getMessage(), 'type' => 'error']); } } }
这将返回包含账户详情的数据,您可以将这些数据展示或发送给用户以进行支付。
处理Webhook
您可以通过监听webhook并服务用户。将重操作写入 handleWebhook() 方法中。
此包将使用密钥散列验证webhook,识别产生webhook的事件,然后添加一个事件键,可以是以下三者之一
CHECKOUT
RESERVED
PAYOUT
在您的控制器中
public function handleWebhook() { // verify webhook and get data marasoftpay()->getWebhookData()->proccessData(function ($data) { // Do something with $data logger($data); $decodedData = json_decode($data, true); if (decodedData['event'] == 'CHECKOUT') { // Do Something } else if (decodedData['event'] == 'RESERVED') { // Do Another Thing } else { // Do Any other thing } // If you have heavy operations, dispatch your queued jobs for them here // OrderJob::dispatch($data); }); // Acknowledge you received the response return http_response_code(200); }
此包建议使用队列作业处理webhook数据,特别是如果您处理重操作,如发送邮件等
Webhook路由 Route::webhook(Controller::class, 'methodName') 的工作原理是什么?
幕后,默认情况下,这将注册一个POST路由 'marasoftpay/webhook' 到您提供的控制器和方法。因为发送webhook的应用程序没有获取csrf-token的方法,您必须将此路由添加到 VerifyCsrfToken中间件的 except 数组中。
protected $except = [ 'marasoftpay/webhook', ];
将 'marasoftpay/webhook' 端点 URL 添加到 MarasoftPay 的三个webhook字段上;
Payments Webhook URL : 127.0.0.1:8000/marasoftpay/webhook
Transfers Webhook URL : 127.0.0.1:8000/marasoftpay/webhook
Card Webhook URL : 127.0.0.1:8000/marasoftpay/webhook
一个示例表单看起来像这样
<form method="POST" action="{{ route('pay') }}"> @csrf <div class="form-group" style="margin-bottom: 10px;"> <label for="name">Name</label> <input class="form-control" type="text" name="name" /> </div> <div class="form-group" style="margin-bottom: 10px;"> <label for="phone-number">Phone Number</label> <input class="form-control" type="tel" name="phone" required /> </div> <div class="form-group" style="margin-bottom: 10px;"> <label for="email">Email</label> <input class="form-control" type="email" name="email" required /> </div> <div class="form-group" style="margin-bottom: 10px;"> <label for="amount">Amount</label> <input class="form-control" type="number" name="amount" required /> </div> <input value="This is the description" type="hidden" name="description" /> <div class="form-submit"> <button class="btn btn-primary btn-block" type="submit"> Pay </button> </div> </form>
当点击提交按钮时,客户将被重定向到支付页面。
所以现在客户在那里进行了某些操作(希望他或她已经支付了订单)现在该包将客户重定向到回调 URL Route::callback()。
我们必须验证重定向到我们站点的是否是一个有效的请求(我们不希望冒充者错误地放置未支付的订单)。
在处理来自支付提供商的请求的控制器中,我们有
MarasoftPay::getPaymentData() - 此函数调用 verifyTransaction() 方法并确保它是一个有效的交易,否则它将抛出异常。
此包提供的其他一些流畅方法在此列出。
收集
/** * Make payment with MPESA mobile money * @returns array */ MarasoftPay::payWithMobileMoney(?array $data); // Or marasoftpay()->payWithMobileMoney(?array $data); /** * Make payment via USSD * @returns array */ MarasoftPay::ussd(); /** * Check your balance for the different currencies available * @returns array */ MarasoftPay::checkBalance();
账户
/** * Generate account statements with custom date ranges * @returns array */ MarasoftPay::accountStatement(?string $start_date = null, ?string $end_date = null); /** * Generate transfer history statements with custom date ranges * @returns array */ MarasoftPay::transferHistory(?string $start_date = null, ?string $end_date = null); /** * Generate payments history statements with custom date ranges * @returns array */ MarasoftPay::paymentsHistory(?string $start_date = null, ?string $end_date = null); /** * Generate reserved account history statements with custom date ranges * @returns array */ MarasoftPay::reservedAccountHistory(?string $start_date = null, ?string $end_date = null);
支付
/** * Move funds from your Marasoft Pay balance to a bank account. * @returns array */ MarasoftPay::transfer($data = null);
工具
/** * Get all the bank codes for all existing banks in our operating countries. * @returns array */ MarasoftPay::getBanks(); /** * Verify the status of a transaction carried out on your Marasoft Pay account * @returns array */ MarasoftPay::verifyTransaction(?string $ref = null); // Or request()->ref = "reference"; marasoftpay()->verifyTransaction(); /** * Verify the status of a transfer carried out from your Marasoft Pay account * @returns array */ MarasoftPay::verifyTransfer(?string $ref = null); /** * Verify the owner of a bank account using the bank code and the account uumber * @returns array */ MarasoftPay::confirmAccount(?string $bank_code = null, ?string $account_number = null);
待办事项
- 添加全面测试
贡献
请随意fork此包并通过提交拉取请求以增强功能来贡献。
我该如何感谢您?
为什么不star github仓库?我很希望得到关注!为什么不分享此仓库的链接到Twitter或HackerNews?传播消息!
谢谢! Chimeremeze Prevail Ejimadu,Akindipe Ambrose。
许可
MIT许可(MIT)。请参阅许可文件获取更多信息。
