Razorpay payment gateway integration in codeigniter 4; In this tutorial, i will show you step by step guide on how to integrate razorpay payment gateway in codeigniter 4 app.
If you are making eCommerce website and or you want to install payment deduction method on your website. So in this tutorial, you will learn how to integrate Razorpay Payment Gateway in codeigniter 4 app.
For codeigniter 4 razorpay payment gateway integration example; I create a simple razorpay payment form. And implement javascript api of razorpay payment gateway in codeigniter 4 app.
How to Integrate Razorpay Payment Gateway In Codegniter 4
- Install Codeigniter 4 Application
- Basic App Configurations
- Install stripe package Via Composer
- Connect App to Database
- Create Razorpay Controller Class
- Create Views
- Setup Routes
- Start Development server
Step 1 – Install Codeigniter 4 Application
First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .
Note that, please change the download folder name “demo”.
Step 2 – Basic App Configurations
Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3 – Install stripe package Via Composer
Install strip package vie composer; so open your terminal and execute the following command on it:
composer require stripe/stripe-php
To use the bindings, use the Composer’s autoload
require_once('vendor/autoload.php');
Step 4 – Connect App to Database
To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'test', 'password' => '4Mu99BhzK8dr4vF1', 'database' => 'demo', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'development'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ];
Step 5 – Create Razorpay Controller Class
Create Razorpay.php file. So, visit app/Controllers directory and create Razorpay.php.Then add the following code into it:
<?php namespace App\Controllers; use CodeIgniter\Controller; use CodeIgniter\HTTP\RequestInterface; class Razorpay extends Controller { public function __construct() { $this->session = \Config\Services::session(); } public function index() { $data = []; $data['title'] = 'Checkout payment | laratutorials.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("home", $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 public 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!'; } } public function success() { $data['title'] = 'Razorpay Success | laratutorials.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'); } public function failed() { $data['title'] = 'Razorpay Failed | laratutorials.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'); } }
- The
index()
function renders razorpay payment template into the view.
Step 6 – Create Views
Create home.php view file, so visit app/views/ directory and create home.php file. Then add the following HTML into home.php file:
<!DOCTYPE html> <html> <head> <title>Codeigniter 4 Razorpay Payment Gateway - Laratutorials.com</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 = '[email protected]'; $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 7 – Setup Routes
To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:
// $routes->setDefaultController('Razorpay'); $routes->get('/', 'Razorpay::index');
Step 8 – Start Development server
Execute the following command into command prompt or terminal to start the codeigniter 4 application:
php spark serve
Then visit your web browser and hit the following url on it:
http://localhost/demo/ OR http://localhost:8080/
Conclusion
Razorpay payment gateway integration in codeigniter 4; In this tutorial, You have learned how to integrate razorpay payment gateway in codeigniter 4 app.
Recommended CodeIgniter 4 Tutorial
- How to Install / Download Codeigniter 4 By Manual, Composer, Git
- How to Remove Public and Index.php From URL in Codeigniter 4
- Codeigniter 4 – Form Validation Example Tutorial
- How to add jQuery Validation on Form in Codeigniter 4 Example
- Codeigniter 4 Ajax Form Submit Validation Example
- Codeigniter 4 File Upload Validation Example
- Image Upload with Validation in Codeigniter 4
- Codeigniter 4 Image Upload Preview Using jQuery Example
- Codeigniter 4 Ajax Image Upload Preview Example
- How to Upload Multiple Images in Codeigniter 4
- Codeigniter 4 Multiple Image Upload with Preview
- Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
- Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
- Codeigniter 4 CRUD with Datatables Example
- Codeigniter 4 Image Crop and Save using Croppie Example
- Dependent Dropdown using jQuery Ajax in Codeigniter 4
- CodeIgniter 4 Rest Api CRUD Example
- Codeigniter 4 Login Registration and Logout Example
- Get Address from Latitude and Longitude in Codeigniter 4
- Codeigniter 4 Google Column Charts Example
- Codeigniter 4 Google Place Autocomplete Address
- Export Data to Excel Example in Codeigniter 4
- Codeigniter 4 Google ReCaptcha V2 Example
- Google Pie Chart in Codeigniter 4
Be First to Comment