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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package nepal-pay-laravel

Nepal Pay for Laravel

Latest Version on Packagist Total Downloads CI PHP Version

Khalti and eSewa payments for Laravel behind one typed API, with server-side verification, signature checks, amount/reference matching and consistent exceptions.

This package follows the same contract as the Node.js package @bijayx/nepal-pay: statuses, error codes and behaviour are identical.

Contents

Requirements

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.

  1. The gateway's server is always asked for the final status (Khalti lookup, eSewa status API). Status values in the callback are never trusted.
  2. eSewa callbacks: the data parameter is decoded and its HMAC signature verified in constant time, and its product_code must match yours, otherwise InvalidSignatureException. If data is missing (for example on the failure URL), $expected with a reference is required.
  3. Khalti callbacks: pidx is taken from the callback, or from $expected->reference.
  4. A reference that differs from $expected->reference throws PaymentMismatchException (REFERENCE_MISMATCH).
  5. A completed payment whose amount differs from $expected->amount throws PaymentMismatchException (AMOUNT_MISMATCH). A mismatched payment is never returned as paid.
  6. 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:

eSewa UAT:

Security checklist

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

PHP Build Version
Package Version
Requires php Version ^8.2
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
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package bijayx/nepal-pay-laravel contains the following files

Loading the files please wait ...