Download the PHP package bijayx/nepal-pay-laravel without Composer
On this page you can find all versions of the php package bijayx/nepal-pay-laravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download bijayx/nepal-pay-laravel
More information about bijayx/nepal-pay-laravel
Files in bijayx/nepal-pay-laravel
Package nepal-pay-laravel
Short Description Khalti and eSewa payment gateways for Laravel behind one typed, verified API.
License MIT
Homepage https://github.com/BijayX/nepal-pay-laravel
Informations about the package nepal-pay-laravel
Nepal Pay for Laravel
Khalti and eSewa payments for Laravel behind one typed API, with server-side verification, signature checks, amount/reference matching and consistent exceptions.
- One interface for every gateway:
initiate(),verify(),lookup(). - Money is always an integer number of paisa (Rs 1 = 100 paisa). No floats.
verify()always confirms with the gateway's server and rejects payments that do not match what you stored (AMOUNT_MISMATCH,REFERENCE_MISMATCH).- eSewa callback signatures are checked in constant time; Khalti's HTTP 400 lookup responses for expired and canceled payments are handled.
- Laravel's HTTP client under the hood, so
Http::fake()works in your tests. - Safe retries for read-only status calls only. Payment creation is never retried.
This package follows the same contract as the Node.js package @bijayx/nepal-pay: statuses,
error codes and behaviour are identical.
Contents
- Requirements
- Installation
- Configuration
- Quick start
- A complete checkout flow
- API reference
- Payment statuses
- Error handling
- Events
- Testing your application
- Sandbox credentials
- Security checklist
- Custom gateways
- Customising the eSewa redirect page
Requirements
- PHP 8.2 or newer
- Laravel 12 or 13
Installation
The service provider and the NepalPay facade are registered automatically.
Publish the configuration file if you want to change defaults:
Configuration
Add your credentials to .env. Only configure the gateways you use.
| Key | Default | Notes |
|---|---|---|
default |
khalti |
Gateway used by NepalPay::initiate() etc. and by PaymentGateway injection. |
environment |
sandbox |
Production is never assumed. Each gateway may override it with gateways.<name>.environment (KHALTI_ENV, ESEWA_ENV). |
http.timeout_ms |
15000 |
Timeout for each gateway request. |
http.retries |
2 |
Extra attempts for read-only calls (Khalti lookup, eSewa status) on network errors, timeouts and 5xx. |
http.retry_delay_ms |
200 |
Backoff base: delay * 2^attempt. |
gateways.khalti.secret_key |
none | Required. |
gateways.khalti.website_url |
none | Required, absolute URL of your site. |
gateways.khalti.base_url |
official | Optional override (proxies, tests). |
gateways.esewa.product_code |
EPAYTEST in sandbox |
Required in production. |
gateways.esewa.secret_key |
UAT secret in sandbox | Required in production. The UAT secret is only used with EPAYTEST. |
gateways.esewa.form_url, status_url |
official | Optional overrides. |
Configuration is validated when a gateway is first resolved. Missing or invalid values throw
ConfigurationException immediately instead of failing during a payment.
Endpoints used:
| sandbox | production | |
|---|---|---|
| Khalti API | https://dev.khalti.com/api/v2/ |
https://khalti.com/api/v2/ |
| eSewa form | https://rc-epay.esewa.com.np/api/epay/main/v2/form |
https://epay.esewa.com.np/api/epay/main/v2/form |
| eSewa status | https://rc.esewa.com.np/api/epay/transaction/status/ |
https://esewa.com.np/api/epay/transaction/status/ |
Quick start
When the payer comes back to your return URL:
$payment->redirect() returns a response that works for both gateways: a 302 redirect for
Khalti, and a small self-submitting HTML form for eSewa (eSewa requires a POST).
You can also type-hint the contract to receive the default gateway:
A complete checkout flow
Migration columns (amounts in paisa):
Routes. Keep the order in the path: eSewa appends ?data=... to the return URL and does not
handle an existing query string.
Controller:
If the payer never returns (closed the tab, lost connection), reconcile pending orders from a
scheduled job with lookup():
API reference
initiate(PaymentRequest|array $request): InitiatedPayment
Accepts an array with snake_case keys or a PaymentRequest object. Input is validated before
any network call; invalid input throws ValidationException with all field errors.
| Key | Type | Rules |
|---|---|---|
amount |
int | Total in paisa, greater than 0. Khalti requires at least 1000 (Rs 10). |
order_id |
string | Unique per payment attempt, 1-64 chars, A-Z a-z 0-9 -. |
order_name |
string | Required, max 255 characters. |
return_url |
string | Absolute http(s) URL. |
failure_url |
string, optional | eSewa only. Defaults to return_url. |
customer |
array, optional | name, email, phone. Sent to Khalti; ignored by eSewa. |
breakdown |
array, optional | tax, service_charge, delivery_charge in paisa (>= 0). Their sum must be less than amount. |
metadata |
array, optional | String values; keys match ^[a-z0-9_]+$. Khalti: merchant_<key>. eSewa: properties[<key>], max 3 keys. |
InitiatedPayment:
| Property | Description |
|---|---|
gateway |
"khalti" or "esewa" |
reference |
Khalti pidx, or eSewa transaction_uuid (equal to order_id). Store it. |
orderId, amount |
As requested (paisa). |
redirect |
RedirectInstruction with method (GET/POST), url, fields (eSewa form fields). |
expiresAt |
CarbonImmutable for Khalti, null for eSewa. |
raw |
Khalti response body, or eSewa form fields. |
redirect() |
Method returning a GatewayRedirectResponse to return from a controller. |
Use $payment->redirect (the instruction) if you build the redirect yourself, for example
in an SPA or mobile app.
eSewa's initiate() makes no HTTP call: it signs the form fields locally.
verify(array $callback, ?ExpectedPayment $expected = null): PaymentResult
Pass the raw query parameters of the return request and what you stored at initiate time.
- The gateway's server is always asked for the final status (Khalti lookup, eSewa status API). Status values in the callback are never trusted.
- eSewa callbacks: the
dataparameter is decoded and its HMAC signature verified in constant time, and itsproduct_codemust match yours, otherwiseInvalidSignatureException. Ifdatais missing (for example on the failure URL),$expectedwith a reference is required. - Khalti callbacks:
pidxis taken from the callback, or from$expected->reference. - A reference that differs from
$expected->referencethrowsPaymentMismatchException(REFERENCE_MISMATCH). - A completed payment whose amount differs from
$expected->amountthrowsPaymentMismatchException(AMOUNT_MISMATCH). A mismatched payment is never returned as paid. - Non-completed statuses (pending, canceled, expired, ...) are returned, not thrown.
$expected is optional, but you should always pass it.
lookup(string $reference, ?int $amount = null): PaymentResult
Fetches the current status from the gateway. eSewa requires $amount (paisa). Lookups are
read-only and are retried on network errors, timeouts and 5xx responses.
PaymentResult
| Member | Description |
|---|---|
gateway |
"khalti" or "esewa" |
status |
PaymentStatus enum |
isPaid() |
true only when status is completed |
reference |
Khalti pidx / eSewa transaction_uuid |
transactionId |
Khalti transaction_id / eSewa ref_id, or null |
amount |
Amount confirmed by the gateway, in paisa |
fee |
Khalti fee in paisa; null for eSewa |
raw |
Gateway response body |
toArray() |
Array representation with snake_case keys |
Money helpers
Payment statuses
BijayX\NepalPay\Enums\PaymentStatus:
| Value | Khalti | eSewa | Meaning |
|---|---|---|---|
completed |
Completed | COMPLETE | Paid. The only status to fulfil on. |
pending |
Pending | PENDING | Not finished yet. Check again later. |
initiated |
Initiated | Payment created, payer has not paid. | |
refunded |
Refunded | FULL_REFUND | Fully refunded. |
partially_refunded |
Partially Refunded | PARTIAL_REFUND | Partly refunded. |
expired |
Expired | Payment link expired. | |
canceled |
User canceled, Canceled | CANCELED | Canceled by the payer. |
failed |
Failed | Payment failed. | |
ambiguous |
AMBIGUOUS | eSewa could not determine the state. Check again later. | |
not_found |
Not found. | NOT_FOUND | No payment for this reference (and amount, for eSewa). |
unknown |
anything else | anything else | Unrecognised status. Treat as not paid. |
Error handling
All exceptions extend BijayX\NepalPay\Exceptions\NepalPayException, which provides
errorCode(), gateway(), details() and context() (merged into Laravel's log context
automatically). Messages and details never contain secret keys.
| Exception | errorCode() |
Thrown when | Suggested handling |
|---|---|---|---|
ConfigurationException |
CONFIGURATION_ERROR |
Missing/invalid config, unknown gateway | Fix configuration. |
ValidationException |
VALIDATION_ERROR |
Invalid input, or field errors returned by the gateway. fields() returns array<string, list<string>>. |
Fix the input; show a generic error to the user. |
AuthenticationException |
AUTHENTICATION_FAILED |
Gateway returned 401/403 (wrong key, or sandbox key in production) | Check keys and environment. |
GatewayException |
GATEWAY_ERROR |
Unexpected status, 5xx, malformed body. statusCode(), responseBody(). |
Retry later. |
NetworkException |
NETWORK_ERROR, TIMEOUT |
Connection failure or timeout | Retry later; for verify, reconcile with lookup(). |
InvalidCallbackException |
INVALID_CALLBACK |
Callback missing data or garbled | Do not fulfil. |
InvalidSignatureException |
INVALID_SIGNATURE |
eSewa signature mismatch or different product code | Treat as tampering. Do not fulfil. |
PaymentMismatchException |
AMOUNT_MISMATCH, REFERENCE_MISMATCH |
Gateway-confirmed payment does not match your order. expected(), actual(). |
Treat as fraud. Do not fulfil. |
Events
| Event | Payload | Dispatched |
|---|---|---|
BijayX\NepalPay\Events\PaymentInitiated |
$event->payment (InitiatedPayment) |
After initiate() succeeds |
BijayX\NepalPay\Events\PaymentVerified |
$event->result (PaymentResult) |
After verify() confirms a payment, whatever its status. Not dispatched when verification throws. |
Check $event->result->isPaid() in listeners.
Testing your application
No real requests are needed. Fake the gateway endpoints with Http::fake().
Khalti:
eSewa: sign a callback with the sandbox secret and fake the status API.
Retries use Illuminate\Support\Sleep, so call Sleep::fake() to keep retry tests instant.
Use Http::preventStrayRequests() to make sure nothing reaches a real gateway.
Sandbox credentials
Khalti sandbox:
- Merchant signup: https://test-admin.khalti.com/#/join/merchant (OTP
987654). Use the test secret key from the merchant dashboard asKHALTI_SECRET_KEY. - Payer Khalti IDs:
9800000000to9800000005, MPIN1111, OTP987654.
eSewa UAT:
- Product code
EPAYTEST, secret key8gBm/:&EnhH.1/q(used automatically in sandbox when nothing is configured). - Payer eSewa IDs:
9711111111,9711111112,9711111113; passwordNepal@123; MPIN1122; token123456.
Security checklist
- Verify server-side. Never mark an order paid from the return URL alone.
verify()always confirms with the gateway's server. - Persist
referenceandamountat initiate, and pass them asExpectedPaymenttoverify(). This blocks replayed callbacks from other orders and amount tampering. - Make "mark paid" idempotent. Callbacks can repeat. Use a row lock (
lockForUpdate()) in a transaction and/or a unique constraint, and skip orders that are already paid. - Use a fresh
order_idper attempt. Both gateways require uniqueness; reusing ids breaks retries after a failed or canceled payment. - Keep secrets in the environment only. Never commit them or send them to the browser.
The package keeps secrets out of exception messages, logs and
dd()output. - Treat
PaymentMismatchExceptionandInvalidSignatureExceptionas fraud signals. Log them and do not fulfil the order. - Set
NEPAL_PAY_ENV=productionexplicitly in production; the package never assumes it.
Custom gateways
Register any gateway that implements BijayX\NepalPay\Contracts\PaymentGateway. Extending
AbstractGateway gives you ExpectedPayment checks and events for free.
Register it in a service provider's boot() method:
Unknown gateway names throw ConfigurationException.
Customising the eSewa redirect page
The auto-submit page has no external assets and works without JavaScript (a "Continue" button is shown). To change it:
Then edit resources/views/vendor/nepal-pay/redirect.blade.php. If your site uses a
Content Security Policy with nonces, pass the nonce:
Development
See CONTRIBUTING.md. Report security issues as described in SECURITY.md, not in public issues.
License
MIT. See LICENSE.
All versions of nepal-pay-laravel with dependencies
illuminate/contracts Version ^12.0|^13.0
illuminate/http Version ^12.0|^13.0
illuminate/support Version ^12.0|^13.0
illuminate/view Version ^12.0|^13.0
guzzlehttp/guzzle Version ^7.8