Razorpay Payment Gateway Integration in PHP

Webs Codex
7 min readDec 22, 2022

--

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.

How to Integration Razorpay Payment Gateway in PHP
Step by Step

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.

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>

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

Visit webscodex for more tutorials and blog post they are help you for your better programming skills and knowledge.

How to Integration Razorpay Payment Gateway in PHP

--

--