If you need Razorpay payment gateway checkout integration in PHP, this is the tutorial for you.
This tutorial will teach you how to integrate the Razorpay payment gateway into PHP. This tutorial also includes the complete source code for razorpay payment gateway integration in PHP, as well as a live demo example.
So, If you’re looking for a tutorial on how to integrate the Razorpay payment gateway in PHP, you’ve come to the right place. This tutorial will demonstrate a simple and easy way to integrate the Razorpay payment gateway in PHP using a live demo.
See also Paytm Payment Gateway Integration in PHP Step by Step
How to Integration Razorpay Payment Gateway in PHP
Let’s follow the following steps to integrate Razorpay payment gateway in PHP:
Create Razorpay Account
To begin, we must create an account on Razorpay and generate a KeyId and Secret Key. To test payment functionality, we will keep the newly created Razorpay account in test mode. If you have already account then Razorpay login and redirect to razorpay dashboard.

Generate Razorpay API Key
To begin, you must generate the Razorpay Key ID. go to razorpay dashboard then ‘Settings’ menu option on the left and then, in the API Keys tab, click to generate the key Id and secret key.

On the previous screen, generate API keys for both Test and Live modes and save the Key Id and Key Secret. Evey mode’s navigation is supplied below.
How to Integrate the Razorpay Payment Gateway with the PHP SDK
To integrate Razorpay Payment Gateway with your PHP website, follow the steps outlined below. The PHP sample app, which includes the following files, is used to demonstrate the integration process.
File Structure

File Name | Purpose |
---|---|
index.php | Contains the Products listing |
config.php | Contains the database connection |
checkout.php | Contains the checkout code |
razorpay-config.php | Contains the API Keys. |
pay.php | Contains the Checkout parameters. |
verify.php | Contains the payment signature verification codes. |
Download the Razorpay PHP SDK
You can either download or run a composer command to install Razorpay PHP SDK.
Download
Download the latest razorpay-php.zip file from the releases section on GitHub. The razorpay-php.zip is pre-compiled to include all dependencies. Add SDK file to your project.
Use Composer Command
You can install Razorpay using a composer command. Run the below command on your Composer: Unzip the SDK file and include the Razorpay.php file in your project.
composer require razorpay/razorpay:2.*
Create Database and Table by SQL query
We need to create database and table, so here I created webscodex database payment_transaction & products table. payment_transaction table holds the records which will be payment success or failed. You can simply create table as following SQL query.
-- -- Database: `webscodex` -- -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `product_name` varchar(100) NOT NULL, `image` varchar(100) NOT NULL, `description` text NOT NULL, `price` float(10,2) NOT NULL, `status` tinyint(4) NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; CREATE TABLE `payment_transaction` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `order_id` varchar(100) NOT NULL, `full_name` varchar(100) NOT NULL, `mobile_number` varchar(100) NOT NULL, `amount` float(10,2) NOT NULL, `status` varchar(100) NOT NULL, `txns_id` varchar(100) NOT NULL, `currency` varchar(100) NOT NULL, `txns_date` datetime NOT NULL, `address` text NOT NULL, `pincode` varchar(100) NOT NULL, `city` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Create Database Configuration File
In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create config.php file on your root directory and put bellow code:
config.php
<?php // Database configuration define('DBSERVER', 'localhost'); define('DBUSERNAME', 'root'); define('DBPASSWORD', ''); define('DBNAME', 'webscodex'); // Create database connection $con = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } ?>
Create Add to cart or Buy Product Page
Create Product list or add to card list in our project for e-commerce feature then buy a product using razorpay payment gateway. We have created an index.php file for product payment form.
index.php
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Rozarpay Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="container"> <div class="py-5 text-center"> <h2> Products List (Rozarpay Payment Gateway Integration) </h2> </div> <div class="row"> <?php // Database configuration require "inc/config.php"; $sql = "SELECT * FROM products WHERE status = '1' order by id DESC"; $query = $con->query($sql); if ($query->num_rows > 0) { while ($row = $query->fetch_assoc()) { ?> <div class="card col-md-4" style="width: 18rem;"> <img src="images/<?php echo $row['image']?>" class="card-img-top" alt="<?php echo $row['product_name']?>" style="width: 350px; height: 250px;"> <div class="card-body"> <h5 class="card-title"><?php echo $row['product_name']?></h5> <p class="card-text"><?php echo $row['description']?></p> <a href="checkout.php?product_id=<?php echo $row['id']?>" class="btn btn-sm btn-primary">Buy Now</a> <b><span style="float: right;"> ₹<?php echo $row['price']?></span></b> </div> </div> <?php } } ?> </div> </div> </body> </html>

Create HTML Checkout Form
Create an HTML checkout form on your website with the required fields so that it can be passed to the Razorpay library to retrieve the order id and other information needed for the payment step. An example HTML form field is shown below. Name of the item, quantity, amount, item description, item address, email, and so on.
checkout.php
<?php // Database configuration require "inc/config.php"; ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Rozarpay Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="container" style="background: #f2f2f2; padding-bottom:20px; border: 1px solid #d9d9d9; border-radius: 5px;"> <div class="py-5 text-center"> <h2> Rozarpay Payment Gateway Integration Checkout</h2> <p class="lead">This Checkout page using Rozarpay Payment Gateway for Testing purpose </p> </div> <form action="pay.php" method="POST"> <div class="row"> <div class="col-md-8"> <h4>Billing address</h4> <div class="card p-3"> <div class="mb-3"> <label for="firstName">Full Name </label> <input type="text" class="form-control" name="full_name" placeholder="Full Name" required=""> </div> <div class="mb-3"> <label for="mobile">Mobile Number</label> <input type="text" class="form-control" name="mobile_number" placeholder="Mobile Number" required=""> </div> <div class="mb-3"> <label for="email">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" name="email" placeholder="Email"> </div> <div class="mb-3"> <label for="address">Flat, House no. Area, Street, Sector, Village</label> <input type="text" class="form-control" name="address" placeholder="Full Address" required=""> </div> <div class="row"> <div class="col-md-6 mb-3"> <label for="city">Town/City</label> <input type="text" class="form-control" name="city" placeholder="Town/City"> </div> <div class="col-md-6 mb-3"> <label for="pincode">Pincode</label> <input type="text" class="form-control" name="pincode" placeholder="6 digits [0-9] Pin code" required=""> </div> </div> </div> </div> <div class="col-md-4"> <?php if (!empty($_GET['product_id']) && isset($_GET['product_id'])) { $pid = $_GET['product_id']; } $sql = "SELECT * FROM products WHERE id = $pid"; $query = $con->query($sql); if ($count = $query->num_rows > 0) { $row = $query->fetch_assoc(); ?> <h4 class="d-flex justify-content-between align-items-center"> <span>Order Summary</span> <span class="badge badge-secondary badge-pill"><?php echo $count; ?></span> </h4> <ul class="list-group mb-3 sticky-top"> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div class="product-list"> <img src="images/<?php echo $row['image']?>" class="card-img-top" style="width:100px; height: 100px;"> <h6><?php echo $row['product_name']?></h6> <small class="text-muted"><?php echo $row['description']?></small> </div> <span class="text-muted">₹<?php echo $row['price']?></span> </li> <li class="list-group-item d-flex justify-content-between"> <strong> Order Total: </strong> <strong>₹<?php echo $row['price']?></strong> <input type="hidden" name="order_amount" value="<?php echo $row['price']?>" /> <input type="hidden" name="product_id" value="<?php echo $row['id']?>" /> </li> </ul> <?php } else{ header("Location:index.php"); } ?> <div> <input class="btn btn-primary btn-block" type="submit" name="check_out" value="Continue to Checkout"> </div> </div> </div> </form> </div> </body> </html>

Razorpay Key Id and Secret Key Config
This file is contains the Razorpay Key Id and Secret Key and Razorpay API, object and payment verification class file also include autoload Razorpay all methods.
razorpay-config.php
<?php //Configuration Rozarpay Test mode Key define('KEY_ID', 'YOUR KEY ID'); // YOUR KEY ID define('KEY_SECRET', 'YOUR SECRET KEY'); // YOUR SECRET KEY // Create the Razorpay Order use Razorpay\Api\Api; use Razorpay\Api\Errors\SignatureVerificationError; // Include Razorpay autoload File require 'vendor/autoload.php'; $api = new Api(KEY_ID, KEY_SECRET); ?>
Code to Add Pay Button
In this file we are add Pay button with Razorpay API and show pay button for payment click on pay button redirect to the Razorpay various payment option. If you want to more details please visit:- Razorpay build integration
pay.php
<?php session_start(); // Database configuration require "inc/config.php"; // Include Razorpay configuration File require "razorpay-config.php"; ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Rozarpay Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <?php if (isset($_POST['check_out']) && !empty($_POST['product_id'])) { date_default_timezone_set("Asia/Kolkata"); $productId = $_POST['product_id']; $fullName = $_POST['full_name']; $email = $_POST['email']; $mobileNumber = $_POST['mobile_number']; $address = $_POST['address']; $city = $_POST['city']; $pincode = $_POST['pincode']; $order_amount = $_POST['order_amount']; $status = 'Pending'; $txnsDate = date('Y-m-d H:i:s'); $query = "SELECT * FROM products WHERE id = $productId"; $result = $con->query($query); if ($result->num_rows > 0) { $rowValue = $result->fetch_assoc(); $productId= $rowValue['id']; $price = $rowValue['price']; $title = $rowValue['product_name']; $website = "Webs Codex"; // Website name $currency = "INR"; // Indian curreny $imageUrl = "https://scontent.fdel8-1.fna.fbcdn.net/v/t39.30808-6/304897693_472566874881298_2491183556982219793_n.png?_nc_cat=104&ccb=1-7&_nc_sid=09cbfe&_nc_ohc=Ro0YLpOyYAAAX-iiwC1&_nc_ht=scontent.fdel8-1.fna&oh=00_AfBFFbnfyIfeNNuaJFe_2W5H0Ai7p1RsWTbpUz4TXC9ynw&oe=63A22175"; // Change Your website or company logo // We create an razorpay order using orders api // Docs: https://docs.razorpay.com/docs/orders // $orderData = [ 'receipt' => 3456, 'amount' => $price * 100, // 2000 rupees in paise 'currency' => 'INR', 'payment_capture' => 1 // auto capture ]; $razorpayOrder = $api->order->create($orderData); $razorpayOrderId = $razorpayOrder['id']; $_SESSION['razorpay_order_id'] = $razorpayOrderId; $displayAmount = $amount = $orderData['amount']; if ($currency !== 'INR') { $url = "https://api.fixer.io/latest?symbols=$currency&base=INR"; $exchange = json_decode(file_get_contents($url), true); $displayAmount = $exchange['rates'][$currency] * $amount / 100; } $data = array(); $data = [ "key" => KEY_ID, "amount" => $amount, "name" => $website, "description" => $title, "image" => $imageUrl, "prefill" => [ "name" => $fullName, "email" => $email, "contact" => $mobileNumber, ], "notes" => [ "address" => $address." ,".$city." ,". $pincode, "merchant_order_id" => "12312321", ], "theme" => [ "color" => "#F37254" ], "order_id" => $razorpayOrderId, ]; if ($currency !== 'INR') { $data['display_currency'] = $currency; $data['display_amount'] = $displayAmount; } $json = json_encode($data); $sqlQuery = "INSERT INTO payment_transaction (order_id, full_name, mobile_number, amount, status, currency, txns_date, address, pincode, city) VALUES ('$razorpayOrderId', '$fullName', '$mobileNumber', '$displayAmount', '$status', '$currency', '$txnsDate', '$address', '$pincode', '$city')"; $con->query($sqlQuery); } } ?> <div class="container"> <div class="py-5 text-center"> <h2> Pay with Razorpay</h2> </div> <div class="row"> <div class="col-md-4 offset-4"> <center> <form action="verify.php" method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="<?php echo $data['key']?>" data-amount="<?php echo $data['amount']?>" data-currency="INR" data-name="<?php echo $data['name']?>" data-image="<?php echo $data['image']?>" data-description="<?php echo $data['description']?>" data-prefill.name="<?php echo $data['prefill']['name']?>" data-prefill.email="<?php echo $data['prefill']['email']?>" data-prefill.contact="<?php echo $data['prefill']['contact']?>" data-notes.shopping_order_id="<?php echo $data['order_id']?>" data-order_id="<?php echo $data['order_id']?>" <?php if ($displayCurrency !== 'INR') { ?> data-display_amount="<?php echo $data['display_amount']?>" <?php } ?> <?php if ($displayCurrency !== 'INR') { ?> data-display_currency="<?php echo $data['display_currency']?>" <?php } ?> > </script> <!-- Any extra fields to be submitted with the form but not sent to Razorpay --> <input type="hidden" name="shopping_order_id" value="<?php echo $data['order_id']?>"> </form> </center> </div> </div> </div> <style> .container{ background: #f2f2f2; padding-bottom:20px; border: 1px solid #d9d9d9; border-radius: 5px; } .razorpay-payment-button{ background-color: #198754; border-radius: 5px; color: #fff; text-align: center; font-size: 17px; font-weight: 600; padding: 8px; width: 250px; } </style> </body> </html>
Verify Payment Status
You can track the status of the payment from the Razorpay Dashboard.
verify.php
<?php session_start(); // // Database configuration require "inc/config.php"; // // Include Razorpay configuration File require "razorpay-config.php"; ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Rozarpay Payment Gateway Integration</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <style type="text/css"> .message{ text-align: center; margin-top: 50px; } </style> <?php $success = true; $status = 'success'; $error = "Payment Failed"; if (empty($_POST['razorpay_payment_id']) === false) { try { // Please note that the razorpay order ID must // come from a trusted source (session here, but // could be database or something else) $attributes = array( 'razorpay_order_id' => $_SESSION['razorpay_order_id'], 'razorpay_payment_id' => $_POST['razorpay_payment_id'], 'razorpay_signature' => $_POST['razorpay_signature'] ); $api->utility->verifyPaymentSignature($attributes); $paymentTxnsId = $attributes['razorpay_payment_id']; $paymentOrderId = $attributes['razorpay_order_id']; } catch(SignatureVerificationError $e) { $success = false; $status = 'failed'; $error = 'Razorpay Error : ' . $e->getMessage(); } } if ($success === true) { $message = "<div class='col-md-8 offset-2 message'> <div class='alert alert-success alert-dismissible'> Your payment was successful </div> </div> <p class='message'><strong>Payment ID:</strong> {$paymentTxnsId}<br> Continue Shopping <a href='index.php'>Home Page</a> </p>"; } else { $message = "<div class='col-md-8 offset-2 message'> <div class='alert alert-danger alert-dismissible'> Your payment failed </div> </div>"; "<p>{$error}<br>Continue Shopping <a href='index.php'>Home Page</a></p>"; } // // Update Payment status and payment transcation Id $query = "UPDATE payment_transaction SET status = '$status', txns_id = '$paymentTxnsId' WHERE order_id = '$paymentOrderId'"; $execute = $con->query($query); if ($execute) { echo $message; } ?> </body> </html>
What is razorpay?
The company offers payment solutions that enable companies to accept, process, and disburse payments. Razorpay was selected for Y Combinator’s W15 cohort and was the second startup in India to be chosen. Razorpay is an introduction. Funding. If you want to more details about razorpay https://wikitia.com/wiki/Razorpay