Are you running an online store in India? Then probably you are looking for a payment gateway through which you can accept customer’s payments online.
PayKun is an Indian payment gateway that accepts payment online using a credit card, Net Banking, Wallet, and UPI. The merchants can check the rates as per the payment method on the pricing page.
Once you are convinced with their service, you look to integrate it into your application. The PayKun provides SDK and Libraries for different programming languages. You can pick the library as per the technology you are using for your website.
For this tutorial, I am going to use their PHP package and show you how to integrate the PayKun payment gateway in Laravel.
Getting Started
As a first step, create an account with PayKun. I first recommend trying integration with sandbox and if everything works as expected then go for production.
To interact with the PayKun gateway, API keys are required. Login to the sandbox dashboard, and generate API keys from Settings->Security->API Key.
Next, get your merchant id by clicking on your profile icon(which is at the top-right corner).
Setup in Laravel to Accept Payment using PayKun
In order to process payment using PayKun, we have copied the merchant id and API keys. Add these values to 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 users make a payment you need to store their transaction details in the database. For this, create a 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->id();
$table->string('payment_id');
$table->string('payer_email');
$table->string('payer_mobile');
$table->float('amount', 10, 2);
$table->string('payment_status');
$table->timestamps();
});
}
Execute this migration by command:
php artisan migrate
This command will create a payments
table in your database. As we are dealing with this table, create a model Payment
that corresponds to the ‘payments’ table.
php artisan make:model Payment
PayKun Payment Gateway Integration in Laravel
As I said, PayKun provides a PHP package which I am going to install using Composer.
composer require paykun/checkout
Next, create the HTML form that has the amount field. As per their documentation, you can add as many fields as customer, billing, and shipping details. But for the sake of the tutorial, I will take only the amount field. The users can extend the form as per their requirements.
payment.blade.php
@if ($message = Session::get('success'))
<div class="success">
<strong>{{ $message }}</strong>
</div>
@endif
@if ($message = Session::get('error'))
<div class="error">
<strong>{{ $message }}</strong>
</div>
@endif
<form action="{{ url('charge') }}" method="post">
<input type="text" name="amount" />
<input type="submit" name="submit" value="Pay Now" />
@csrf
</form>
I set the action URL to the route ‘charge’. We also require a few routes like success URL, failed URL, etc. Let’s define them as follows.
routes/web.php
Route::get('/payment', 'PaymentController@index');
Route::post('/charge', 'PaymentController@charge');
Route::get('/paymentsuccess', 'PaymentController@payment_success');
Route::get('/error', 'PaymentController@payment_error');
As I used PaymentController
in the above routes, let’s create this controller.
php artisan make:controller PaymentController
Now, this controller will be responsible to grab the amount, processing the payment, and storing the transaction details in the database.
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\Models\Payment as PaymentModel;
class PaymentController extends Controller
{
private $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('error'));
// Add Customer
$this->gateway->addCustomer('', '', '');
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'];
$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 redirect("payment")->with("success", "Payment is successful. Your payment id is: ". $arr_transaction['payment_id']);
}
}
}
public function payment_error(Request $request)
{
return redirect("payment")->with("error", "Something went wrong. Try again later.");
}
}
If you look at the constructor, I passed the last parameter as ‘false’. When going live, you don’t need to pass this parameter. Also in the production mode, remove or comment on 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.
If you want to send additional details of a customer, shipping, and billing to PayKun you can do it as follows.
// Add Customer
$this->gateway->addCustomer('<customerName>', '<customerEmail>', '<customerContactNo>');
// Add Shipping address
$this->gateway->addShippingAddress('<country>', '<state>', '<city>', '<postalCode>', '<fullAddress>');
// Add Billing Address
$this->gateway->addBillingAddress('<country>', '<state>', '<city>', '<postalCode>', '<fullAddress>');
That’s it! I hope you understand the PayKun payment gateway integration in Laravel. I would like to hear your thoughts and suggestions in the comment section below.
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
getting invalid request error. any idea why ?
You can set amount in this statement
How can I set purpose value?