Razorpay Payment Gateway Integration in CodeIgniter 4

Share this Article
Reading Time: 9 minutes

There are several payment gateway available in web applications for payment processing like Paypal, Stripe, Authorize.net, Razorpay etc. Inside this article we will the step by step guide for Razorpay payment gateway integration in codeigniter 4.

Razorpay – Best Payment Gateway for Online Payments. We will implement by the help of this tutorial.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.

Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

 // Do it to 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store transactions data. Let’s create table with some columns.

CREATE TABLE transactions (
  amount int(11) NOT NULL,
  currency varchar(5) NOT NULL,
  trnx_id varchar(30) NOT NULL,
  card_id varchar(30) NOT NULL,
  status varchar(20) NOT NULL,

Successfully, we have created a database and a table. Let’s connect with the application.

Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi

Now, database successfully connected with application.

Razorpay Gateway – Composer Installation

Open project into terminal and run this composer command.

$ composer require razorpay/razorpay

It will install the package into /vendor folder at project root.

Razorpay APIs Key Setup

Next, we need to get the api key and secret for application.

Step #1

Open official site https://razorpay.com/ and click on login. Pass your login details to login into dashboard.

Login screen after click on login

Step #2

Go to dashboard, Click on Settings menu. Have a look,

To regenerate api keys for razorpay, follow the same as,

Step #3

Open .env file from application. Add these two environment variables into application. Right here, we have passed our values, you can change it to yours

//.. Other settings

# Razor keys

Create Routes

Open Routes.php from /app/Config folder.

//.. Other routes

// Get Route For Show Payment Form
$routes->get('payment-form', 'RazorpayController::payWithRazorpay');
// Post Route For making Payment Request
$routes->post('payment', 'RazorpayController::processPayment');

Create Model

Open project into terminal and run this spark command.

$ php spark make:model Transaction --suffix

It will create a file with name TransactionModel.php at /app/Models folder.

Open TransactionModel.php and write this following code into it.


namespace App\Models;

use CodeIgniter\Model;

class TransactionModel extends Model
	protected $DBGroup              = 'default';
	protected $table                = 'transactions';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];

Create Controller

Run this spark command to create application controller.

$ php spark make:controller Razorpay --suffix

It will create a file with name RazorpayController.php at /app/Controllers folder.

Open RazorpayController.php and write this following code into it.


namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\TransactionModel;
use Razorpay\Api\Api;

class RazorpayController extends BaseController
    public function payWithRazorpay()
        return view('payment-form');

    public function processPayment()
        //Input items of form
        $input = $this->request->getVar();
        //get API Configuration
        $api = new Api(env('razorKey'), env('razorSecret'));
        //Fetch payment information by razorpay_payment_id
        $payment = $api->payment->fetch($input['razorpay_payment_id']);

        if (count($input) && !empty($input['razorpay_payment_id'])) {
            try {

                $response = $api->payment->fetch($input['razorpay_payment_id'])->capture(array('amount' => $payment['amount']));

            } catch (\Exception $e) {
                return $e->getMessage();
                session()->setFlashdata("error", $e->getMessage());
                return redirect()->back();

            // save transaction details
            $trnx = new TransactionModel();

                "amount" => $response->amount,
                "currency" => $response->currency,
                "trnx_id" => $response->id,
                "card_id" => $response->card_id,
                "status" => $response->status,

        session()->setFlashdata('success', 'Payment successfully done');
        return redirect()->back();

Create Payment Form

Create a file with name payment-form.php at /app/Views folder.

Open file and write this code to create a layout for payment form.

<!DOCTYPE html>
<html lang="en">
  <title>Razorpay Payment gateway Integration - Online Web Tutor</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="container">
  <h3 style="text-align: center;">Razorpay Payment gateway Integration - Online Web Tutor</h3>
  <div class="panel panel-primary">
    <div class="panel-heading">Razorpay Payment gateway Integration - Online Web Tutor</div>
    <div class="panel-body">

        <?php if (session()->has('error')) {?>
        <div class="alert alert-danger alert-dismissible fade in" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">×</span>
            <strong>Error!</strong> <?=session("error")?>
        <?php }?>

        <?php if (session()->has('success')) {?>
            <div class="alert alert-success alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                <strong>Success!</strong> <?=session("success")?>
        <?php }?>

        <form action="<?=base_url('payment')?>" method="POST" >
            <!-- Note that the amount is in paise 1 INR = 1000 Paisa -->

            <!--amount need to be in paisa-->
            <script src="https://checkout.razorpay.com/v1/checkout.js"
                    data-buttontext="Pay 10 INR"
                    data-description="Sample order description"


Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/payment-form

We hope this article helped you to learn Razorpay Payment Gateway Integration in CodeIgniter 4 Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

5 thoughts on “Razorpay Payment Gateway Integration in CodeIgniter 4”

  1. $payment = $api->payment->fetch($input[‘razorpay_payment_id’]);

    error : Undefined array key “razorpay_payment_id”

    What to do?

      • Hi thanks for reply,
        i am unable to found razorpay_payment_id inside payment form, there is data key but not this ‘razorpay_payment_id’ .
        I am stuck since yesterday. Now $response variable is out of scope .

  2. in try catch block $response variable is undefined outside try catch block so how can we access it outside

Comments are closed.