Laravel: Integrate eSewa Payment Gateway

Link Copied To Clipboard !

integrate-esewa-in-laravel Frameworks

eSewa is the popular online payment gateway in Nepal. It is probably the first payment gateway ever in Nepal. It supports both online as well as offline payment. With growing online businesses and technological advancement, people now prefer to pay via their online wallet instead of going to the stations physically and stay in queue for hours. This makes the online payment gateway integration for online businesses the first priority.

Laravel is a popular web framework that is used to develop various websites/webapps. Many small websites as well as big websites use laravel in order to provide better functionalities and features to end users. The current release enhances the developer capabilities which makes it even more easier and broader in terms of application development.

With increasing number of ecommerce businesses in Nepal, integrating payment gateways like eSewa has been the first requirement to be fulfilled by developers. In this article, I will walk you through integrating eSewa payment gateway in Laravel. Before going to the coding part, let’s first see what are the steps we will be covering.

How to integrate eSewa payment gateway in Laravel ?

  1. Create Laravel application
  2. Create necessary routes
  3. Create and integrate controller functions
  4. Create views
  5. Test
  6. Move to production

The first step is to create laravel application. If you are searching for the integration tutorial, you might already have an application ready. So you can just go to next step, which is creating necessary routes. You have to determine the actual point where the need of launching esewa payment gateway is necessary. Considering ecommerce application, the point could be during checkout. When an user clicks on “PAY WITH ESEWA” button, the system is supposed to provide esewa payment method to user. For this, you need to make a route and a controller function. Let’s say the route is /checkout/payment/esewa and controller is EsewaController@payWithEsewa .

Now, we move to next step, which is making controller functions. The basic idea we are doing here is that, when the route mentioned above is hit, we return a view with necessary data and with the help of javascript, we submit a form, provided in official documentation of esewa. Then the payment process will be handled by esewa and the response with either success or failure will be returned, which we will need to handle later.

Create a file payment/esewa.blade.php inside resources/views and paste the following.

<form id="paymentForm" action="" method="POST">
    <input value="{{$totalAmount}}" name="tAmt" type="hidden">
    <input value="{{$amount}}" name="amt" type="hidden">
    <input value="{{$taxAmount}}" name="txAmt" type="hidden">
    <input value="{{$serviceCharge}}" name="psc" type="hidden">
    <input value="{{$shippingCharge}}" name="pdc" type="hidden">
    <input value="EPAYTEST" name="scd" type="hidden">
    <input value="{{$pid}}" name="pid" type="hidden">
    <input value="{{route('esewa.success')}}?q=su" type="hidden" name="su">
    <input value="{{route('esewa.failure')}}?q=fu" type="hidden" name="fu">
    document.addEventListener("DOMContentLoaded", function(event) {

The function EsewaController@payWithEsewa will simply return this view with necessary data. Here, the action url we have used is for development mode only and it needs to be changed to production url while moving to production. Also, the scd has to be changed with actual merchant scd. Another thing we have added here is routes for success and failure responses. So, we need to make these as well in routes.php .

The next step is to create functions to handle success and failure responses. In case of failure, you can just redirect user to certain page and display failure message but for success, the best practice is that you validate and verify payment details before actually placing order. For failure, you could do something like below:

public function paymentFailure(Request $request, BaseHttpResponse $response){
        return $response
        -> setNextUrl(route('public.checkout.information', OrderHelper::getOrderSessionToken()))
        ->setMessage(__('eSewa Payment Failed !'));

The code written above is just a sample and you have to write your own that suits your need. Now, for the success response, you have to perform some verification with esewa in order to make sure whether its actual payment or fraud.

How to verify esewa payment in Laravel ?

The success response contains some details about payment with reference id. Our job is to validate actual system amount with the one user just payed. The actual verification happens in esewa’s end but we are the one who make request. It’s possible with the help of reference id provided by the payment response. Let’s get into the actual coding part. Following code verifies payment and sets some validation variables to their respective values.

public function paymentSuccess(Request $request, BaseHttpResponse $response)
        //system total price
        $amountToBePaid = Cookie::get('amount'); //change it to your own that suits your need
        $data = [
            'amt' => $amountToBePaid,
            'rid' => $_GET['refId'],
            'pid' => $_GET['oid'],
            'scd' => get_payment_setting('public', ESEWA_PAYMENT_METHOD_NAME)

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, ESEWA_VERIFICATION_URL);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        //convert xml response to array
        $response = json_decode(json_encode(simplexml_load_string($response)), TRUE);
        $response_code = trim(strtolower($response['response_code'])); //remove whitespaces
        $status = PaymentStatusEnum::PENDING;
        $verified = false;

        if (strcmp($response_code, 'success') == 0) {
            //payment verified
            $status = PaymentStatusEnum::COMPLETED;
            $verified = true;
        } else {
            //not verified
            $status = PaymentStatusEnum::FRAUD;
            $verified = false;

        if (!$verified) {
            //payment was not verified.
            //DO SOMETHING
        //payment verified
        return $response
        ->setNextUrl(route('public.checkout.success', OrderHelper::getOrderSessionToken()))
        ->setMessage(__('Checkout Successful!'));

Note: Above code is just a sample and you might have to make some changes to variables and returns.

We have now done the integration part and it’s time to test it. For the test credentials, please visit official website .

After successful testing, its time to move to production. Remember that you must register as a merchant for production access. You have to contact esewa for integration support.

These were the actual steps involving esewa payment gateway integration. You can modify and change the codes as you like.


You May Also Like