Looking to hire Laravel developers? Try LaraJobs

laravel-nepal-pay maintained by pra-j

Description
Secure eSewa and Khalti payments for Laravel: server-side verification, amount checks and race-safe status transitions.
Last update
2026/12/05 12:51 (dev-main)
License
Downloads
0

Comments
comments powered by Disqus

Laravel Nepal Pay

tests

eSewa and Khalti payments for Laravel, built so that a customer cannot pay less than they owe or get an order marked paid without paying.

  • The gateway's server decides. Redirect parameters are never trusted. Every payment is confirmed with a server-to-server status lookup that uses only values stored on your side.
  • Amounts are checked. A payment completes only if the gateway reports exactly the amount you asked for. Amounts are integers in paisa, so there are no float rounding bugs.
  • PaymentCompleted is never lost and never doubled by races. Status changes happen under a row lock, and events are dispatched after the outermost transaction commits. If your listener fails, the reconcile command delivers the event again.
  • Signed eSewa callbacks are verified with a constant-time comparison, and must sign the fields that matter.
  • Safe by default. No open redirects, rate-limited callbacks, sandbox mode off unless enabled and refused in production, TLS always on, and secrets kept out of logs and exceptions.
Gateway API Status
eSewa ePay v2 Supported
Khalti ePayment (KPG-2) Supported
Fonepay Dynamic QR Planned

Requires PHP 8.3+ and Laravel 12 or 13.

Status: pre-1.0. The design and tests are complete, but the package has not had an independent security review yet. Read SECURITY.md and test in the sandbox before taking real payments.

Installation

composer require pra-j/laravel-nepal-pay
php artisan migrate

Publishing the config is optional:

php artisan vendor:publish --tag=nepal-pay-config

Configuration

Sandbox mode must be turned on explicitly. It needs no credentials for eSewa (it uses eSewa's public test merchant). For Khalti, use your own key from test-admin.khalti.com, or the public sandbox key from Khalti's documentation for a quick try.

NEPAL_PAY_SANDBOX=true

KHALTI_SECRET_KEY=your-khalti-live-secret-key

For real payments:

NEPAL_PAY_SANDBOX=false

ESEWA_PRODUCT_CODE=your-merchant-code
ESEWA_SECRET_KEY=your-esewa-secret

KHALTI_SECRET_KEY=your-khalti-live-secret-key

APP_URL must be your site's public URL. Callback and redirect URLs are built from it, never from the request's Host header.

Usage

1. Start a payment

use NepalPay\Facades\NepalPay;

public function pay(Order $order)
{
    return NepalPay::checkout(
        gateway: 'esewa',               // or 'khalti'
        amount: $order->total_paisa,    // Rs. 1,250.50 => 125050
        description: "Order #{$order->id}",
        payable: $order,
        successUrl: route('orders.show', $order),
        failureUrl: route('checkout', $order),
    );
}

The returned Checkout is a response. Khalti redirects the customer, and eSewa gets an auto-submitting form. For Inertia or an SPA, build the response yourself:

$checkout = NepalPay::checkout(/* ... */);

if ($checkout->isRedirect()) {
    return Inertia::location($checkout->url());
}

// eSewa: POST $checkout->fields() to $checkout->url() from the browser.

Always take the amount from your database, never from the request.

2. Fulfil the order

The customer comes back through the package's callback route. The package confirms the payment with the gateway, then redirects to your successUrl or failureUrl with ?payment={uuid} added. Fulfil orders in a listener, not in that page:

use NepalPay\Events\PaymentCompleted;

Event::listen(function (PaymentCompleted $event) {
    $order = $event->payment->payable;

    $order->markAsPaid($event->payment);
});

PaymentCompleted is dispatched after the status change is committed, never twice because of concurrent callbacks. If a listener throws, the payment is still completed, the customer is still redirected, and the reconcile command dispatches the event again later. Delivery is therefore at least once: make the listener idempotent, for example by checking whether the order is already paid.

A customer who pays twice for the same order (two tabs, two attempts) creates two completed payments. Check for that in your listener and refund the extra one.

3. Schedule the reconcile command

Customers close the tab or lose signal before returning from the gateway. The reconcile command checks pending and expired payments with the gateway, least recently checked first, and redelivers PaymentCompleted where a listener failed:

// routes/console.php
Schedule::command('nepal-pay:reconcile')->everyTenMinutes()->withoutOverlapping();

Events

Event When
PaymentCompleted Gateway confirmed the full amount. Fulfil the order.
PaymentStatusChanged Any status change. Has $payment and $from.
PaymentAmountMismatch Gateway reported a different amount. The payment is flagged (amount_mismatch_at), left unchanged, and never processed automatically again. Investigate it manually.

Statuses

pending, completed, failed (the gateway refused to start the payment), canceled, expired, refunded, partially_refunded.

Statuses only move forward. A completed payment can only become refunded. A canceled or expired payment still becomes completed if the gateway later confirms it, because the gateway's record of the money wins.

Querying payments

use NepalPay\Models\Payment;
use NepalPay\PaymentStatus;

Payment::forPayable($order)->withStatus(PaymentStatus::Completed)->exists();

Every attribute on Payment is guarded. Create payments with NepalPay::checkout() and change their status only with NepalPay::verify().

How a payment is verified

customer ──► your app: checkout()            payment row created as pending
         ──► gateway: pays
         ──► /nepal-pay/{gateway}/{uuid}/return
               1. payment looked up by uuid and gateway (404 otherwise)
               2. callback checked: eSewa signature + uuid, Khalti pidx (400 otherwise)
               3. server-to-server status lookup with stored values only
               4. amount compared with the stored amount
               5. status changed under a row lock, events dispatched after commit
         ──► redirected to your successUrl or failureUrl

The callback in step 2 only filters out junk. Even a genuinely signed eSewa callback saying COMPLETE changes nothing until step 3 confirms it.

Testing

composer test                                          # unit and feature tests, no network
NEPAL_PAY_SANDBOX_TESTS=1 vendor/bin/pest --group=sandbox   # calls the real eSewa sandbox
composer analyse                                       # PHPStan level 8

To test a full payment by hand in sandbox mode, use Khalti test ID 9800000001 with MPIN 1111 and OTP 987654, or eSewa test ID 9806800001 with password Nepal@123 and token 123456. Khalti adds its service charge on its own page; the lookup still reports your amount, so the amount check passes.

Security

Please report vulnerabilities privately. See SECURITY.md, which also describes the threat model and what the package does not protect against.

License

MIT. See LICENSE.

This project is not affiliated with eSewa or Khalti.