cyberdesignz
05-18-2010, 07:45 AM
I have found the the best integration of paypal in php...i cant find any attachment tag here so i m pasting it here..i hope it will help you. I have commented out which will help you to learn the working.
<?php
/** PayPal IPN Script
*
* See https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_html_instantpaymentnotif
* for a lot of good information about IPN
*
* This script requires a MySQL database with
* the appropriate tables created. See paypal_ipn.sql
*
* Brief overview of how IPN works:
*
* After a paypal sale is completed AND the seller has
* setup PayPal Instant Payment Notification, Paypal sends
* information about the transaction to this script.
*
* Once this script receives the information from PayPal, it
* sends the same information back to PayPal. PayPal verifies
* that the information this script sent back matches
* what was PayPal originally sent. If it matches, PayPal
* sends 'VERIFIED' back to this script. Once 'VERIFIED' is
* received, you can be sure that a legitimate transaction took
* place.
*
* If it does not match, or PayPal did not send any information
* to this script,
*
* This script must be placed in a web accessible directory
* and PayPal must know the location of this script. PayPal is
* informed of the location of this script when the seller
* sets up Instant Payment Notification.
*
* You can look at the long list of $_POST[''] variables below
* to see what potentially could be sent to this script. Or see
* https://www.paypal.com/IntegrationCenter/ic_ipn-pdt-variable-reference.html
*
* The base of this script is provided by PayPal at
* https://www.paypal.com/cgi-bin/webscr?cmd=p/xcl/rec/ipn-code-outside
* and
* https://www.paypaltech.com/SG2/
*
* These scripts were modified and commented by Jason DeBord www.jasondebord.net
*
*/
// First prepare to send all of the information back to Paypal
$req = 'cmd=_notify-validate';
// Build string by putting all of the $_POST variables together: $req = &item_name=someitem&item_number=somenumber etc...
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); // 'ssl://www.sandbox.paypal.com' for sandbox testing
// Assign posted variables to local variables to use in your database entries later on
// See https://www.paypal.com/IntegrationCenter/ic_ipn-pdt-variable-reference.html for details about each of these variables
// Many of them probably won't be used
$item_name = $_POST['item_name'];
$business = $_POST['business'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$mc_gross = $_POST['mc_gross']; // Total of transaction
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$receiver_id = $_POST['receiver_id'];
$quantity = $_POST['quantity'];
$num_cart_items = $_POST['num_cart_items'];
$payment_date = $_POST['payment_date'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$payment_type = $_POST['payment_type'];
$payment_status = $_POST['payment_status'];
/*
* Payment Status is important. You can use the value
* of this variable in your custom scripting below to
* handle the different values assigned to this variable.
* You obviously would not want to ship an item until the
* payment has been "completed"
*
* Possible payment_status values:
*
* Canceled-Reversal
* Completed
* Denied
* Expired
* Failed
* In-Progress
* Pending
* Processed
* Refunded
* Reversed
* Voided
*/
$payment_gross = $_POST['payment_gross'];
$payment_fee = $_POST['payment_fee'];
$settle_amount = $_POST['settle_amount'];
$txn_type = $_POST['txn_type'];
$payer_status = $_POST['payer_status'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$item_number = $_POST['item_number'];
$tax = $_POST['tax'];
$option_name1 = $_POST['option_name1'];
$option_selection1 = $_POST['option_selection1'];
$option_name2 = $_POST['option_name2'];
$option_selection2 = $_POST['option_selection2'];
$for_auction = $_POST['for_auction'];
$invoice = $_POST['invoice'];
$custom = $_POST['custom']; // Pass custom information to the script for an item. Customer does not see this variable's value.
$notify_version = $_POST['notify_version'];
$verify_sign = $_POST['verify_sign'];
$payer_business_name = $_POST['payer_business_name'];
$payer_id =$_POST['payer_id'];
$mc_currency = $_POST['mc_currency'];
$mc_fee = $_POST['mc_fee'];
$exchange_rate = $_POST['exchange_rate'];
$settle_currency = $_POST['settle_currency'];
$parent_txn_id = $_POST['parent_txn_id'];
$pending_reason = $_POST['pending_reason'];
$reason_code = $_POST['reason_code'];
$payer_email = $_POST['payer_email']; // PayPal user's email (customer's email that they use with their paypal account)
// subscription specific vars
$subscr_id = $_POST['subscr_id'];
$subscr_date = $_POST['subscr_date'];
$subscr_effective = $_POST['subscr_effective'];
$period1 = $_POST['period1'];
$period2 = $_POST['period2'];
$period3 = $_POST['period3'];
$amount1 = $_POST['amount1'];
$amount2 = $_POST['amount2'];
$amount3 = $_POST['amount3'];
$mc_amount1 = $_POST['mc_amount1'];
$mc_amount2 = $_POST['mc_amount2'];
$mc_amount3 = $_POST['mcamount3'];
$recurring = $_POST['recurring'];
$reattempt = $_POST['reattempt'];
$retry_at = $_POST['retry_at'];
$recur_times = $_POST['recur_times'];
$username = $_POST['username'];
$password = $_POST['password'];
//auction specific vars
$for_auction = $_POST['for_auction'];
$auction_closing_date = $_POST['auction_closing_date'];
$auction_multi_item = $_POST['auction_multi_item'];
$auction_buyer_id = $_POST['auction_buyer_id'];
//DB connect credentials and email
// Your email here. This script will send IPN notifications to this email.
// You can customize the emails below.
$notify_email = "your@email.here";
$your_account_email = "your@paypal account email";
// You can hard code your MYSQL information below, or preferably, you can reference
// it by using require_once('mysql_variables.php'); and putting these variables
// in a php file in your php include directory above your public web root.
//
// If you use a custom script for you MySQL variables AND connection mysql_connect()
// you'll need to delete, comment out, or otherwise modify below where the connection
// and database selection is made ~ line 174
$DB_Server = ""; //your MySQL Server
$DB_Username = ""; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = ""; //your MySQL Database Name
if (!$fp) { // Could not make a socket connection with PayPal
// HTTP Error : Something is wrong with PayPal's system.
// You may want to send yourself an email notifying you of this and then
// manually check your PayPal account to see what transaction has taken place.
// Put php code here to handle this situation.
} else { // Socket connection with the PayPal was successful. Now determine if the transaction is VERIFIED or INVALID
fputs ($fp, $header . $req); // Send variables back to PayPal so that PayPal
// can confirm that this script received legitimate payment information.
while (!feof($fp)) {
$res = fgets ($fp, 1024); // VERIFIED or INVALID is assigned to the $res variable here
if (strcmp ($res, "VERIFIED") == 0) { // php "string compare" strcmp() function determines if $res matches the word VERIFIED
//create MySQL connection
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die ("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect) or die ("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
$fecha = date("m")."/".date("d")."/".date("Y");
$fecha = date("Y").date("m").date("d");
//check if transaction ID has been processed before
$checkquery = "select txnid from paypal_payment_info where txnid='".$txn_id."'";
$sihay = mysql_query($checkquery) or die("Duplicate txn id check query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
$nm = mysql_num_rows($sihay); // If this number is not zero, then a duplicate transaction has occurred
if ($nm == 0) { // Not a duplicate transaction
//execute query
if ($txn_type == "cart") { // PayPal Cart
$strQuery = "insert into paypal_payment_info(paymentstatus,buyer_email,firstname,lastname,street,city,state,zipcode,country,m c_gross,mc_fee,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')";
$result = mysql_query($strQuery) or die("Cart - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
for ($i = 1; $i <= $num_cart_items; $i++) {
$itemname = "item_name".$i;
$itemnumber = "item_number".$i;
$on0 = "option_name1_".$i;
$os0 = "option_selection1_".$i;
$on1 = "option_name2_".$i;
$os1 = "option_selection2_".$i;
$quantity = "quantity".$i;
$struery = "insert into paypal_cart_info(txnid,itemnumber,itemname,os0,on0,os1,on1,quantity,invoice,custom) values ('".$txn_id."','".$_POST[$itemnumber]."','".$_POST[$itemname]."','".$_POST[$on0]."','".$_POST[$os0]."','".$_POST[$on1]."','".$_POST[$os1]."','".$_POST[$quantity]."','".$invoice."','".$custom."')";
$result = mysql_query($struery) or die("Cart - paypal_cart_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
}
} else { // Here is where you write all the code you want to run when a VERIFIED Transaction has occurred
// and it is NOT a duplicate transaction AND it is not of transaction type "cart". Basically, someone has attempted
// to send you money for somthing.
// You can: Build and execute queries to your database, send emails to buyers and / or yourself, etc...
// For example:
// You may want to check the payment status and make sure that the receiver email
// ( your paypal account / account that is supposed to receive payment )
// is the email address that the payment was sent to.
// Execute database entries only if payment_status is completed and the receiver_email is YOUR PayPal Account Email
if ( ($payment_status == "Completed") && ($receiver_email == "$your_account_email") ) {
// The following query inserts standard information into the "paypal_payment_info" table of your database.
// This table can be created with paypal_ipn.sql
// The query was written and provided by PayPal
$result = mysql_query("insert into paypal_payment_info(paymentstatus,buyer_email,firstname,lastname,street,city,state,zipcode,country,m c_gross,mc_fee,itemnumber,itemname,os0,on0,os1,on1,quantity,memo,paymenttype,paymentdate,txnid,pendi ngreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$item_number."','".$item_name."','".$option_name1."','".$option_selection1."','".$option_name2."','".$option_selection2."','".$quantity."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')") or die("Default - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
// Put other database queries here if necessary
// Send an email to buyer informing them that they have successfully made payment, etc...
} else { // Either payment status is not "Completed" or the receiver email is not your email.
// Put code here to handle payment's that are not completed
if ( $receiver_email != "$your_account_email" ) { // A payment has been made for your item, but the money
// was sent to someone else's paypal account
// Send mail to notify yourself of this
mail($notify_email, "Security Alert Payment Receiver EMAIL Address doesn't match!", "Paypal has sent payment to the wrong account\n\n$res\n $req\n $strQuery\n $struery\n $strQuery2");
} // END $receiver_email != "$your_account_email"
}
}
// Send an email to $notify_email if VERIFIED was returned no matter what else happened.
mail($notify_email, "VERIFIED IPN", "$res\n $req\n $strQuery\n $struery\n $strQuery2");
} else { // A duplicate transaction occurred
// Mail yourself an email informing you of this, then handle it manually and / or add any other php code here to use in this situation
mail($notify_email, "VERIFIED DUPLICATED TRANSACTION", "$res\n $req \n $strQuery\n $struery\n $strQuery2");
}
// subscription handling branch. If you don't offer subscriptions, this code will never run.
if ( $txn_type == "subscr_signup" || $txn_type == "subscr_payment" ) { // Only used if what you are selling involves a subscription
// insert subscriber payment info into paypal_payment_info table
$strQuery = "insert into paypal_payment_info(paymentstatus,buyer_email,firstname,lastname,street,city,state,zipcode,country,m c_gross,mc_fee,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')";
$result = mysql_query($strQuery) or die("Subscription - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
// insert subscriber info into paypal_subscription_info table
$strQuery2 = "insert into paypal_subscription_info(subscr_id , sub_event, subscr_date ,subscr_effective,period1,period2, period3, amount1 ,amount2 ,amount3, mc_amount1, mc_amount2, mc_amount3, recurring, reattempt,retry_at, recur_times, username ,password, payment_txn_id, subscriber_emailaddress, datecreation) values ('".$subscr_id."', '".$txn_type."','".$subscr_date."','".$subscr_effective."','".$period1."','".$period2."','".$period3."','".$amount1."','".$amount2."','".$amount3."','".$mc_amount1."','".$mc_amount2."','".$mc_amount3."','".$recurring."','".$reattempt."','".$retry_at."','".$recur_times."','".$username."','".$password."', '".$txn_id."','".$payer_email."','".$fecha."')";
$result = mysql_query($strQuery2) or die("Subscription - paypal_subscription_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
mail($notify_email, "VERIFIED IPN", "$res\n $req\n $strQuery\n $struery\n $strQuery2");
}
// END subscription handling branch
} else if (strcmp ($res, "INVALID") == 0) { // An invalid transaction occurred
// Custom Invalid Transaction code here:
mail($notify_email, "INVALID IPN", "$res\n $req"); // Mails you stating that an INVALID
// transaction has occurred.
} // END INVALID transaction section
}
fclose ($fp); // Close socket connection with PayPal
}
?>