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.
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
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
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.
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
Create button and copy the code paste into your page
Step 3 : Create a button page in your websites like pay.php and add a my button code
<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"> </form>
Step 4: Create Instant payment notification page ipnhandler.php
<?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 //https://www.sandbox.paypal.com/cgi-bin/webscr $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 if(curl_errno($ch)) { //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 { //NO HTTP ERROR OCCURRED, CLEAN //CHECK IF VERIFIED 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']; $productname=$_POST['item_name']; $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']; $username=$_POST['payer_id']; $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='incomplete'; $downloadstatus = mysql_real_escape_string($downloadstatus); // Here GOES YOUR OWN CODE //Log validated IPN records to MySQL database mysql_query(" 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")); mysql_close($dbhandle); $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 mysql_close($dbhandle); } 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 curl_close($ch); ?>
Stpe 3 : Create database in table name customerrecords
CREATE TABLE IF NOT EXISTS `customerrecords` ( `id` int(11) NOT NULL AUTO_INCREMENT, `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, `Cur_TimeStamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `username` varchar(50) NOT NULL, `package_access` int(12) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Step 4 : Add url to Instant Payment notification setting
Select Instant payment notification option and enable this option add your ipnhandler.php page
Thats it now save the changes and run your pay.php file and click pay button you may pay with your created buyer account.
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
Demo the payments and Enjoy the code
payment demo
email : buyerr@xyz.com
password : Buyer@123