Razorpay Payment Gateway Integration

Razorpay Payment Gateway Integration in PHP and MySQL

In this article, We will discuss in detail about the Razorpay Payment Gateway Integration in PHP and MySQL. Before writing the PHP code, We need to create the Razorpay account on the Razorpay Official Website.

Source Code link available in the bottom

Activate your Key ID and Key Secret on Razorpay Dashboard

Once you have completed the registration process go to the setting section and activate your AppID and SecreteID.

The sample Razorpay secrete ID and App ID given below.

$keyId = 'rzp_test_qdHKFln0F7KYZO';
$keySecret = 'Bti7lHMBzy67W5G8oDj9e5go';

Creating Database

We need to store the customer’s information with payment status as “PENDING” in MySQL database, before sending the request to the Razorpay Payment Gateway. So we will create the Database and one database table. The Database script is given below.

CREATE TABLE IF NOT EXISTS `onlinepayment` (
  `pID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(300) NOT NULL,
  `email` varchar(300) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `service` varchar(300) NOT NULL,
  `typeProduct` varchar(300) NOT NULL,
  `toValue` varchar(300) NOT NULL,
  `message` varchar(300) NOT NULL,
  `razorpayOrderId` varchar(300) NOT NULL,
  `razorpayPaymentId` varchar(300) NOT NULL,
  `paymentStatus` varchar(300) NOT NULL,
  `makerstamp` datetime NOT NULL,
  `updatestamp` datetime NOT NULL,
  PRIMARY KEY (`pID`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Creating PHP Form

Form is required to post the customers information to the Razorpay Payment Gateway for processing the request. The form Code is given below.

Razorpay Payment Gateway
<div class="container-contact100">
  <div class="wrap-contact100">
    <form method="POST" action="pay.php" class="contact100-form validate-form">
      <span class="contact100-form-title"> Razorpay Payment Gateway Integration </span>
      <div class="wrap-input100 validate-input bg1" data-validate="Please Type Your Name"> <span class="label-input100">FULL NAME *</span>
        <input class="input100" type="text" name="name" placeholder="Enter Your Name">
      </div>
      <div class="wrap-input100 validate-input bg1 rs1-wrap-input100" data-validate = "Enter Your Email (e@a.x)"> <span class="label-input100">Email *</span>
        <input class="input100" type="text" name="email" placeholder="Enter Your Email ">
      </div>
      <div class="wrap-input100 bg1 rs1-wrap-input100"> <span class="label-input100">Phone</span>
        <input class="input100" type="text" name="phone" placeholder="Enter Number Phone">
      </div>
      <div class="wrap-input100 input100-select bg1"> <span class="label-input100">Needed Services *</span>
        <div>
          <select class="js-select2" name="service">
            <option>Please chooses</option>
            <option>eCommerce Bussiness</option>
            <option>UI/UX Design</option>
            <option>Online Services</option>
          </select>
          <div class="dropDownSelect2"></div>
        </div>
      </div>
      <div class="w-full dis-none js-show-service">
        <div class="wrap-contact100-form-radio"> <span class="label-input100">What type of products do you sell?</span>
          <div class="contact100-form-radio m-t-15">
            <input class="input-radio100" id="radio1" type="radio" name="typeProduct" value="physical" checked="checked">
            <label class="label-radio100" for="radio1"> Phycical Products </label>
          </div>
          <div class="contact100-form-radio">
            <input class="input-radio100" id="radio2" type="radio" name="typeProduct" value="digital">
            <label class="label-radio100" for="radio2"> Digital Products </label>
          </div>
          <div class="contact100-form-radio">
            <input class="input-radio100" id="radio3" type="radio" name="typeProduct" value="service">
            <label class="label-radio100" for="radio3"> Services Consulting </label>
          </div>
        </div>
        <div class="wrap-contact100-form-range"> <span class="label-input100">Budget *</span>
          <div class="contact100-form-range-value"> Rs.<span id="value-lower">10</span> - Rs.<span id="value-upper">2000</span>
            <input type="text" name="fromValue">
            <input type="text" name="toValue">
          </div>
          <div class="contact100-form-range-bar">
            <div id="filter-bar"></div>
          </div>
        </div>
      </div>
      <div class="wrap-input100 validate-input bg0 rs1-alert-validate" data-validate = "Please Type Your Message"> <span class="label-input100">Message</span>
        <textarea class="input100" name="message" placeholder="Your message here..."></textarea>
      </div>
      
      <div class="container-contact100-form-btn">
        <button class="contact100-form-btn" name="btn-submit"> <span> Submit <i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i> </span> </button>
      </div>
    </form>
  </div>
</div>

Now we will send the customer information to the Razorpay payment gateway, when user click on the submit button and also insert one record into the database table with payment status as “PENDING“.

Razorpay Payment Gateway Integration in PHP

Creating pay.php

<?php
require('config.php');
require('Razorpay.php');
require_once 'common.php';
session_start();
use Razorpay\Api\Api;
$onlinePay = new STUDENT();
$sql9 = $DB_con->prepare( "select max(pID) as pID from onlinepayment" );
$sql9->execute();
$result9 = $sql9->fetch( PDO::FETCH_ASSOC ) ;
$pID = $result9['pID'];
$mOrderID= "0000".$pID ;
$api = new Api($keyId, $keySecret);

if(isset($_POST['btn-submit']))
{
$name =  $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$typeProduct = $_POST['typeProduct'];
$toValue = $_POST['toValue'];
$message = $_POST['message'];
$razorpayPaymentId ="";
$paymentStatus ="PENDING";
$makerstamp=date('Y-m-d h:i:s');
$updatestamp=date('Y-m-d h:i:s');
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['phone'] = $phone;
$_SESSION['service'] = $service;
$_SESSION['typeProduct'] = $typeProduct;
$_SESSION['toValue'] = $toValue;
$orderData = [
    'receipt'         => 3456,
    'amount'          => $toValue * 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;
}

$data = [
    "key"               => $keyId,
    "amount"            => $amount,
    "name"              => "IIIT Delhi",
    "description"       => "HTML CSS3 Tutorials",
    "image"             => "https://htmlcss3tutorials.com/wp-content/themes/htmlcss/images/logo.png",
    "prefill"           => [
    "name"              => $name,
    "email"             =>$email,
    "contact"           => $phone,
    ],
    "notes"             => [
    "address"           => "Online Payments",
    "merchant_order_id" => $mOrderID,
    ],
    "theme"             => [
    "color"             => "#F37254"
    ],
    "order_id"          => $razorpayOrderId,
];

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

		if($onlinePay->razorPayOnline($name,$email,$phone, $service, $typeProduct, $toValue, $message,$razorpayOrderId,$razorpayPaymentId,$paymentStatus,$makerstamp,$updatestamp))
			
		{			
			//$successMSG = "Your payment has been done successfully.";
			$json = json_encode($data);
		}
		else
		{
			$errMSG = "sorry , Query could no execute...";
		}		
	}
?>
<body>
<div class="container-contact100">
  <div class="wrap-contact100">

<table>
  <tr>
    <td class="txt-agl-rt">Your Name</td>
    <td class="txt-agl-lt"><?php echo $name; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Your Email</td>
    <td class="txt-agl-lt"><?php echo $email; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Mobile Number</td>
    <td class="txt-agl-lt"><?php echo $phone; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Selected Service</td>
    <td class="txt-agl-lt"><?php echo $service; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Product Type</td>
    <td class="txt-agl-lt"><?php echo $typeProduct; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Amount</td>
    <td class="txt-agl-lt"><?php echo $toValue; ?></td>
  </tr>
</table>	
<div class="payment">
   <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="3456"
    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="3456">
<input type="hidden" name="callback_url" value="verify.php">
<input type="hidden" name="cancel_url" value="verify.php">
</form>
	</div>	  

  </div>
</div>

Now Creating verify.php to get the response from Razorpay Payment gateway and update the response in a database table.

Razorpay Confirmation page
<?php
require('config.php');
session_start();
require_once 'common.php';
$applicatF = new STUDENT();
require('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
    {
        $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)
{
	
	$razorpayOrderId = $_SESSION['razorpay_order_id'];
	$razorpayPaymentId = $_POST['razorpay_payment_id'];
	$name = $_SESSION['name'];
	$email = $_SESSION['email'];
	$phone = $_SESSION['phone'];
	$service = $_SESSION['service'];
	$typeProduct = $_SESSION['typeProduct'];
    $toValue = $_SESSION['toValue'];
	$paymentStatus = 'SUCCESS';
	$updatestamp=date('Y-m-d h:i:s');
	$stmt = $applicatF->runQuery("SELECT * FROM onlinepayment WHERE email=:email1 and razorpayOrderId='$razorpayOrderId' and razorpayPaymentId <>'' ");
	$stmt->execute(array(":email1"=>$email));
	$rows = $stmt->fetch(PDO::FETCH_ASSOC);
	if($stmt->rowCount() > 0)
	{
		$errMSG = "You have already submited.";    
	}
	else
	{
	
	if($applicatF->updatePayStatus($email, $razorpayOrderId, $razorpayPaymentId, $paymentStatus, $updatestamp ))
		{			
			
			$successMSG = "Your payment has been completed successfuly..";
			
		}
		else
		{
			$errMSG = "sorry , Query could no execute...";
		}
	
  //$html = "{$_POST['razorpay_payment_id']}";
}
}
else
{
$paymentStatus = 'FAILURE';
$updatestamp=date('Y-m-d h:i:s');
$applicatF->updatePayStatus($email, $razorpayOrderId, $razorpayPaymentId, $paymentStatus, $updatestamp );
}

<div class="container-contact100">
  <div class="wrap-contact100">
	   <?php
	if(isset($errMSG)){
			?>
		  <div class="alert alert-danger alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <h4 style="font-size: 14px;"><i class="icon fa fa-ban"></i> <?php echo $errMSG; ?></h4>
               
              </div>
            <?php
	}
	else if(isset($successMSG)){
		?>
		    <div class="alert alert-success alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <h4 style="font-size: 14px;"><i class="icon fa fa-check"></i> <?php echo $successMSG; ?></h4>
               
              </div>
        <?php
	}

	?> 
    <table>
  <tr>
    <td class="txt-agl-rt">Your Name</td>
    <td class="txt-agl-lt"><?php echo $name; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Your Email</td>
    <td class="txt-agl-lt"><?php echo $email; ?></td>
  </tr>
 <tr>
    <td class="txt-agl-rt">Order ID</td>
    <td class="txt-agl-lt"><?php echo $razorpayOrderId; ?></td>
  </tr>
	<tr>
    <td class="txt-agl-rt">Payment ID</td>
    <td class="txt-agl-lt"><?php echo $razorpayPaymentId; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Mobile Number</td>
    <td class="txt-agl-lt"><?php echo $phone; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Selected Service</td>
    <td class="txt-agl-lt"><?php echo $service; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Product Type</td>
    <td class="txt-agl-lt"><?php echo $typeProduct; ?></td>
  </tr>
  <tr>
    <td class="txt-agl-rt">Amount</td>
    <td class="txt-agl-lt"><?php echo $toValue; ?></td>
  </tr>
</table>
  </div>
</div>

comman.php

<?php
require_once 'dbconfig.php';

class STUDENT {

	private $conn;

	public function __construct() {
		$database = new Database();
		$db = $database->dbConnection();
		$this->conn = $db;
	}

	public function runQuery( $sql ) {
		$stmt = $this->conn->prepare( $sql );
		return $stmt;
	}

	public function lasdID() {
		$stmt = $this->conn->lastInsertId();
		return $stmt;
	}


	public function razorPayOnline($name,$email,$phone, $service, $typeProduct, $toValue, $message,$razorpayOrderId,$razorpayPaymentId,$paymentStatus,$makerstamp,$updatestamp) {
		try {
			$stmt = $this->conn->prepare( "INSERT INTO onlinepayment(name, email, phone, service, typeProduct, toValue, message, razorpayOrderId, razorpayPaymentId, paymentStatus,makerstamp,updatestamp) 	
			VALUES(:name_o,:email_o,:phone_o,:service_o,:typeProduct_o,:toValue_o,:message_o,:razorpayOrderId_o,:razorpayPaymentId_o,:paymentStatus_o,:makerstamp_o,:updatestamp_o)" );
			$stmt->bindparam( ":name_o", $name );
  			$stmt->bindparam( ":email_o", $email );
  			$stmt->bindparam( ":phone_o", $phone );
  			$stmt->bindparam( ":service_o", $service );
  			$stmt->bindparam( ":typeProduct_o", $typeProduct ); 
			$stmt->bindparam( ":toValue_o", $toValue ); 
			$stmt->bindparam( ":message_o", $message );
			$stmt->bindparam( ":razorpayOrderId_o", $razorpayOrderId );
			$stmt->bindparam( ":razorpayPaymentId_o", $razorpayPaymentId );
			$stmt->bindparam( ":paymentStatus_o", $paymentStatus );
			$stmt->bindparam( ":makerstamp_o", $makerstamp );
			$stmt->bindparam( ":updatestamp_o", $updatestamp );
			$stmt->execute();
			return $stmt;

		} catch ( PDOException $ex ) {
			echo $ex->getMessage();
		}
	}
	
	public function updatePayStatus($email, $razorpayOrderId, $razorpayPaymentId, $paymentStatus, $updatestamp) {
		try {
			$stmt = $this->conn->prepare( "UPDATE onlinepayment SET razorpayPaymentId=:razorpayPaymentId,paymentStatus=:paymentStatus,updatestamp=:updatestamp WHERE email=:email and razorpayOrderId='$razorpayOrderId'" );
			$stmt->bindparam( ":email", $email );
  			$stmt->bindparam( ":razorpayPaymentId", $razorpayPaymentId );
			$stmt->bindparam( ":paymentStatus", $paymentStatus );
  			$stmt->bindparam( ":updatestamp", $updatestamp );
			$stmt->execute();
			return $stmt;

		} catch ( PDOException $ex ) {
			echo $ex->getMessage();
		}
	}
}

dbconfig.php

<?php
class Database
{
     
    private $host = "localhost";
    private $db_name = "razorpaypatment";
    private $username = "root";
    private $password = "";
    public $conn;
     
    public function dbConnection()
	{
     
	    $this->conn = null;    
        try
		{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
			$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	
        }
		catch(PDOException $exception)
		{
            echo "Connection error: " . $exception->getMessage();
        }
         
        return $this->conn;
    }
}

$DB_HOST = 'localhost';
	$DB_USER = 'root';
	$DB_PASS = '';
	$DB_NAME = 'razorpaypatment';
	
	try{
		$DB_con = new PDO("mysql:host={$DB_HOST};dbname={$DB_NAME}",$DB_USER,$DB_PASS);
		$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}
	catch(PDOException $e){
		echo $e->getMessage();
	}
$connection=mysqli_connect("localhost","root","","razorpaypatment");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

?>

Razorpay Payment gateway integration

Razorpay integration
Razorpay Payment Gateway response page

Conclusion

We explained how to integrate Razorpay Payment Gateway Integration in PHP and MySQL. Hope you like it so please like and share.

Read Also: How to display data from database in PHP in table

Read Also: How to make a dependent dropdown list using jquery Ajax Download