I downloaded this script http://www.micahcarrick.com/php-paypal-ipn-integration-class.html It seems this function is not working and I am not getting any notification. Neither any log is created. What changes I have to made to make this script for a live website? if ($p->validate_ipn()) { my code to insert records to db and email PHP: Can anyone help me in this Complete script: <?php // Setup class require_once('paypal.class.php'); // include the class file $p = new paypal_class; // initiate an instance of the class $p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; // testing paypal url //$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr'; // paypal url // setup a variable for this script (ie: 'http://www.micahcarrick.com/paypal.php') $this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; // if there is not action variable, set the default action of 'process' if (empty($_GET['action'])) $_GET['action'] = 'process'; switch ($_GET['action']) { case 'process': // Process and order... $p->add_field('business', 'krysta_1306161995_biz@gmail.com'); $p->add_field('return', $this_script.'?action=success'); $p->add_field('cancel_return', $this_script.'?action=cancel'); $p->add_field('notify_url', $this_script.'?action=ipn'); $p->add_field('item_name', 'Paypal Test Transaction'); $p->add_field('amount', '10'); $p->submit_paypal_post(); // submit the fields to paypal //$p->dump_fields(); // for debugging, output a table of all the fields break; case 'success': // Order was successful... echo "<html><head><title>Success</title></head><body><h3>Thank you for your order.</h3>"; echo "Transanction : " . $custom['txtdob']; foreach ($_POST as $key => $value) { echo "$key: $value<br>"; } echo "</body></html>"; break; case 'cancel': // Order was canceled... echo "<html><head><title>Canceled</title></head><body><h3>The order was canceled.</h3>"; echo "</body></html>"; break; case 'ipn': // Paypal is calling page for IPN validation... if ($p->validate_ipn()) { // For this example, we'll just email ourselves ALL the data. $subject = 'Instant Payment Notification - Recieved Payment'; $to = 'krystalmarketings@gmail.com'; // your email $body = "An instant payment notification was successfully recieved\n"; $body .= "from ".$p->ipn_data['payer_email']." on ".date('m/d/Y'); $body .= " at ".date('g:i A')."\n\nDetails:\n"; /* This is just to test the IPN, If it works */ $myFile = "log.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "Success"; fwrite($fh, $stringData); fclose($fh); foreach ($p->ipn_data as $key => $value) { $body .= "\n$key: $value"; } mail($to, $subject, $body); } break; } ?> PHP: paypal.class.php <?php class paypal_class { var $last_error; // holds the last error encountered var $ipn_log; // bool: log IPN results to text file? var $ipn_log_file; // filename of the IPN log var $ipn_response; // holds the IPN response from paypal var $ipn_data = array(); // array contains the POST values for IPN var $fields = array(); // array holds the fields to submit to paypal function paypal_class() { // initialization constructor. Called when class is created. $this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr'; $this->last_error = ''; $this->ipn_log_file = '.ipn_results.log'; $this->ipn_log = true; $this->ipn_response = ''; // populate $fields array with a few default values. See the paypal // documentation for a list of fields and their data types. These defaul // values can be overwritten by the calling script. $this->add_field('rm','2'); // Return method = POST $this->add_field('cmd','_xclick'); } function add_field($field, $value) { $this->fields["$field"] = $value; } function submit_paypal_post() { echo "<html>\n"; echo "<head><title>Processing Payment...</title></head>\n"; echo "<body onLoad=\"document.forms['paypal_form'].submit();\">\n"; echo "<center><h2>Please wait, your order is being processed and you"; echo " will be redirected to the paypal website.</h2></center>\n"; echo "<form method=\"post\" name=\"paypal_form\" "; echo "action=\"".$this->paypal_url."\">\n"; foreach ($this->fields as $name => $value) { echo "<input type=\"hidden\" name=\"$name\" value=\"$value\"/>\n"; } echo "<center><br/><br/>If you are not automatically redirected to "; echo "paypal within 5 seconds...<br/><br/>\n"; echo "<input type=\"submit\" value=\"Click Here\"></center>\n"; echo "</form>\n"; echo "</body></html>\n"; } function validate_ipn() { // parse the paypal URL $url_parsed=parse_url($this->paypal_url); // generate the post string from the _POST vars aswell as load the // _POST vars into an arry so we can play with them from the calling // script. $post_string = ''; foreach ($_POST as $field=>$value) { $this->ipn_data["$field"] = $value; $post_string .= $field.'='.urlencode(stripslashes($value)).'&'; } $post_string.="cmd=_notify-validate"; // append ipn command // open the connection to paypal $fp = fsockopen($url_parsed[host],"80",$err_num,$err_str,30); if(!$fp) { // could not open the connection. If loggin is on, the error message // will be in the log. $this->last_error = "fsockopen error no. $errnum: $errstr"; $this->log_ipn_results(false); return false; } else { // Post the data back to paypal fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); fputs($fp, "Host: $url_parsed[host]\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $post_string . "\r\n\r\n"); // loop through the response from the server and append to variable while(!feof($fp)) { $this->ipn_response .= fgets($fp, 1024); } fclose($fp); // close connection } if (eregi("VERIFIED",$this->ipn_response)) { // Valid IPN transaction. $this->log_ipn_results(true); return true; } else { // Invalid IPN transaction. Check the log for details. $this->last_error = 'IPN Validation Failed.'; $this->log_ipn_results(false); return false; } } function log_ipn_results($success) { if (!$this->ipn_log) return; // is logging turned off? // Timestamp $text = '['.date('m/d/Y g:i A').'] - '; // Success or failure being logged? if ($success) $text .= "SUCCESS!\n"; else $text .= 'FAIL: '.$this->last_error."\n"; // Log the POST variables $text .= "IPN POST Vars from Paypal:\n"; foreach ($this->ipn_data as $key=>$value) { $text .= "$key=$value, "; } // Log the response from the paypal server $text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response; // Write to log $fp=fopen($this->ipn_log_file,'a'); fwrite($fp, $text . "\n\n"); fclose($fp); // close file } function dump_fields() { echo "<h3>paypal_class->dump_fields() Output:</h3>"; echo "<table width=\"95%\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\"> <tr> <td bgcolor=\"black\"><b><font color=\"white\">Field Name</font></b></td> <td bgcolor=\"black\"><b><font color=\"white\">Value</font></b></td> </tr>"; ksort($this->fields); foreach ($this->fields as $key => $value) { echo "<tr><td>$key</td><td>".urldecode($value)." </td></tr>"; } echo "</table><br>"; } } PHP: paypalfunction.php <?php /******************************************** Payflow API Module Defines all the global variables and the wrapper functions ********************************************/ $PROXY_HOST = '127.0.0.1'; $PROXY_PORT = '808'; $Env = "pilot"; //'------------------------------------ //' Payflow API Credentials //'------------------------------------ $API_User="test"; //' Fill in the API_Password variable yourself, the wizard will not do this automatically $API_Password=""; $API_Vendor="test"; $API_Partner="test"; // BN Code $sBNCode = "PF-CCWizard"; /* ' Define the PayPal Redirect URLs for Express Checkout ' This is the URL that the buyer is first sent to do authorize payment with their paypal account ' change the URL depending if you are testing on the sandbox or the live PayPal site ' ' For the sandbox, the URL is https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token= ' For the live site, the URL is https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token= */ if ($Env == "pilot") { $API_Endpoint = "https://payflowpro.paypal.com"; $PAYPAL_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="; } else { $API_Endpoint = "https://pilot-payflowpro.paypal.com"; $PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="; } $USE_PROXY = false; if (session_id() == "") session_start(); function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL) { //------------------------------------------------------------------------------------------------------------------------------------ // Construct the parameter string that describes SetExpressCheckout in the shortcut implementation $nvpstr = "&TENDER=P&ACTION=S"; if ("Sale" == $paymentType) { $nvpstr .= "&TRXTYPE=S"; } elseif ("Authorization" == $paymentType) { $nvpstr .= "&TRXTYPE=A"; } else //default to sale { $nvpstr .= "&TRXTYPE=S"; } $nvpstr .= "&AMT=" . $paymentAmount; $nvpstr .= "&CURRENCY=" . $currencyCodeType; $nvpstr .= "&CANCELURL=" . $cancelURL; $nvpstr .= "&RETURNURL=" . $returnURL; $_SESSION["currencyCodeType"] = $currencyCodeType; $_SESSION["PaymentType"] = $paymentType; // Each part of Express Checkout must have a unique request ID. $unique_id = generateGUID(); $resArray = hash_call($nvpstr,$unique_id); $ack = strtoupper($resArray["RESULT"]); if($ack=="0") { $token = urldecode($resArray["TOKEN"]); $_SESSION['TOKEN']=$token; } return $resArray; } function CallMarkExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum ) { //------------------------------------------------------------------------------------------------------------------------------------ // Construct the parameter string that describes SetExpressCheckout in the mark implementation $nvpstr = "&TENDER=P&ACTION=S"; if ("Sale" == $paymentType) { $nvpstr .= "&TRXTYPE=S"; } elseif ("Authorization" == $paymentType) { $nvpstr .= "&TRXTYPE=A"; } else //default to sale { $nvpstr .= "&TRXTYPE=S"; } $nvpstr .= "&AMT=" . $paymentAmount; $nvpstr .= "&CURRENCY=" . $currencyCodeType; $nvpstr .= "&CANCELURL=" . $cancelURL; $nvpstr .= "&RETURNURL" . $returnURL; $nvpstr .= "&SHIPTOSTREET=" . $shipToStreet; $nvpstr .= "&SHIPTOSTREET2=" . $shipToStreet2; $nvpstr .= "&SHIPTOCITY=" . $shipToCity; $nvpstr .= "&SHIPTOSTATE=" . $shipToState; $nvpstr .= "&SHIPTOCOUNTRY=" . $shipToCountryCode; $nvpstr .= "&SHIPTOZIP=" . $shipToZip; $nvpstr .= "&ADDROVERRIDE=1"; // address override $_SESSION["currencyCodeType"] = $currencyCodeType; $_SESSION["PaymentType"] = $paymentType; // Each part of Express Checkout must have a unique request ID. $unique_id = generateGUID(); //'--------------------------------------------------------------------------------------------------------------- //' Make the API call to Payflow //' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment. //' If an error occured, show the resulting errors //'--------------------------------------------------------------------------------------------------------------- $resArray = hash_call($nvpstr,$unique_id); $ack = strtoupper($resArray["RESULT"]); if($ack=="0") { $token = urldecode($resArray["TOKEN"]); $_SESSION['TOKEN']=$token; } return $resArray; } function GetShippingDetails( $token ) { //'--------------------------------------------------------------------------- //' Build a second API request to Payflow, using the token as the //' ID to get the details on the payment authorization //'--------------------------------------------------------------------------- $paymentType = $_SESSION['paymentType']; $nvpstr = "&TOKEN=" . $token . "&TENDER=P&ACTION=G"; if ("Sale" == $paymentType) { $nvpstr .= "&TRXTYPE=S"; } elseif ("Authorization" == $paymentType) { $nvpstr .= "&TRXTYPE=A"; } else //default to sale { $nvpstr .= "&TRXTYPE=S"; } // Each part of Express Checkout must have a unique request ID. $unique_id = generateGUID(); $resArray = hash_call($nvpstr,$unique_id); $ack = strtoupper($resArray["RESULT"]); if($ack == "0") { $_SESSION['payer_id'] = $resArray['PAYERID']; } return $resArray; } function ConfirmPayment( $FinalPaymentAmt ) { //Format the other parameters that were stored in the session from the previous calls $token = $_SESSION['token']; $paymentType = $_SESSION['paymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; $payerID = $_SESSION['payer_id']; $serverName = $_SERVER['SERVER_NAME']; $nvpstr = "&TENDER=P&ACTION=D"; if ("Sale" == $paymentType) { $nvpstr .= "&TRXTYPE=S"; } elseif ("Authorization" == $paymentType) { $nvpstr .= "&TRXTYPE=A"; } else //default to sale { $nvpstr .= "&TRXTYPE=S"; } $nvpstr .= "&TOKEN=" . $token . "&PAYERID=" . $payerID . "&AMT=" . $FinalPaymentAmt; $nvpstr .= '&CURRENCY=' . $currencyCodeType . '&IPADDRESS=' . $serverName; // Each part of Express Checkout must have a unique request ID. // Save it as a session variable in order to avoid duplication $unique_id = isset($_SESSION['unique_id']) ? $_SESSION['unique_id'] : generateGUID(); $_SESSION['unique_id'] = $unique_id; /* Make the call to PayPal to finalize payment If an error occured, show the resulting errors */ $resArray = hash_call($nvpstr,$unique_id); $ack = strtoupper($resArray["RESULT"]); return $resArray; } function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, $countryCode, $currencyCode, $orderdescription ) { // Construct the parameter string that describes the credit card payment $replaceme = array("-", " "); $card_num = str_replace($replaceme,"",$creditCardNumber); $nvpstr = "&TENDER=C"; if ("Sale" == $paymentType) { $nvpstr .= "&TRXTYPE=S"; } elseif ("Authorization" == $paymentType) { $nvpstr .= "&TRXTYPE=A"; } else //default to sale { $nvpstr .= "&TRXTYPE=S"; } // Other information $ipaddr = $_SERVER['REMOTE_ADDR']; $nvpstr .= '&ACCT='.$card_num.'&CVV2='.$cvv2.'&EXPDATE='.$expDate.'&ACCTTYPE='.$creditCardType.'&AMT='.$paymentAmount.'&CURRENCY='.$currencyCode; $nvpstr .= '&FIRSTNAME='.$firstName.'&LASTNAME='.$lastName.'&STREET='.$street.'&CITY='.$city.'&STATE='.$state.'&ZIP='.$zip.'&COUNTRY='.$countryCode; $nvpstr .= '&CLIENTIP='. $ipaddr . '&ORDERDESC=' . $orderdescription; $nvpstr .= '&VERBOSITY=MEDIUM'; // The $unique_id field is storing our unique id that we'll use in the request id header. $unique_id = date('ymd-H').rand(1000,9999); $resArray = hash_call($nvpstr,$unique_id); return $resArray; } function hash_call($nvpStr,$unique_id) { //declaring of global variables global $API_Endpoint, $API_User, $API_Password, $API_Vendor, $API_Partner; global $USE_PROXY, $PROXY_HOST, $PROXY_PORT; global $gv_ApiErrorURL; global $sBNCode; $len = strlen($nvpStr); $headers[] = "Content-Type: text/namevalue"; $headers[] = "Content-Length: " . $len; // Set the server timeout value to 45, but notice below in the cURL section, the timeout // for cURL is set to 90 seconds. Make sure the server timeout is less than the connection. $headers[] = "X-VPS-CLIENT-TIMEOUT: 45"; $headers[] = "X-VPS-REQUEST-ID:" . $unique_id; // set the host header if ($Env == "pilot") { $headers[] = "Host: pilot-payflowpro.paypal.com"; } else { $headers[] = "Host: payflowpro.paypal.com"; } //setting the curl parameters. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$API_Endpoint); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_VERBOSE, 1); //turning 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_TIMEOUT, 90); // times out after 90 secs curl_setopt($ch, CURLOPT_POST, 1); //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled. //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php if($USE_PROXY) curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT); //NVPRequest for submitting to server $nvpreq = "USER=".$API_User.'&VENDOR='.$API_Vendor.'&PARTNER='.$API_Partner.'&PWD='.$API_Password . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode); //setting the nvpreq as POST FIELD to curl curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); //getting response from server $response = curl_exec($ch); //convrting NVPResponse to an Associative Array $nvpResArray=deformatNVP($response); $nvpReqArray=deformatNVP($nvpreq); $_SESSION['nvpReqArray']=$nvpReqArray; if (curl_errno($ch)) { // moving to display page to display curl errors $_SESSION['curl_error_no']=curl_errno($ch) ; $_SESSION['curl_error_msg']=curl_error($ch); //Execute the Error handling module to display errors. } else { //closing the curl curl_close($ch); } return $nvpResArray; } function RedirectToPayPal ( $token ) { global $PAYPAL_URL; // Redirect to paypal.com here $payPalURL = $PAYPAL_URL . $token; header("Location: ".$payPalURL); } function deformatNVP($nvpstr) { $intial=0; $nvpArray = array(); while(strlen($nvpstr)) { //postion of Key $keypos= strpos($nvpstr,'='); //position of value $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr); /*getting the Key and Value values and storing in a Associative Array*/ $keyval=substr($nvpstr,$intial,$keypos); $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1); //decoding the respose $nvpArray[urldecode($keyval)] =urldecode( $valval); $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr)); } return $nvpArray; } function generateCharacter () { $possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); return $char; } function generateGUID () { $GUID = generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter()."-"; $GUID = $GUID .generateCharacter().generateCharacter().generateCharacter().generateCharacter()."-"; $GUID = $GUID .generateCharacter().generateCharacter().generateCharacter().generateCharacter()."-"; $GUID = $GUID .generateCharacter().generateCharacter().generateCharacter().generateCharacter()."-"; $GUID = $GUID .generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter(); return $GUID; } ?> p.php [PHP]<?php require_once ("paypalfunctions.php"); if ( $PaymentOption == "Visa" || $PaymentOption == "MasterCard" || $PaymentOption == "Amex" || $PaymentOption == "Discover" ) { $finalPaymentAmount = $_SESSION["Payment_Amount"]; $creditCardType = "<<Visa/MasterCard/Amex/Discover>>"; //' Set this to one of the acceptable values (Visa/MasterCard/Amex/Discover) match it to what was selected on your Billing page $creditCardNumber = "<<CC number>>"; // ' Set this to the string entered as the credit card number on the Billing page $expDate = "<<Expiry Date>>"; // ' Set this to the credit card expiry date entered on the Billing page $cvv2 = "<<cvv2>>"; // ' Set this to the CVV2 string entered on the Billing page $firstName = "<<firstName>>"; // ' Set this to the customer's first name that was entered on the Billing page $lastName = "<<lastName>>"; // ' Set this to the customer's last name that was entered on the Billing page $street = "<<street>>"; // ' Set this to the customer's street address that was entered on the Billing page $city = "<<city>>"; // ' Set this to the customer's city that was entered on the Billing page $state = "<<state>>"; // ' Set this to the customer's state that was entered on the Billing page $zip = "<<zip>>"; // ' Set this to the zip code of the customer's address that was entered on the Billing page $countryCode = "<<PayPal Country Code>>"; // ' Set this to the PayPal code for the Country of the customer's address that was entered on the Billing page $currencyCode = "<<PayPal Currency Code>>"; // ' Set this to the PayPal code for the Currency used by the customer $orderDescription = "<<OrderDescription>>"; // ' Set this to the textual description of this order $paymentType = "Sale"; $resArray = DirectPayment ( $paymentType, $finalPaymentAmount, $creditCardType, $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, $countryCode, $currencyCode, $orderDescription ); $ack = $resArray["RESULT"]; if( $ack != "0" ) { // See pages 50 through 65 in https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_PayflowPro_Guide.pdf for a list of RESULT values (error codes) //Display a user friendly Error on the page using any of the following error information returned by Payflow $ErrorCode = $ack; $ErrorMsg = $resArray["RESPMSG"]; echo "Credit Card transaction failed. "; echo "Error Message: " . $ErrorMsg; echo "Error Code: " . $ErrorCode; } } ?> PHP: