PayKun Payment Gateway Integration in Laravel

Are you running an online store in India? Then probably you are looking for payment gateway through which your customer can pay online.

PayKun is an Indian payment gateway that accepts payment online using a credit card, Net Banking, Wallet and UPI. They provide 2 types of plans for merchants – Standards and Enterprise. You can check out their plan on pricing page. In this article, we study how to integrate PayKun payment gateway in Laravel.

PayKun

Getting Started

For getting started with PayKun integration in Laravel, you need to have first create account on PayKun. Upon creating account generate API keys from Settings->Security->API Key.

We first recommend to try integration first with sandbox and if everything works as expected then go for production. You can generate sandbox API keys for a sandbox environment in the same way as production. To enter the sandbox dashboard, click on the top right corner icon and then on ‘Test Mode’.

PayKun

Next, get your merchant id from My Accounts->Profile.

Basic Setup in Laravel to Accept Payment using PayKun

In order to process payment using PayKun, merchant id and API keys are required. So add these values in the .env file.

PAYKUN_ACCESS_TOKEN=PASTE_ACCESS_TOKEN_HERE
PAYKUN_KEY_SECRET=PASTE_API_KEY_SECRET_HERE
PAYKUN_MERCHANT_ID=PASTE_MERCHANT_ID_HERE

When your users make a payment you need to store their transaction details in the database for later use. So, let’s create migration using the command:

php artisan make:migration create_payments_table

Open this migration file and add the code below in the up method.

<?php
...
...

public function up()
{
    Schema::create('payments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('payment_id');
        $table->string('payer_email');
        $table->string('payer_mobile');
        $table->float('amount', 10, 2);
        $table->string('payment_status');
        $table->timestamps();
    });
}

Run this migration by command:

php artisan migrate

This migration will create a ‘payments’ table in your database. As we need to store transactions in this table, create a model ‘Payment’ correspond to the ‘payments’ table.

php artisan make:model Payment

We all set with basic setup and can go ahead for integrating the PayKun library in our Laravel project.

PayKun Payment Gateway Integration in Laravel

PayKun has provides SDKs for PHP, .NET, Java, Python, etc. We are going to use their GitHub library created for PHP applications.

Install the PayKun library in your Laravel project using the following composer command:

composer require paykun/checkout

If you read on their GitHub page you can add as many fields like customer, billing and shipping details. But for the sake of the tutorial, we will take only the amount field. The users can extend the form as per their requirements.

payment.blade.php

<form action="{{ url('charge') }}" method="post">
    <input type="text" name="amount" />
    {{ csrf_field() }}
    <input type="submit" name="submit" value="Pay Now">
</form>

We passed the action URL to the route ‘charge’. You will require a few routes like success URL, failed URL, charge, etc. Let’s define it as follows.

routes/web.php

Route::get('payment', 'PaymentController@index');
Route::post('charge', 'PaymentController@charge');
Route::get('paymentsuccess', 'PaymentController@payment_success');
Route::get('paymenterror', 'PaymentController@payment_error');

The next thing that needs to do is create a controller file that will collect the amount, send a user to the PayKun website for processing payment, and then finally insert the transaction details in the database.

php artisan make:controller PaymentController

Add the code below in this controller file which will handle all payment-related stuff.

PaymentController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Paykun\Checkout\Payment;
use App\Payment as PaymentModel;

class PaymentController extends Controller
{
    public $gateway;
 
    public function __construct()
    {
        $this->gateway = new Payment(env('PAYKUN_MERCHANT_ID'), env('PAYKUN_ACCESS_TOKEN'), env('PAYKUN_KEY_SECRET'), false); // here we pass last parameter as false to enable sandbox mode.
    }

    public function index()
    {
        return view('payment');
    }

    public function charge(Request $request)
    {
        if($request->input('submit'))
        {
            try {

                $this->gateway->setCustomFields(array('udf_1' => 'test')); //remove or comment this line when go live

                $this->gateway->initOrder('ORD'.uniqid(), 'My Product Name', $request->input('amount'), url('paymentsuccess'), url('paymenterror'));

                // Add Customer
                $this->gateway->addCustomer('', '', '');

                // Add Shipping address
                $this->gateway->addShippingAddress('', '', '', '', '');

                // Add Billing Address
                $this->gateway->addBillingAddress('', '', '', '', '');

                echo $this->gateway->submit();
            } catch(Exception $e) {
                return $e->getMessage();
            }
        }
    }

    public function payment_success(Request $request)
    {

        if ($request->input('payment-id'))
        {
            $transactionData = $this->gateway->getTransactionInfo($request->input('payment-id'));

            if ($transactionData['status'])
            {
                $arr_transaction = $transactionData['data']['transaction'];

                // Check if payment_id already exists in the database
                $isPaymentExist = PaymentModel::where('payment_id', $arr_transaction['payment_id'])->first();
         
                if(!$isPaymentExist)
                {
                    $payment = new PaymentModel;
                    $payment->payment_id = $arr_transaction['payment_id'];
                    $payment->payer_email = $arr_transaction['customer']['email_id'];
                    $payment->payer_mobile = $arr_transaction['customer']['mobile_no'];
                    $payment->amount = $arr_transaction['order']['gross_amount'];
                    $payment->payment_status = $arr_transaction['status'];
                    $payment->save();
                }
         
                return "Payment is successful. Your transaction id is: ". $arr_transaction['payment_id'];
            }
        }
    }

    public function payment_error(Request $request)
    {
        return "Something went wrong. Try again later.";
    }
}

If you look at the constructor code, we passed the last parameter as ‘false'(boolean value). When going live, you don’t need to pass this parameter. Also on the production mode, remove or comment the below line in the ‘charge’ method.

$this->gateway->setCustomFields(array('udf_1' => 'test'));

While you are testing sandbox payment, you need to enter dummy credit card numbers which you will get here.

That’s it! We hope you understand the PayKun payment gateway integration in Laravel. We would like to hear your thoughts in the comment section below.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

2 thoughts on “PayKun Payment Gateway Integration in Laravel

  1. You can set amount in this statement

    $this->gateway->initOrder('ORD'.uniqid(), 'My Product Name', $request->input('amount'), url('paymentsuccess'), url('paymenterror'));

Leave a Reply

Your email address will not be published. Required fields are marked *