PayPal is an American international e-commerce business allowing payments and money transfers to be made through the Internet. 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 a payment system on the website.
PayPal Standard Payment Gateway is the quickest way to accept payment online. The buyer can make the payment from the website to purchase an item online. In this tutorial, we will show you how to integrate PayPal standard payment gateway in PHP and store the transaction data in the database using PayPal IPN. Our step-by-step guide on PayPal payment gateway integration in PHP helps you to easily integrate the online payment feature in your web project.
Since the PayPal Standard payment is on the Legacy version, we recommended integrating PayPal Standard Checkout for the new payment gateway integration.
In the example script, we will implement the following functionality to demonstrate the PayPal Payment Gateway integration process.
Before getting started to integrate PayPal payment gateway API in PHP, take a look at the files structure.
paypal_integration_php/ ├── config.php ├── dbConnect.php ├── index.php ├── success.php ├── cancel.php ├── ipn.php ├── css/ │ └── style.css └── images/
PayPal has two environments such as Sandbox and Real Time. PayPal Sandbox allows developers to do their test transaction before the project go live. The real-time environment is used after the project is live on the production server. Once the PayPal payment process is working properly on the Sandbox environment, you can set the PayPal payment gateway for Real-Time environment.
Before start accepting payment from buyers via PayPal, the payment gateway needs to be tested. To test the transaction process you need to create a PayPal sandbox account.
You may follow the detailed guide on creating a PayPal Sandbox account from this tutorial – Creating PayPal Sandbox Test Account and Website Payments Pro Account
To store product and payment information two tables needs to be created in the database.
The following SQL creates a products
table in the MySQL database to store the product data.
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;
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;
In the config.php
file, constant variables of the PayPal and database settings are defined.
PayPal Constants:
Database Constants:
<?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");
The dbConnect.php
file is used to connect the database using PHP and MySQL.
<?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();
}
Initially, all the products are fetched from the database and listed on the webpage.
<?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>
After successful payment on PayPal, the buyer is redirected to this page.
<?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 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 } ?>
</div>
<a href="index.php" class="btn-link">Back to Products</a>
</div>
If the buyer wishes to cancel payment at the PayPal payment page, the buyer is redirected to this page.
<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>
Make sure you have configured Auto Return for Website Payments on your PayPal business account. Otherwise, you’ll not get the transaction information from PayPal in the success.php
file. See the following guide to enable Auto Return, Payment Data Transfer and set Return URL on your PayPal account.
To make the PayPal Standard Payment secure, validate the transaction with PayPal Instant Payment Notification (IPN). Follow the below steps to setup IPN in PayPal standard payment gateway integration.
Enable IPN:
To use this feature, IPN must be enabled in the PayPal account. We’ve already published a step-by-step guide to enable IPN in PayPal, please see the below tutorial.
Add Notify URL in PayPal Form:
Add the following input field (notify_url
) HTML along with the other PayPal HTML Variables.
<input type="hidden" name="notify_url" value="<?php echo PAYPAL_NOTIFY_URL; ?>">
Validate Transaction:
Once IPN is enabled, PayPal will send the transaction data to the Notify URL (http://www.example.com/ipn.php
). Place the following code in the ipn.php
file to validate the transaction and insert payment information into the database.
<?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."')");
}
}
?>
Note that: Once the PayPal IPN setup is completed, the database insertion code is not required in the success.php
file.
When the application payment flow testing is completed, you should make the PayPal payment gateway live.
In the config.php file,
PAYPAL_ID
.PAYPAL_SANDBOX
to FALSE.define('PAYPAL_ID', 'Insert_PayPal_Business_Email');
define('PAYPAL_SANDBOX', FALSE);
PayPal Pro Payment Gateway Integration in PHP
PayPal standard payment gateway is the easiest way to accept payment on the web application. With our example script, you can easily integrate the PayPal payment API on the website. To make the payment process user-friendly, you can integrate PayPal Express Checkout for the online payment.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Nice One ..this tutorial is very helpfull…Nice article.
Hello sir
Such a very helpfull Code to integrate with my site
but can you please tell me one thing
how can i insert the one more column in database via IPN.PHP
so that i can verify for which post user have make payment and for which they have not
means simple to say is
how can i insert post Url and user id of the user in database via IPN.PHP.
(WORDPRESS)
I want to configure payapal as _cart. I did everything but in DB item_number and item_id not store because in code it take item_number_1, item_number_2, item_number_3…
How to store it in DB ?
@Krishna For that, you can user PayPal Add To Cart payment system. See the tutorial for Accepting Payment for Multiple Items with PayPal from here – http://www.codexworld.com/paypal-standard-add-to-cart-multiple-items-php/
Update to my previous comment:
I discovered the issue was currency. I’m in the UK and if the currency is set to USD the payment status comes back as ‘Pending’. However, changing works fine!
I will add a condition to check if status is completed to success.php
Hi,
Great code. Been trying many different tutorials online and yours is the first that works for me! I just have one issue. After payment is successful, I’m getting payment status as ‘Pending’ in the database. Do you know how to change this so payment status is ‘completed’?
Can this code can be used to buy multiple items at the same time?please guide me
@Ammar We’ll publish the PayPal tutorial soon for purchasing multiple items. Meantime, subscribe our newsletter to get notified about tutorials update.
Hi,
Excellent explanation. I got the answer what i want. Fantastic page appearance .
Great work….
Hello codexworld, in case that i want to enable real transactions into my website are you sure that i should change only the paypal url from sandbox to paypal or should i login into my paypal account ( not the sandbox one ) and change from there the values AUTO RETURN, PAYMENT DATA TRANSFER and IPN. I am asking you cause those changes in this tutorial are in testing sandbox account and not into a real one account. Thank you in advance!
@Bill Not only the business email but also the PayPal Auto Return, Payment Data Transfer, and IPN need to be configured in your PayPal account.
Paypal Payment is Working on localhost(wamp)?
Yes, you can test PayPal payment gateway on localhost with Sandbox environment.
Paypal does not pass any value to the success.php
@Timothy You need to Configure PayPal Sandbox Auto Return and Payment Data Transfer for getting the response data in
success.php
.Hi, first things first, thanks for this tutorial, great and simple.
There is one var I don’t understand though.
In the success.php file there is a $prevRowNum var in the if statement.
I did not find other references to this var in your code and I don’t understand what it contains.
Thanks for your time.
Cheers,
Camille.
@Camille We’ve updated the code, please use the latest version of the code.
ndefined variable: prevRowNum
Can’t see you guys defining it, uhm help? 🙂
@Thomas Thanks for notifying this issue. We’ve updated the code, you can download the latest version of the source code.
in success.php undefined index item_number,txn_id , amt, cc, st error is occured,, please give me rply
@Shamali You need to Configure PayPal Sandbox Auto Return and Payment Data Transfer for getting the response data in
success.php
.sir where i can meet my paypal url and paypal id into my account
@Ram PayPal URL would be same as like mentioned in the script and your PayPal business email is used as PayPal ID.
I want to add 4 more fields in url of success.php using get method
I Want same functionality for Instamojo payment gateway integration in php.
@Nelson We’ll try to publish your requested payment gateway tutorial soon. Please subscribe our newsletter to get notified.
Nice One ..this tutorial is very helpfull…
Can you update new topic in cakephp 3.2 for PayPal Account And User login with facebooks,gmail etc. in cakephp 3.2
Hope you will reply my comments.
I need help codexworld Am not getting response values from paypal .,
@Arun You need to Configure PayPal Sandbox Auto Return and Payment Data Transfer for getting the response data in success.php.
Nice article,
I have not imolemented this yet but your article makes it sound a lot easier . I just have one question
What if someone hits success url with the values in query string where he gives any transaction id and gives exact price and other details for item?
How can wr make sure that the info in get is from paypal and not just url hit with query string?
@Abhinav For preventing this situation you need to use PayPal IPN. Please see the Using IPN section in our tutorial.
Hey nice tutorial.
I don’t see cancel button on paypal site. Incase user want to cancel
i have enabled it in the live paypal but not sandbox mode, how do I enable IPN in sandbox mode?
IPN setup on PayPal Sandbox account has described here – How to enable PayPal Instant Payment Notification (IPN)
Thank you for the reply, at the mo I am testing it in sandbox mode and am sure I enabled PayPal IPN in sandbox mode
Hi @CodexWorld
Thank you for the reply, I have added the notify_url in the PayPal form and in the notify_url file
But it is not adding the buyers first name and payer email address
Can you help me please,
@Lan You need to enable the PayPal IPN from PayPal Business account. Please checkout this tutorial – How to enable PayPal Instant Payment Notification (IPN)
Hi
I got this script all working now, just got a quick question
Is it possible to get first and last name in PayPal and store in the database
@Lan If you want to get the information about the buyer, then use
notify_url
variable in PayPal posts HTML FORM. You will receive the payment information on this URL and can store the buyer details into the database.After payment it is not displaying anything for my success.php file. I followed the directions above and changed what was needed on my paypal account but it is still not doing it. Just displays a blank page. Any suggestions?
@Kevin You need to Configure PayPal Sandbox Auto Return and Payment Data Transfer. It will help to solve this issue.
Is there a way to make the buy now button trigger a recurring payment from paypal ? I want to do recurring payments on my website but I like the method above you use, I just need to make the payments recurring payments.
@Keven In that case, you can use PayPal Subscribe Buttons for recurring payment.
Hello, I’m just wondering, is it safe if we put the price value in a hidden input?
Because I think that we can always manipulate the value of the price if we do inspect element. Is there another way we can do to supply the price information to the PayPal?
@Omar
Yes, there is a way. You can add a link to the Buy button, which will redirect to the PHP page (like
payment.php
). From this PHP page (payment.php
) you can generate a form with required PayPal variable and submit to the PayPal URL. Please try and let us know if you need any help.Hello,
I have used this code for my site..And when i do payment it successfully pay.But on success.php it shows your payment failed.Because it didn’t the value of paypal transaction or my form field’s value.So can you please give me some advice for it??
Thanks
@Mansi
Please read CodexWorld’s reply regarding Shubhum’s comment above.
how to purchase multi items?
See this tutorial to accepting payments for multiple items with PayPal in PHP – https://www.codexworld.com/paypal-standard-add-to-cart-multiple-items-php/
Thanks a lot mate….
last 2 days im tring to redirect page after payment done. but its not get any success. please help me.
@Amol
Please read CodexWorld’s reply regarding Shubhum’s comment above.
Can you please explain how the cancel url is working? because when I enter a card number with zero balance sandbox paypal redirects the system to the success url. how can it be done to the cancel url. thanks
@Yohan
Cancel URL is specified by the cancel_return variable. PayPal redirects the buyers to the cancel URL if they cancel checkout before completing their payments. You can check the transaction status with the success URL. Please follow the sample code of the success.php page.
What is the Buisness ID you have speciied?
@Pravin
Business ID means your PayPal Business Email.
I m Not geeting auto redirected page after payment….And after completing tranasctions not redirecting to sucess page automatically..On sucess page not showing values of transaction id.
@Lovnish
Please read CodexWorld’s reply regarding Shubhum’s comment above.
when i change the $paypal_id to my test id after done the payment paypal not automatically redirect. can you please tell me why is that? when i put your test email id then it’s work again.
Please check CodexWorld’s reply regarding Shubhum’s comment above. You would need to make the mentioned settings into your live PayPal account.
Thanks a lot.
How to go live after this complete.
You need to change
$paypal_url
variable value withhttps://www.paypal.com/cgi-bin/webscr
and change$paypal_id
variable value with the original PayPal Business ID.Hello, thanks very much for the tutorial, everything works well except that i can’t get any data in success.php from paypal. It seems that paypal didn’t sent any data back. Also, i would like that the page redirects from paypal directly after payment has been completed! At present, i should click to return back to site! Advise please! Thanks very much..
Please follow the below steps for solving the payment data and page redirect issue.
1. Login with your business account from here – https://www.sandbox.paypal.com
2. Now click on profile tab of My account and click on the My selling tools link from the left side menus section.
3. Under the Selling online section you will see Website preferences.
4. Click on the Update link of Website preferences.
5. Under the Auto Return for Website Payments section select Auto Return On and enter the Return URL.
6. Under the Payment Data Transfer section select the Payment Data Transfer On.
7. Click on the Save button.
Now user would be automatically redirected to the specified Return URL and the Payment Information would be sent as a query string to the Return URL.
We have modified the code of
success.php
file, please check once.Dear Author,
Great Jobs
I have one issue related to Paypal payment gateway. why use developer sandbox paypal gateway. Many E commerce Website like flipkart using paypal option. payment complete without creating account. but In sandbox require create account. please solve my issue.
Thanks Mahipal.
Sandbox is a test account used by PayPal developers for testing their code end-to-end by creating personal and business test accounts.
But buyer’s do not need to create Sandbox account. They can make payment with or without PayPal account.
If you needs any clarification feel free to comment here.
Good job…