How do i integrate Razorpay Payment gateway in PHP Mysql website

Published October 27, 2021


In this PHP example tutorial we will learn about integrate Razorpay payment gateway in PHP website. In this example we will create a simple form with product services to users , when they going to purchase the service we will show payment options with Razorpay SDK, upon successful payment we confirm the user order and update in the mysql database.

 

To integrate Razorpay sdk first we need to create an application at Razorpay dashboard. Follow the Razorpay app configuration at their official website.

Steps to integrate Razorpay SDk

  • Create App and get keys from Razorpay Dashboard
  • Create Database tables to Handle the User Orders
  • Create a Form to select the Services
  • Send user Order details to server

 

Create App and get keys from Razorpay Dashboard

From the Razorpay app dashboard you will find two keys

$keyId = 'rzp_test_qsdjjjsAjhdsl';
$keySecret = 'CHaindkW5G8oxYskhdDAa';

copy these two keys, we will use these two keys while we start payment process with Rzorpay.

 

Create Database tables to Handle the User Orders

On each service we need to manage the customer information along with order status. For this we will create a table with below filed information.

 

PHP rayzorpay payment gateway db structure

 

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;

 

Create Form

Now we need to create our ui which will display the product information along with user information fields.

 

PHP Razorpay Payment Gateway integration

 

Our form will be like above

<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>

 

Send Order to server

Now we need to send user information along with order details to server and from there we will initiate payment process by send required data to Razorpay payment gateway.

For this process we will create a php file called pay.php This file contains below code

 

PHP Rayzorpay SDK
<?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>

 

Upon payment process finish we will create a verify.php file to manage the response from Rayzorpay gateway

 

<?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>

 

Database connection

create a configuration file dbconfig.php to manage the database connection details

<?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();
  }

?><gwmw style="display:none;"><gwmw style="display:none;"><gwmw style="display:none;"></gwmw><gwmw style="display:none;">

 

Now let's run the application you will find output like below

Razorpay payment Gateway html php mysql

 

Razorpay Payment gateway

 

 

PHP how do i integrate razorpay payment gateway

 

 

Conclusion: In this PHP tutorial example we covered how to create Order with razorpay payment gateway integration

 

 

Download Source code

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

74 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions