PayPal Payment Gateway Integration in PHP

Dec 29 2017
CreepesLab

PayPal is the most popular payment gateway to send and receive payment worldwide. PayPal is a widely used payment gateway to accept payment in the web application. PayPal payment gateway is the easiest option for the web developer to implement payment system on the website.

PayPal has two environments such as Sandbox and Real Time. PayPal Sandbox allows developers to do their test transaction before the project go live. Real Time environment is used after project live. Once PayPal payment process is working fine on Sandbox environment, you can set PayPal to Real-Time environment.

Creating a PayPal Sandbox Account

Before start accepting payment from buyers via PayPal, payment gateway needs to be tested. To test transaction process you need to create PayPal sandbox account.

  • Go to the PayPal Developer page and log in to your PayPal account. If you don’t have any PayPal account, sign up for a PayPal account first.
  • After logged in you would be redirected to the developer homepage. Now click on the Dashboard link from the top navigation menu.
  • Click on the Accounts link under the Sandbox label from the left menu panel.
  • 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 a merchant account.

Database Tables Creation

To store products details and payment transaction information two tables need to be created in MySQL database. The products data is stored into the products table and paypal-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 `paypal-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;

Database Configuration (connect.php)

This file is used to connect and select database using PHP and MySQL. Change $dbHost, $dbUsername, $dbPassword, and $dbName variable’s value with your database credentials.

<?php
//Database credentials
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword '';
$dbName 'creepeslab';

//Connect with the database
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

//Display error if failed to connect
if ($db->connect_errno) {
    printf("Connect failed: %s\n"$db->connect_error);
    exit();
}
?>

Products (products.php)

All the products will be fetched from the products table and listed with PayPal Buy Now button. To use PayPal standard payment gateway, you need to submit a form with some predefined PayPal HTML form field variable.

<?php
//Include DB configuration file
include 'connect.php';

//Set useful variables for paypal form
$paypalURL 'https://www.sandbox.paypal.com/cgi-bin/webscr'//Test PayPal API URL
$paypalID 'info@creepeslab.com'//Business Email

?>
<?php
    //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 $paypalURL?>" method="post">
        <!-- Identify your business so that you can collect the payments. -->
        <input type="hidden" name="business" value="<?php echo $paypalID?>">

        <!-- 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://localhost/paypal_integration_php/cancel.php'>
        <input type='hidden' name='return' value='http://localhost/paypal_integration_php/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 ?>

Note: Don’t forget to change the cancel_return and return input field value with your desired URL in PayPal HTML form.

Payment Success (success.php)

Once the PayPal payment is successful, the buyer is redirected to this page. The transaction information is received using $_GET method and inserts payment data into the database.

<?php
include 'connect.php';

//Get payment 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 from database
$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 ?>

Payment Cancel (cancel.php)

If the buyer wishes to cancel payment at the PayPal payment page, the buyer is redirected to this page.

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

Thank you for reading the article. Hope to share and comment if you like the article.

Share: