Codeigniter 4 Razorpay Payment Gateway Integration Tutorial

In this tutorial, we’ll learn how to integrate the Razorpay payment gateway into your CodeIgniter 4 app. Razorpay is a popular payment gateway in India that allows you to accept payments online.

This tutorial will guide you step-by-step on how to integrate the Razorpay payment gateway into your CodeIgniter 4 app. We’ll provide a live demo along the way so you can see how it works in action.

Razorpay Payment Gateway Integration In PHP Codeigniter 4

here are the steps you need to follow to integrate the Razorpay payment gateway into your PHP CodeIgniter 4 app:

  • Step 1 – Download Codeigniter Latest
  • Step 2 – Basic Configurations
  • Step 3 – Setup Database Credentials
  • Step 4 – Create Controller
  • Step 5 – Create Views
  • Step 6 – Start Development server

Step 1 – Download Codeigniter 4 Project

Let’s begin by downloading the latest version of CodeIgniter 4 from the official website. You can download it from this link: https://codeigniter.com/download. Once downloaded, extract the files and save them in your local system’s xampp/htdocs/ directory.

Now, change the folder name to “demo” to make it easy to remember and work with. This step is important as we will be using the CodeIgniter 4 framework for our image file upload example.

Step 2 – Basic Configurations

In the next step, we need to make some basic configurations to the app/config/app.php we will go to the application/config/ directory and open the config.php file in a text editor.

Set Base URL Like This

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Setup Database Credentials

Next, you need to connect your project to the database. To do this, navigate to the “app/Config” directory and open the “Database.php” file in a text editor. Within this file, you will need to set up your database credentials as follows:

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];

Step 4 – Create Controller

To integrate Razorpay payment gateway in your CodeIgniter 4 app, you need to create a new controller named Payment.php and add the following code to it:

<?php
namespace App\Controllers;
class Razorpay extends BaseController
{
    public function __construct()
    {
        $this->session = \Config\Services::session();
    }
    function index()
    { 
        $data                 = [];
        $data['title']        = 'Checkout payment | Tutsmake.com';
        $data['callback_url'] = base_url() . '/razorpay/callback';
        $data['surl']         = base_url() . '/razorpay/success';
        ;
        $data['furl'] = base_url() . '/razorpay/failed';
        ;
        $data['currency_code'] = 'INR';
        echo view("checkout", $data);
    }
    // initialized cURL Request
    private function curl_handler($payment_id, $amount)
    {
        $url           = 'https://api.razorpay.com/v1/payments/' . $payment_id . '/capture';
        $key_id        = "YOUR_KEY_ID";
        $key_secret    = "YOUR_SECRET";
        $fields_string = "amount=$amount";
        //cURL Request
        $ch            = curl_init();
        //set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERPWD, $key_id . ':' . $key_secret);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        return $ch;
    }
    // callback method
    function callback()
    {
        if (!empty($this->request->getPost('razorpay_payment_id')) && !empty($this->request->getPost('merchant_order_id'))) {
            $razorpay_payment_id = $this->request->getPost('razorpay_payment_id');
            $merchant_order_id   = $this->request->getPost('merchant_order_id');
            $this->session->set('razorpay_payment_id', $this->request->getPost('razorpay_payment_id'));
            $this->session->set('merchant_order_id', $this->request->getPost('merchant_order_id'));
            $currency_code = 'INR';
            $amount        = $this->request->getPost('merchant_total');
            $success       = false;
            $error         = '';
            try {
                $ch          = $this->curl_handler($razorpay_payment_id, $amount);
                //execute post
                $result      = curl_exec($ch);
                $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if ($result === false) {
                    $success = false;
                    $error   = 'Curl error: ' . curl_error($ch);
                } else {
                    $response_array = json_decode($result, true);
                    //Check success response
                    if ($http_status === 200 and isset($response_array['error']) === false) {
                        $success = true;
                    } else {
                        $success = false;
                        if (!empty($response_array['error']['code'])) {
                            $error = $response_array['error']['code'] . ':' . $response_array['error']['description'];
                        } else {
                            $error = 'RAZORPAY_ERROR:Invalid Response <br/>' . $result;
                        }
                    }
                }
                //close curl connection
                curl_close($ch);
            }
            catch (Exception $e) {
                $success = false;
                $error   = 'Request to Razorpay Failed';
            }
            if ($success === true) {
                if (!empty($this->session->get('ci_subscription_keys'))) {
                    $this->session->unset('ci_subscription_keys');
                }
                if (!$order_info['order_status_id']) {
                    return redirect()->to($this->request->getPost('merchant_surl_id'));
                } else {
                    return redirect()->to($this->request->getPost('merchant_surl_id'));
                }
            } else {
                return redirect()->to($this->request->getPost('merchant_furl_id'));
            }
        } else {
            echo 'An error occured. Contact site administrator, please!';
        }
    }
    function success()
    {
        $data['title'] = 'Razorpay Success | Tutsmake.com';
        echo "<h4>Your transaction is successful</h4>";
        echo "<br/>";
        echo "Transaction ID: " . $this->session->get('razorpay_payment_id');
        echo "<br/>";
        echo "Order ID: " . $this->session->get('merchant_order_id');
    }
    function failed()
    {
        $data['title'] = 'Razorpay Failed | Tutsmake.com';
        echo "<h4>Your transaction got Failed</h4>";
        echo "<br/>";
        echo "Transaction ID: " . $this->session->get('razorpay_payment_id');
        echo "<br/>";
        echo "Order ID: " . $this->session->get('merchant_order_id');
    }
}

Step 5 – Create Views

To create the checkout page for Razorpay payment gateway integration, you need to follow these steps:

<!DOCTYPE html>
<html>
    <head>
        <title>Codeigniter 4 Razorpay Payment Gateway - torqueprogramming.co.in</title>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="" />
        <meta name="author" content="" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" />
    </head>
    <body>
        <?php
$description        = "Product Description";
$txnid              = date("YmdHis");     
$key_id             = "YOUR_KEY_ID";
$currency_code      = $currency_code;            
$total              = (1* 100); // 100 = 1 indian rupees
$amount             = 1;
$merchant_order_id  = "ABC-".date("YmdHis");
$card_holder_name   = 'David Chase';
$email              = 'info@torqueprogramming.co.in';
$phone              = '9158876092';
$name               = "RazorPay Infovistar";
?>
        <div class="container">
            <div class="page-header">
                <h1>Pay with Razorpay</h1>
            </div>
            <div class="page-body">
                <form name="razorpay-form" id="razorpay-form" action="<?php echo $callback_url; ?>" method="POST">
                    <input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id" />
                    <input type="hidden" name="merchant_order_id" id="merchant_order_id" value="<?php echo $merchant_order_id; ?>" />
                    <input type="hidden" name="merchant_trans_id" id="merchant_trans_id" value="<?php echo $txnid; ?>" />
                    <input type="hidden" name="merchant_product_info_id" id="merchant_product_info_id" value="<?php echo $description; ?>" />
                    <input type="hidden" name="merchant_surl_id" id="merchant_surl_id" value="<?php echo $surl; ?>" />
                    <input type="hidden" name="merchant_furl_id" id="merchant_furl_id" value="<?php echo $furl; ?>" />
                    <input type="hidden" name="card_holder_name_id" id="card_holder_name_id" value="<?php echo $card_holder_name; ?>" />
                    <input type="hidden" name="merchant_total" id="merchant_total" value="<?php echo $total; ?>" />
                    <input type="hidden" name="merchant_amount" id="merchant_amount" value="<?php echo $amount; ?>" />
                </form>
                <table width="100%">
                    <tr>
                        <th>No.</th>
                        <th>Product Name</th>
                        <th class="text-right">Cost</th>
                    </tr>
                    <tr>
                        <td>1</td>
                        <td>HeadPhones</td>
                        <td class="text-right">₹ 1.00</td>
                    </tr>
                </table>
                <div class="mt-2 text-right">
                    <input id="pay-btn" type="submit" onclick="razorpaySubmit(this);" value="Buy Now" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
        <script>
            var options = {
                key: "<?php echo $key_id; ?>",
                amount: "<?php echo $total; ?>",
                name: "<?php echo $name; ?>",
                description: "Order # <?php echo $merchant_order_id; ?>",
                netbanking: true,
                currency: "<?php echo $currency_code; ?>", // INR
                prefill: {
                    name: "<?php echo $card_holder_name; ?>",
                    email: "<?php echo $email; ?>",
                    contact: "<?php echo $phone; ?>",
                },
                notes: {
                    soolegal_order_id: "<?php echo $merchant_order_id; ?>",
                },
                handler: function (transaction) {
                    document.getElementById("razorpay_payment_id").value = transaction.razorpay_payment_id;
                    document.getElementById("razorpay-form").submit();
                },
                modal: {
                    ondismiss: function () {
                        location.reload();
                    },
                },
            };
            var razorpay_pay_btn, instance;
            function razorpaySubmit(el) {
                if (typeof Razorpay == "undefined") {
                    setTimeout(razorpaySubmit, 200);
                    if (!razorpay_pay_btn && el) {
                        razorpay_pay_btn = el;
                        el.disabled = true;
                        el.value = "Please wait...";
                    }
                } else {
                    if (!instance) {
                        instance = new Razorpay(options);
                        if (razorpay_pay_btn) {
                            razorpay_pay_btn.disabled = false;
                            razorpay_pay_btn.value = "Pay Now";
                        }
                    }
                    instance.open();
                }
            }
        </script>
    </body>
</html>

Step 6 – Start Development Server

In this step, open your terminal and execute the following command to start development sever:

php spark serve

Then, Go to the browser and hit below the URL:

http://localhost:8080

You May Also Like

  1. CodeIgniter 4 Server Side DataTable Example
  2. Codeigniter 4 Google Map Multiple Markers Example
  3. Codeigniter 4 Get Latitude and Longitude From Address
  4. Country State City Dependent Dropdown in Codeigniter 4
  5. Codeigniter 4 Import Data to Excel/CSV File From MySQL Database
  6. Codeigniter 4 Dynamic Dependent Dropdown with Ajax
  7. Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS
  8. Codeigniter 4 PDF Generator Tutorial Example
  9. Crop and Save Image using jQuery Coppie in Codeigniter 4

Leave a Reply

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