Integrate PayUMoney Payment Gateway in PHP

Webs Codex
8 min readAug 16, 2023

What is PayU Money Payment Gateway?

In order to integrate payment gateways for ecommerce shopping sites, the company must be a registered legal entity a Sole Proprietorship or Pvt. Here is the PayU Money payment gateway in the picture. This payment gateway offers users the offer to accept payments from customers even if the company is not registered. It is a payment gateway for private individuals.

PayU Money ranks among the best payment gateways invented in India.Your customers can seamlessly send you money via credit and debit cards, online banking, and many other ways. Simply integrate PayU Money into your website. In the following tutorial you will learn how to integrate the PayU Money Gateway in PHP into your web applications. If you want to learn more about PayU Money, click on the links

How to integrate PayUMoney payment Gateway in PHP?

Integrating PayU Money with PHP is an extremely easy task. Here are some steps you need to follow to integrate PayU Money with PHP:

See also

Register a PayUMoney Account

Go to the PayUMoney website and create a test environment Payumoney account. PayUMoney strongly recommends you to test it using a test environment and then use your test merchant key and salt. Please note that at the time of sign-up, please use your valid email address, set your strong password and valid 10 digit mobile number for verification.

Generate Test Merchant Key and Salt

After PayUMoney login successful go to your dashboard and click on the Payment Gateway under Collection Payments from the menu of left side. You can find your Merchant Key and Salt Key. To integrate PayUMoney into your PHP code, just copy and paste your key into your code.

Create Database and Table by SQL query

We need to create database and table, so here I created webscodex database products table. products table holds the all products records. which is show on the products listing page and details page. You can simply create table as following SQL query.

-- Database: `webscodex`
-- --------------------------------------------------------
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`product_name` varchar(100) NOT NULL,
`image` varchar(100) NOT NULL,
`description` text NOT NULL,
`price` int(50) 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 Database Configuration

In this step, we require to create database configuration file, here we will set database name, server, username and password. So let’s create config.php file on your root directory and put bellow code:

<?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 Payumoney payment gateway. We have created an index.php file for product payment form.

Paytm Payment Gateway Integration in PHP Step by Step

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>PayUMoney 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">
</head>
<body>
<div class="container" style="background:#e6e6e6;padding: 50px;">
<div class="py-5 text-center">
<h2> Products List (PayUMoney 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="col-md-4">
<div class="card" style="height: 543px;">
<img src="images/<?php echo $row['image']?>" style="width:325px; 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>
</div>
<?php } } ?>
</div>
</div>
</body>
</html>

Create HTML Checkout Form

Create a HTML checkout form on your website with the required fields so that it can be passed to the Payumoney Payment 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

// Merchant Key and Salt as provided by Payu.
$MERCHANT_KEY = "<YOUR_MARCHANT_KEY>";
$SALT = "<YOUR_SALT>";

$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);

$PAYU_BASE_URL = "https://test.payu.in"; // For Sandbox Mode
// $PAYU_BASE_URL = "https://sandboxsecure.payu.in"; // For Sandbox Mode
// $PAYU_BASE_URL = "https://secure.payu.in"; // For Live Mode

$action = '';

$posted = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) {
$posted[$key] = $value;
}
}

$formError = 0;

if(empty($posted['txnid'])) {
// Generate random transaction id
$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
$txnid = $posted['txnid'];
}

$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty($posted['hash']) && sizeof($posted) > 0) {

if(empty($posted['key']) || empty($posted['txnid']) || empty($posted['amount']) || empty($posted['firstname']) || empty($posted['email']) || empty($posted['phone']) || empty($posted['productinfo']) || empty($posted['surl']) || empty($posted['furl']) || empty($posted['service_provider']) ) {
$formError = 1;
} else {
$hashVarsSeq = explode('|', $hashSequence);
$hash_string = '';

foreach($hashVarsSeq as $hash_var) {
$hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
$hash_string .= '|';
}

$hash_string .= $SALT;

$hash = strtolower(hash('sha512', $hash_string));
$action = $PAYU_BASE_URL . '/_payment';
}
} elseif(!empty($posted['hash'])) {
$hash = $posted['hash'];
$action = $PAYU_BASE_URL . '/_payment';
}

?>
<html>

<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>PayUMoney 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">
<!-- Include External CSS -->
<link rel="stylesheet" href="inc/style.css" />
<script>
var hash = '<?php echo $hash ?>';

function submitPayuForm() {
if (hash == '') {
return;
}
var payuForm = document.forms.payuForm;
payuForm.submit();
}
</script>
</head>

<body onload="submitPayuForm()">
<div class="container" style="background: #f2f2f2; padding-bottom:20px; border: 1px solid #d9d9d9; border-radius: 5px;">
<div class="py-5 text-center">
<h2> PayUMoney Payment Gateway Integration Checkout</h2>
<p class="lead">This Checkout page using PayUMoney Payment Gateway for Testing purpose </p>
</div>
<?php if($formError) { ?>
<div class="alert alert-danger align-items-center">Please fill all mandatory fields.</div>
<?php } ?>
<form action="<?php echo $action; ?>" method="post" name="payuForm">
<div class="row">
<div class="col-md-8">
<div class="card p-3">
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" />
<input type="hidden" name="hash" value="<?php echo $hash ?>" />
<input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstname">Firstname</label>
<input name="firstname" class="form-control" value="<?php echo (empty($posted['firstname'])) ? '' : $posted['firstname']; ?>" placeholder="First Name" />
</div>
<div class="col-md-6 mb-3">
<label for="lastname">Lastname</label>
<input name="lastname" class="form-control" id="lastname" value="<?php echo (empty($posted['lastname'])) ? '' : $posted['lastname']; ?>" placeholder="Last Name" />
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="email">Email</label>
<input name="email" id="email" class="form-control" value="<?php echo (empty($posted['email'])) ? '' : $posted['email']; ?>" placeholder="Email" />
</div>
<div class="col-md-6 mb-3">
<label for="phone">Mobile number</label>
<input name="phone" class="form-control" value="<?php echo (empty($posted['phone'])) ? '' : $posted['phone']; ?>" placeholder="Mobile number" />
</div>
</div>
<div class="row">
<div class="col-md-12 mb-3">
<label for="address">Flat, House no. Area, Street, Sector, Village</label>
<input name="address1" class="form-control" value="<?php echo (empty($posted['address1'])) ? '' : $posted['address1']; ?>" placeholder="Full Address" />
</div>
<input type="hidden" name="surl" value="http://localhost/BlogPost/Payumoney-Payment-gateway-in-php/success.php" />
<input type="hidden" name="furl" value="http://localhost/BlogPost/Payumoney-Payment-gateway-in-php/failure.php" />
<input type="hidden" type="hidden" name="service_provider" value="payu_paisa" size="64" />
<input type="hidden" name="udf1" value="<?php echo (empty($posted['udf1'])) ? '' : $posted['udf1']; ?>" />
<input type="hidden" name="udf2" value="<?php echo (empty($posted['udf2'])) ? '' : $posted['udf2']; ?>" />
<input type="hidden" name="udf3" value="<?php echo (empty($posted['udf3'])) ? '' : $posted['udf3']; ?>" />
<input type="hidden" name="udf4" value="<?php echo (empty($posted['udf4'])) ? '' : $posted['udf4']; ?>" />
<input type="hidden" name="udf5" value="<?php echo (empty($posted['udf5'])) ? '' : $posted['udf5']; ?>" />
<input type="hidden" name="pg" value="<?php echo (empty($posted['pg'])) ? '' : $posted['pg']; ?>" />
</div>

<div class="row">
<div class="col-md-6 mb-3">
<label for="city">City</label>
<input name="city" class="form-control" value="<?php echo (empty($posted['city'])) ? '' : $posted['city']; ?>" placeholder="City" />
</div>
<div class="col-md-6 mb-3">
<label for="pincode">Pin code</label>
<input name="zipcode" class="form-control" value="<?php echo (empty($posted['zipcode'])) ? '' : $posted['zipcode'] ?>" placeholder="Pincode" />
</div>
</div>
</div>
</div>
<div class="col-md-4">
<?php
// Database configuration
require "inc/config.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']?>" 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="amount" value="<?php echo $row['price']?>" />
<input type="hidden" name="productinfo" value="<?php echo $row['product_name']?>" />
</li>
</ul>
<?php }
else{
header("Location:index.php");
}
?>
<?php if(!$hash) { ?>
<div class="row">
<div class="col-md-12 mb-3">
<button type="submit" class="btn-submit btn-block text-white">Continue to checkout</button>
</div>
</div>
<?php } ?>
</div>
</div>
</form>
</div>
</body>
</html>

PayUMoney Successful

If payment status is Status then payment page is redirected to success page and show payment status, Transaction Id and amount details. I have used this type of method which you can change as per your choice.

Paypal Payment Gateway Integration in PHP Step by Step

success.php

<?php

$status = $_POST["status"];
$firstname = $_POST["firstname"];
$amount = $_POST["amount"];
$txnid = $_POST["txnid"];
$posted_hash = $_POST["hash"];
$key = $_POST["key"];
$productinfo = $_POST["productinfo"];
$email = $_POST["email"];

$salt="";

// Salt should be same Post Request

If (isset($_POST["additionalCharges"])) {
$additionalCharges=$_POST["additionalCharges"];
$retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
} else {
$retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
}
$hash = hash("sha512", $retHashSeq);

if ($hash != $posted_hash) {
echo "Invalid Transaction. Please try again";
} else {
echo "<h3>Thank You. Your order status is ". $status .".</h3>";
echo "<h4>Your Transaction ID for this transaction is ".$txnid.".</h4>";
echo "<h4>We have received a payment of Rs. " . $amount . ". Your order will soon be shipped.</h4>";
}

?>

PayUMoney Cancellation or Failure

When a buyer cancel or failed a payment, they typically return to the cancel page. on the other hand, You can instead use the failure.php page to show the cancellation or failed page.

failure.php

<?php

$status = $_POST["status"];
$amount = $_POST["amount"];
$txnid = $_POST["txnid"];
$firstname = $_POST["firstname"];
$posted_hash = $_POST["hash"];
$key = $_POST["key"];
$productinfo = $_POST["productinfo"];
$email = $_POST["email"];

$salt="";


// Salt should be same Post Request

If (isset($_POST["additionalCharges"])) {
$additionalCharges = $_POST["additionalCharges"];
$retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
} else {
$retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
}

$hash = hash("sha512", $retHashSeq);

if ($hash != $posted_hash) {
echo "Invalid Transaction. Please try again";
} else {
echo "<h3>Your order status is ". $status .".</h3>";
echo "<h4>Your transaction id for this transaction is ".$txnid.". You may try making the payment by clicking the link below.</h4>";
}

?>

You can visit on my blog page for more payment gateway articles and other blog click on the below link

Integrate Payumoney Payment gateway in PHP application

Conclusion

In this tutorial, I have explain the process of How you can integrate Payumoney Payment gateway in PHP application. I have explain the very simple way to Payumoney payment integrate. You can extend this to more complex uses like online shops etc.

--

--

Webs Codex

Webs Codex is programming and web development blog