We have already discussed in our previous blog, how to Integrate PayPal payment gateway using PHP and PDO (PHP Data Objects) to collect online payments.

Think, if you want to add a coupon feature also so that users get attracted to your offers and go for a payment instantly.



Here, in this tutorial we will be going to see, how we can add Coupon Code feature in our PayPal payment system.


 

Watch the live demo or download code from the below-given links

paypal-checkout-coupon-code-pdo

Note : The installation documentation is given in the download file.


 

Basic concept of generating coupon code:

Initially, we store coupon codes and discounted value in our database ( table: coupon_detail ). In run time, we fetch the coupon id randomly and based upon that we fetch coupon value of that particular id.

//This function is used for fetching one random record.
function Select_One_Random_Record($table_name) {
global $conn;
$sql = "SELECT * FROM $table_name ORDER BY RAND() LIMIT 1";
try {
$stmt = $conn->query($sql);
return $stmt;
} catch (PDOException $e) {
print $e->getMessage();
}
}

After this using, Ajax function will validate the coupon id and its value to prevent false implementation.

function check_promo_code() {
$.ajax({
url: "check_promocode.php",
type: "POST",
data: {code: $("input#promocode").val(), id:<?php echo $result['id']; ?>},
success: function(data) {
if (data == 'FALSE') {
$("span#wrong_code").html('Please enter a valid Voucher Code');
$("span#right_code").html('');
$("div#without_promo").show();
$("div#promo_offer").hide();
}
else {
$("span#right_code").html('PromoCode applied Successfully');
$("span#wrong_code").html('');
$("div#without_promo").hide();
$("div#promo_offer").show();
$("input#p_id").val('1');
$("input#promo_id").val(<?php echo $result['id']; ?>);}
}
}
});
}

Then both the product id and coupon id is sent to process.php page to validate if the coupon selected is right or not. It may happen that someone tries to change it using some coding tricks, but that too is not possible as we are validating it twice. Then further, the PayPal payment process takes place.


 

Tutorial Scripts in detail:

Below are the details of the code used in this tutorial with proper explanation.

MY-SQL Code

CREATE DATABASE `coupon`;
USE `coupon`;
CREATE TABLE IF NOT EXISTS `coupon_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`coupon_code` varchar(255) NOT NULL,
`coupon_value` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `product_detail` (
`p_id` int(10) NOT NULL AUTO_INCREMENT,
`p_name` varchar(255) NOT NULL,
`p_description` text NOT NULL,
`p_price` varchar(255) NOT NULL,
`product_currency` varchar(255) NOT NULL,
`p_img` varchar(255) NOT NULL,
PRIMARY KEY (`p_id`)
)

Note : When you will create database tables then you have to store the coupon and product information.

 

Connection.php

This is the file used for database connectivity. It is used for making connection variable by PDO (PHP Data Objects).

<?php
function connection_open() {
// Database credential
$servername = "localhost";
$username = "root";
$password = "";
//Database name
$dbname = "coupon";
try {
global $conn;
// Open the connection using PDO.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// echo $sql . "<br>" . $e->getMessage();
die();
}
}
function connection_close() {
global $conn;
$conn = null;
}
?>

 

Function.php

This file contains all required function for database operation.


<?php
//This function is used for fetching all the records from the table
function Select_All_Records($table_name) {
global $conn;
$sql = "select * from $table_name";
try {
$stmt = $conn->query($sql);
return $stmt;
} catch (PDOException $e) {
print $e->getMessage();
}
}

//This function is used for fetching record with one Filter.
function Select_Record_By_One_Filter($data, $table_name) {
global $conn;
$key = array_keys($data);
$value = array_values($data);
$sql = "select * from $table_name where $key[0] = '$value[0]'";
try {
$stmt = $conn->query($sql);
return $stmt;
} catch (PDOException $e) {
print $e->getMessage();
}
}

//This function is used for fetching record with two Filter.
function Select_Record_By_Two_Filter($data, $table_name) {
global $conn;
$key = array_keys($data);
$value = array_values($data);
$sql = "select * from $table_name where $key[0] = '$value[0]' AND $key[1] = '$value[1]'";
try {
$stmt = $conn->query($sql);
return $stmt;
} catch (PDOException $e) {
print $e->getMessage();
}
}

//This function is used for fetching one random record.
function Select_One_Random_Record($table_name) {
global $conn;
$sql = "SELECT * FROM $table_name ORDER BY RAND() LIMIT 1";
try {
$stmt = $conn->query($sql);
return $stmt;
} catch (PDOException $e) {
print $e->getMessage();
}
}
?>

 

Index.php

This is the main file in which the products details are being displayed with Promotional/Voucher Code button.



<?php
include('include/function.php');
include('include/connection.php');
connection_open();
$data = array(
'p_id' => 1
);
$p_query = Select_Record_By_One_Filter($data, 'product_detail');
$p_query->setFetchMode(PDO::FETCH_ASSOC);
$p_result = $p_query->fetch();
$p_price = $p_result['p_price'];
?>
<html>
<head>
<title>Paypal Coupon Codes</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jquery.min.js"></script>
</head>
<body>
<div id="main">
<h1 style="text-align: center;margin-left: 0px;">Paypal Coupon Codes in PHP</h1>
<?php
$query = Select_One_Random_Record('coupon_detail');
$query->setFetchMode(PDO::FETCH_ASSOC);
$result = $query->fetch()
?>
<div id="message-placeholder"><p class="msg" style="text-align:center;">Use Promotional/Voucher Code <b><?php echo $result['coupon_code']; ?></b> and get <b><?php echo $result['coupon_value']; ?>% </b>Discount. T&amp;C's Apply.</p></div>
<div id="login">
<h2><?php echo $p_result['p_name']; ?></h2>
<hr/>
<div class="clear"></div>
<div id="product_img">
<img src="<?php echo $p_result['p_img']; ?>"/>
</div>
<div class="content_wrapper">
<div class="content">
<p id="description"><?php echo $p_result['p_description']; ?></p>
</div>

<div class="content" style="height:70px;">
<div id="get_promo_code">
<form action="" method="post" style="margin-bottom: 0px;">
<input type="text" id="promocode" placeholder="Enter Promotional/Voucher Code">
<input type='button' value="Apply" name="submit" onclick='check_promo_code()'>
</form>
<span id="wrong_code"></span>
<span id="right_code"></span>
</div>
</div>
<div class="content" style="height: 70px;">
<div id="amount">
<div id="without_promo" >
<p>
<b>Total Amount : $<?php echo $p_price; ?></b>
</p>
</div>
<div id="promo_offer">

<?php
$amount_after_offer = $p_price - ($p_price * $result['coupon_value'] / 100)
?>
<p><b>Total Amount : $<?php echo $amount_after_offer; ?></b></p>
<del><p>Total Amount : $<?php echo $p_price; ?></p></del>
</div>
</div>
<div id="buynow">
<form action="process.php" method="POST">
<input type="hidden" value="" id="promo_id" name="promo_id">
<input type="hidden" value="1" id="p_id" name="p_id">
<div><input type="submit" class="fr" value="Buy Now" name="submit"></div>
</form>
</div>
</div>
</div>
</div><img id="paypal_logo" src="secure-paypal-logo.jpg">
</div>
</body>
<script language="javascript" type="text/javascript">
function check_promo_code() {
$.ajax({
url: "check_promocode.php",
type: "POST",
data: {code: $("input#promocode").val(), id:<?php echo $result['id']; ?>},
success: function(data) {
if (data == 'FALSE') {
$("span#wrong_code").html('Please enter a valid Voucher Code');
$("span#right_code").html('');
$("div#without_promo").show();
$("div#promo_offer").hide();
}
else {
$("span#right_code").html('PromoCode applied Successfully');
$("span#wrong_code").html('');
$("div#without_promo").hide();
$("div#promo_offer").show();
$("input#p_id").val('1');
$("input#promo_id").val(<?php echo $result['id']; ?>);

}
}
});
}
</script>
</html>
<?php connection_close(); ?>

 

Process.php

This file contains code to process payment to PayPal. For the PayPal process, you have to paste merchant_email in line no. 38.

<?php

include('include/function.php');
include('include/connection.php');
if (isset($_POST['submit'])) {
connection_open();
if (isset($_POST['p_id'])) {
if (isset($_POST['promo_id'])) {
$data = array(
'p_id' => $_POST['p_id']
);
$p_query = Select_Record_By_One_Filter($data, 'product_detail');
$p_query->setFetchMode(PDO::FETCH_ASSOC);
$p_result = $p_query->fetch();
$p_price = $p_result['p_price'];

$data = array(
'id' => $_POST['promo_id']
);
$promo_query = Select_Record_By_One_Filter($data, 'coupon_detail');
$promo_query->setFetchMode(PDO::FETCH_ASSOC);
$promo_result = $promo_query->fetch();
$product_price = $p_price - ($p_price * $promo_result['coupon_value'] / 100);
} else {
$data = array(
'p_id' => $_POST['p_id']
);
$p_query = Select_Record_By_One_Filter($data, 'product_detail');
$p_query->setFetchMode(PDO::FETCH_ASSOC);
$p_result = $p_query->fetch();
$product_price = $p_result['p_price'];
}
$product_name = $p_result['p_name'];
$product_currency = $p_result['product_currency'];
$product_id = $_POST['p_id'] . '#' . $_POST['promo_id'];
//Here we have to use PayPal URL or sanbox URL.
$paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
//Here we have to use seller email id.
$merchant_email = '[email protected]';
//here we have to put cancel URL when payment is not completed.
$cancel_return = "http://localhost/paypal-coupon-codes/index.php";
//here we have to put cancel URL when payment is Successful.
$success_return = "http://localhost/paypal-coupon-codes/success.php";

echo connection_close();
?>
<div style="margin-left: 38%"><img src="ajax-loader.gif"/><img src="processing_animation.gif"/></div>
<form name="myform" action="<?php echo $paypal_url; ?>" method="post" target="_top">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="cancel_return" value="<?php echo $cancel_return ?>">
<input type="hidden" name="return" value="<?php echo $success_return; ?>">
<input type="hidden" name="business" value="<?php echo $merchant_email; ?>">
<input type="hidden" name="lc" value="C2">
<input type="hidden" name="item_name" value="<?php echo $product_name; ?>">
<input type="hidden" name="item_number" value="<?php echo $product_id; ?>">
<input type="hidden" name="amount" value="<?php echo $product_price; ?>">
<input type="hidden" name="currency_code" value="<?php echo $product_currency; ?>">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="0">
</form>
<script type="text/javascript">
document.myform.submit();
</script><?php
}
}
?>

 

Success.php

PayPal calls this file when payment gets successfully completed and provide $_REQUEST array which contains product id, PayPal transaction ID, PayPal received amount value, PayPal received currency type and PayPal product status which is displayed in this page.

<?php
include('include/function.php');
include('include/connection.php');
echo connection_open();
?>
<html>
<head>
<title>Paypal Coupon Codes</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
if (!empty($_REQUEST)) {
$product_no = $_REQUEST['item_number']; // Product ID
$product_transaction = $_REQUEST['tx']; // Paypal transaction ID
$product_price = $_REQUEST['amt']; // Paypal received amount value
$product_currency = $_REQUEST['cc']; // Paypal received currency type
$product_status = $_REQUEST['st']; // Paypal product status
$description = explode('#', $product_no);
if ($description[0] != '') {
if ($description[1] != '') {
$data = array(
'p_id' => $description[0]
);
$p_query = Select_Record_By_One_Filter($data, 'product_detail');
$p_query->setFetchMode(PDO::FETCH_ASSOC);
$p_result = $p_query->fetch();
$p_price = $p_result['p_price'];

$data = array(
'id' => $description[1]
);
$promo_query = Select_Record_By_One_Filter($data, 'coupon_detail');
$promo_query->setFetchMode(PDO::FETCH_ASSOC);
$promo_result = $promo_query->fetch();
$product_actual_price = $p_price - ($p_price * $promo_result['coupon_value'] / 100);
} else {
$data = array(
'p_id' => $description[0]
);
$p_query = Select_Record_By_One_Filter($data, 'product_detail');
$p_query->setFetchMode(PDO::FETCH_ASSOC);
$p_result = $p_query->fetch();
$product_actual_price = $p_result['p_price'];
}
}
echo connection_close();
}
?>
<div id="main">
<h1>Paypal Coupon Codes in PHP</h1>

<div id="return">
<h2>Payment Status </h2>
<hr/>

<?php
//Rechecking the product price and currency details
if ($product_price ==$product_actual_price && $product_currency == $p_result['product_currency']) {
echo "<h3 id='success'>Payment Successful</h3>";
echo "<P>Transaction Status - " . $product_status . "</P>";
echo "<P>Transaction Id - " . $product_transaction . "</P>";
echo "<div class='back_btn'><a href='index.php' id= 'btn'><< Back to Products</a></div>";
} else {
echo "<h3 id='fail'>Payment Failed</h3>";
echo "<P>Transaction Status - Unompleted</P>";
echo "<P>Transaction Id - " . $product_transaction . "</P>";
echo "<div class='back_btn'><a href='index.php' id= 'btn'><< Back to Products</a></div>";
}
?>
</div>

<!-- Right side div -->
<div class="fr"id="formget">
<a href=https://www.formget.com/app><img src="formget.jpg" alt="Online Form Builder"/></a>
</div>
</div>
</body>
</html>

 

Style.css

Includes basic styling of HTML elements.

@import url(http://fonts.googleapis.com/css?family=Raleway);
h1 {
margin-left: 14%;
}

#main{
width:960px;
margin:50px auto;
font-family:raleway;
}

#login {
width: 815px;
float: left;
border-radius: 10px;
font-family: raleway;
border: 1px solid #ccc;
padding: 10px 40px 25px;
margin: 17px 35px;
}
h2 {
background-color: #fcf8e3;;
text-align: center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 15px;
color:#8A6D3A;
font-size: 20px;
}
hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
margin-bottom: 30px;
}
#product_img{
width: 50%;
float: left;
border: 1px dashed rgba(0, 0, 0, 0.15);
}
#product_img img{
padding: 10px;
width: 95%;
height: 340px;
}
.content_wrapper{
float: right;
width: 48%;
}
.content{
border: 1px dashed rgba(0, 0, 0, 0.15);
margin-bottom: 20px;
padding: 11px;
}
.content p#description{
text-align:justify;
padding:10px;
}
#get_promo_code input[type=button] {
width: 24%;
background-color: white;
float: right;
color: #FFBC00;
border: 2px solid #FFCB00;
padding: 10px;
font-size: 20px;
cursor: pointer;
border-radius: 5px;
}
input[type=text],input[type=password]{
width: 73%;
padding: 13px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 15px;
font-family:raleway;
border-radius: 5px;
}
#amount{
width: 50%;
float: left;
}

#promo_offer{
display: none;
}
#promo_offer del p{
color: rgba(128, 128, 128, .8);
}
#buynow{
width: 50%;
float: right;
}
input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}
span#wrong_code{
color:red;
}
span#right_code{
color:green;
}
#return {
width: 492px;
height: 350px;
float: left;
border-radius: 10px;
font-family: raleway;
border: 2px solid #ccc;
padding: 10px 40px 11px;
margin: 16PX;
}
#message-placeholder {
margin: 10px auto auto;
background: #fcf8e3!important;
border: 1px solid #faebcc;
width: 875px;
color: #8a6d3b;
padding: 10px;
position: relative;
z-index: 1;
}
#message-placeholder b {
color: rgb(14, 207, 14);
}
#return h3#success {
text-align: center;
font-size: 24px;
margin-top: 50px;
color: green;
}
#return P {
margin-left: 122px;
}
#return .back_btn {
margin-top: 51px;
margin-left: 19%;
}
#btn {
width: 100%;
background-color: #FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px 70px;
font-size: 20px;
cursor: pointer;
border-radius: 5px;
margin-bottom: 15px;
margin: 0 auto;
}
a{
text-decoration:none;
color: cornflowerblue;
}

i{
color: cornflowerblue;
}
#product_content {
float: right;
width: 400px;
height: 250px;
margin-top: 20px;
margin-bottom: 23px;
font-size: 14px;
border: 1px solid rgba(128, 128, 128, 0.17);
}
#get_promo_code input[type=button]:hover{
background-color:#FFBC00;
color: white;
}
.clear{
clear: both;
}
.fr {
float: right;
}
img#paypal_logo{
float: right;
margin-right:25px;
padding-bottom:15px;
}

Pabbly Subscription Billing


Conclusion :

After reading the above post, I am sure you will give a try to the script provided and implement it in your own projects as well. Feel free to visit our website again in the future to get in touch with new coding tricks. You can let us know about your feedback in the space provided below :)

Recommended blogs –