Dj Techblog

A blog on web development

Razorpay payment gateway integration in php

Last modified on Nov 3, 2021

Razorpay payment gateway integration in php
Razorpay is one of the leading payment gateway that can be easily integrated in ecommerce websites running on php. In this article we will see how can we integrate the payment gateway and start receiving money from the ecommerce websites. We can also use the inbuilt payment button to send it via Email and receive money from customers.

Every payment gateway provides two modes of operation the test mode and live mode. In test mode we test the code for demo transaction and when we are are assured of everything is running fine, we can go live then.

Every mode of operation has separate credentials. Client id and secret key are the two keys that are used as credentials for secured payment. Login to your account after registration and go to Dashboard -> Settings -> API keys tabs. Generate the API keys and save them for future use. You can view the secret key only once, so save them in secured place. However, client id can be viewed as many times.

Steps to integrate Razorpay payment gateway in php

  1. Display products to purchase.
  2. Place an Order.
  3. Configure the config.php
  4. Create Order-id and pass along with payment details to checkout
  5. Process the payment in the checkout
  6. Verify the payment and save the payment details in the database
  7. Test the payment.

1. Display products to purchase.

index.php


<!DOCTYPE html>
<html lang="en">
  <head>
      <script async src="https://www.googletagmanager.com/gtag/js?id=UA-174570699-5"></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', 'UA-174570699-5');
        </script>
    <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="icon" href="../../favicon.ico">

    <title>Demo Shopping Page</title>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"  crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"  crossorigin="anonymous"></script>
  </head>

  <body>
    <div class="container">

      <div class="page-header">
        <h1><a href="index.php">Razorpay Payment Gateway Integration</a></h1>
        <p class="lead">A test product page</p>
      </div>

      <h3>Details</h3>
  
<div class="col-md-4">
<img src="/php/projects/payments/download.jpg" width="300" alt="..." class="img-rounded">
<h4> Shirts Mens </h4>
<h6> Price: 500</h6>
<h5> ID: 111</h5>
<a rel="nofollow" href="order.php?id=111" class="btn btn-success"> Buy Now </a>
</div>

<div class="col-md-4">
<img src="/php/projects/payments/demo-shirt.jpg" width="300" height="300" alt="..." class="img-rounded">
<h4> T Shirt Mens </h4>
<h6> Price: 700</h6>
<h5> ID: 112</h5>
<a rel="nofollow" href="order.php?id=112" class="btn btn-success"> Buy Now </a>
</div>


<div class="col-md-4">
<img src="/php/projects/payments/demo-jeans.jpg" width="300" height="300" alt="..." class="img-rounded">
<h4> Jeans Mens </h4>
<h6> Price:1000</h6>
<h5> ID: 113</h5>
<a rel="nofollow" href="order.php?id=113" class="btn btn-success"> Buy Now </a>
</div>

     
      
    </div> <!-- /container -->


  </body>
</html>

Create a list of products in your website where user user can browse the products and can proceed for placing an order. Show all the necessary product details.

2. Place an Order

order.php

<?php 

if(isset($_GET['id']) && $_GET['id'] == 111){

    $prd_name = "Shirt Mens #111";
	$price = 500;

	// Price calculation with tax and fee
	$fee = 3 +($price*.02);
	$tax = $fee * .15;
	$prd_price = $fee + $tax + $price;
	
 } 
 	else if(isset($_GET['id']) && $_GET['id'] == 112){
    $prd_name = "T Shirt Mens #112";
   	$price = 700;

	// Price calculation with tax and fee
	$fee = 3 +($price*.02);
	$tax = $fee * .15;
	$prd_price = $fee+ $tax + $price;	
 } 
 	else if(isset($_GET['id']) && $_GET['id'] == 113){
    $prd_name = "Jeans Mens #113";
    $price = 1000;

	// Price calculation with tax and fee
	$fee = 3 +($price*.02);
	$tax = $fee * .15;
	$prd_price = $fee+ $tax + $price;	
 } else {

 	echo "No such a prodcut to purchase :(";
 	exit();
 }

 ?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <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="icon" href="../../favicon.ico">

    <title>Buy <?php echo $prd_name; ?></title>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  </head>

  <body>
    <div class="container">

      <div class="page-header">
        <h1><a href="index.php">Test Payment for Razorpay</a></h1>
        <p class="lead">A test payment integration for Razorpay payment gateway. Written in PHP</p>
      </div>

		<p>
		<b>Product name :</b> <?php echo $prd_name; ?>
		</p>
		<p>
		<b>Price : </b> <?php echo $price; ?>
		</p>
		<p><b>Bank Fee : </b> <?php echo $tax + $fee ; ?> <small> (Rs:3+ 2% of fee+ 15% Service Tax)</small></p>

		<p><b>Total : </b> <?php echo $prd_price; ?></p>

		<h3>Payment Details for the product <?php echo $prd_name; ?></h3>
		<hr>
		<form action="razorpay-php-testapp-master/pay.php?checkout=manual" method="POST" accept-charset="utf-8">
	
		<input type="hidden" name="product_name" value="<?php echo $prd_name; ?>"> 
		<input type="hidden" name="product_price" value="<?php echo $prd_price; ?>"> 

		<div class="form-group">
    	<label>Your Name</label>
   		<input type="text" class="form-control" name="name" placeholder="Enter your name">	 <br/>
		</div>

		<div class="form-group">
    	<label>Your Mobile</label>
   		<input type="text" class="form-control" name="mobile" placeholder="Enter your phone number"> <br/>
		</div>


		<div class="form-group">
    	<label>Your Email</label>
   		<input type="email" class="form-control" name="email" placeholder="Enter you email"> <br/>
		</div>
		
		<div class="form-group">
    	<label>Shipping Address</label>
   		<textarea class="form-control" name="shipping-address" placeholder="Enter shipping address"></textarea> <br/>
		</div>
		
		<div class="form-group">
    	<label>Billing Address</label>
   		<textarea class="form-control" name="billing-address" placeholder="Enter billing address"> </textarea><br/>
		</div>

		<input type="submit" class="btn btn-success btn-lg" value="Click here to Pay Rs:<?php echo $prd_price; ?> ">

		 </form>
 <br/>
  <br/>     
    </div> <!-- /container -->
  </body>
</html>

Create a form here, let customer fill its details and proceed to Pay with Razorpay. At this stage customer places an order and all the customer and product details are forwarded to pay.php.

3. Configure the config.php

config.php

    <?php
    
    $keyId = '<Put Key id here>';
    $keySecret = '<Put Key secret here>';
    $displayCurrency ' = '<Put currency mode here>';';
    
    //These should be commented out in production
    // This is for error reporting
    // Add it to config.php to report any errors
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

Enter all the details as shown above.

4. Create Order-id and pass along with payment details to checkout

pay.php

<?php

require('config.php');
require('razorpay-php/Razorpay.php');
session_start();
$product_name = $_POST["product_name"] ;
$price = $_POST["product_price"];
$name = $_POST["name"];
$phone = $_POST["mobile"];
$email = $_POST["email"];
$address = $_POST["shipping-address"];
// Create the Razorpay Order

use Razorpay\Api\Api;

$api = new Api($keyId, $keySecret);

//
// 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 ($displayCurrency !== 'INR')
{
    $url = "https://api.fixer.io/latest?symbols=$displayCurrency&base=INR";
    $exchange = json_decode(file_get_contents($url), true);
    $displayAmount = $exchange['rates'][$displayCurrency] * $amount / 100;
}

$checkout = 'automatic';

if (isset($_GET['checkout']) and in_array($_GET['checkout'], ['automatic', 'manual'], true))
{
    $checkout = $_GET['checkout'];
}

$data = [
    "key"               => $keyId,
    "amount"            => $amount,
    "name"              => $product_name,
    "description"       => "Tron Legacy",
    "image"             => "https://s29.postimg.org/r6dj1g85z/daft_punk.jpg",
    "prefill"           => [
    "name"              => $name,
    "email"             => $email,
    "contact"           => $phone,
    ],
    "notes"             => [
    "address"           => $address,
    "merchant_order_id" => "12312321",
    ],
    "theme"             => [
    "color"             => "#F37254"
    ],
    "order_id"          => $razorpayOrderId,

];

if ($displayCurrency !== 'INR')
{
    $data['display_currency']  = $displayCurrency;
    $data['display_amount']    = $displayAmount;
}

$json = json_encode($data);

require("checkout/{$checkout}.php");


In the pay.php we create an instance of Razorpay api by passing key_id and Key_secret. Fillup the $orderData details and create a razorpayOrder and then generate an order-id named $razorpayOrderid that will be passed to Checkout along with $data.

5. Process the payment in the Checkout

manual.php

<button id="rzp-button1">Pay with Razorpay</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<form name='razorpayform' action="verify.php" method="POST">
    <input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id">
    <input type="hidden" name="razorpay_signature"  id="razorpay_signature" >
</form>
<script>
// Checkout details as a json
var options = <?php echo $json?>;

/**
 * The entire list of Checkout fields is available at
 * https://docs.razorpay.com/docs/checkout-form#checkout-fields
 */
options.handler = function (response){
    document.getElementById('razorpay_payment_id').value = response.razorpay_payment_id;
    document.getElementById('razorpay_signature').value = response.razorpay_signature;
    document.razorpayform.submit();
};

// Boolean whether to show image inside a white frame. (default: true)
options.theme.image_padding = false;

options.modal = {
    ondismiss: function() {
        console.log("This code runs when the popup is closed");
    },
    // Boolean indicating whether pressing escape key 
    // should close the checkout form. (default: true)
    escape: true,
    // Boolean indicating whether clicking translucent blank
    // space outside checkout form should close the form. (default: false)
    backdropclose: false
};

var rzp = new Razorpay(options);

document.getElementById('rzp-button1').onclick = function(e){
    rzp.open();
    e.preventDefault();
}
</script>

On clicking the button a new instance of the Razorpay Class is created which actually starts the processing of payment.

6. Verify the payment and save the details into database

verify.php

<?php

require('config.php');

session_start();

require('razorpay-php/Razorpay.php');
use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

$success = true;

$error = "Payment Failed";

if (empty($_POST['razorpay_payment_id']) === false)
{
    $api = new Api($keyId, $keySecret);

    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);
    }
    catch(SignatureVerificationError $e)
    {
        $success = false;
        $error = 'Razorpay Error : ' . $e->getMessage();
    }
}

if ($success === true)
{
    // Save the razorpay_order_id razorpay_payment_id and all other details to database here.
    $html ="";
    $html .= "

Payment Successful.

"; $html .= "

"; $html .= "

Your payment for the order {$_SESSION['razorpay_order_id']} was successful, Payment ID: {$_POST['razorpay_payment_id']}

"; } else { $html = "

Your payment failed

{$error}

"; } echo $html;

We generate a new instance of the razorpay api and use the inbuilt api utility to check for the validity of razorpay payment signature. If the signature seems valid mark the payment as success and proceed forward to save the payment and order relatred details to the database.

6. Test the Razorpay payment gateway integration in php


Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.