PayPal payment gateway integration in PHP

PayPal is an American international e-commerce business allowing payments and money transfers to be made through the Internet. PayPal is very popular payment gateway for every web project. This tutorial will explain about PayPal payment gateway integration in PHP. With this tutorial you can easily integrate the payment option in your web project. At first we will receive payment from the buyers and then store the transaction information at the database.

PayPal has two environments such as Sandbox and Real Time. Sandbox environment help developers to do their test transaction before the project go live. Real Time environment is used after project live.

PayPal payment gateway integration
PayPal payment gateway integration

Step 1 ( Creating a new Sandbox test account )

At first we need to create a new Sandbox test account. Following steps would be help to create Sandbox account.

  • Step 1 – Go to the https://developer.paypal.com/. Log in with your PayPal account. If you don’t have any PayPal account, first sign up at PayPal. Once the sign up is completed, login with this account.
  • Step 2 – After logged in you would be redirected to the developer home page. Now click on the “Dashboard” link from the top navigation menu.
  • Step 3 – Click on the “Accounts” link under the “Sandbox” label from the left menu section.
  • Step 4 – Create buyer account and merchant account from the “Create Account” link. For buyer account you need to select “Personal” radio button under the “Account type” section or select Business radio button for merchant account.

Step 2 ( Database Tables Creation )

We have created two tables named products and payments. products data is stored into the products table and payments table is used for storing the transaction information provided by 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` (
 `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;

Step 3 ( db_config.php File )

<?php
//Database credentials
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'db_tutsocean';
//Connect with the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db->connect_errno) {
    printf("Connect failed: %sn", $db->connect_error);
    exit();
}
?>

Step 4 ( products.php File )

<?php

include 'db_config.php';

//Set useful variables for paypal form
$paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; //Test PayPal API URL
$paypal_id = 'info@tutsocean.com'; //Business Email

//fetch products from the database
$results = $db->query("SELECT * FROM products");

while($row = $results->fetch_assoc())
{
?>

    <img src="images/<?php echo $row['image']; ?>"/>
    Name: <?php echo $row['name']; ?>
    Price: <?php echo $row['price']; ?>
    <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="USD">
        
        <!-- Specify URLs -->
        <input type='hidden' name='cancel_return' value='http://example.com/cancel.php'>
        <input type='hidden' name='return' value='http://example.com/success.php'>
        
        <!-- Display the payment button. -->
        <input type="image" name="submit" border="0"
        src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online">
        <img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >
    
    </form>

<?php } ?>

Step 5 ( success.php File )

Once the PayPal payment is successful, buyer would be redirected to this page. We have received the transaction information with $_GET variable and insert transaction data into the database. If the payment is successful, then buyer would be see the success message otherwise failed message.

<?php
include 'db_config.php';

//Store transaction information from PayPal
$item_number = $_GET['item_number']; 
$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];

//Get product price
$productResult = $db->query("SELECT price FROM products WHERE id = ".$item_number);
$productRow = $productResult->fetch_assoc();
$productPrice = $productRow['price'];

if(!empty($txn_id) && $payment_gross == $productPrice){

    //Check if payment data exists with the same TXN ID.
    $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");

    if($prevPaymentResult->num_rows > 0){
        $paymentRow = $prevPaymentResult->fetch_assoc();
        $last_insert_id = $paymentRow['payment_id'];
    }else{
        //Insert tansaction 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."')");
        $last_insert_id = $db->insert_id;
    }
?>

<h1>Your payment has been successful.</h1>
<h1>Your Payment ID - <?php echo $last_insert_id; ?>.</h1>

<?php
}else{
?>

<h1>Your payment has failed.</h1>

<?php
}
?>

Step 6 ( cancel.php File )

If the buyers wish to cancel payment at the PayPal payment page, then buyer would be redirected to this page.

<h1>Your PayPal transaction has been canceled.</h1>

That is all you need to setup the paypal standard into your php website.