How To Paypal Integration Php

How To Paypal Integration Php

How To Paypal Integration Php

0 Sales


PayPal is an American international e-commerce business that makes it possible to make payments and money transfers via the Internet. PayPal is the world's most popular portal to sending and receiving payment. PayPal is a commonly used portal for the web application to accept payment. PayPal payment gateway is the web developer's easiest way to implement a website payment system.


PayPal Standard Payment Gateway is the fastest way to accept online payment. The customer must make the website fee to purchase an item online. In this tutorial, we'll show you how to integrate PayPal's standard payment gateway into PHP and store transaction data in the database using PayPal IPN. Our step-by-step PayPal payment gateway integration guide in PHP helps you integrate the online payment feature easily into your web project.


The following functionality will be implemented in the example script to demonstrate the integration process of the PayPal Payment Gateway.


  1. Collect the products from the database and use the PayPal Buy button on the web page.

  2. To complete the payment, the Buy button redirects the buyer to the PayPal site.

  3. The buyer will return to the website after the payment and the payment details will be displayed.

  4. The transaction data is stored by the PayPal IPN in the database.


Before getting started to integrate PayPal payment gateway API in PHP, take a look at the files structure.


├── config.php

├── dbConnect.php

├── index.php

├── success.php

├── cancel.php

├── ipn.php

├── css/

│   └── style.css

└── images/


PayPal has two sandbox and real time environments. PayPal Sandbox allows developers to perform their testing before the project goes live. After the project is live on the production server, the real-time environment is used. Once the payment process for PayPal works properly on the Sandbox environment, you can set the Real-Time environment payment gateway for PayPal.


Create PayPal Sandbox Account

The payment gateway must be tested before accepting payment from buyers via PayPal. You need to set up a PayPal sandbox account to test the transaction process.


  • Go to the Developer page of PayPal and log in to your PayPal account. Register for a PayPal account first if you don't have a PayPal account.

  • You'd be redirected to the developer homepage after logging in. Now click the link at the top of the navigation menu on the Dashboard.

  • Click the Accounts link from the left menu panel under the Sandbox label.

  • Use the Create Account link to create a buyer account and a merchant account. You need to select Personal radio button under the Account type section for your buyer account or select Business radio button for a merchant account.


Create Database Tables


Two tables need to be created in the database to store product and payment information.


The following SQL creates a table of products for the storage of product data in the MySQL database.


CREATE TABLE `products` (


 `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',


) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates a payments table in the MySQL database to store the transaction data provided by PayPal.

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;


PayPal Settings and Database Configuration (config.php)

Constant PayPal variables and database settings are defined in the config.php file.

PayPal Constants:

  • PAYPAL ID–Specify the PayPal Business account email address.

  • PAYPAL SANDBOX–Specify if you are using the TRUE / FALSE environment.

  • PAYPAL RETURN URL–Specify the URL after payment where the purchaser will be redirected.

  • PAYPAL CANCEL URL–Specify the URL after the cancelation of the payment where the buyer will be redirected.

  • PAYPAL NOTIFY URL–Specify the URL where PayPal IPN will send the transaction data for verification.

  • PAYPAL CURRENCY–The currency code is specified.


Database Constants:

  • DB HOST – Enter the host of the database.

  • DB USERNAME – Enter the username of the database.

  • DB PASSWORD – Specify the password for the database.

  • DB NAME – Enter the name of the database.




 * PayPal and database configuration



// PayPal configuration

define('PAYPAL_ID', 'Insert_PayPal_Business_Email');


define('PAYPAL_RETURN_URL', '');

define('PAYPAL_CANCEL_URL', '');

define('PAYPAL_NOTIFY_URL', '');


// 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)?"":"");


Database Connection (dbConnect.php)

The dbConnect.php file is used to use PHP and MySQL to connect the database.



// Connect with the database


// Display error if failed to connect

if ($db->connect_errno) {

    printf("Connect failed: %s\n", $db->connect_error);



Products (index.php)

All products are initially retrieved from the database and listed on the web page.


  • Each product is fitted with a PayPal Buy Now button.

  • You need to submit a form with some predefined PayPal HTML field variable to use PayPal standard payment gateway.

  • To learn about the hidden fields of the form, follow the comment tags (<! ––>).



// Include configuration file

include_once 'config.php';

// Include database connection file

include_once 'dbConnect.php';


<div class="container">


        // 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="">




    <?php } ?>


Payment Success (success.php)

The buyer will be guided to this site after an effective transaction on PayPal. 


  • Using the PHP $ GET method, the transaction data is retrieved from the URL.

  • Insert/update the transaction ID-based payment information in the database.

  • Transaction information are shown on the web page.



// 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'];


        // 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."')");

        $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 } ?>


    <a href="index.php" class="btn-link">Back to Products</a>



Payment Cancellation (cancel.php)

The buyer will be guided to this site if the buyer wants to cancel the transaction on the PayPal payment section.


<div class="container">

    <div class="status">

        <h1 class="error">Your PayPal Transaction has been Canceled</h1>


    <a href="index.php" class="btn-link">Back to Products</a>


Configure PayPal Auto Return and Payment Data Transfer

Make sure you have configured your PayPal business account with Auto Return for Website Payments. Otherwise, in the success.php file, you will not receive transaction information from PayPal. For Auto Return, Payment Data Transfer and Return URL on your PayPal account, see the following guide.


Setup PayPal Instant Payment Notification (IPN)

Validate the transaction with PayPal Instant Payment Notification (IPN) to secure the PayPal Standard Payment. Follow the steps below to set up IPN in the integration of the standard PayPal payment gateway.


Enable IPN:


IPN must be enabled in the PayPal account to use this feature. A step-by-step guide to activate IPN in PayPal has already been written, please see the tutorial below.


Add Notify URL in PayPal Form:


Together with the other PayPal HTML variables, add the following input field (notify url) HTML.


<input type="hidden" name="notify_url" value="<?php echo PAYPAL_NOTIFY_URL; ?>">

Validate Transaction:


PayPal sends the transaction data to the Notify URL (http:/ until IPN is allowed. To verify the transaction, put the following code in the ipn.php file and insert payment information into the server.



// 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_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){



        // 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."')");





Make PayPal Payment Gateway Live

You will make the PayPal payment gateway live once the software transaction flow check is completed.


  • Specify the PayPal account email in PAYPAL ID in the config.php file.



define('PAYPAL_ID', 'Insert_PayPal_Business_Email');



You can use it for personal or commercial projects. You can't resell it partially or in this form.


Create Date : May 14, 2020

Updated Date : Apr 16, 2021


Comments : 0

Downloads : 0