Paypal IPN verified problems - php

I'm experiencing some problems with my paypal ipn script:
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$header = '';
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.paypal.com\r\n";
$header .= "Connection: close\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
}
else {
fputs ($fp, $header . $req);
$response = '';
while (!feof($fp)) {
$res = fgets ($fp, 1024);
$res = trim($res);
if (strpos($res,'VERIFIED') !== false) {
}
else {
// not verified
}
}
}
if (strpos($res,'VERIFIED') !== false) is always false.
This is what $res returns:
HTTP/1.1 200 OK
Server: Apache
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=14400
Strict-Transport-Security: max-age=14400
Content-Type: text/html; charset=UTF-8
DC: slc-a-origin-www-1.paypal.com
Date: Thu, 27 Feb 2014 20:50:47 GMT
Content-Length: 8
Connection: close
Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=KVmAID_U9eq9TG0lkX119TL840BG6Xau98CeIZX3jTQTx9a4uGno9gxDJGS6VrX8CoBQnj9_n7cUnfeLjb8bD_pyJvE1_XJY5j-Sl5dVIROlu-Cn3_PmfiwL1S0RB-hCOCJzLNIzLsV7H4_xyZg7u4eCzBKTZdlfRru95teI1r2A2tFCtNcYgejjmUHfHzy4nSMco604T_4OJZX_6PvoheXYKqj8tOR_hNW_s3057XoT0wbqzwWA0YI00DZRoRocUuY77_hR6THpxJ6ZnekN3nrdsh74z4XvF39eaf2kdQLGKArjel4sFCAFtmO0NkVQs7VOM_upvhbruJQdm94oOue4UWUpx2NQMUE2JWYNgrgUaBliTrzbFgWOLFidJ1bNJoopcthU5nDUFDXDka7_JSRL44rPMWS0o0kLQIZDnfTiVqhdZsnWNT6wxH4; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Sun, 25-Feb-2024 20:50:47 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Sat, 27-Feb-2016 20:50:47 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.73.8.134.1393534247185146; path=/; expires=Sat, 20-Feb-44 20:50:47 GMT
Set-Cookie: X-PP-SILOVER=name%3DLIVE5.WEB.1%26silo_version%3D880%26app%3Dslingshot%26TIME%3D665128787; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Set-Cookie: Apache=10.73.8.46.1393534247177026; path=/; expires=Sat, 20-Feb-44 20:50:47 GMT
Set-Cookie: AKDC=slc-a-origin-www-1.paypal.com; expires=Thu, 27-Feb-2014 21:20:47 GMT; path=/; secure

A few possible things, based off a working example I'm using...
You might be running into serialization issues.
You're posting back to ssl://www.paypal.com instead of https://www.paypal.com/cgi-bin/webscr
There may be a problem with the way you're checking for verification? My example uses strcmp() instead of strpos()
// read raw POST data to prevent serialization issues w/ $_POST
$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';
foreach ($myPost as $key => $value) {
if (get_magic_quotes_gpc()) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Post IPN back to PayPal to validate the IPN data is genuine
$paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
$ch = curl_init($paypal_url);
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_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'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
// $cert = __DIR__ . "./cacert.pem";
// curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
curl_close($ch);
// Inspect IPN validation result and act accordingly
if (strcmp($res, "VERIFIED") == 0) {
// good to go...
}
References:
https://developer.paypal.com/webapps/developer/docs/classic/products/instant-payment-notification/
http://paypal.github.io/sdk/sample-apps/

Related

Paypal IPN sends invalid response after successful payment completion

First thing first,
Language: PHP
Framework: Code Igniter
This is the first time I'm implementing PayPal payment in my website so that users can pay from their PayPal accounts to the owner. Obviously.
Tutorial I followed for implementing PayPal payment is here.
And for implementing IPN listener, I used this code.
I wrote IPN listener in core php and it's a standalone file (no relation with codeigniter framework or website). A cron job makes this file run 24x7. I thought that's necessary but not quite sure. So IPN listener listens every time and whenever PayPal sends an IPN, it takes the data from POST and checks the verification. If it is verified, it write the POST data to database and log a file accordingly.
This whole things was already a mess and I think I made it worse.
My IPN listener is:
<?php
require_once 'Query.php';
define("DEBUG", 1);
define("USE_SANDBOX", 1);
define("LOG_FILE", "./ipn.log");
$raw_post_data = str_replace('=utf-8', '=UTF-8', 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';
foreach ($myPost as $key => $value)
{
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
}
curl_close($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) {
$user_id = $_POST['custom'];
$product_id = $_POST["item_number"];
$txn_id = $_POST["txn_id"];
$payment_gross = $_POST["mc_gross"];
$currency_code = $_POST["mc_currency"];
$payer_email = $_POST["payer_email"];
$payment_status = $_POST["payment_status"];
$qry2="INSERT INTO payments(user_id,product_id,txn_id,payment_gross,currency_code,payer_email,payment_status) VALUES(".$user_id.",".$product_id.",'".$txn_id."',".$payment_gross.",'".$currency_code."','".$payer_email."','".$payment_status."')" ;
setData($qry2);
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
?>
What I'm trying to say here is , if the condition if (strcmp ($res, "VERIFIED") == 0) is true, then only database write operation occurs and then I write to a log file using this error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
I checked my log file and try to do a search for Verified IPN but couldn't find anything. Here is my IPN log.
[2016-03-07 05:41 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate
[2016-03-07 05:41 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:41:03 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=WKlHKpJ3laas07Yu1WCXQPNlPGNpVTmx79in33FVjVu-1QcqQ1BKO2BLcO-ltHCgRNg4BYmHLqdIeaKPMYLdWqa1qP3eqTtCdlN-erDGl_NuifHufy7yejBynYZJS7W8xkoFUHBVW5eQocb6f3uGTwoVGpYBHeWXRejcU1o37sflJyynvgzkWMzHuvsG7pS9t19ZcqfrldHnv8pYpTXlBa4UeWbyuEVWiyuTVhBDE_UlA1L7E-Ho8J-rui0BFKqOHVsalakqcz9xP1XbyfIjb2hLrtpDDFmkqNqTs2ibxlGO-EjNhcJG1boI06ISlT4Dg0ZfGPlthPobrKZ0aS59OCOTaGOYReArBWqdDZXWq0tDwI8uIJwMaFT9w0fproQ5167v1nWS6QIZYnXmeZCO40Ss93NQW2OTeLRaKx-1e92aGSL3uxSq_YdE5Dm; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:41:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:41:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329263101875; path=/; expires=Wed, 28-Feb-46 05:41:03 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: d4da8be813fa0
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D1863638358; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
INVALID
[2016-03-07 05:41 UTC] Invalid IPN: cmd=_notify-validate
[2016-03-07 05:42 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate
[2016-03-07 05:42 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:42:02 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=f8rnnKoWpS27ajK43K_vGgiHMCbyL0kxcaLbl_qXj8X0JLk-LbcHgcR3owKzLqj_MJu_uo7CX7WOoie45aYro6IcO7wJJlXCvHm90MzDnGfwXjHYddOtovs9ZRpPcmiQ2o7Rxw6UhyVsaQ3stNXCFJ2RXouWssYRY8YTDST6VyVJWdtPzSIe24BebKqH2B1jbPOt_VJ1xhLRb_fmVpR6CB4ScN9fhgNdkyueDqEfp3o-xbT-VzHbfuTdSR3p2vvKKAVFBOs7ooDFmIylSOkxNkrBhvR2UwkGcpOo9HOBYWpqkfn2TlLBW6W1PpKSGnzY5M8TxaA-a1HtkKVMQ6TN4vyc46B7Ekps0ZLO3vtt9arFvvscgRMxOPGcQvwsGYrGHQv4Vyv_m47hrRRojf-yBdmebyhugsUKYSBjUSPiFDi5Ozg2inODpq0o0vC; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:42:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:42:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329322876295; path=/; expires=Wed, 28-Feb-46 05:42:02 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: ec94240d19c4
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D2853494102; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
INVALID
[2016-03-07 05:42 UTC] Invalid IPN: cmd=_notify-validate
[2016-03-07 05:43 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate
[2016-03-07 05:43 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:43:02 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=qFIftmj81M9XVbnGK-_ZFd_plIa-_hITqhkt7tHsSgU2hJnYg1P7b2xqdRFTOWeXIJnXWMBBwbAOFwF1azF07vQ_StCVY9SfONsm83OIv3S8WCTk9ekaXS6owbCFW4qVLtyDKxaKfNkLU576_BYmAFXULVJ3pAkLeGFUkzNC9kjY5ouHRKu3bzO7eSHrRpgQHnBQdoI6NcTHh697bQfeGAfFYpMIXDbYHEiSpaKm22v0j7hS4A_nntlaxbwrrRoZtZmTuoJdQNKF3wS26pJJkM4zYWpdY8xP21vISCk9sAAQjIOZCspps1tTjsXhDI4nYUZeJNjqG8xshBqB_lFweeqCQQC17MEivchn19F32ojFh--lfsp3cZA9YY34RBjxL1TnY-owkzw9n3qHpn-tnVP6--DgtJ-H3AqF0Q6QS3gCFam3tlNd5TEi9z0; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:43:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:43:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329382840458; path=/; expires=Wed, 28-Feb-46 05:43:02 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: 8ad4234c9398
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D3860127062; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
INVALID
[2016-03-07 05:43 UTC] Invalid IPN: cmd=_notify-validate
There's nothing like 'Verified' in it and log file has 'INVALID' in it that means
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
this function gets executed. BUT DATA IS WRITTEN INTO DATABASE ALSO.
I don't what's wrong here. Can anyone point out the mistakes? Should I take any additional security measures? Thanks. Gracias.
public function success()
{
if(isset($_GET['tx']))
{
$tx = $_GET['tx'];
$result=$this->verifyWithPayPal($tx);
// $this->load->view('success',$result);
}
}
public function verifyWithPayPal($tx)
{
// $tx = $_REQUEST['tx'];
$token = $this->config->item('authtokan');
$paypal_url = $this->config->item('posturl').'?cmd=_notify-synch&tx='. $tx.'&at='.$token;
$curl= curl_init($paypal_url);
$data=array(
"cmd"=>"_notify-synch",
"tx"=>$tx,
"at"=>$token
);
$data_string=json_encode($data);
curl_setopt($curl,CURLOPT_HEADER, 0);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$headers= array(
'Content-Type:application/x-www-form-urlencoded',
'Host: www.sandbox.paypal.com',
'Connection: close'
);
curl_setopt($curl,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
$response= curl_exec($curl);
$lines= explode("\n", $response);
$keyarray = array();
if(strcmp($lines[0],"SUCCESS")==0){
for($i=1;$i<count($lines)-1; $i++){
list($key,$val)=explode("=",$lines[$i]);
$keyarray[urldecode($key)]=urldecode($val);
}
$this->getListProducts($keyarray);
}
}
public function getListProducts($result)
{
$i=1;
$data = array();
// echo "<pre>";
// print_r($result);
// echo "</pre>";
foreach($result as $key => $value)
{
if(0===strpos($key,'item_number')){
$product = array(
'first_name' => $result['first_name'],
'last_name' => $result['last_name'],
'receiver_email' => $result['receiver_email'],
'txn_type' => $result['txn_type'],
'txn_id' => $result['txn_id'],
'payment_date' => $result['payment_date'],
'payer_id' => $result['payer_id'],
'payer_email' => $result['payer_email'],
'address_street' => $result['address_street'],
'address_zip' => $result['address_zip'],
'address_status' => $result['address_status'],
'address_country_code' => $result['address_country_code'],
'address_name' => $result['address_name'],
'address_country' => $result['address_country'],
'address_city' => $result['address_city'],
'address_state' => $result['address_state'],
'receiver_id' => $result['receiver_id'],
'receiver_email' => $result['receiver_email'],
'item_number' => $result['item_number1'],
'item_name' => $result['item_name1'],
'quantity' => $result['quantity1'],
'mc_currency' => $result['mc_currency'],
'mc_fee' => $result['mc_fee'],
'mc_gross' => $result['mc_gross_1'],
'payment_gross' => $result['payment_gross']
);
$this->load->model('mdl_order');
$this->mdl_order->insert_record($product);
// echo "alert<script>successfully Transaction</script>";
if(isset($product)){
//echo 'hello';
$time=$this->session->userdata('last_time');
// echo $time;
//$data=array( $time=$this->session->userdata('last_time'));
$this->load->model('mdl_order');
$this->mdl_order->update($time);
echo "success update";
}
// redirect('manage_order');
$this->load->view('success',$product);
}
}
return $data;
}

Paypal IPN does not respond, only "Connection Close"

I'm developing an IPN response page but seems there're some problem:
I receive correctly Paypal post data, when I send data do get confirm, Paypal does not respond!
here's my PHP code:
$paypal_url = "www.sandbox.paypal.com";
$url = "https://" . $paypal_url . "/cgi-bin/webscr";
$req = 'cmd=_notify-validate'; // Add 'cmd=_notify-validate' to beginning of the acknowledgement
foreach ($_POST as $key => $value)
{ // Loop through the notification NV pairs
$value = urlencode(stripslashes($value)); // Encode these values
$req .= "&$key=$value"; // Add the NV pairs to the acknowledgement
}
$header =
"POST /cgi-bin/webscr HTTP/1.0\r\n" .
"Host: www.sandbox.paypal.com\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
fputs($fp, $header . $req."\r\n\r\n");
$counter = 0;
while (!feof($fp))
{
$res = $res . fgets($fp, 1024);
$counter++;
if($counter > 10)break;
}
fclose($fp);
$tfile=fopen("text.txt","a+");
fwrite($tfile,$req . "\r\n");
fwrite($tfile,$res . "\r\n");
fclose($tfile);
On my text.txt test file :
cmd=_notify- validate&mc_gross=0.02&protection_eligibility=Eligible&address_status=unconfirmed&item_number1=&payer_id=M4DXNVMDFB8TY&tax=0.00&address_street=Gandhi+5%0D%0ABO&payment_date=01%3A05%3A50+Feb+19%2C+2016+PST&payment_status=Completed&charset=windows-1252&address_zip=40069&mc_shipping=0.00&mc_handling=0.00&first_name=test&mc_fee=0.02&address_country_code=IT&address_name=test+facilitator&notify_version=3.8&custom=56&payer_status=verified&business=andreafilippini90%40gmail.com&address_country=Italy&num_cart_items=1&mc_handling1=0.00&address_city=Zola+Predosa&verify_sign=AAllE9FA13ABhVwJYLWEzvptA49cACmRumx.SAuIktyCdTEuwgwrBDOF&payer_email=andreafilippini90-facilitator%40gmail.com&mc_shipping1=0.00&tax1=0.00&txn_id=2XL26853PJ6650947&payment_type=instant&payer_business_name=test+facilitator%27s+Test+Store&last_name=facilitator&address_state=&item_name1=lol&receiver_email=andreafilippini90%40gmail.com&payment_fee=&quantity1=1&receiver_id=36AE5DEXKKHSY&txn_type=cart&mc_gross_1=0.02&mc_currency=EUR&residence_country=IT&test_ipn=1&transaction_subject=&payment_gross=&ipn_track_id=436b4ca66c696
HTTP/1.1 200 OK
Date: Fri, 19 Feb 2016 09:05:59 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=B2WFzbH6YM2Qyocy2U8eFnZLXwNKbE5H6baCy7qZWiquQveA1SY6UXyZGdfVwZhcRZgDRdhebwuzWFRSDj-JjwIGDp30AX8j3Ps5vhehIHBj7BlRSHWnIDfGq1pdF2_4Ffl6U9PpApn2XMxLLOHKuaJ3avnkqrE7ZZBw9dqp1RtWr6t60ZSDuSrek2zMtn08YXZ7thh1wF88X-1wqF1u3e6pDEZKeDuUOvSxut-QuRsEwIcNSJmDkmbdqAUYASBlgTNG1TolLzQgt3FbOVOI-zXfyu1uDk9BWlgAYpxL_XL00vjCVaX6iYkdC98OXbfhj2mnJvlWxFjbPiDjCKamWlD84U_EeV7GhjUbN5qns_F5OSMbXBm0erybHvlGMTCIJ53-j8FSw68imXw6WkM6Fzl_bq67Zle08eDb3mhLuzekpw_Xg-CpL5TMZne; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Mon, 16-Feb-2026 09:06:00 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Sun, 18-Feb-2018 09:06:00 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1455872759947539; path=/; expires=Sun, 11-Feb-46 09:05:59 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
Any idea??
Why it does not respond?
Thank you.
This is the Verify Request step with IPN so you're getting the data that PayPal has POSTed to your IPN script and sending it back to PayPal to verify it; this step does fail occasionally btw even if everything is correct so you have to prepare to handle that.
You can do this with a cURL call that looks like:
//Sandbox URL
$sURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
//QueryString
$sQueryString = "cmd=_notify-validate";
foreach($_POST as $sPostKey => $sPostData) { $sQueryString .= "&{$sPostKey}={$sPostData}"; }
//Open the cURL session
$hCurl = curl_init();
//set cURL options
curl_setopt($hCurl, CURLOPT_URL, $sURL); //URI
curl_setopt($hCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); //HTTP version
curl_setopt($hCurl, CURLOPT_HEADER, 0); //no HTTP headers
curl_setopt($hCurl, CURLOPT_POST, 1); //REQUEST => POST
curl_setopt($hCurl, CURLOPT_POSTFIELDS, $sQueryString); //POST data
curl_setopt($hCurl, CURLOPT_RETURNTRANSFER, 1); //return raw data to script rather than browser
curl_setopt($hCurl, CURLOPT_TIMEOUT, 60); //set timeout
curl_setopt($hCurl, CURLOPT_FORBID_REUSE, 1);
curl_setopt($hCurl, CURLOPT_HTTPHEADER, array('Connection: Close'));
//ensure that cURL is using the server IP address
curl_setopt($hCurl, CURLOPT_INTERFACE, $_SERVER['SERVER_ADDR']);
//The next two lines must be present for the kit to work with newer version of cURL
//You should remove them if you have any problems in earlier versions of cURL
curl_setopt($hCurl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($hCurl, CURLOPT_SSL_VERIFYHOST, 2);
//post and retrieve the response
$sRawResponse = trim(curl_exec($hCurl));
//throw Exceptions if cURL failed
if(curl_error($hCurl)) { throw new Exception(curl_error($hCurl), E_USER_ERROR); }
if(!$sRawResponse) { throw new Exception("No response from PayPal - cURL possibly failed"); }
//close the cURL handle
curl_close($hCurl);
At the end of which you should have the response back from PayPal stored in the $sRawResponse variable which, if everything has gone according to plan, should simply have the word VERIFIED in it.

paypal ipn always invalid

Paypal ipn always return invalid
Hi everyone, i'm stuck with this problem from a week. What I'm trying to do is to pass a variable in php containing all the data of a pdf via paypal button in order to be processed on my page later. So here's my code generated by paypal where i've added notify_url and custom variable.
<form action="https://www.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="AEJ7FLWRMAK44">
<input type="hidden" name="notify_url" value="http://mysite.it/ipn_listener.php">
<input type="hidden" name="custom" value="<?php $base; ?>">
<input type="image" src="https://www.paypalobjects.com/it_IT/IT/i/btn/btn_buynow_SM.gif" border="0" name="submit" alt="PayPal รจ il metodo rapido e sicuro per pagare e farsi pagare online.">
<img alt="" border="0" src="https://www.paypalobjects.com/it_IT/i/scr/pixel.gif" width="1" height="1">
</form>
The variable $base contains all the data of the PDF created in this page,i need to pass them through paypal form.
And here the code of the listener(Directly from paypal).
<?php
require('fpdf.php');
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 0);
define("LOG_FILE", "./ipn.log");
// 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
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
//$cert = __DIR__ . "./cacert.pem";
//curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
}
echo $res;
// 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) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your PayPal email
// check that payment_amount/payment_currency are correct
// process payment and mark item as paid.
// 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'];
$plan = $_POST ['$custom'];
$plan -> Output('filename.pdf','D');
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
?>
and this is the log that result after pay:
[2015-12-13 13:06 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate
[2015-12-13 13:06 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Server: Apache
X-Frame-Options: SAMEORIGIN
Paypal-Debug-Id: 3c9689e4c464d
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=UTF-8
DC: dcg11-origin-www-2.paypal.com
Date: Sun, 13 Dec 2015 13:06:48 GMT
Content-Length: 7
Connection: close
Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=h1DUElHT0plodZm1lFPnTdqF1LiGzLoXG7dYHHRSRG9RL2cia6MdmQ6MahF1Zv2nJHPi_OHvGTI9k7icIO_xteZXVKW6_1Eanm2OzV6EUhqfCx5RaJVVZ0k6kREma-fge47I2jdAUVmGU3WkpxycLClRTtW4yxG7Upafo701Ey7HFKhzN9Q9h0FlegIaInROJAbI6it8h-Mvg-2rOIsVPBRkIJ132Jmyg0Yg0-Gi0_gQjnixauCWZ8J3yrCA_--4FroiKAAF5oRfqVPwGs9nmUOMA7nPwgSf0HHZQ6uCJ7LSUkfU3ezY77NrNaLnnEpZQ59MNutMaQeR5Blt3aAKCVQdOKicNO7ilgSho4_MygvMVCsUxcDhmlFaGE5KmkkYHdRW7MpIXivjpwSf987gDNope3f8dyq06XXnMeBMiCNhpKlh5BclrWcI7Cm; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Wed, 10-Dec-2025 13:06:48 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Tue, 12-Dec-2017 13:06:48 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=name%3DLIVE9.WEB.1%26silo_version%3D880%26app%3Dappdispatcher%26TIME%3D1735224662; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Set-Cookie: Apache=10.16.1.3.1450012007804246; path=/; expires=Tue, 05-Dec-45 13:06:47 GMT
Set-Cookie: AKDC=dcg11-origin-www-2.paypal.com; expires=Sun, 13-Dec-2015 13:36:48 GMT; path=/; secure
Strict-Transport-Security: max-age=63072000
INVALID
[2015-12-13 13:06 UTC] Invalid IPN: cmd=_notify-validate
I've activated IPN in my paypal account but i've always return invalid, also by deleting the piece of code that sends and receives the variable custom the result does not change. Can somebody help me? this problem is giving me a headache for a week. Thanks in advance to all for answers.

Paypal IPN working but returns error status 500

I'm having trouble with Paypal IPN. I'm using the IPN script from github:
Script link
This is the php code for the script:
<?php
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 0);
define("LOG_FILE", "./ipn.log");
// 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
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
//$cert = __DIR__ . "./cacert.pem";
//curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
}
curl_close($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) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your PayPal email
// check that payment_amount/payment_currency are correct
// process payment and mark item as paid.
// 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'];
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
?>
...with my post-processing code being after the verifiy check
if (strcmp ($res, "VERIFIED") == 0) {
When someone pays via Paypal, everything seems to work in terms of my site receiving the IPN data and processing it. However, when I check the IPN logs in Paypal it has a status code of 500 (internal server error) and keeps resending the IPN data.
I have no idea why this is happening. This same IPN script (or close variations) are all over the net so I presume the script is fine.
Here is the log file recorded by the script:
[2015-08-15 13:31 Europe/London] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.paypal.com
Accept: */*
Connection: Close
Content-Length: 1014
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate&mc_gross=4.95&protection_eligibility=Eligible&address_status=unconfirmed&payer_id=--------&tax=0.00&address_street=------&payment_date=05%3A25%3A51+Aug+15%2C+2015+PDT&payment_status=Completed&charset=windows-1252&address_zip=------&first_name=-----&mc_fee=0.27&address_country_code=ES&address_name=-----&notify_version=3.8&custom=&payer_status=verified&business=--------&address_country=Spain&address_city=-------&quantity=1&verify_sign=AEWexEu2HAXvtIxtV.FjJ4XDJIdfA8MGuWBu9unU4dGBd7qVw2YL2a0p&payer_email=--------&txn_id=-------&payment_type=instant&payer_business_name=------&last_name=W----&address_state=------&receiver_email=--------&payment_fee=&receiver_id=-------&txn_type=web_accept&item_name=---------&mc_currency=GBP&item_number=------&residence_country=GB&handling_amount=0.00&transaction_subject=&payment_gross=&shipping=0.00&ipn_track_id=--------
[2015-08-15 13:31 Europe/London] HTTP response of validation request: HTTP/1.1 200 OK
Server: Apache
X-Frame-Options: SAMEORIGIN
Paypal-Debug-Id: 85e8fa12ae5b4
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=UTF-8
DC: slc-origin-www.paypal.com
Date: Sat, 15 Aug 2015 12:31:22 GMT
Content-Length: 8
Connection: close
Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=GsUqRUQy6PV-FIg6NZNaoWTmld6up9P1KKqndXexz_jj_zeAZ4x0Kn30L4uIpy__dU4bnuACyaC89S34gzVIGmA2RmA8EBSoiH6oFumGT1YG-PxlbiMrDzyyNIjAnfFEJ0XPZmwovk7hutZlJannbvBOGibCAawKZ3rpqkphLxNrDZR-AZa0OAwjsUNEJtcy8gxroi8dbImfynYwQxhP_tTP1422-p2gLl8hxdhVqzO1PgDbCALd3kqfM67UCXZ0TVNpr5Pi84KsVZkZ1X00PblzKmbsFJ8vS7wbmocXEJveA6o1mPllq-qKO9MOEppBM0IxMS8rbwafRFDBzkFepW_gsNCkQPAATYNkLS6PTiBYMzL5-VV4ku_b4xTAsT_q4cotE5q4d-hqH1sE4fkdbql8HGCNwIiq2RpYrsI00nmMDrkGmZbHMV02BMG; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Tue, 12-Aug-2025 12:31:22 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Mon, 14-Aug-2017 12:31:22 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.16.0.147.1439641881720232; path=/; expires=Mon, 07-Aug-45 12:31:21 GMT
Set-Cookie: X-PP-SILOVER=name%3DLIVE9.WEB.1%26silo_version%3D880%26app%3Dappdispatcher%26TIME%3D422694741; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Set-Cookie: Apache=10.16.0.206.1439641881713999; path=/; expires=Mon, 07-Aug-45 12:31:21 GMT
Set-Cookie: AKDC=slc-origin-www.paypal.com; expires=Sat, 15-Aug-2015 13:01:22 GMT; path=/; secure
Strict-Transport-Security: max-age=63072000
VERIFIED
Does anyone know why I could be getting this 500 error?
I've searched the net for a solution but can't find out what's wrong.
Thanks
Try to put a "/" at the end of the url.
Example:
The URL http:///paypal/notify gives the error status 500 but the URL http:///paypal/notify/ works fine.

PayPal IPN Sandbox not working but simulator does

UPDATE #1: I've located the problem, when I use the simulator the $res variable has the string 'VERIFIED' as it should be, since it's being exploded from the headers, however it doesn't seem to be the case when I use the sandbox, the headers stay in that variable. What can I do?
I've used the IPN php code provided by PayPal to make a payment (which depends on the product you choose) in my website. If I use the IPN simulator it works correctly, and posts the log fine, however when using the sandbox accounts (I enabled IPN on my seller account), it doesn't log after the word VERIFIED, see here, the first is the sandbox test, the other is the simulator test
[2013-11-21 14:52 Europe/Rome] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 1057
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
for IPN payload: cmd=_notify-validate&mc_gross=244.00&protection_eligibility=Eligible&address_status=unconfirmed&payer_id=SJQRWD9JWG3WQ&tax=44.00&address_street=Via+Unit%1A+d%27Italia%2C+5783296&payment_date=05%3A52%3A43+Nov+21%2C+2013+PST&payment_status=Completed&charset=windows-1252&address_zip=80127&first_name=Spazioagenti&mc_fee=8.65&address_country_code=IT&address_name=Spazioagenti+Buyer&notify_version=3.7&custom=3%7C14%7C2%7C10%7C244%7C7&payer_status=verified&business=seller%40spazioagenti.it&address_country=Italy&address_city=Napoli&quantity=10&verify_sign=AYoLATaZgB5cTatNJOgByicud-f2AZq2KG1cXXct8eRGc2LKOUoshqub&payer_email=buyer%40spazioagenti.it&txn_id=2LL473335A169684V&payment_type=instant&last_name=Buyer&address_state=Napoli&receiver_email=seller%40spazioagenti.it&payment_fee=&receiver_id=2N8MTA3G7BX2W&txn_type=web_accept&item_name=Pacchetto+Appuntamenti+per+Sorgenia&mc_currency=EUR&item_number=&residence_country=IT&test_ipn=1&handling_amount=0.00&transaction_subject=3%7C14%7C2%7C10%7C244%7C7&payment_gross=&shipping=0.00&ipn_track_id=d05cb7a39bc8d
[2013-11-21 14:52 Europe/Rome] HTTP response of validation request: HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Thu, 21 Nov 2013 13:52:48 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=Gsyvkagbs7ElOYK0w0MSz-85N_LQTZUfWbDB5VEBBGSXea41hUfW8kgqvr3S64gHZtDYnHKAAnxhtUudwDEoAKfy_qcwPREwYFGlKypB27oMLdN0IX5Z8kuy9guw7vyR2dJVEuDwAtCRyivAANNzi_pB_b6GCdtDpqmefesbBv1XKrJc_HR675wuSqn7ECOeREJBn-P8Q5OrTCSYlsz62eE9oFM0gsVXWRGr3rX1DR_rlk-Z9OmIGRbScwwYPY6qm6oj-3IEtyZBltdvuH3PZdeRA0BCf46x773bJOgg_D50XwRzCSDo8hCVLPZRKDjrgVYjnd69TrELucb97rYChCPHuErWVO-9_RZNJQSvIIZp7cSSeCg9ktVthqYfbrgeBLmefARnHdcR0wqjjPlyp1GWJXL2pgseS87dtyZ2DdVKJfKaa2KRBFvmSoi; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Sun, 19-Nov-2023 13:52:48 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Sat, 21-Nov-2015 13:52:48 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.109.11.1385041968439630; path=/; expires=Sat, 14-Nov-43 13:52:48 GMT
Connection: close
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D880%26app%3Dslingshot%26TIME%3D806391378; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Set-Cookie: Apache=10.72.128.11.1385041968427891; path=/; expires=Sat, 14-Nov-43 13:52:48 GMT
Vary: Accept-Encoding
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
VERIFIED
-----------------------------------------------------------------------------------------------------------------------------
[2013-11-21 15:03 Europe/Rome] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 852
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate&residence_country=US&invoice=abc1234&address_city=San+Jose&first_name=John&payer_id=TESTBUYERID01&shipping=3.04&mc_fee=0.44&txn_id=369761703&receiver_email=seller%40paypalsandbox.com&quantity=1&custom=xyz123&payment_date=05%3A53%3A46+21+Nov+2013+PST&address_country_code=US&address_zip=95131&tax=2.02&item_name=something&address_name=John+Smith&last_name=Smith&receiver_id=seller%40paypalsandbox.com&item_number=AK-1234&verify_sign=An5ns1Kso7MWUdW4ErQKJJJ4qi4-AdDhuqhHs5YWS2Bd.yigopmmBy7J&address_country=United+States&payment_status=Completed&address_status=confirmed&business=seller%40paypalsandbox.com&payer_email=buyer%40paypalsandbox.com&notify_version=2.1&txn_type=web_accept&test_ipn=1&payer_status=verified&mc_currency=USD&mc_gross=12.34&address_state=CA&mc_gross1=9.34&payment_type=instant&address_street=123%2C+any+street
[2013-11-21 15:03 Europe/Rome] HTTP response of validation request: HTTP/1.1 200 OK
Date: Thu, 21 Nov 2013 14:03:33 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=KR7iqlBBbqQKnRabL5TJ6Dnbg5xydQBOGeaPIRc-ShkauU79QmQF20HOui5yoQz2r3lXcrzoTn22w10461k6VaYZ1j8cP-Ps-GqlxqppLmaQfclCczIrDOLku7ewLjaSnETDJ4-zd3VLXpTT6Vv_FJeaBpNZkpAFO4yq6gCL48D40CcaOPEkBB7l-ZrW_6vKsByKiV2ocW5EMS-Zl1TqmNBGAFRh5WeWspN772rwHQJdBsUM4CljSWyM2e2H0Jzr3tpNJb9OMaq7BQcefNBc5jSWqLL_-GUpZ6BgtXL2urDFNjB3BuetscxsqwwR8cSX6wuY4gZRJ4-pE0vf-x_o6Ao4Sz-A9FgVM_gl5LO0RrJoYYj4yPzHncig0cwgBRF-_GB3S6sznJVnIkQMifoGuEIOkVisXl1jKMatG7YI3H8t5cqXyyqOYVxLp-y; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Sun, 19-Nov-2023 14:03:33 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Sat, 21-Nov-2015 14:03:33 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.109.11.1385042613169322; path=/; expires=Sat, 14-Nov-43 14:03:33 GMT
Connection: close
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D880%26app%3Dslingshot%26TIME%3D3037892178; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Set-Cookie: Apache=10.72.128.11.1385042613160303; path=/; expires=Sat, 14-Nov-43 14:03:33 GMT
Vary: Accept-Encoding
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
VERIFIED
[2013-11-21 15:03 Europe/Rome] POST DATA: Array
(
[residence_country] => US
[invoice] => abc1234
[address_city] => San Jose
[first_name] => John
[payer_id] => TESTBUYERID01
[shipping] => 3.04
[mc_fee] => 0.44
[txn_id] => 369761703
[receiver_email] => seller#paypalsandbox.com
[quantity] => 1
[custom] => xyz123
[payment_date] => 05:53:46 21 Nov 2013 PST
[address_country_code] => US
[address_zip] => 95131
[tax] => 2.02
[item_name] => something
[address_name] => John Smith
[last_name] => Smith
[receiver_id] => seller#paypalsandbox.com
[item_number] => AK-1234
[verify_sign] => An5ns1Kso7MWUdW4ErQKJJJ4qi4-AdDhuqhHs5YWS2Bd.yigopmmBy7J
[address_country] => United States
[payment_status] => Completed
[address_status] => confirmed
[business] => seller#paypalsandbox.com
[payer_email] => buyer#paypalsandbox.com
[notify_version] => 2.1
[txn_type] => web_accept
[test_ipn] => 1
[payer_status] => verified
[mc_currency] => USD
[mc_gross] => 12.34
[address_state] => CA
[mc_gross1] => 9.34
[payment_type] => instant
[address_street] => 123, any street
)
[2013-11-21 15:03 Europe/Rome] Verified IPN: cmd=_notify-validate&residence_country=US&invoice=abc1234&address_city=San+Jose&first_name=John&payer_id=TESTBUYERID01&shipping=3.04&mc_fee=0.44&txn_id=369761703&receiver_email=seller%40paypalsandbox.com&quantity=1&custom=xyz123&payment_date=05%3A53%3A46+21+Nov+2013+PST&address_country_code=US&address_zip=95131&tax=2.02&item_name=something&address_name=John+Smith&last_name=Smith&receiver_id=seller%40paypalsandbox.com&item_number=AK-1234&verify_sign=An5ns1Kso7MWUdW4ErQKJJJ4qi4-AdDhuqhHs5YWS2Bd.yigopmmBy7J&address_country=United+States&payment_status=Completed&address_status=confirmed&business=seller%40paypalsandbox.com&payer_email=buyer%40paypalsandbox.com&notify_version=2.1&txn_type=web_accept&test_ipn=1&payer_status=verified&mc_currency=USD&mc_gross=12.34&address_state=CA&mc_gross1=9.34&payment_type=instant&address_street=123%2C+any+street
The code I'm using for the IPN listener is this:
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 1);
define("LOG_FILE", "./ipn.log");
// 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
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
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_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
//$cert = __DIR__ . "./cacert.pem";
//curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
// Split response headers and payload
list($headers, $res) = explode("\r\n\r\n", $res, 2);
}
curl_close($ch);
}
// Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
error_log(date('[Y-m-d H:i e] '). "POST DATA: ". print_r($_POST, true) . PHP_EOL, 3, LOG_FILE);
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your PayPal email
// check that payment_amount/payment_currency are correct
// process payment and mark item as paid.
// 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'];
if(DEBUG == true) {
mail('anooxy#gmail.com', 'Verified IPN', 'verified');
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
mail('anooxy#gmail.com', 'Invalid IPN', 'not verified');
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
I'm assuming there's something wrong with my form? I added everything as suggested by PayPal Javascript buttons
Here's my buy no button form HTML code:
<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr" class="paypal-button" target="_top">
<input type="hidden" name="button" value="buynow">
<input type="hidden" name="item_name" value="Pacchetto Appuntamenti per Sorgenia">
<input type="hidden" name="amount" value="20">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="quantity" value="10">
<input type="hidden" name="tax_rate" value="22">
<input type="hidden" name="lc" value="IT">
<input type="hidden" name="env" value="www.sandbox">
<input type="hidden" name="return" value="http://test.xxxxx.it/utente/storicoordini">
<input type="hidden" name="notify_url" value="http://test.xxxxx.it/utente/ipn">
<input type="hidden" name="custom" value="3|14|2|10|244|7">
<input type="hidden" name="rm" value="2"><input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="2N8MTA3G7BX2W">
<input type="hidden" name="bn" value="JavaScriptButton_buynow">
<button type="submit" class="paypal-button large">Buy Now</button>
</form>
You're only splitting out the headers IF debug is on. Perhaps that's the problem. I'm not sure why you bother to pull out the headers as the response is going to be exactly the same plus VERIFIED (or not). I just match against the entire response.
if (preg_match("!(VERIFIED)\s*\Z!",$res))
{ /*payment verified, handle */ }
else
{ /* boo fake payment OR paypal is having problems */ }

Categories