Razorpay Integration in CodeIgniter 4 (PHP)

Hemant Sharma 24 Mar 2025
Instragram-Image

Table of Contents

Razorpay Integration in CodeIgniter

Step 1: Set Up Razorpay Keys

To set up Razorpay, log in to the Razorpay Dashboard, navigate to API Keys under the Settings tab, and generate your Key_ID and Secret_Key for integration.

Step 2: Generate Razorpay Order ID

To generate a Razorpay Order ID, create a function in your backend. Use cURL to call Razorpay's REST API endpoint /orders with the required parameters: amount, currency, and receipt. Parse the response to extract the Order ID, save it along with relevant data in your database for further processing.

function generateOrderID($amount, $ReceiptNo, $courseName, $register_id): string 
{ 
$curl = curl_init(); 
$key_id = 'rzp_test_xxxxxxxxxxxxx'; 
$secret_key = 'xxxxxxxxxxxxxxxxxxx'; 
curl_setopt_array($curl, array( 
CURLOPT_URL => 'https://api.razorpay.com/v1/orders', 
CURLOPT_RETURNTRANSFER => true, 
CURLOPT_ENCODING => '', 
CURLOPT_MAXREDIRS => 10, 
CURLOPT_TIMEOUT => 0, 
CURLOPT_FOLLOWLOCATION => true, 
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 
CURLOPT_CUSTOMREQUEST => 'POST', 
 CURLOPT_POSTFIELDS => json_encode([ 
 "amount" => $amount * 100, // Amount in paise 
 "currency" => "INR", 
 "receipt" => $ReceiptNo, 
 "notes" => [ 
 "notes_key_1" => $courseName, 
 "notes_key_2" => "" 
 ] 
 ]), 
 CURLOPT_HTTPHEADER => [ 
 'Content-Type: application/json', 
 'Authorization: Basic ' . base64_encode($key_id . ':' . $secret_key) 
 ], 
  )); 
 
 
  $response = curl_exec($curl); 
  curl_close($curl); 
 
 
  $resArr = json_decode($response, true); 
  if ($resArr['status'] == 'created') { 
 $payModel = new PaymentModel(); 
 $paymentData = [ 
 'register_id' => $register_id, 
 'order_id' => $resArr['id'], 
 'payment_status' => $resArr['status'], 
 'currency' => 'INR', 
 'reciept' => $resArr['receipt'], 
 'attempts' => $resArr['attempts'], 
 'amount' => $amount, 
 'amount_paid' => $resArr['amount_paid'], 
 'response' => $response, 
'created_at' => date('Y-m-d H:i:s'), 
]; 
$payModel->insert($paymentData); 
return $resArr['id']; 
} else { 
log_message('error', 'Razorpay Order Creation Failed: ' . json_encode($resArr)); 
return ''; 
} 
}
    

Step 3: Display Razorpay Checkout Button

In the controller, generate the Razorpay Order ID and pass it to the view. On the frontend, create a form and use Razorpay's Checkout.js to display the payment button. On form submission, pass the Order ID to Razorpay and handle the payment process, submitting the payment ID to the backend for verification.

        var options = {
            "key": "rzp_test_xxxxxxxxxxxxx",
            "amount":  $selectedCourseSellingPrice * 100 ,
            "currency": "INR",
            "name": "",
            "description": " $selectedCourseName",
            "image": "site_url('assets/img/techthaastu-logo.webp')",
            "order_id": " $orderID",
            "callback_url": " site_url('thank-you')",
            "handler": function(response) {
                var selectedCourseSellingPrice =  $selectedCourseSellingPrice ;
                var paymentData = {
                    razorpay_payment_id: response.razorpay_payment_id,
                    razorpay_order_id: response.razorpay_order_id,
                    razorpay_signature: response.razorpay_signature,
                    response: response,
                    amount: selectedCourseSellingPrice
                };

                $.ajax({
                    url: " site_url('verify-payment') ",
                    type: 'POST',
                    data: paymentData,
                    success: function(response) {
                        console.log('Payment verification success: ', response);
                        if (response.status === 'success') {
                            window.location.href = "site_url('thank-you') ";
                        } else {
                            window.location.href = "site_url('register') ";
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log('Request failed: ' + error);
                    }
                });
            },
            "prefill": {
                "name": "$formData['name'] ",
                "email": " $formData['email'] ",
                "contact": "+91 $formData['phone'] "
            },
            "notes": {
                "address": ""
            },
            "theme": {
                "color": "#3399cc"
            }
        };

        var rzp1 = new Razorpay(options);
        rzp1.open();

        rzp1.on('payment.failed', function(response) {
            const faileddata = {
                fulldata: response.error,
                error_code: response.error.code,
                description: response.error.description,
                source: response.error.source,
                step: response.error.step,
                reason: response.error.reason,
                order_id: response.error.metadata.order_id,
                payment_id: response.error.metadata.payment_id
            };

            $.ajax({
                url: " site_url('payment-failed') ",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(faileddata),
                success: function(response) {
                    console.log(response);
                    window.location.href = "site_url('register') ";
                },
                error: function(xhr, status, error) {
                    console.log('Request failed: ' + error);
                }
            });
        });

Step 4: Verify the Payment

Create a backend endpoint to verify payment by validating the payment signature using Razorpay's API. Capture the payment ID and order ID from the frontend, then send a request to Razorpay's /payment/verify endpoint. Compare the generated signature with the one sent from the frontend for successful verification.

public function verifyPayment() 
{ 
$paymentId = $this->request->getPost('razorpay_payment_id'); 
$orderId = $this->request->getPost('razorpay_order_id'); 
$signature = $this->request->getPost('razorpay_signature'); 
$amount = $this->request->getPost('amount'); 
$secret = ''xxxxxxxxxxxxx '; 
$generated_signature = hash_hmac('sha256', $orderId . '|' . $paymentId, $secret); 
if ($generated_signature === $signature) { 
$payModel = new PaymentModel(); 
$payModel->updatePaymentStatus([ 
'payment_id' => $paymentId, 
'order_id' => $orderId, 
'payment_status' => 'success', 
'amount_paid' => $amount, 
'created_at' => date('Y-m-d H:i:s'), 
]); 
return $this->response->setJSON(['status' => 'success', 'message' => 'Payment verification 
successful']); 
} else { 
log_message('error', 'Signature mismatch'); 
return $this->response->setJSON(['status' => 'error', 'message' => 'Signature mismatch']); 
} 
}
    

Step 5: Handle Success and Failure

After verifying the payment status, handle success and failure scenarios in the callback function. If the payment is successful, redirect the user to the "Thank You" page. For failures, redirect them to the "Registration" page.

UpdatepaymentStatus function written in PaymentModel
public function updatePaymentStatus(array $data) 
{ 
return $this->where('order_id', $data['order_id']) ->set([ 
'payment_status' => $data['payment_status'], 
'payment_id' => $data['payment_id'], 
'created_at' => $data['created_at'], 
'amount_paid' => $data['amount_paid'], 
]) ->update(); 
}
    

Step 6: Handle Failure Payment

After verifying the payment status, handle success and failure scenarios in the callback function. If the payment is successful, redirect the user to the "Thank You" page. For failures, redirect them to the "Registration" page.

public function Paymentfailed() 
{ 
$input = $this->request->getBody(); 
$data = json_decode($input, true); 
log_message('debug', 'Received payment data: ' . json_encode($data)); 
$paymentId = $data['payment_id'] ?? null; 
$orderId = $data['order_id'] ?? null; 
$errorCode = $data['error_code'] ?? null; 
$errorDescription = $data['description'] ?? null; 
$errorReason = $data['reason'] ?? null; 
$fulldata = $data['fulldata'] ?? null; 
$payModel = new PaymentModel(); 
$paymentFailureData = [ 
'payment_id' => $paymentId, 
'order_id' => $orderId, 
'error_code' => $errorCode, 
'amount_paid' => 0, 
'error_reason' => $errorReason, 
'response' => json_encode($fulldata), 
'payment_status' => 'failed',  
            'created_at' => date('Y-m-d H:i:s')  
        ]; 
 
        // pr($paymentFailureData,true); 
 
       $payModel->updatePaymentStatus($paymentFailureData); 
    }
    

Related Blogs

Explore blogs you should also liked

Best PHP Framework to Start for Business Web Applications in 2026
Best PHP Framework to Start for Business Web Applications in 2026

Why PHP frameworks like Laravel and CodeIgniter4 remain strong choices for business web apps in 2026. Financial benefits, pros & cons, top frameworks and future trends.

Updated On: 2025-10-14 18:59:11

Read More
How to Integrate PhonePe Payment Gateway in PHP
How to Integrate PhonePe Payment Gateway in PHP

Integrate PhonePe payment gateway in your website for secure and seamless online transactions. Techthaastu Sharing Source Code and Instuctions how to implement PhonePe Payment Gateway.

Updated On: 2025-05-19 13:44:22

Read More
Techthaastu icon

Techthaastu Support Team 1
Typically replies within an hour

Support Team
Hi there 👋

How can I help you?
06:45 AM
×
Chat with Us
Techthaastu Logo

Techthaastu Support Team 2
Typically replies within an hour

Chat with Us