IPN Listener di Paypal, non riesco a registrare utente nel mio DB

gandalf1959

Utente Attivo
21 Nov 2013
208
1
18
Buongiorno a tutti.
Sto cercando di impostare un sistema di pagamento immediato nel sito della nostra scuola di cucina e ho impostato un bottone "paga adesso" nella sandbox di Paypal.
Il bottone si trova su una pagina che contiene l'elenco dei corsi e che viene generata ogni volta effettuando una query sul database.
A fianco di ogni lezione appare il bottone in questione, che è fatto così:
HTML:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
       <input type="hidden" name="cmd" value="_xclick">
       <input type="hidden" name="currency_code" value="EUR" />
       <input type="hidden" name="lc" value="IT" />
       <input type="hidden" name="item_name" value="Corso <?php echo $titolo; ?> a teatro7 | Lab" />
       <input type="hidden" name="amount" value="<?php echo $euro; ?>" />
       <input type="hidden" name="business" value="[email protected]" />
       
      <input type="submit" value="PAGA ADESSO" />
L'importo viene correttamente passato a Paypal e il pagamento e la ricezione dello stesso risultano correttamente nei due account del compratore e del venditore.
A questo punto ho impostato un listener (listener_t7.php) partendo dall'esempio presente nella documentazione di Paypal. Ho pensato di fare così perchè è la prima volta che affronto l'argomento e mi sembrava più semplice partire da un esempio predisposto.
Naturalmente l'ho personalizzato con i miei dati e ho seguito le istruzioni inserite nei commenti del file stesso, ma evidentemente non ho capito bene qualcosa. Siccome è un paio di giorni che sto cercando di capire dove sbaglio e non ne vengo a capo, sono qui a chiedere aiuto.
Di seguito il codice del listener:
PHP:
<?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", 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);
		}
		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
	if (trim($_POST['payment_status')] === "COMPLETED") {
		$pagamento = 1;
	}
	// check that txn_id has not been previously processed
	include 'dati_db.php';
	$query = "SELECT idTransazione FROM utentiscuola";
	$result = $conn->query($query);
	if ($result->num_rows > 0) {$transazione=1;}
	$conn->close();
	// check that receiver_email is your PayPal email
	if(USE_SANDBOX == true) {
		$mail = "[email protected]";
	} else {
		$mail = "[email protected]";
	}
	if (trim($_POST['receiver_email']) === $mail) {
		$mailricevente = 1;
	}
	// check that payment_amount/payment_currency are correct

	// process payment and mark item as paid.

	// assign posted variables to local variables
	$nomecliente = $_POST['first_name'];
	$cognomecliente = $_POST['last_name'];
	$payment_status = $_POST['payment_status'];
	$payment_amount = $_POST['mc_gross'];
	$txn_id = $_POST['txn_id'];
	$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);
	}
}

// Adesso inserisco i dati nel DB

function getRandPassword()
        {
            $pwd = "";
            for($i = 0;$i < 10; $i++)
            {
                $chr = rand(40,126);
                $pwd .= chr($chr);
            }
            return $pwd;
        }

        $password = $this->getRandPassword();
        $md5password = md5($password);

include 'dat_db.php';
		$sql = "INSERT INTO utentiscuola
                VALUES ('', '$nomecliente','$cognomecliente','$payer_email','$payer_email','$md5password','$txn_id')";
        $conn->close();

?>
Come posso capire se il codice viene eseguito ed eventualmente dove si interrompe la cosa? E come mai non mi inserisce nessun dato nel db?

Grazie per tutto l'aiuto che potrete darmi a capire.
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
per far il debug di uno script php è utile la funzione var_dump(variabile) da mettere dove ti serve e poi togliere o commentare dopo il debug, ti faccio
PHP:
<?php
//vario codice php
var_dump($pinco);
//ecc...
?>
il var_dump ti restituisce il tipo e valore, se es. non esiste ti riporta NULL
poi per l'inserimento, immagino che tu ti rifirisca alla fine dello script, mi sembra che tu utilizzi le funzioni mysqli, vedo la querystringa ma non la funzione di inserimento
PHP:
<?php
//...
$sql = "INSERT INTO utentiscuola
                VALUES ('', '$nomecliente','$cognomecliente','$payer_email','$payer_email','$md5password','$txn_id')";
/*manca la funzione di inserimento
che se usi il medodo procedurale dovrebbe essere
$ris=mysqli_query($conn,$sql);
o ad oggetti
$ris = $conn->query($sql); 
*/      
$conn->close();
?>
 

gandalf1959

Utente Attivo
21 Nov 2013
208
1
18
grazie,
intanto c'era anche un altro piccolo errore di parentesi, uno di battitura e mancava appunto la funzione di inserimento.
Ho corretto, ma il db resta vuoto.
Probabilmente non arriva alla fine dello script.
Adesso riscrivo tutto per conto mio (sulla pagina di Paypal ci sono pezzi di codice che non capisco benissimo) cercando di semplificare al massimo il procedimento, poi ci risentiamo.
A presto
 

gandalf1959

Utente Attivo
21 Nov 2013
208
1
18
Scusa un'altra cosa, riguardo il var_dump (e la mia ignoranza);
il listener non manda niente a video, quindi se anche rilevo la presenza di una variabile in un determinato punto dello script, come faccio a verificarlo? Mi devo mandare una mail?
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
con pazienza parti dalla prima
PHP:
<?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", 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');
var_dump($raw_post_data);
//eccetera.......
?>
guardi se ti restituisce qualcosa e se quel qualcosa è quello che deve essere, o qualcosa che non c'entra o NULL
se quello che ti restituisce è giusto, commenti la riga e passi alla seconda
da quelle che capisco dovrebbe restiturti qualcosa del genere
STRING (345) "quello che c'è nella stringa"
//(345) o altro lunghezza della stinga
se non OK l'errore avviene prima, forse nella pagiana che la chiama
PHP:
<?php
//.........
// issues with array data in POST. Reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
//var_dump($raw_post_data);
$raw_post_array = explode('&', $raw_post_data); 
var_dump($raw_post_array);//questo è meglio scriverlo così var_dump('<pre>',$a,'</pre>'); altrimenti tutto su una riga
//eccetera.......
?>
e qui qualcosa del genere
array(4) {
[0]=>
string(5) "pinco"
[1]=>
string(1) "1"
[2]=>
int(1)
[3]=>
float(4.3)
}
o int se l'elemento è un intero,float se un numero e tra parentesi quello che contiene l'elemento dell'array
e avanti cos' sino a quando non scopri l'inghippo
 

gandalf1959

Utente Attivo
21 Nov 2013
208
1
18
Cio,
non c'e' verso, non riesco a scrivere sul db e non riesco a capire dove si pianta la procedura del lettore IPN, che ho riscritto semplificandolo al massimo.
Provo a postare il codice delle due pagine coinvolte:
La prima e' dat_db_php e contiene i dati per la connessione al db (ho solo oscurato la password...):
PHP:
<?php
session_start();


// Connessione al db
mysql_connect('hostingmysql238.register.it','RG6819_gandalf','xxxxxxxx');
mysql_select_db('teatro7_com_catering');

?>

La seconda è il listener vero e proprio:
PHP:
<?php
require 'dati_db.php';

$prezzo_ok = $_SESSION['prezzo_lezione'];

function getRandPassword()
        {
            $pwd = "";
            for($i = 0;$i < 10; $i++)
            {
                $chr = rand(40,126);
                $pwd .= chr($chr);
            }
            return $pwd;
        }

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';


foreach ($_POST as $key => $value) {
	$value = urlencode(stripslashes($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

$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Lenght: " .strlen($req) . "\r\n\r\n";
$fp = fsockopen('ssl://https://www.sandbox.paypal.com/cgi-bin/webscr', 443, $errno, $errstr, 30);


	$nome_cliente = $_POST['first_name'];
	$cognome_cliente = $_POST['last_name'];
	$stato_pagamento = $_POST['payment_status'];
	$importo = $_POST['mc_gross'];
	$valuta = $_POST['mc_currency'];
	$transazione = $_POST['txn_id'];
	$miamail = $_POST['receiver_email'];
	$mail_cliente = $_POST['payer_email'];
	$id_lezione = mysql_real_escape_string((int)$_POST['custom')];

if(!$fp) {
	$subject = "$add Problema IPN";
    $message = "Si è verificato un problema nella seguente transazione:\r\n\r\n";
    $message .= "Nome: " . $nome_cliente . ' ' . $cognome_cliente . "\r\n";
    $message .= "email: " . $mail_cliente . "\r\n";
    $message .= "id transazione: " . $transazione . "\r\n";
    $message .= "oggetto: " . $_POST['transaction_subject'];

	mail("[email protected]",$subject,$message,"From: " . NO_REPLY);

} else {
	fputs ($fp, $header . $req);
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);
		if (strcmp($res, "VERIFIED") == 0){

			if ($stato_pagamento=='Completed') {

				$txn_id_check = mysql_query("SELECT 'idTransazione' FROM 'utentiscuola' WHERE 'idTransazione'='".$transazione."'");
				if (mysql_num_rows($txn_id_check) !=1) {
					if ($miamail=='[email protected]') {
						if ($importo==$prezzo_ok && $valuta=='EUR') {

							//recupero la psw generata in precedenza e la codifico
							$password = $this->getRandPassword();
        					$md5password = md5($password);


							//aggiungo utente e transazione al db
							$aggiungi_query = mysql_query("INSERT INTO 'utentiscuola' VALUES ('','$nome_cliente','$cognome_cliente','$mail_cliente','$mail_cliente','$md5password','$transazione')");

						}
					}
				}

			}


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

			$subject = "$add Problema IPN";
    		$message = "Si è verificato un problema nella seguente transazione:\r\n\r\n";
    		$message .= "Nome: " . $nome_cliente . ' ' . $cognome_cliente . "\r\n";
    		$message .= "email: " . $mail_cliente . "\r\n";
    		$message .= "id transazione: " . $transazione . "\r\n";
    		$message .= "oggetto: " . $_POST['transaction_subject'];

        	mail("[email protected]",$subject,$message,"From: " . NO_REPLY);

		}
	}
	fclose($fp);
}





?>

Perchè non funziona????
Ufffffff
Se qualcuno riesce a darmi una dritta mi salva du un prossimo esaurimento... :)
Grazie
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
non posso provarla quindi sto andando un po' per tentativi
prova a modificare la query
PHP:
<?php
$aggiungi_query = mysql_query("INSERT INTO 'utentiscuola' VALUES ('','$nome_cliente','$cognome_cliente','$mail_cliente','$mail_cliente','$md5password','$transazione')");
?>
in questo modo (guarda che ho messo i nomi dei campi a caso)
PHP:
<?php
$aggiungi_query = mysql_query("INSERT INTO utentiscuola(nome, cognome, email, password, transazione) VALUES ('$nome_cliente','$cognome_cliente','$mail_cliente','$md5password','$transazione')");
?>
poi nella query vedo una cosa che non mi torna: inserisci due volte la $mail_cliente?
io l'ho messa una volta sola
 

gandalf1959

Utente Attivo
21 Nov 2013
208
1
18
ciao,
intanto confermo il doppio inserimento della mail che una volta e' nel campo indirizzo mail, l'altra nel campo userId. Ma è un dettaglio.
Cambiato il codice come suggerito e non cambia nulla.
Mi sa che non arriva proprio al momento dell'inserimento nel DB. Ci deve essere qualcosa prima che blocca lo script. Ho inserito una semplice riga
PHP:
$messaggio = "verificato";
			mail('[email protected]','passaggio1',$messaggio);
dopo il ...if VERIFIED...
e un'altra volta dopo il ...if completed...
e non ho ricevuto nessuna mail. Quindi probabilmente non arriva neppure fino a li'. Questo significa tra l'altro che non devo aver capito come funziona il meccanismo di Paypal relativamente agli IPN...
Incoraggiante...
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
tu hai questo file che viene chiamato da qualcosa
PHP:
<?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", 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); 
//eccetera eccetera
?>
giusto? o prima del commento // CONFIG: Enable debug mode.... c'è qualcos'altro?
hai provato a mettere il var_dump subito alla prima istruzione?
PHP:
<?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", 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');
var_dump($raw_post_data);//QUESTO
$raw_post_array = explode('&', $raw_post_data); 
//eccetera eccetera
?>
se il var_dump non ti riporta nulla sei sicuro che php://input sia un nome valido?
prova a dare un occhio a http://it1.php.net/manual/en/function.file-get-contents.php
 

gandalf1959

Utente Attivo
21 Nov 2013
208
1
18
Fermi tutti!
Il problema e' qui:
PHP:
$fp = fsockopen('ssl://https://www.sandbox.paypal.com/cgi-bin/webscr', 443, $errno, $errstr, 30);

Non si apre la connessione con la sandbox di paypal.
Suggerimenti sull'utilizzo di Fsockopen? Ho guardato il manuale, ma mi sembra tutto giusto...
grazie mille ancora...
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
dal punto di vista sintattico sembrerebbe giusto, l'unica cosa, ma non sono sicuro, è come è scritto l'indirizzo.
credo che il suffisso ssl serva per la sicurezza, prova toglierlo.
il tutto salvo che sempre per ragioni di sicurezza la sandbox sia protetta dalla lettura tramite script.
forse l'unica è sentire paypal o, visto il tuo username, sentire saruman o meglio sauron
 

gandalf1959

Utente Attivo
21 Nov 2013
208
1
18
Buongiorno a tutti.
CE L'HO FATTA!
E siccome odio quelle discussioni nei forum che si limitano a dire cose del tipo "ok ho risolto grazie",
posto di seguito il codice completo funzionante del listener per i pagamenti express (con bottone Paga Subito) di Paypal, con tutte le verifiche e l'inserimento finale nel db. Ovviamente ora implemento altre funzionalita', ma la base c'e'!
Ecco il codice completo:
PHP:
<?php
session_start();

// 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", 0);

// 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);
}


// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));


$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) {

			if ($_POST['payment_status'] == "Completed") {

				//controllo che la transazione non esista già
				include 'connect.php';

				$trans = $_POST['txn_id'];
				$txn_id_check = ("SELECT idTransazione FROM utentiscuola WHERE idTransazione='$trans'");
				$risultato = mysql_query($txn_id_check);
				while ($row = mysql_fetch_assoc($risultato)) {
          			$trans_attuale = $row['idTransazione'];
        		}
        		mysql_free_result($risultato);

				// recupero il prezzo della lezione dal mio db
				$a = $_POST['custom'];
				$recuperoprz = ("SELECT euro FROM calendario WHERE id_lezione='$a'");
				$risultato2 = mysql_query($recuperoprz);
				while ($row2 = mysql_fetch_assoc($risultato2)) {
		          $prezzo_corrente = $row2['euro'];
		        }
		        mysql_free_result($risultato2);


		        // Se l'id della transazione non c'e'...
				if (!$trans_attuale) {

					// verifico che la mail del venditore corrisponda alla mia
					if ($_POST['receiver_email'] == "[email protected]" ) {

						// Verifico che prezzo e valuta non siano stati cambiati
						if ($_POST['mc_gross'] == $prezzo_corrente && $_POST['mc_currency'] == "EUR") {


							//genero una password casuale e la codifico
							$pwd = "";
				            for($i = 0;$i < 10; $i++) {
				            	$chr = rand(40,126);
					            $pwd .= chr($chr);
					            }
				            $password = $pwd;

        					$md5password = md5($password);

        					// assegno le variabili ricevute da Paypal a variabili locali
							$nome_cliente = $_POST['first_name'];
							$cognome_cliente = $_POST['last_name'];
							$stato_pagamento = $_POST['payment_status'];
							$importo = $_POST['mc_gross'];
							$valuta = $_POST['mc_currency'];
							$transazione = $_POST['txn_id'];
							$miamail = $_POST['receiver_email'];
							$mail_cliente = $_POST['payer_email'];
							$id_lezione = $_POST['custom'];


							//aggiorno il db
							include 'connect.php';
							$aggiungi_query = ("INSERT INTO utentiscuola VALUES ('','$nome_cliente','$cognome_cliente','$mail_cliente','$mail_cliente','$md5password','$transazione')");
							$risultato = mysql_query($aggiungi_query);
						}
					}
				}

			}


	
	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
	$messaggio = "invalido";
	mail('[email protected]','invalido',$messaggio);


	if(DEBUG == true) {
		error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
	}
}

?>

Grazie comunque per i suggerimenti e le risposte. Per effettuare il debug del tutto, visto che il listener viene eseguito in background e non ha un'interfaccia, avevo inserito dopo ogni passaggio un invio di una mail di verifica, tipo
PHP:
$messaggio = "inizio";
mail("[email protected]","passaggio0",$messaggio);
E poi pezzo per pezzo fino a che non ho ricevuto tutte le mail...

A presto e grazie ancora a tutti
 
Discussioni simili
Autore Titolo Forum Risposte Data
F Paypal _xclick IPN non risponde PHP 1
C [PHP] Ipn Pay PAL Mobile PHP 0
baobabdesign [PHP] Annullare abbonamento con paypal IPN da sito esterno PHP 0
M Ipn paypal problema nella risposta PHP 1
N Problema IPN paypal PHP 0
M IPN PayPal PHP 2
Pi3tro IPN paypal problema PHP 2
S Wsse listener aiuto PHP 0
gandalf1959 Passare variabili da listener Paypal a un'altra pagina PHP 0
D Due oggetti con listener per mouse.roll_over che si sovrappongono Flash 0
Z PayPal dubbio PHP 0
gandalf1959 formattazione carrello plug-in WP Simple Paypal Shopping cart WordPress 2
Z Problema di sincronizzazione PAYPAL con PHP PHP 1
A Come creare pulsante donazione PayPal HTML e CSS 5
D [Javascript] salvare immagine canvas - paypal Javascript 0
M [SPONSOR] A BASSO PREZZO - PAYPAL Vendere e Acquistare pubblicita' online 0
C [PHP] Aggiungere pulsante paypal PHP 2
felino Risolto - [Wordpress][WooCommerce] PayPal Checkout e campi di fatturazione WordPress 2
felino [Wordpress][WooCommerce] PayPal: nessun notifica email dopo il pagamento WordPress 1
S form php che invia dati a Paypal PHP 4
A [PHP] Url pagamento paypal in email PHP 2
C [PHP] internal error paypal PHP 6
webmachine [PHP] Integrazione PayPal con PHP PHP 0
romeocharly nuove norme di sicurezza paypal Guadagnare col Sito 3
A configurare pagamento paypal PHP 0
C Come posso integrare il bottone "paga adesso" di paypal e un form php per invio dati? PHP 1
L Paypal - aggiornamenti alla sicurezza PHP 5
N **AAA** CERCASI ACCOUNT FACEBOOK CON ALMENO 5.000 AMICI, se con seguaci MEGLIO, PAGO CON PAYPAL Annunci servizi di Social Media Marketing 0
Gabriele Visioli PayPal Gratuito o a Pagamento? Discussioni Varie 2
R configurazione tasto paypal PHP 0
novello88 Storno pagamento PayPal e nota di credito Leggi, Normative e Fisco 0
L Calcolo della percentuale PayPal che varia in base al totale. E-Commerce 1
L Integrazione PayPal. Con tasto paga adesso e link di ritorno PHP 5
S Sconto su pagamento paypal PHP 1
R [Risolto] Passare Variabile importo carrello a Paypal Classic ASP 7
C Notifiche paypal express Magento 0
P Prestashop pagamento paypal CMS (Content Management System) 2
I [Risolto] ASP VBSCRIPT e PAYPAL problemi con le spese di spedizione dinamiche Classic ASP 3
M Paypal inviare e ricevere variabili E-Commerce 1
M paypal PHP 0
N Paypal ha problemi di pagamento? E-Commerce 4
I variabile prezzo paypal PHP 4
F Pagamento con paypal PHP 11
A problema con form paypal HTML e CSS 0
A probliemi con il codice paypal HTML e CSS 0
L Devo pagare le tasse sulle donazioni PayPal? Leggi, Normative e Fisco 2
L Pagamento con Paypal e ritorno di dati al sito E-Commerce 4
I Problema tasto paypal E-Commerce 1
I PHP e Paypal PHP 9
P Bottone donazioni paypal E-Commerce 2

Discussioni simili