Integrated Paypal Payment Using Php With Instant Payment Notification(IPN)

Google+ Pinterest LinkedIn Tumblr

Integrated Paypal Payment Using Php With Instant Payment Notification(IPN)

Nowadays, All the products are sell in online. If your are online seller then payment is one of the important part that you faced.   PayPal is your best choice. Almost every website selling stuff or subscriptions use PayPal to manage its transactions. While PayPal back-end allows users to fully manage their accounts. its very easy to integrate.

No need to do anything manually for sell products paypal have Instant payment Notification(IPN). It means you will get notification of payment details instantly. If you don’t want to use third part services, PayPal offers the Instant Payment Notification to automate your digital deliveries.  So In this tutorials will explain the basic paypal payment setup, pay mode and Instant Payment Notification setup easily.

Step 1 : Sign up with paypal

you cant directly access the paypal for free. so there is Developer websites for paypal Sandbox.paypal.com 
For first time  Sign up with www.sandbox.paypal.com
You must create account to developer.paypal.com  and Sign up with your details in paypal. Integrated Paypal Payment Using Php

Integrated Paypal Payment Using Php

After signup with valid details in paypal. you can login with developer.paypal.com. There you see Sandbox menu in left side and accounts
Sandbox –> Accounts

integrated paypal payment using php

Create two types of account one for business(Seller) and another for personal(buyer). will create any type user name like sellar@xyz.com or seller@qwr.com, etc

Integrated Paypal Payment Using Php

Same way for seller after created login credentials go to sandbox.paypal.com and login with seller credential

Step 2: Create a Paypal buy now button

After login with sandbox paypal click profile link and you can see all options there.

Integrated Paypal Payment Using Php

You see there My saved buttons and Instant payment Notification options. These 2 options we are going to use. first click my saved button and create buy now button with valid price

Integrated Paypal Payment Using Php

Create button and copy the code paste into your page

Integrated Paypal Payment Using Php

Integrated Paypal Payment Using Php

Step 3 : Create a button page in your websites like pay.php and add a my button code

Integrated Paypal Payment Using Php

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="5G32D5X3RT6EQ">
<input type="hidden" name="return" value="http://demos.developerdesks.com/paypal_IPN/home.php">
<input type="hidden" name="cancel_return" value="http://demos.developerdesks.com/paypal_IPN/cancel.php">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">

Step 4: Create Instant payment notification page ipnhandler.php


$req = 'cmd=' . urlencode('_notify-validate');
    foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";

//NEW CODE: using Curl instead of fsockopen
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.sandbox.paypal.com/cgi-bin/webscr'); // if use paypal replace https://www.paypal.com/cgi-bin/webscr
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host:www.sandbox.paypal.com')); // replace host name as www.paypal.com for paypal
$res = curl_exec($ch);

//assign posted variables to PHP variables

//Connect to MySQL database
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "records";

$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");

//include "connect.php";
//Check if any error occured

//HTTP ERROR occurred
//Log error to database for troubleshooting
$log='http error='.curl_error($ch);
$log = mysql_real_escape_string($log);
mysql_query("INSERT INTO ipnlogs (eventlog) VALUES ('$log')");  // error verified
else {

if (strcmp ($res, "VERIFIED") == 0) {

$log='Verified IPN Transaction';
$log = mysql_real_escape_string($log);
mysql_query("INSERT INTO ipnlogs (eventlog) VALUES ('$log')");  // success verified 

//log success to database

$payment_status = $_POST['payment_status'];   // payment status
$payment_amount = $_POST['mc_gross'];   // payment amount 
$payment_currency = $_POST['mc_currency']; // payment currency type
$txn_id = $_POST['txn_id'];          // transaction id 
$receiver_email = $_POST['receiver_email'];  
$payer_email = $_POST['payer_email'];   //payer email id
$invoice = $_POST['invoice'];       // invoice number 
$register_email = $_POST['custom'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$address_city = $_POST['address_city'];
$address_country = $_POST['address_country'];
$address_country_code = $_POST['address_country_code'];
$address_name = $_POST['address_name'];
$address_state = $_POST['address_state'];
$address_status = $_POST['address_status'];
$address_stree = $_POST['address_stree'];
$address_zip = $_POST['address_zip'];
$server = $_SERVER['HTTP_HOST'];

//IPN transaction is VERIFIED
//check that txn_id has not been previously processed
//query the database
$txn_id = mysql_real_escape_string($txn_id);

//no records found, transaction ID is new
//proceed with the rest of validation
// check that receiver_email is your Primary PayPal email
//check if payment currency is USD
//check if the payment amount is correct
//retrieve the product price in the MySQL database for the purchased product 
//check if the payment_status is Completed

//Set download status to incomplete because the user still need to download bought material
$downloadstatus = mysql_real_escape_string($downloadstatus);

//Log validated IPN records to MySQL database
INSERT INTO customerrecords (PaymentStatus,PaymentAmount,PaymentCurrency,PayerEmail,ReceiverEmail,TransactionID,ProductPurchased,IPAddress,DownloadStatus,username,package_access) VALUES ('Completed','$payment_amount','$payment_currency','$payer_email','$receiver_email','$txn_id','$productname','$username','$downloadstatus','$register_email','$id')")
or die(mysql_error("querry wrong"));

$to      = $register_email;
$subject = 'Purchased Details';
$message = '
Thank you for purchasing the products

Here is your Product purchased details
Registered Email: '.$productname.'
Transaction Id : '.$txn_id.'
Pay Amount: '.$payment_amount.'

if you like our coding please subscribe
https://www.developerdesks.com/ ';
$headers = 'From:info@developerdesks.com' . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);

//close MySQL database connection

else if (strcmp ($res, "INVALID") == 0) 

//Invalid IPN transaction
//You can alternatively log this transaction to your database for troubleshooting purposes
$log='Invalid IPN transaction';
$log = mysql_real_escape_string($log);
mysql_query("INSERT INTO ipnlogs (eventlog) VALUES ('$log')");

//close the connection

Stpe 3 : Create database in table  name customerrecords

CREATE TABLE IF NOT EXISTS `customerrecords` (
  `PaymentStatus` varchar(20) DEFAULT NULL,
  `PaymentAmount` decimal(6,2) DEFAULT NULL,
  `PaymentCurrency` varchar(20) DEFAULT NULL,
  `PayerEmail` varchar(50) DEFAULT NULL,
  `ReceiverEmail` varchar(50) DEFAULT NULL,
  `TransactionID` varchar(30) DEFAULT NULL,
  `ProductPurchased` varchar(60) DEFAULT NULL,
  `IPAddress` varchar(15) DEFAULT NULL,
  `DownloadStatus` varchar(10) DEFAULT NULL,
  `username` varchar(50) NOT NULL,
  `package_access` int(12) NOT NULL,
  PRIMARY KEY (`id`)

Step 4 : Add url to Instant Payment notification setting Integrated Paypal Payment Using Php

Select Instant payment notification option and enable this option add your ipnhandler.php page

Integrated Paypal Payment Using Php

Thats it now save the changes and run your pay.php file and click pay button you may pay with your created buyer account.

Integrated Paypal Payment Using Php

After paid the product, You will get the Product name, Product price, payer email, payer name, product currency name, ect you can save it for ur future

Integrated Paypal Payment Using Php

Demo the payments and Enjoy the code

payment demo
email : buyerr@xyz.com
password : Buyer@123


I'm Rajasekar - Web developer, Freelancer, Blogger and Owner of DeveloperDesks. From India lives in Bahrain. I love to do coding, Creating websites and trying different with code and designs. You Can Hire Me