{{announcement.body}}
{{announcement.title}}

How to Integrate a PayPal Payment Gateway in PHP

DZone 's Guide to

How to Integrate a PayPal Payment Gateway in PHP

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

· Integration Zone ·
Free Resource

Magnifying glass on PayPal website

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

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

Java




xxxxxxxxxx
1
19


 
1
paypal_integration_php/ 
2
 
           
3
├── config.php 
4
 
           
5
├── dbConnect.php 
6
 
           
7
├── index.php 
8
 
           
9
├── success.php 
10
 
           
11
├── cancel.php 
12
 
           
13
├── ipn.php 
14
 
           
15
├── css/ 
16
 
           
17
 └── style.css 
18
 
           
19
└── 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.

  1. 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.
  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
    1. Click Create Account
    2. Set the Account Type to Business
    3. Select a Country
    4. 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:

Java




xxxxxxxxxx
1
15


 
1
CREATE TABLE `products` ( 
2
 
           
3
`id` int(11NOT NULL AUTO_INCREMENT,
4
 
           
5
`name` varchar(200COLLATE utf8_unicode_ci NOT NULL,
6
 
           
7
`image` varchar(255COLLATE utf8_unicode_ci NOT NULL,
8
 
           
9
`price` float(10,2NOT NULL,
10
 
           
11
`status` tinyint(1NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
12
 
           
13
PRIMARY KEY (`id`)
14
 
           
15
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


For payment:

Java




xxxxxxxxxx
1
17


 
1
CREATE TABLE `payments` (
2
 
           
3
`payment_id` int(11NOT NULL AUTO_INCREMENT,
4
 
           
5
`item_number` varchar(50COLLATE utf8_unicode_ci NOT NULL,
6
 
           
7
`txn_id` varchar(50COLLATE utf8_unicode_ci NOT NULL,
8
 
           
9
`payment_gross` float(10,2NOT NULL,
10
 
           
11
`currency_code` varchar(5COLLATE utf8_unicode_ci NOT NULL,
12
 
           
13
`payment_status` varchar(20COLLATE utf8_unicode_ci NOT NULL,
14
 
           
15
PRIMARY KEY (`payment_id`)
16
 
           
17
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.

Java




xxxxxxxxxx
1
22


 
1
<?php 
2
 /* 
3
* PayPal and database configuration 
4
*/ 
5
 
           
6
// PayPal configuration 
7
 define('PAYPAL_ID''Insert_PayPal_Business_Email'); 
8
 define('PAYPAL_SANDBOX'TRUE); //TRUE or FALSE 
9
 
           
10
 define('PAYPAL_RETURN_URL''http://www.example.com/success.php'); 
11
 define('PAYPAL_CANCEL_URL''http://www.example.com/cancel.php'); 
12
 define('PAYPAL_NOTIFY_URL''http://www.example.com/ipn.php'); 
13
 define('PAYPAL_CURRENCY''USD'); 
14
 
           
15
 // Database configuration 
16
 define('DB_HOST''MySQL_Database_Host'); 
17
 define('DB_USERNAME''MySQL_Database_Username'); 
18
 define('DB_PASSWORD''MySQL_Database_Password'); 
19
 define('DB_NAME''MySQL_Database_Name'); 
20
 
           
21
 // Change not required 
22
 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)

Java




xxxxxxxxxx
1
11


 
1
PHP and MySQL are used to connect the database
2
 
           
3
<?php 
4
 // Connect with the database 
5
 $db = new mysqli(DB_HOSTDB_USERNAMEDB_PASSWORDDB_NAME); 
6
 
           
7
 // Display error if failed to connect 
8
 if ($db->connect_errno) { 
9
     printf("Connect failed: %s\n"$db->connect_error); 
10
exit(); 
11
 }


Step 5: Products (index.php)

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




xxxxxxxxxx
1
70


 
1
<?php
2
 
           
3
// Include configuration file
4
 
           
5
include_once 'config.php'; 
6
 
           
7
 // Include database connection file 
8
 include_once 'dbConnect.php'; 
9
 ?>
10
 
           
11
<div class="container">
12
 
           
13
<?php 
14
 // Fetch products from the database 
15
 $results = $db->query("SELECT * FROM products WHERE status = 1"); 
16
 while($row = $results->fetch_assoc()){ 
17
 
           
18
?>
19
 
           
20
<div class="pro-box">
21
 
           
22
<img src="images/<?php echo $row['image']; ?>"/>
23
 
           
24
<div class="body">
25
 
           
26
<h5><?php echo $row['name']; ?></h5>
27
 
           
28
<h6>Price<?php echo '$'.$row['price'].' '.PAYPAL_CURRENCY?></h6>                                                                            
29
 
           
30
<!-- PayPal payment form for displaying the buy button -->
31
 
           
32
<form action="<?php echo PAYPAL_URL; ?>" method="post">
33
 
           
34
<!-- Identify your business so that you can collect the payments. -->
35
 
           
36
<input type="hidden" name="business" value="<?php echo PAYPAL_ID; ?>">                                                                                                
37
 
           
38
<!-- Specify a Buy Now button. -->
39
 
           
40
<input type="hidden" name="cmd" value="_xclick">                                                                                        
41
 
           
42
<!-- Specify details about the item that buyers will purchase. -->
43
 
           
44
<input type="hidden" name="item_name" value="<?php echo $row['name']; ?>">
45
 
           
46
<input type="hidden" name="item_number" value="<?php echo $row['id']; ?>">
47
 
           
48
<input type="hidden" name="amount" value="<?php echo $row['price']; ?>">
49
 
           
50
<input type="hidden" name="currency_code" value="<?php echo PAYPAL_CURRENCY; ?>">
51
 
           
52
<!-- Specify URLs -->
53
 
           
54
<input type="hidden" name="return" value="<?php echo PAYPAL_RETURN_URL; ?>">
55
 
           
56
<input type="hidden" name="cancel_return" value="<?php echo PAYPAL_CANCEL_URL; ?>">                                                                                                
57
 
           
58
<!-- Display the payment button. -->
59
 
           
60
<input type="image" name="submit" border="0" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif">
61
 
           
62
                </form>
63
 
           
64
            </div>
65
 
           
66
        </div>
67
 
           
68
     <?php } ?>
69
 
           
70
</div>



Step 6: Successful Payment (success.php)

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
Java




xxxxxxxxxx
1
77


 
1
<?php 
2
 // Include configuration file 
3
 include_once 'config.php'; 
4
 
           
5
 // Include database connection file 
6
 include_once 'dbConnect.php'; 
7
 
           
8
 // If transaction data is available in the URL 
9
 if(!empty($_GET['item_number']) && !empty($_GET['tx']) && !empty($_GET['amt']) && !empty($_GET['cc']) && !empty($_GET['st'])){ 
10
     // Get transaction information from URL 
11
     $item_number = $_GET['item_number'];  
12
     $txn_id = $_GET['tx']; 
13
     $payment_gross = $_GET['amt']; 
14
     $currency_code = $_GET['cc']; 
15
     $payment_status = $_GET['st']; 
16
 
           
17
     // Get product info from the database 
18
     $productResult = $db->query("SELECT * FROM products WHERE id = ".$item_number); 
19
     $productRow = $productResult->fetch_assoc(); 
20
 
           
21
     // Check if transaction data exists with the same TXN ID. 
22
     $prevPaymentResult = $db->query("SELECT * FROM payments WHERE txn_id = '".$txn_id."'"); 
23
 
           
24
     if($prevPaymentResult->num_rows > 0){ 
25
         $paymentRow = $prevPaymentResult->fetch_assoc(); 
26
         $payment_id = $paymentRow['payment_id']; 
27
         $payment_gross = $paymentRow['payment_gross']; 
28
         $payment_status = $paymentRow['payment_status']; 
29
}else{ 
30
         // Insert transaction data into the database 
31
         $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."')"); 
32
         $payment_id = $db->insert_id; 
33
} 
34
} 
35
 ?>
36
 
           
37
 
38
 
           
39
<div class="container">
40
 
           
41
    <div class="status">
42
 
           
43
        <?php if(!empty($payment_id)){ ?>
44
 
           
45
            <h1 class="success">Your Payment has been Successful</h1>
46
 
           
47
                                                         
48
 
           
49
            <h4>Payment Information</h4>
50
 
           
51
            <p><b>Reference Number:</b> <?php echo $payment_id?></p>
52
 
           
53
            <p><b>Transaction ID:</b> <?php echo $txn_id?></p>
54
 
           
55
            <p><b>Paid Amount:</b> <?php echo $payment_gross?></p>
56
 
           
57
            <p><b>Payment Status:</b> <?php echo $payment_status?></p>
58
 
           
59
                                                         
60
 
           
61
            <h4>Product Information</h4>
62
 
           
63
            <p><b>Name:</b> <?php echo $productRow['name']; ?></p>
64
 
           
65
            <p><b>Price:</b> <?php echo $productRow['price']; ?></p>
66
 
           
67
        <?php }else?>
68
 
           
69
            <h1 class="error">Your Payment has Failed</h1>
70
 
           
71
        <?php } ?>
72
 
           
73
    </div>
74
 
           
75
    <a href="index.php" class="btn-link">Back to Products</a>
76
 
           
77
</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.

Java




xxxxxxxxxx
1


 
1
<div class="container">
2
<div class="status">
3
<h1 class="error">Your PayPal Transaction has been Canceled</h1>
4
</div>
5
<a href="index.php" class="btn-link">Back to Products</a>
6
</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.

Java




xxxxxxxxxx
1


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

Java




xxxxxxxxxx
1
85


 
1
<?php 
2
 // Include configuration file 
3
 include_once 'config.php'; 
4
 
           
5
 // Include database connection file 
6
 include_once 'dbConnect.php'; 
7
 
           
8
 /* 
9
* Read POST data 
10
* reading posted data directly from $_POST causes serialization 
11
* issues with array data in POST. 
12
* Reading raw POST data from input stream instead. 
13
*/ 
14
 $raw_post_data = file_get_contents('php://input'); 
15
 $raw_post_array = explode('&'$raw_post_data); 
16
 $myPost = array(); 
17
 foreach ($raw_post_array as $keyval) { 
18
     $keyval = explode ('='$keyval); 
19
     if (count($keyval) == 2) 
20
         $myPost[$keyval[0]] = urldecode($keyval[1]); 
21
} 
22
 
           
23
 // Read the post from PayPal system and add 'cmd' 
24
 $req = 'cmd=_notify-validate'; 
25
 if(function_exists('get_magic_quotes_gpc')) { 
26
     $get_magic_quotes_exists = true; 
27
} 
28
 foreach ($myPost as $key => $value) { 
29
     if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) { 
30
         $value = urlencode(stripslashes($value)); 
31
} else { 
32
         $value = urlencode($value); 
33
} 
34
     $req .= "&$key=$value"; 
35
} 
36
 
           
37
 /* 
38
* Post IPN data back to PayPal to validate the IPN data is genuine 
39
* Without this step, anyone can fake IPN data 
40
*/ 
41
 $paypalURL = PAYPAL_URL; 
42
 $ch = curl_init($paypalURL); 
43
 if ($ch == FALSE) { 
44
     return FALSE; 
45
} 
46
 curl_setopt($chCURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_1_1); 
47
 curl_setopt($chCURLOPT_POST1); 
48
 curl_setopt($chCURLOPT_RETURNTRANSFER,1); 
49
 curl_setopt($chCURLOPT_POSTFIELDS$req); 
50
 curl_setopt($chCURLOPT_SSLVERSION6); 
51
 curl_setopt($chCURLOPT_SSL_VERIFYPEER1); 
52
 curl_setopt($chCURLOPT_SSL_VERIFYHOST2); 
53
 curl_setopt($chCURLOPT_FORBID_REUSE1); 
54
 
           
55
 // Set TCP timeout to 30 seconds 
56
 curl_setopt($chCURLOPT_CONNECTTIMEOUT30); 
57
 curl_setopt($chCURLOPT_HTTPHEADERarray('Connection: Close''User-Agent: company-name')); 
58
 $res = curl_exec($ch); 
59
 
           
60
 /* 
61
* Inspect IPN validation result and act accordingly 
62
* Split response headers and payload, a better way for strcmp 
63
*/ 
64
 $tokens = explode("\r\n\r\n"trim($res)); 
65
 $res = trim(end($tokens)); 
66
 if (strcmp($res"VERIFIED") == 0 || strcasecmp($res"VERIFIED") == 0) { 
67
 
           
68
     // Retrieve transaction info from PayPal 
69
     $item_number    = $_POST['item_number']; 
70
     $txn_id         = $_POST['txn_id']; 
71
     $payment_gross     = $_POST['mc_gross']; 
72
     $currency_code     = $_POST['mc_currency']; 
73
     $payment_status = $_POST['payment_status']; 
74
 
           
75
     // Check if transaction data exists with the same TXN ID 
76
     $prevPayment = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'"); 
77
     if($prevPayment->num_rows > 0){ 
78
exit(); 
79
}else{ 
80
         // Insert transaction data into the database 
81
         $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."')"); 
82
} 
83
 
           
84
} 
85
 ?>


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.

Java




xxxxxxxxxx
1


 
1
define('PAYPAL_ID''Insert_PayPal_Business_Email'); 
2
 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’'

20 Years of Open Source: Why the Best Payment APIs Use Shared Code

Topics:
php ,paypal integration ,integration ,tutorial ,paypal payment gateway api

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}