can't make paypal ipn working - php

I am trying to make a donation in my website with paypal. As the result, I want the donators to be displayed. For that I use ipn. I figured and made it working, but it seems to be working fine only with paypal sandbox only.
Here's my code:
page.php
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="frmPayPal1">
<input type="hidden" name="business" value="<?php echo $merchant_id; ?>">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="item_name" value="Donation">
<input type="hidden" name="item_number" value="1">
<input type="hidden" name="credits" value="510">
<input type="hidden" name="userid" value="1">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="handling" value="0">
<input type="hidden" name="cancel_return" value="http://domain.com/donation">
<input type="hidden" name="return" value="http://domain.com/donation">
<div class = "donator_name_choice">
Enter the name you want to be displayed as: <input type="text" class = "donate_amount" name="custom" maxlength="14">
</div>
<div class = "donator_donation">
Enter the value You want to donate(EUR): <input type="number" class = "donate_amount" name="amount" step = "0.01">
</div>
<div class = "donation_submit">
<input type="submit" name="submit" value = "DOTANE" class = "donate_here">
</div>
</form>
ipnlistener.php:
<?php
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$user_name = $_POST['custom'];
$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'];
$payment_date = $_POST['payment_date'];
$item_name = $_POST['item_name'];
$sql162 = "INSERT INTO donators (user_name, receiver_email, payer_email, txn_id, payment_gross, currency_code, payment_status, payment_date) VALUES ('" . $user_name . "', '". $receiver_email ."', '" . $payer_email . "', '" . $txn_id . "', '" . $payment_amount . "', '" . $payment_currency . "', '" . $payment_status . "', '" . $payment_date . "')";
if ($MySQLi_CON->query($sql162) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql162 . "<br>" . $MySQLi_CON->error;
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
Could anyone explain me what am I missing? Thanks !

Related

Fail to send variables back to return address while Paypal payment

I am unable to get variables in my return address while paying with Paypal.
My form is like below:
<form action="<?php echo $ps_paypal_url; ?>" method="post">
<input type="hidden" name="business" value="<?php echo $ps_paypal_merchant; ?>">
<input type="hidden" name="notify_url" value="<?php echo 'http://'.$_SERVER['SERVER_NAME'].CONF_WEBROOT_URL. 'paypal-ipn.php'; ?>">
<input type="hidden" name="item_name" value="<?php echo 'For Order ' . $_POST['ORDER']; ?>">
<input type="hidden" name="user_name" value="<?php echo $_SESSION['logged_user']['user_id']; ?>">
<input type="hidden" name="quantity" value="1">
<input type="hidden" name="item_number" value="<?php echo $_POST['ORDER']; ?>">
<input TYPE="hidden" name="cmd" value="_xclick">
<input type="hidden" name="amount" value="<?php echo round($total_payable, 2); ?>">
<?php if($_POST['wallet'] > 0){ ?>
<input type="hidden" name="discount_amount" value="<?php echo round($_POST['wallet'],2); ?>" />
<?php } ?>
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="custom" value="<?php echo $_SESSION['logged_user']['user_id']; ?>">
<?php
$success = 'http://' . $_SERVER['SERVER_NAME'] . CONF_WEBROOT_URL .'success/;
?>
<input type='hidden' name='rm' value='2'>
<input type="hidden" name="return" value="<?php echo $success ; ?>">
<input type="hidden" name="currency_code" value="<?php echo CONF_CURRENCY_CODE; ?>">
</form>
In my return address I am trying to read for example item_name or amount. But no success so far. I beleive paypal is disabled this function and variables are not allowed to be posted to return address. In my return file I am trying to read the variables like below:
<?php
$amount = $_GET['amount'];
$amountpost = $_POST['amount'];
echo $amount;
echo $amountpost ;
?>
The result is empty. There is not any problem with ipn file once it is verified I am able to get the result with ipn file but why it is needed for me is because I need to add pending orderd in users purchase history. So when user will be redirected to success.php I will add pending order to account and once it is completed I will check via ipn and will change the status to "paid".
Any help would be highly appreciated.
PS: I don't want to send parameters in URL as $_GET parameters. I just want to get parameters of form.
First, please enable IPN explicitly after logging in your Paypal account and set the IPN url (e.g. set as http://www.yoursite.com/payment1234A.php)
Second, please remove notify_url from your form (to avoid hacking)
Thirdly, please add return and cancel_return url as hidden fields. For example:
<input type="hidden" name="return" value="http://www.yoursite.com/success.php">
<input type="hidden" name="cancel_return" value="http://www.yoursite.com/cancelled.php">
So, if you want to collect USD1000 , then the form to be sent to paypal should be like the following form:
Note:
I have added a javascript autosubmit so that the user does not need to click a submit button);
I have used the "custom" field to send a unique data, it can be something like [customerserial-transactionserial] so that your IPN script can use it to do your db update.
The minimum requested fields to be submitted in the form are:
business, item_name, amount, currency_code. For further details please refer to Paypal's official documentation.
<form id=form1 action="https://www.paypal.com/cgi-bin/webscr" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="yourpaypalemail#yoursite.com">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="Purchase">
<input type="hidden" name="amount" value="1000">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="custom" value="<?php echo $_SESSION["checkcode"]; ?>">
<input type="hidden" name="return" value="http://www.yoursite.com/success.php">
<input type="hidden" name="cancel_return" value="http://www.yoursite.com/cancelled.php">
</form>
<script>
document.getElementById('form1').submit();
</script>
Finally, use (and customize if necessary) the following standard paypal IPN php script in your IPN link (e.g.payment1234A.php). Please note that the amount you submitted will be returned as $_POST['mc_gross'] (not $_GET['amount'] nor $_POST['amount']) . But the custom field will be returned as $_POST['custom'].
The file below : payment1234A.php
<?php
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
if (1==2) {
// STEP 2: Post IPN data back to paypal to validate
// only works if your IPN url is https, otherwise remark this block as 1==2
$ch = curl_init('https://ipnpb.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
}
// STEP 3: Inspect IPN validation result and act accordingly
if (1==1) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$custom = $_POST['custom'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
// <---- HERE you can do your INSERT to the database
if ( trim($payment_status)=="Completed" ) {
/// do whatever you want for successful transaction
}
}
?>

Payment with PayPal hangs inside the notify_url page

I have this page to pay with paypal, and receive the notification in "notify_url". The purchase goes well but fails to receive the notification. Everything is fine until it reaches these two lines: $valid_txnid = check_txnid ($data ['txn_id']);$valid_price = check_price ($data ['payment_amount'], $data ['item_number']);
where the program hangs. (I know it because I have sent emails from various points of the program until I get there that I do not receive anything).
And also I don't know where the check_txnid () and check_price () functions come from, which I don't see defined anywhere. The code is taken from this other post: How to get transaction details in notify_url page in paypal
index.php
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" style="padding: 0; margin: 0;">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="sb-pwrdu1932120#business.example.com" />
<input type="hidden" name="quantity" value="1" />
<input type="hidden" name="item_name" value="MiArticulo" />
<input type="hidden" name="item_number" value="1" />
<input type="hidden" name="amount" value="1" />
<input type="hidden" value="19" name="invoice">
<input type="hidden" name="notify_url" value="http://infrangible-discoun.000webhostapp.com/pruebaPaypal/notifyUrl.php">
<input type="hidden" name="currency_code" value="EUR" />
<input type="hidden" name="rm" value="2" >
<input type="hidden" name="return" value="http://infrangible-discoun.000webhostapp.com/paypal4/newfile1.php">
<input type="image" border="0" name="paypal" src="images/btn_paypal_nl.gif" onClick=""/>
</form>
notifyUrl.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require("conexion.php");
require 'phpmailer/Exception.php';
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
// Response from Paypal
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
//$value = urlencode($value);
$value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
// assign posted variables to local variables
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['invoice'] = $_POST['invoice'];
$data['paypallog'] = $req;
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
////mail('atiftariq80#gmail.com','Step 9','Step 9');
$res = fgets ($fp, 1024);
if (true || strcmp($res, "VERIFIED") == 0) {
////mail('atiftariq80#gmail.com','PAYMENT VALID','PAYMENT VALID');
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){ //doesn't pass this if.
//----------------- INSERT RECORDS TO DATABASE-------------------------------------
$name=$_POST['item_name'];
mysqli_query($db,"insert into ventas value(0,'$name')");
if ($data['invoice']=='basic') {
$price = 39;
} else {
$price = 159;
}
$this->user_model->update_user(
array(
'id' => $data['custom'],
'user_status' => 1,
'payment_date' => date("Y-m-d H:i:s",time()),
'next_payment_date' => date('Y-m-d', strtotime('+32 days')),
'user_package' => $data['invoice'],
'package_price' => $price
)
);
$data2 = array('id' => '',
'txn_id' => $data['txn_id'],
'amount' => $data['payment_amount'],
'mode ' => $data['payment_status'],
'paypal_log' => $data['paypallog'],
'user_id' => $data['custom'],
'created_at' => date('Y-m-d H:i:s',time())
);
$this->db->insert('tbl_paypal_log', $data2);
//----------------- INSERT RECORDS TO DATABASE-------------------------------------
}else{
// Payment made but data has been changed
// E-mail admin or alert user
}
} elseif ($res=='INVALID') {
// PAYMENT INVALID & INVESTIGATE MANUALY!
// E-mail admin or alert user
////mail('atiftariq80#gmail.com','PAYMENT INVALID AND INVESTIGATE MANUALY','PAYMENT INVALID AND INVESTIGATE MANUALY');
}
}
fclose ($fp);
}
?>
I don't know where the check_txnid () and check_price () functions come from, which I don't see defined anywhere.
That seems to be your problem. Don't call functions that don't exist.
If you want to to check the transaction ID and the price are unique and valid for what you are offering, create actual functions that actually do this.
You could for example use 'custom' or 'invoice' to match against an existing order record in your database and validate the price corresponds, if you provided such a unique number to PayPal as part of the transaction.

Paypal IPN data receiveing on localhost using ngrok

Does paypal send IPN data to localhost when accessing via internet using ngrok? I tested it with Payza and it successfully sent the IPN data and I could insert the data into the database. But when tried with paypal, I am not receiving any data. Does paypal not send to localhost's accessed via internet using ngrok? Or, is there another problem in my code?
I am successfully getting redirected to success page after payment but the data is not inserted in my database.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Custom PayPal Test Integration</title>
<meta charset="utf-8">
</head>
<body>
<form action="https://sandbox.paypal.com/cgi-bin/webscr" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="shubhamjha900#gmail.com">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="Test Item">
<input type="hidden" name="item_number" value="12345">
<input type="hidden" name="amount" value="5.50">
<input type="hidden" name="currency_code" value="USD">
<!-- Specify URLs -->
<input type='hidden' name='cancel_return' value='http://229a1c8a.ngrok.io/sites/paypal6/failed.php'>
<input type='hidden' name='return' value='http://229a1c8a.ngrok.io/sites/paypal6/success.php'>
<input type='hidden' name='notify_url' value='http://229a1c8a.ngrok.io/sites/paypal6/ipn.php' />
<!-- Display the payment button. -->
<input type="image" name="submit" border="0"
src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online">
<img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >
</form>
</body>
</html>
ipn.php
<?php
$dbname = "codexworld";
$username = "root";
$password = "";
$dbhost = "localhost";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://sandbox.paypal.com/cgi-bin/webscr'); // change to [...]sandbox.paypal[...] when using sandbox to test
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
if ($_POST['mc_gross'] != NULL)
$payment_amount = $_POST['mc_gross'];
else
$payment_amount = $_POST['mc_gross1'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$custom = $_POST['custom'];
$stmt = $pdo->prepare("INSERT INTO payments(user_id)VALUES(1)");
$stmt-> execute();
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
Please help me guys. I am stuck on this since a few days. I really need to implement it and get through. Please help!!

Issue getting result back from Paypal IPN

I have followed the pay pal IPN documentation on this. Created a file called payment_notify.php its identical to whats found here : https://developer.paypal.com/docs/classic/ipn/ht_ipn/
My pay pal form is set to POST data to : https://www.sandbox.paypal.com/cgi-bin/webscr
I have my pay pal sandbox business account notify url set to my website url / payment_notify.php.
My code allows users to click the buy now button, it brings them to the paypal login screen, allows them to 'pay' for the product, displays a paypal screen saying the transaction was successful then finally when it returns to my site it gives me back nothing. I have tried inserting the POST variables from paypal into my database but nothing happens.
Im a total beginner at paypal API but heres my attempt :
<form action="<?php echo $paypal_url; ?>" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="<?php echo $paypal_id; ?>">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_number" value="<?php echo $row['id'];?>">
<input type="hidden" name="item_name" value="<?php echo $row['credit_price'].": credits"; ?>">
<input type="hidden" name="amount" value="<?php echo $row['credit_price']; ?>">
<input type="hidden" name="currency_code" value="<?echo $row['currency'];?>">
<!-- Specify URLs -->
<input type='hidden' name='cancel_return' value="<? echo 'http://www.$_SERVER[HTTP_HOST]/cancel.php';?>">
<input type='hidden' name='return' value="<? echo 'http://www.$_SERVER[HTTP_HOST]/success.php';?>">
<input type='hidden' name='notify_url' value="<? echo 'http://www.$_SERVER[HTTP_HOST]/payment_notify.php';?>">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<input type="image" name="submit" border="0"
src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" alt="PayPal - The safer, easier way to pay online">
<img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >
</form>
Then for my payment_notify file :
<?php
session_start();
require("db_connection.php");
// STEP 1: read POST data
// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if (function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Step 2: POST IPN data back to PayPal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if ( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// The IPN is verified, process it:
$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'];
foreach($_POST as $key => $value) {
echo $key . " = " . $value . "<br>";
}
// insert the valid transaction into the database :
$insert = "INSERT INTO tableNAME (item,txn_id,payment_gross,currency_code,paid_by,payment_status)VALUES('$item_number',$txn_id,'$payment_amount','$payment_currency','$payer_email','$payment_status')";
$result=mysqli_query($con,$insert);
} else if (strcmp ($res, "INVALID") == 0) {
// IPN invalid, log for manual investigation
echo "The response from IPN was: <b>" .$res ."</b>";
}
?>
You have to check two things here:
Change $ch = curl_init('https://www.paypal.com/cgi-bin/webscr'); to
$ch = curl_init('https://www.sandbox.paypal.com/cgi-bin/webscr');
Try to get the result of response in log file to see what is the actual result you are getting.

PayPal IPN not working anymore

Since yesterday the PayPal IPN was working fine, but today I can't receive any IPNs. I checked the MySQL, checkt the IPN Adresse and everything is fine. I was thinking PayPal did some changes on their IPN Server, that woman on the Phone told me no. Kind of weird.
So could someone check the ipn.php & the add.php?
add php
<?
define('BASEPATH', true);
require_once("../../config.php");
if(!$is_online){
redirect('../../../index.php');
exit;
}
$s_host = parse_url($site['site_url']);
if($_GET['cash'] != '' && is_numeric($_GET['cash'])){
$cash = ($_GET['cash'] < 1 ? 1 : $_GET['cash']);
$cash = number_format($cash, 2, '.', '');
}else{
redirect('../../../index.php');
exit;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Redirecting...</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<style>body{background: #fff;font: 13px Trebuchet MS, Arial, Helvetica, Sans-Serif;color: #333;line-height: 160%;margin: 0;padding: 0;text-align: center;}h1{font-size: 200%;font-weight: normal}.centerdiv{position: absolute;top: 50%; left: 50%; width: 340px; height: 200px;margin-top: -100px; margin-left: -160px;}</style>
<script type="text/javascript">
setTimeout('document.paypalform.submit()',1000);
</script>
</head>
<body>
<div class="centerdiv"><h1>Connecting to Paypal <img src="<?=$site['site_url']?>/img/go_loader.gif" /></h1></div>
<form name="paypalform" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="<?=$site['paypal']?>">
<input type="hidden" name="item_name" value="<?='Add Funds - '.$data['login'].' - '.$s_host['host']?>">
<input type="hidden" name="custom" value="<?=($data['id'].'|'.$cash.'|'.VisitorIP())?>">
<input type="hidden" name="amount" value="<?=$cash?>">
<input type="hidden" name="currency_code" value="<?=($site['currency_code'] == '' ? 'USD' : $site['currency_code'])?>">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="<?=$site['site_url']?>/bank.php?success">
<input type="hidden" name="cancel_return" value="<?=$site['site_url']?>/bank.php?cancel">
<input type="hidden" name="notify_url" value="<?=$site['site_url']?>/system/payments/paypal/ipn.php">
</form>
</body>
</html>
ipn
<?php
define('BASEPATH', true);
require("../../config.php");
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$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 .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
// 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'];
$custom = $_POST['custom'];
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
$get_data = explode('|', $custom);
if($site['paypal_auto'] == 1){
if($payment_status == 'Completed'){
$user = $db->QueryFetchArray("SELECT id,login FROM `users` WHERE `id`='".$get_data[0]."'");
$check = $db->QueryGetNumRows("SELECT id FROM `transactions` WHERE `gateway`='paypal' AND `trans_id`='".$txn_id."'");
if($check == 0){
$db->Query("INSERT INTO `transactions` (user, user_id, money, gateway, date, user_ip, trans_id) VALUES('".$user['login']."','".$user['id']."', '".$payment_amount."', 'paypal', NOW(), '".$get_data[2]."', '".$txn_id."')");
if($user['id'] > 0){
$db->Query("UPDATE `users` SET `account_balance`=`account_balance`+'".$payment_amount."' WHERE `id`='".$user['id']."'");
}
}
}
}else{
$user = $db->QueryFetchArray("SELECT id,login FROM `users` WHERE `id`='".$get_data[0]."'");
$check = $db->QueryGetNumRows("SELECT id FROM `transactions` WHERE `gateway`='paypal' AND `trans_id`='".$txn_id."'");
if($check == 0){
$db->Query("INSERT INTO `transactions` (user, user_id, money, gateway, date, paid, user_ip, trans_id) VALUES('".$user['login']."','".$user['id']."', '".$payment_amount."', 'paypal', NOW(), '0', '".$get_data[2]."', '".$txn_id."')");
}
}
}
}
fclose ($fp);
}
?>
I had the same problem. They started adding "\r\n" to the end of the response so I was comparing "VERIFIED" to "VERIFIED\r\n" and it was failing. You can do:
trim($res)
before testing for VERIFIED, or you can use strpos instead of strcmp:
if (strpos($res, "VERIFIED") === 0) (needs ===, not ==)
Finally, they also asked all customers a while back to start adding the Connection header:
$header .= "Connection: close\r\n";
To solving this problem, you need to edit Instant Payment Notification setting in your PayPal business account. This step by step instructions helps lot to enable IPN - PayPal IPN / Notify URL is not working on Sandbox Account

Categories