Site Admin
Site Admin Founder of MeaningArticles
1301 Views

PHP PayPal Payment Gateway Integration

Hello Dev.

In this article, see the way to integrate a PayPal payment gateway in PHP.

An e-commerce web site isn't complete without a payment gateway. there are many payment gateways you can actually choose from, however the maximum famous online payment gateway is PayPal. it is an American that has been around for many years now. to start with, it became called Confinity, but since 2001 it's miles known as PayPal.

PHP is one of the most common systems for e-commerce websites. php is a secure, speedy, and relied language in relation to the banking and financial enterprise. today numerous e-commerce websites run on PHP.

in this step-by-step guide, permit's discover ways to integrate a PayPal payment gateway into php.

Below are the functions that we are able to perform inside the demonstration process of integrating PayPal into php.

1. The PayPal buy button pulls products from the database and the webpage.

2. When the buyer clicks the PayPal button, the buyer redirects to the PayPal page, where the payment is processed.

3. The buyer is redirected back to the webpage after the payment at PayPal; the payment details will be available on the webpage.

PayPal has a sandbox environment to test functionalities earlier than developer makes them live. This way the software developer can iron out any issues earlier than a enterprise starts accepting bills from any customer. A developer can without difficulty get entry 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.

1. The first thing you need it to have a PayPal account. If you don’t, you can sign up for one over HERE. If you already have a PayPal account, head to the PayPal developer PAGE and sign in.

2. Now click on the Dashboard; it is visible on the top navigation.

3. Now click accounts under the sandbox label.

4. You would see that there is a buyer account created by default; this is created using your email-buyer.

5. 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:

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:

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

The consent variables of the Paypal gateway are defined in the config.php file.

config.php

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

PHP and MySQL are used to connect the database.

dbConnect.php 

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

1. All the products are pulled from the database and listed on the webpage

2. A PayPal buy now button is placed at the side of each product

3. To access the payment gateway, you need to submit an HTML form with predefined PayPal variables.

index.php

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

Once the payment is successful, the following steps take place

1. After the payment is successful at PayPal, the buyer is the redirected to this page

2. Using the PHP$_Get method, the transaction data is retrieved from the URL

3. The payment information is saved in the database, based on the transaction id

4. The payment details are made available on the webpage

success.php

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

If a buyer cancels the payment at the PayPal page, he/she will be redirected to this page.

cancel.php

<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

1. Log into your PayPal account (Business)

2. On my account TAB click on profile

3. Now under the hosted payment services click website payments preferences

4. Select the radio button “Auto Return,” and enter redirect URL in the URL field

5. Also, select the radio button “Payment data transfer.”

6. 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.

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

Now log into your Paypal account and follow the below steps:

1. Click on the gear icon to reach settings

2. Go to selling tools and click on instant payment notifications

3. On this page click on choose IPN settings

4. Enter the notification URL and enable receive IPN messages

5. 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.

ipn.php

<?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.

config.php

define('PAYPAL_ID', 'Insert_PayPal_Business_Email');
 define('PAYPAL_SANDBOX', FALSE);

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.