How to Integrate a PayPal Payment Gateway in PHP
In this article, see how to integrate a PayPal payment gateway in PHP.
Join the DZone community and get the full member experience.
Join For FreeAn e-commerce site is not complete without a payment gateway. There are many payment gateways one can choose from, but the most famous online payment gateway is PayPal. It is an American that has been around for two decades now. Initially, it was known as Confinity, but since 2001 it is known as PayPal.
PHP is one of the most common platforms for e-commerce sites. PHP is a secure, fast, and trusted language when it comes to the banking and financial industry. Today various e-commerce websites run on PHP.
In this step-by-step guide, let's learn how to integrate a PayPal payment gateway into PHP.
Below are the functions that we will perform in the demonstration process of integrating PayPal into PHP.
- The PayPal buy button pulls products from the database and the webpage.
- When the buyer clicks the PayPal button, the buyer redirects to the PayPal page, where the payment is processed.
- The buyer is redirected back to the webpage after the payment at PayPal; the payment details will be available on the webpage.
You might also like: A Multi-Gateway Payment Processing Library for Java
Before we go ahead and integrate the PayPal payment gateway API, let us see the file structure once.
xxxxxxxxxx
paypal_integration_php/
├── config.php
├── dbConnect.php
├── index.php
├── success.php
├── cancel.php
├── ipn.php
├── css/
│ └── style.css
└── images/
PayPal has a sandbox environment to test functionalities before developer makes them live. This way the software developer can iron out any issues before a business starts accepting payments from any customer. A developer can easily get access to this sandbox by signing up for a PayPal sandbox account.
Step 1: Create Sandbox Accounts
The steps to open a PayPal sandbox account are listed below.
- The first thing you need it to have a PayPal account. If you don’t, you can sign up for one over here https://www.paypal.com/in/webapps/mpp/account-selection. If you already have a PayPal account, head to the PayPal developer page https://developer.paypal.com/ and sign in.
- Now click on the Dashboard; it is visible on the top navigation.
- Now click accounts under the sandbox label.
- You would see that there is a buyer account created by default; this is created using your email-buyer.
- You would need to create a merchant account by doing the following
- Click Create Account
- Set the Account Type to Business
- Select a Country
- Click Create Account
Step 2: Create Database Tables
You need two tables to store the product and payment information in the database. The below SQL quires create product and payment tables in the MySQL database.
For product:
xxxxxxxxxx
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) 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' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
For payment:
xxxxxxxxxx
CREATE TABLE `payments` (
`payment_id` int(11) NOT NULL AUTO_INCREMENT,
`item_number` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`txn_id` varchar(50) 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(20) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`payment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Step 3: PayPal Settings and Data Configuration (config.php)
The consent variables of the Paypal gateway are defined in the config.php file.
xxxxxxxxxx
<?php
/*
* PayPal and database configuration
*/
// PayPal configuration
define('PAYPAL_ID', 'Insert_PayPal_Business_Email');
define('PAYPAL_SANDBOX', TRUE); //TRUE or FALSE
define('PAYPAL_RETURN_URL', 'http://www.example.com/success.php');
define('PAYPAL_CANCEL_URL', 'http://www.example.com/cancel.php');
define('PAYPAL_NOTIFY_URL', 'http://www.example.com/ipn.php');
define('PAYPAL_CURRENCY', 'USD');
// Database configuration
define('DB_HOST', 'MySQL_Database_Host');
define('DB_USERNAME', 'MySQL_Database_Username');
define('DB_PASSWORD', 'MySQL_Database_Password');
define('DB_NAME', 'MySQL_Database_Name');
// Change not required
define('PAYPAL_URL', (PAYPAL_SANDBOX == true)?"https://www.sandbox.paypal.com/cgi-bin/webscr":"https://www.paypal.com/cgi-bin/webscr");
Step 4: Connecting the Database (dbConnect.php)
xxxxxxxxxx
PHP and MySQL are used to connect the database.
<?php
// Connect with the database
$db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Display error if failed to connect
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
Step 5: Products (index.php)
- All the products are pulled from the database and listed on the webpage
- A PayPal buy now button is placed at the side of each product
- To access the payment gateway, you need to submit an HTML form with predefined PayPal variables.
xxxxxxxxxx
<?php
// Include configuration file
include_once 'config.php';
// Include database connection file
include_once 'dbConnect.php';
?>
<div class="container">
<?php
// Fetch products from the database
$results = $db->query("SELECT * FROM products WHERE status = 1");
while($row = $results->fetch_assoc()){
?>
<div class="pro-box">
<img src="images/<?php echo $row['image']; ?>"/>
<div class="body">
<h5><?php echo $row['name']; ?></h5>
<h6>Price: <?php echo '$'.$row['price'].' '.PAYPAL_CURRENCY; ?></h6>
<!-- PayPal payment form for displaying the buy button -->
<form action="<?php echo PAYPAL_URL; ?>" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="<?php echo PAYPAL_ID; ?>">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="<?php echo $row['name']; ?>">
<input type="hidden" name="item_number" value="<?php echo $row['id']; ?>">
<input type="hidden" name="amount" value="<?php echo $row['price']; ?>">
<input type="hidden" name="currency_code" value="<?php echo PAYPAL_CURRENCY; ?>">
<!-- Specify URLs -->
<input type="hidden" name="return" value="<?php echo PAYPAL_RETURN_URL; ?>">
<input type="hidden" name="cancel_return" value="<?php echo PAYPAL_CANCEL_URL; ?>">
<!-- Display the payment button. -->
<input type="image" name="submit" border="0" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif">
</form>
</div>
</div>
<?php } ?>
</div>
Step 6: Successful Payment (success.php)
Once the payment is successful, the following steps take place
- After the payment is successful at PayPal, the buyer is the redirected to this page
- Using the PHP$_Get method, the transaction data is retrieved from the URL
- The payment information is saved in the database, based on the transaction id
- The payment details are made available on the webpage
xxxxxxxxxx
<?php
// Include configuration file
include_once 'config.php';
// Include database connection file
include_once 'dbConnect.php';
// If transaction data is available in the URL
if(!empty($_GET['item_number']) && !empty($_GET['tx']) && !empty($_GET['amt']) && !empty($_GET['cc']) && !empty($_GET['st'])){
// Get transaction information from URL
$item_number = $_GET['item_number'];
$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];
// Get product info from the database
$productResult = $db->query("SELECT * FROM products WHERE id = ".$item_number);
$productRow = $productResult->fetch_assoc();
// Check if transaction data exists with the same TXN ID.
$prevPaymentResult = $db->query("SELECT * FROM payments WHERE txn_id = '".$txn_id."'");
if($prevPaymentResult->num_rows > 0){
$paymentRow = $prevPaymentResult->fetch_assoc();
$payment_id = $paymentRow['payment_id'];
$payment_gross = $paymentRow['payment_gross'];
$payment_status = $paymentRow['payment_status'];
}else{
// Insert transaction data into the database
$insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
$payment_id = $db->insert_id;
}
}
?>
<div class="container">
<div class="status">
<?php if(!empty($payment_id)){ ?>
<h1 class="success">Your Payment has been Successful</h1>
<h4>Payment Information</h4>
<p><b>Reference Number:</b> <?php echo $payment_id; ?></p>
<p><b>Transaction ID:</b> <?php echo $txn_id; ?></p>
<p><b>Paid Amount:</b> <?php echo $payment_gross; ?></p>
<p><b>Payment Status:</b> <?php echo $payment_status; ?></p>
<h4>Product Information</h4>
<p><b>Name:</b> <?php echo $productRow['name']; ?></p>
<p><b>Price:</b> <?php echo $productRow['price']; ?></p>
<?php }else{ ?>
<h1 class="error">Your Payment has Failed</h1>
<?php } ?>
</div>
<a href="index.php" class="btn-link">Back to Products</a>
</div>
Step 7: Payment Cancelation (cancel.php)
If a buyer cancels the payment at the PayPal page, he/she will be redirected to this page.
xxxxxxxxxx
<div class="container">
<div class="status">
<h1 class="error">Your PayPal Transaction has been Canceled</h1>
</div>
<a href="index.php" class="btn-link">Back to Products</a>
</div>
Step 8: Setup PayPal Auto-Return and Payment Transfer
This is required to get the transaction details back from PayPal; if this is not done, you will get details you need.
Follow the steps
- Log into your PayPal account (Business)
- On my account TAB click on profile
- Now under the hosted payment services click website payments preferences
- Select the radio button “Auto Return,” and enter redirect URL in the URL field
- Also, select the radio button “Payment data transfer.”
- Click Save
Step 9: Setup IPN
This setup is required to make the payment secure. The first thing you need to do is add the below code to the HTML form with the PayPal variables.
xxxxxxxxxx
<input type="hidden" name="notify_url" value="<?php echo PAYPAL_NOTIFY_URL; ?>">
Now log into your Paypal account and follow the below steps:
- Click on the gear icon to reach settings
- Go to selling tools and click on instant payment notifications
- On this page click on choose IPN settings
- Enter the notification URL and enable receive IPN messages
- Click save
Step 10: Set up and Validate the Transaction
Now, as your IPN is enabled, PayPal will send you instant transaction notifications. Add the below code to ipn.php to validate the transaction and save the payment information into the database.
xxxxxxxxxx
<?php
// Include configuration file
include_once 'config.php';
// Include database connection file
include_once 'dbConnect.php';
/*
* Read POST data
* reading posted data directly from $_POST causes serialization
* issues with array data in POST.
* Reading raw POST data from input stream instead.
*/
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// Read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
/*
* Post IPN data back to PayPal to validate the IPN data is genuine
* Without this step, anyone can fake IPN data
*/
$paypalURL = PAYPAL_URL;
$ch = curl_init($paypalURL);
if ($ch == FALSE) {
return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close', 'User-Agent: company-name'));
$res = curl_exec($ch);
/*
* Inspect IPN validation result and act accordingly
* Split response headers and payload, a better way for strcmp
*/
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp($res, "VERIFIED") == 0 || strcasecmp($res, "VERIFIED") == 0) {
// Retrieve transaction info from PayPal
$item_number = $_POST['item_number'];
$txn_id = $_POST['txn_id'];
$payment_gross = $_POST['mc_gross'];
$currency_code = $_POST['mc_currency'];
$payment_status = $_POST['payment_status'];
// Check if transaction data exists with the same TXN ID
$prevPayment = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");
if($prevPayment->num_rows > 0){
exit();
}else{
// Insert transaction data into the database
$insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
}
}
?>
Step 11: Making the Gateway Live
Once you are done with the testing, it is time to make the payment gateway live. To do this, you need to make a change in the config.php file. You need to set up the business PayPal ID and disable the sandbox ID.
xxxxxxxxxx
define('PAYPAL_ID', 'Insert_PayPal_Business_Email');
define('PAYPAL_SANDBOX', FALSE);
That’s it! Your PayPal payment gate is live now.
Conclusion
By following these steps, you should be able to integrate the PayPal payment gateway with PHP successfully. If you face any issues, you can always visit PayPal and see if they have a solution there. Or you can hire a PHP developer who has experience integrating PayPal and PHP.
Please feel free to reach us in the comments.
Further Reading
The Mystery Behind Testing ‘’The Integration of Payment Gateways’'
Opinions expressed by DZone contributors are their own.
Comments