Paypal is the most popular payment gateway to send and receive money using web applications and mobile. PayPal provides functionality to receive and send funds using the internet.

This PHP payment gateway tutorial help to add a PayPal gateway with a web application using PHP. Paypal has two environments, one is a sandbox account for developer testing and the other is prod, for a live environment. This PayPal payment gateway tutorial will use a PayPal sandbox account to test product transactions.

How to Create a New PayPal Sandbox Account

  • Log in with your PayPal account. If you do not have created your PayPal account yet, first sign up at PayPal and create a PayPal account.
  • Now logged in with a PayPal account using credentials(which were given at the time of signup), Now you can see the developer home page and click the Dashboard.
  • Then click on the Accounts link under the Sandbox.
  • Now create test accounts for seller and buyer by selecting Business and Personal from the create an account link.
paypal-php-mysql

You can check other recommended tutorials of Payment Gateway,

There are following files will participate in this tutorial:

  • product_listing.php : This file will use to display the product listing.
  • connection.php : This file will use to establish a connection with PHP and MySQL.
  • success.php : This file will use to display success payment information.
  • cancel.php : This file will use to show cancel payment information.

You will have two configuration parameters that are required for Paypal gateway integration.The $paypalURL and $paypalID value with live PayPal URL and business email.

$paypalURL = 'https://www.paypal.com/cgi-bin/webscr';
$paypalID = 'PayPalBusinessEmailID';

MySQL Database Tables Creation

We will create two tables products and payments_info into the MySQL ‘test’ database. The products table will be used to store product details information and payments_info table will be used for storing the transaction details from PayPal.

CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`price` float(10,2) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `payments_info` (
`payment_id` int(11) NOT NULL AUTO_INCREMENT,
`item_number` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`payment_gross` float(10,2) NOT NULL,
`currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
`payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`payment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Create MySQL database connection

We will create connection.php file. This file is used to connect and select database using PHP and MySQL.We will add $dbhost , $username , $password , and $dbname variable’s value with your database credentials.

dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$this->conn = $con;
}
return $this->conn;
}
}
?>

We have created a connection with the MySQL database, so now we will fetch product information from the product table and display it on a page. We will add some information with each product listing record. The product details will have the product name, product number, amount, and currency using HTML input hidden fields.

We will add a PayPal buy now button with each listed record and the user will click on that to purchase a product. The hidden parameters will send to the PayPal account.
We will add the product_listing.php file and add the below code to display the product listing.

getConnstring();
$sql = "SELECT * FROM products";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $row = mysqli_fetch_assoc($resultset) ) {
?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail"><img src="images/<?php echo $row['image']; ?>">
<div class="caption">
<h4 class="pull-right">Price: <?php echo $row['price']; ?></h4>
<h4>Name: <?php echo $row['name']; ?></h4>
</div>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<!-- Paypal business test account email id so that you can collect the payments. --> 
<input name="business" type="hidden" value="<?php echo $paypal_email; ?>"> 
<!-- Buy Now button. --> 
<input name="cmd" type="hidden" value="_xclick"> 
<!-- Details about the item that buyers will purchase. --> 
<input name="item_name" type="hidden" value="<?php echo $row['name']; ?>"> 
<input name="item_number" type="hidden" value="<?php echo $row['id']; ?>">
<input name="amount" type="hidden" value="<?php echo $row['price']; ?>"> 
<input name="currency_code" type="hidden" value="USD"> 
<!-- URLs --> 
<input name="cancel_return" type="hidden" value="http://localhost/paypal_integration_php/cancel.php"> 
<input name="return" type="hidden" value="http://localhost/paypal_integration_php/success.php"> <!-- payment button. --> 
<input alt="PayPal - The safer, easier way to pay online" name="submit" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" type="image"> <img src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" alt="" width="1" height="1" border="0"></form></div>
</div>

When the PayPal payment is successful, a buyer would be redirected to provide a success page or on failed message on transaction failed. We will receive the transaction information with $_GET variable and insert transaction data into the payments information database table. We will add the below code to success.php file.

getConnstring();
$item_number = $_GET['item_number'];
$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];
//Get product price to store into database
$sql = "SELECT * FROM products WHERE id = ".$item_number;
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!empty($txn_id) && $payment_gross == $row['price']){
//Insert tansaction data into the database
mysqli_query($conn, "INSERT INTO payments_info(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
$last_insert_id = mysqli_insert_id($conn);
?>
<h1>Your payment has been successful.</h1>
<h1>Your Payment ID -  echo $last_insert_id; ?>.</h1>
}else{
?>
<h1>Your payment has failed.</h1>
}
?>

Please make sure you have enabled Auto Return for Website Payments on your PayPal business account to get transaction information from PayPal in success.php file.

Cancel Paypal Payment

The user will get the below message when he canceled the transaction. We will redirect the user to the can page and show a message. We will add the below ode into cancel.php file.

Your PayPal transaction has been cancelled.

Genislab Technologies

NexGeneration complete end-2-end software testing & modern development operations tooling & solutions

Do you want to discuss your testing requirements with us? please don’t hesitate to hit the contact us button below, and we will get back to you at our earliest..