PayPal how to get post back params if response is FAIL - paypal

Could I get post back params if in scenario to a buyer click 'cancel and return to xxx store'? below code is how I tried to have post back params echo out after buyer click cancel during the palpal webscr process:
$req = 'cmd=_notify-synch';
$pp_hostname = "www.sandbox.paypal.com";
$tx_token = $_GET['tx'];
$auth_token = "Ti-bfX-sv-zNDXZS";
$req .= "&tx=".$tx_token."&at=".$auth_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://".$pp_hostname."/cgi-bin/webscr");
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);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".$pp_hostname));
$res = curl_exec($ch);
curl_close($ch);
if(!$res){
//HTTP ERROR
}else{
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if(strcmp($lines[0], "SUCCESS") == 0){
for($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
//process payment
}else if(strcmp($lines[0], "FAIL") == 0){
$lines = explode("\n", $res);
$keyarray = array();
for($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// echo post back params if FAIL
echo "<p><h3>Transaction ".$keyarray['payment_status']."!</h3></p>";
}
}
Is that possible to get post back params if response FAIL? I need some data to process in db if buyer cancel the transaction.
Thanks.

PayPal would not pass back any parameters to your cancel your, but you could pass back your own. You could dynamically populate the cancel URL that helps you to identify the user or order, and then read that on the cancel URL. For example, you could dynamically populate the cancel URL to something like https://www.mysite.com/cancel.php?orderid=483723 and then you would do your own look up in your system based on the order id, or what ever you pass over and back to your cancel URL.

paypal provide all things about transaction information for more information check below link info
reason_code
https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/

Related

Paypal IPN CURL returns "SSL connect error"

I am trying to implement ipn in my system but shows error
SSL connect error
TLS version shows TLS 1.0
It is a client's system. I downloaded the code from paypal website. I am currently testing it.
but it throws error
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$ch = curl_init('https://www.howsmyssl.com/a/check');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data);
echo $json->tls_version;
file_put_contents('NAB/paypal-ipn.txt', var_export($_POST, true));
echo "ipn processing";
// STEP 1: read POST data
// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream.
$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]);
}
echo "<br>1";
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if (function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
echo "<br>2";
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";
}
echo "<br>3";
// Step 2: POST IPN data back to PayPal to validate
$ch = curl_init('https://www.sandbox.paypal.com/cgi-bin/webscr');
//$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
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);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
echo "<br>3";
if ( !($res = curl_exec($ch)) ) {
error_log("Got " . curl_error($ch) . " when processing IPN data");
echo curl_error($ch);
curl_close($ch);
//exit;
}
If 'howsmyssl' is reporting that the systems supports only TLS v 1.0, it is likely that an upgrade is necessary to support TLS v 1.2. The curl_setopt($ch, CURLOPT_SSLVERSION, 6); is requesting TLS v 1.2 (see list in PHP Curl (with NSS) is probably using SSLv3 insted of TLS when connecting to https).
Also, as of June 30,2017, PayPal will be requiring TLS v 1.2 (see https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US and Php curl set ssl version).
You may be able to test your integration using TLS v 1.0 (until 6/30/2017) by changing to curl_setopt($ch, CURLOPT_SSLVERSION, 4);.
I had a similar problem problem when implementing the paypal ipn listener code. The script would stop executing where step 2 starts in the code you've provided. I solved it by downloading cacert.pem from http://curl.haxx.se/docs/caextract.html. Then I copied the downloaded file to the same folder as paypalipnlistener.php and then uncommented the following code in paypalipnlistener.php // curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem'); to curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem'); and the script executed successfully.

After issuing partial refund via PayPal RefundTransaction NVP API, IPN listener only shows payment status as "Refunded," not "Partially_Refunded"

When I issue a partial refund on my site using the RefundTransaction API operation, the refund is processed successfully. However, my IPN listener continually receives a payment status of just Refunded for this transaction. I am not sure why it isn't Partially_Refunded.
I have tested partial refunds with PayPal's IPN Simulator and my IPN listener returns Partially_Refunded every time during these tests.
Here's the beginning of my IPN listener file:
$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 IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$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";
}
// STEP 2: POST IPN data back to PayPal to validate
$ch = curl_init($paypal_url);
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
//mscampMail($my_email, 'MSCamp curl error', "Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// The IPN is verified, process it:
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process the notification
require_once ('includes/mysql_connect.php');
// Get payment status & parent_txn_id if refund
$payment_status = escape_data($_POST['payment_status']);
// Cart Items
$num_cart_items = isset($_POST['num_cart_items']) ? $_POST['num_cart_items'] : '';
$txn_id = escape_data($_POST['txn_id']);
$user_id = escape_data($_POST['custom']);
$order_total = escape_data($_POST['mc_gross']);
$shipping_fee = escape_data($_POST['mc_handling']);
$first_name = escape_data($_POST['first_name']);
$last_name = escape_data($_POST['last_name']);
// For guest orders, need name & address info for shipping
$guest = $user_id == 0 ? 'guest' : '';
$address_street = escape_data($_POST['address_street']);
$address_city = escape_data($_POST['address_city']);
$address_state = escape_data($_POST['address_state']);
$address_zip = escape_data($_POST['address_zip']);
And the function that posts partial refund data to PayPal:
function PPHttpPost($methodName_, $nvpStr_, $env) {
global $live;
// Set up your API credentials, PayPal end point, and API version.
if("sandbox" === $env)
$API_Endpoint = "https://api-3t.$env.paypal.com/nvp";
else
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$version = urlencode('122');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
And finally, code from the page that calls the function above when a user initiates the partial refund:
if ($live === false) $env = "sandbox";
// Set request-specific fields.
$item = urlencode($refund_detail['item']);
$amount = urlencode($refund_detail['cost']);
$inventory_num = urlencode($order_detail_id_for_refund);
$transactionID = urlencode($refund_detail['paypal_txn_id']);
$refundType = urlencode('Partial'); // or 'Partial'
$memo = urlencode("Refund of ".$refund_detail['item']); // required if Partial.
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&L_INVOICEITEMNAME0=$item&L_SKU0=$inventory_num&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType&CURRENCYCODE=$currencyID";
if(isset($memo)) {
$nvpStr .= "&NOTE=$memo";
}
if(strcasecmp($refundType, 'Partial') == 0) {
if(!isset($amount)) {
exit('Partial Refund Amount is not specified.');
} else {
$nvpStr = $nvpStr."&AMT=$amount";
}
if(!isset($memo)) {
exit('Partial Refund Memo is not specified.');
}
}
Any advice or nudge in the right direction would be greatly appreciated as my client needs to be able to process partial refunds on the site. I've scoured Stackoverflow and Google for more information to no avail. Thanks.
Mike,
The payment_status = Refunded txn will have a parent_txn_id field with the value of the transaction that was "partially" refunded.
Assuming you have stored that original payment in your database, the IPN listener can look up the original transaction and compare mc_gross from that record with the same field in the current IPN txn. If different, it is "partial" refund.
In PayPal IPN, refer to https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNandPDTVariables/. payment_status variable doesn't have 'Partially_refunded' value. For "Partially_refunded' transaction, the value is refunded. . The IPN Simulator appears to have some inaccurate variable values.

PayPal REST API shipping address Codeigniter

How to get shipping address with TOKEN using paypal REST api? I found this useful but I cant see example of usage anywhere.
I struggled with this issue a lot and finally found solution, so I want to share it if anyone else need it.
So question: How to get order details with TOKEN?
Add this function :
function PPHttpPost($methodName_, $nvpStr_) {
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('xxxxxxxxxx');
$API_Password = urlencode('xxxxxxxxxx');
$API_Signature = urlencode('xxxxxxxxxx');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('85.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit('$methodName_ failed: '.curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
and simply make a call to that function :
// Set request-specific fields.
$token = urlencode(htmlspecialchars($data['TOKEN'])); //$data['TOKEN'] is token
// Add request-specific fields to the request string.
$nvpStr = "&TOKEN=$token";
$httpParsedResponseAr = $this->PPHttpPost('GetExpressCheckoutDetails', $nvpStr);
print_r($httpParsedResponseAr); // will hold all details such as shipping address, country...
additionally you can add check if payment was successful:
if( "SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]) ) { .. }
reference

PayPal - IPN Not working

I can't get my IPN to work,
I've added it, and it sends to the form. But I can't get the listener to work, I have the following as my listener;
<?php
// STEP 1: read POST data
// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream.
$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 IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$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";
}
// Step 2: POST IPN data back to PayPal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// The IPN is verified, process it:
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process the notification
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$con=mysqli_connect("********);
$sessid=$_SESSION['id'];
$check = mysqli_query($con,"SELECT * Members WHERE id='$sessid'");
$check2 = mysqli_fetch_assoc($check);
$totalam = $_POST['mc_gross'] + $check2['credit'];
mysqli_query($con,"UPDATE members SET credit='$totalam' WHERE id='$sessid'");
// IPN message values depend upon the type of notification sent.
// To loop through the &_POST array and print the NV pairs to the screen:
foreach($_POST as $key => $value) {
echo $key." = ". $value."<br>";
}
} else if (strcmp ($res, "INVALID") == 0) {
// IPN invalid, log for manual investigation
echo "The response from IPN was: <b>" .$res ."</b>";
}
?>
But
it's not working,. It's not receiving details and adding it to my database,
can anyone help?
I posted it on the paypal forum and got told to come here for more tech support.
After the following line:
// inspect IPN validation result and act accordingly
Try adding the following line:
$res = trim($res);
Most likely the curl verification is not working in your case (it happens in some systems). One of the methods to tackle it will be:
(a) remove the step 2 block , and (b) change the following verified statement to check payment status, and (c) remove the else if block (In my opinion there is no point to do anything if the payment status is not successful, just like if the user clicks the cancel button during the payment process, nothing will be done.)
(a) Remove step 2 block by deleting the following:
// Step 2: POST IPN data back to PayPal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
(b) change the verified condition to check the payment_status instead.
if (strcmp ($res, "VERIFIED") == 0) {
to
if (trim($_POST['payment_status'])=="Completed") {
(c) remove the else if block by removing the following:
else if (strcmp ($res, "INVALID") == 0) {
// IPN invalid, log for manual investigation
echo "The response from IPN was: <b>" .$res ."</b>";
}
Of course another method to tackle the problem is to check and fix your CURL data transfer problem.

Is it possible to pass the amount back to my site

I am new to developer.paypal.com and i am creating a subscribe button in www.sandbox.paypal.com,is it possible to pass back the amount paid for the subscription by the customer to my website or the details that have been made in www.sandbox.paypal.com?if it is, can you show me some example on how to do this.
after i tried the subscription button this are the value returned i could not find some value in the link that you provided.or the subscription variable how can i show them up?
I could not get the start date and the ending date of my subscription
Thank you.
You could do this one of two ways. You could use IPN or PDT to return information to your site once a payment completes. The better of the two ways, would be to use IPN, or atleast use IPN in conjunction with PDT.
Instant Payment Notification (IPN) is a message service that notifies you of events related to PayPal transactions. You can use it to automate back-office and administrative functions, such as fulfilling orders, tracking customers, and providing status and other information related to a transaction.
You can find more on IPN the page here. Also on that page, off to the left hand side are some more links that are useful as well. There are pages for creating a listener, setup, testing, IPN history, IPN with FMF, IPN/PDT variables, and sample code here. There are also a few more examples of sample code here as well.
PayPal’s PDT system sends order confirmations to merchant sites that use PayPal Payments Standard and lets them authenticate this information. Such sites can then display this data locally in an “order confirmation” page. IPN is more reliable than PDT, and also with PDT it is dependent on the buyer clicking a button to return to your site. If they they dont click on the button to return to your site, no information is sent back and you can not resend this information like you can with IPN. You can find more on PDT here.
I personally only use PDT for crating a dynamic thank you page on my site, and use IPN for updating my database and automating some tasks. Hope this helps. :)
SAMPLE PHP (v5.2) IPN SCRIPT
<?php
// STEP 1: Read POST data
// reading posted data from 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";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
SAMPLE PDT PHP (v5.3) SCRIPT
<?php
$pp_hostname = "www.paypal.com"; // Change to www.sandbox.paypal.com to test against sandbox
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "GX_sTf5bW3wxRfFEbgofs88nQxvMQ7nsI8m21rzNESnl_79ccFTWj2aPgQ0";
$req .= "&tx=$tx_token&at=$auth_token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$pp_hostname/cgi-bin/webscr");
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);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: $pp_hostname"));
$res = curl_exec($ch);
curl_close($ch);
if(!$res){
//HTTP ERROR
}else{
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$itemname = $keyarray['item_name'];
$amount = $keyarray['payment_gross'];
echo ("<p><h3>Thank you for your purchase!</h3></p>");
echo ("<b>Payment Details</b><br>\n");
echo ("<li>Name: $firstname $lastname</li>\n");
echo ("<li>Item: $itemname</li>\n");
echo ("<li>Amount: $amount</li>\n");
echo ("");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
?>
Your transaction has been completed, and a receipt for your purchase has been emailed to you.<br> You may log into your account at <a href='https://www.paypal.com'>www.paypal.com</a> to view details of this transaction.<br>