aratkruglik/monobank-laravel 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

aratkruglik/monobank-laravel

Composer 安装命令:

composer require aratkruglik/monobank-laravel

包简介

A comprehensive Monobank API integration for Laravel 11, 12, 13

README 文档

README

A robust, idiomatic Laravel package for integrating with the Monobank Acquiring API. Designed specifically for e-commerce applications, it provides secure invoice creation, payment processing, refund handling, and webhook verification.

Latest Version on Packagist Tests Total Downloads

Features

  • 🚀 Full Acquiring API Support: Create invoices, check statuses, process refunds.
  • 🔒 Security First: Automatic verification of Monobank Webhook signatures (ECDSA) using dynamic Public Key caching.
  • 📦 Strictly Typed: Uses DTOs and Enums for all requests and responses. No magic arrays.
  • Laravel Native: Integration with Laravel's Event system, HTTP Client, and Service Container.
  • 🛡️ Security Hardened: User-friendly error messages that don't expose API internals, sanitized logging, input validation.

Official Documentation

For detailed information about the Monobank Acquiring API, please refer to the official documentation:

Requirements

  • PHP 8.3+
  • Laravel 11.x-13.x

Installation

You can install the package via composer:

composer require aratkruglik/monobank-laravel

Publish the configuration file:

php artisan vendor:publish --tag="monobank-config"

Configuration

Add your Monobank Acquiring Token (X-Token) to your .env file:

MONOBANK_TOKEN=your_token_here
MONOBANK_REDIRECT_URL=https://your-site.com/checkout/success
MONOBANK_WEBHOOK_URL=https://your-site.com/api/monobank/webhook

You can customize the configuration in config/monobank.php.

Usage

1. Creating an Invoice

To accept a payment, create an invoice. You can pass the amount as float (major units, e.g., 100.50 UAH) or integer (cents, e.g., 10050).

use AratKruglik\Monobank\Facades\Monobank;
use AratKruglik\Monobank\DTO\InvoiceRequestDTO;
use AratKruglik\Monobank\Enums\CurrencyCode;

$invoice = Monobank::createInvoice(new InvoiceRequestDTO(
    amount: 100.00, // 100.00 UAH
    ccy: CurrencyCode::UAH,
    destination: 'Payment for Order #12345',
    reference: 'ORDER-12345',
    redirectUrl: 'https://myshop.com/thank-you',
    successUrl: 'https://myshop.com/success',
    failUrl: 'https://myshop.com/failure',
    webHookUrl: 'https://myshop.com/api/webhook',
    validity: 3600 // 1 hour
));

// Redirect user to the payment page
return redirect($invoice->pageUrl);

With Cart Items

You can pass detailed cart information for the fiscal check.

use AratKruglik\Monobank\DTO\CartItemDTO;

$cart = [
    new CartItemDTO(name: 'T-Shirt', qty: 2, sum: 50.00, code: 'tshirt-001'), // 50.00 UAH
    new CartItemDTO(name: 'Socks', qty: 1, sum: 2.00, code: 'socks-001'), // 2.00 UAH
];

$request = new InvoiceRequestDTO(
    amount: 102.00, // Total: 102.00 UAH
    cartItems: $cart
);

$invoice = Monobank::createInvoice($request);

2. Checking Invoice Status

Retrieve the current status of an invoice. The response uses strict Enums.

use AratKruglik\Monobank\Enums\InvoiceStatus;

$status = Monobank::getInvoiceStatus('invoice_id_here');

if ($status->status === InvoiceStatus::SUCCESS) {
    // Order paid!
} elseif ($status->status === InvoiceStatus::FAILURE) {
    // Payment failed
}

3. Cancelling / Refunding

You can cancel an unpaid invoice or refund a paid one (fully or partially).

// Full refund / Cancel
Monobank::cancelInvoice('invoice_id_here');

// Partial refund (e.g., refunding 50.50 UAH)
Monobank::cancelInvoice(
    invoiceId: 'invoice_id_here',
    amount: 50.50 // 50.50 UAH
);

You can also remove an unpaid invoice entirely, or finalize a "hold" invoice (capture the previously authorized amount):

// Remove an invoice
Monobank::removeInvoice('invoice_id_here');

// Finalize a hold invoice (full capture)
Monobank::finalizeInvoice('invoice_id_here');

// Finalize a hold invoice (partial capture, e.g., 50.50 UAH)
Monobank::finalizeInvoice('invoice_id_here', 50.50);

4. Merchant Details

Get information about your merchant account.

$details = Monobank::getDetails();
echo $details['merchantName'];

QR Acquiring

You can manage your physical QR stands using the following methods.

1. List QR Registers

$list = Monobank::getQrList();

foreach ($list as $qr) {
    echo $qr->qrId . ' - ' . $qr->pageUrl;
}

2. Get QR Details

$qr = Monobank::getQrDetails('qr_id_here');
echo $qr->shortQrId;

3. Invoice for QR Stand

To assign an amount to a specific QR stand (so the client scans it and sees the amount), create an invoice passing the qrId.

$invoice = Monobank::createInvoice(new InvoiceRequestDTO(
    amount: 150.00,
    qrId: 'qr_id_here'
));

4. Reset QR Amount

Remove the assigned amount from a QR stand.

Monobank::resetQrAmount('qr_id_here');

Recurring Payments (Subscriptions)

You can manage subscriptions for recurring payments.

Note: createSubscription, getSubscriptionDetails, and deleteSubscription are documented, officially supported Monobank Acquiring API endpoints, confirmed via the official API docs, though not present in the bundled .claude/skills/monobank-acquiring reference set.

1. Create Subscription

use AratKruglik\Monobank\DTO\SubscriptionRequestDTO;

$subscription = Monobank::createSubscription(new SubscriptionRequestDTO(
    amount: 100.00, // 100.00 UAH
    interval: '1m', // 1 month
    webHookStatusUrl: 'https://site.com/sub/status',
    redirectUrl: 'https://site.com/thank-you'
));

return redirect($subscription->pageUrl);

2. Get Subscription Details

$details = Monobank::getSubscriptionDetails('sub_id_here');

3. Cancel Subscription

Monobank::deleteSubscription('sub_id_here');

Direct & Token Payments

You can charge a card directly (without redirecting the customer to a Monobank hosted page), process a synchronous payment via card/Apple Pay/Google Pay data, or charge a previously saved wallet card token.

⚠️ PCI DSS: PaymentDirectRequestDTO and SyncPaymentRequestDTO carry raw cardholder data (PAN, expiry, CVV). Your application must be PCI DSS compliant to collect and transmit this data. Never log these DTOs or their toArray() output.

use AratKruglik\Monobank\DTO\PaymentDirectRequestDTO;

$response = Monobank::paymentDirect(new PaymentDirectRequestDTO(
    amount: 100.00, // 100.00 UAH
    cardData: [
        'pan' => '4242424242424242',
        'exp' => '1230',
        'cvv' => '123',
    ],
));

// A payment may require 3-D Secure confirmation before it settles.
if ($response->tdsUrl !== null) {
    return redirect($response->tdsUrl);
}
use AratKruglik\Monobank\DTO\SyncPaymentRequestDTO;

// Exactly one of cardData, applePay, googlePay must be provided.
$status = Monobank::syncPayment(new SyncPaymentRequestDTO(
    amount: 50.00,
    cardData: [
        'pan' => '4242424242424242',
        'exp' => '1230',
        'cvv' => '123',
    ],
));

To charge a previously saved wallet card, or manage a customer's saved cards:

use AratKruglik\Monobank\DTO\WalletPaymentRequestDTO;

$response = Monobank::walletPayment(new WalletPaymentRequestDTO(
    cardToken: 'card_token_here',
    amount: 20.00,
    initiationKind: 'merchant',
));

// List cards saved for a wallet/customer
$cards = Monobank::getWalletCards('wallet_id_here');

// Delete a saved card
Monobank::deleteWalletCard('card_token_here');

Statement & Reporting

Retrieve a report of transactions for a given time period (unix timestamps).

$statement = Monobank::getStatement(
    from: strtotime('-1 day'),
    to: time()
);

foreach ($statement as $item) {
    echo $item->invoiceId . ' - ' . $item->amount;
}

Employees

Retrieve the list of employees configured for your merchant account (used for tips distribution).

$employees = Monobank::getEmployeeList();

foreach ($employees as $employee) {
    echo $employee->name;
}

Fiscal Checks & Receipts

Retrieve fiscal check statuses for an invoice, and download a receipt file.

$checks = Monobank::getFiscalChecks('invoice_id_here');

foreach ($checks as $check) {
    echo $check->status . ' - ' . $check->type;
}

$receiptFile = Monobank::getReceipt('invoice_id_here');

Marketplace / Split Payments

You can split a payment between multiple recipients (sub-merchants) by specifying splitReceiverId for each item in the cart.

1. Get Split Receivers

Retrieve a list of available sub-merchants.

$receivers = Monobank::getSplitReceivers();

foreach ($receivers as $receiver) {
    echo $receiver->code . ' - ' . $receiver->iban;
}

2. Create Split Invoice

use AratKruglik\Monobank\DTO\CartItemDTO;

$cart = [
    new CartItemDTO(
        name: 'Item from Partner A', 
        qty: 1, 
        sum: 100.00, 
        splitReceiverId: 'receiver_id_a'
    ),
    new CartItemDTO(
        name: 'Item from Partner B', 
        qty: 1, 
        sum: 200.00, 
        splitReceiverId: 'receiver_id_b'
    ),
];

$request = new InvoiceRequestDTO(
    amount: 300.00,
    cartItems: $cart
);

$invoice = Monobank::createInvoice($request);

Webhooks

This package handles webhook security automatically. It fetches Monobank's public key, caches it, and verifies the X-Sign header for every incoming request.

1. Setup Route

Register the webhook route in your routes/api.php using the provided macro:

use Illuminate\Support\Facades\Route;

// This registers a POST route that handles signature verification
Route::monobankWebhook('/monobank/webhook');

2. Handle Events

When a valid webhook is received, the package dispatches the AratKruglik\Monobank\Events\WebhookReceived event. You should listen for this event in your application.

EventServiceProvider:

use AratKruglik\Monobank\Events\WebhookReceived;
use App\Listeners\HandleMonobankPayment;

protected $listen = [
    WebhookReceived::class => [
        HandleMonobankPayment::class,
    ],
];

Listener:

namespace App\Listeners;

use AratKruglik\Monobank\Events\WebhookReceived;
use AratKruglik\Monobank\Enums\InvoiceStatus;

class HandleMonobankPayment
{
    public function handle(WebhookReceived $event): void
    {
        $payload = $event->payload;
        
        // $payload is an array containing invoiceId, status, amount, etc.
        $invoiceId = $payload['invoiceId'];
        $status = $payload['status'];

        if ($status === InvoiceStatus::SUCCESS->value) {
            // Mark order as paid
        }
    }
}

Error Handling

The package provides typed exceptions with user-friendly messages that don't expose sensitive API details:

use AratKruglik\Monobank\Exceptions\ValidationException;
use AratKruglik\Monobank\Exceptions\AuthenticationException;
use AratKruglik\Monobank\Exceptions\RateLimitExceededException;
use AratKruglik\Monobank\Exceptions\ServerException;

try {
    $invoice = Monobank::createInvoice($request);
} catch (ValidationException $e) {
    // User-friendly message for display
    $userMessage = $e->getMessage(); // "Payment validation failed..."

    // API details for logging (not exposed to users)
    Log::error('Monobank error', $e->getApiErrorDetails());
} catch (RateLimitExceededException $e) {
    // Retry after the specified time
    $retryAfter = $e->retryAfter; // seconds
} catch (AuthenticationException $e) {
    // Check your API token
}

Testing

The package is fully tested with Pest. You can run the tests using:

composer test

Testing & Development

To test your integration without real money:

  1. Obtain a Test Acquiring Token from the Monobank Dashboard.
  2. Set this token in your .env file: MONOBANK_TOKEN=your_test_token.
  3. In the test environment, you can use any valid card number (passing Luhn validation) to simulate payments. Financial authorization is skipped.

License

The MIT License (MIT). Please see License File for more information.

aratkruglik/monobank-laravel 适用场景与选型建议

aratkruglik/monobank-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 124 次下载、GitHub Stars 达 6, 最近一次更新时间为 2026 年 01 月 12 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「laravel」 「Banking」 「finance」 「monobank」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 aratkruglik/monobank-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 aratkruglik/monobank-laravel 我们能提供哪些服务?
定制开发 / 二次开发

基于 aratkruglik/monobank-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 124
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 19
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-12