So I am working on a small site which takes a single payment per user.
When I do payments through the sandbox, if the payment is a success then i always get a IPN response and am able to use that to update my DB
BUT when using live even if paypal says it was a success the IPN returns INVALID
I have looked around for an answer and people have been saying make sure you are using paypal.com and not sandbox.paypal.com, I have done all the suggestions but still no luck.
A working answer to this would be much appreciated!
Here is my code:
This is the html form:
<form class="paypal" action="payments.php" method="post" id="paypal_form" target="_blank">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="UK" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="first_name" value="Customer's First Name" />
<input type="hidden" name="last_name" value="Customer's Last Name" />
<input type="hidden" name="payer_email" value="customer#example.com" />
<input type="hidden" name="item_number" value="123456" / >
<input type="hidden" name="invoice" value="<?php echo $invoice ?>" / >
<input class="submit" type="submit" name="submit" value="Start Payment Process"/>
</form>
This code starts the payment:
<?php
// Database variables
$servername = "localhost";
$username = "un";
$password = "pw";
$dbname = "dbn";
// PayPal settings
$paypal_email = 'email#email.com';
$return_url = 'http://domain.co.uk/paypal/test.php';
$cancel_url = 'http://domain.co.uk/paypal/payment-cancelled';
$notify_url = 'http:/domain.co.uk/paypal/test.php';
$item_name = 'Item Name';
$item_amount = 1.00;
$invoice = $_POST['invoice'];
// Include Functions
include("functions.php");
// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
$querystring = '';
// Firstly Append paypal account to querystring
$querystring .= "?business=".urlencode($paypal_email)."&";
// Append amount& currency (£) to quersytring so it cannot be edited in html
//The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
$querystring .= "item_name=".urlencode($item_name)."&";
$querystring .= "amount=".urlencode($item_amount)."&";
$querystring .= "invoice=".urlencode($invoice)."&";
//loop for posted values and append to querystring
foreach($_POST as $key => $value){
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
// Append paypal return addresses
$querystring .= "return=".urlencode(stripslashes($return_url))."&";
$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
$querystring .= "notify_url=".urlencode($notify_url);
// Append querystring with custom field
//$querystring .= "&custom=".USERID;
// Redirect to paypal IPN
header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
exit();
} else {
//Database Connection
$link = mysql_connect($servername, $username, $password);
mysql_select_db($db_name);
// 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 = 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'];
// 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.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp($res, "VERIFIED") == 0) {
// Used for debugging
// mail('user#domain.com', 'PAYPAL POST - VERIFIED RESPONSE', print_r($post, true));
// 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) {
$orderid = updatePayments($data);
if ($orderid) {
// Payment has been made & successfully inserted into the Database
mail("email#email.com","Success","Payment made successfully");
echo "updated";
} else {
// Error inserting into DB
// E-mail admin or alert user
mail('email#email.com', 'PAYPAL POST - INSERT INTO DB WENT WRONG', print_r($data, true));
}
} else {
// Payment made but data has been changed
// E-mail admin or alert user
}
} else if (strcmp ($res, "INVALID") == 0) {
// PAYMENT INVALID & INVESTIGATE MANUALY!
// E-mail admin or alert user
// Used for debugging
//#mail("user#domain.com", "PAYPAL DEBUGGING", "Invalid Response<br />data = <pre>".print_r($post, true)."</pre>");
}
}
fclose ($fp);
}
}
?>
This code handles the response from paypal:
<?php
// STEP 1: read POST data
// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if (function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Step 2: POST IPN data back to PayPal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if ( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// The IPN is verified, process it
} else if (strcmp ($res, "INVALID") == 0) {
// IPN invalid, log for manual investigation
}
// inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// The IPN is verified, process it:
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process the notification
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$invoice = $_POST['invoice'];
// IPN message values depend upon the type of notification sent.
// To loop through the &_POST array and print the NV pairs to the screen:
foreach($_POST as $key => $value) {
echo $key . " = " . $value . "<br>";
}
echo $res;
} else if (strcmp ($res, "INVALID") == 0) {
// IPN invalid, log for manual investigation
echo "Error! Paypal stated payment as: <b>" .$res ."<br />";
}
?>
Related
I am using PayPal IPN in Sandbox mode and this code isn't working for some reason.
What I want to happen is where it says "VERIFIED" to do the thing between the brackets. But it isnt and I don't know any PhP but I need this to work for my money.
Here is my store's index.php
<head>
<title>Donation Store | EndersoulsRH</title>
</head>
<body>
<center>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="text" name="username" placeholder="Your Minecraft Username"> <br>
<input type="hidden" name="itemname" value="VIP">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="SHW4WRJBFNDQA">
<input type="image" src="http://www.endersouls.us/img/buynow.png" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!" width="200px;">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="text" name="username" placeholder="Your Minecraft Username"> <br>
<input type="hidden" name="itemname" value="VIP">
<input type="hidden" name="command" value="warp Ranks Hayno">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XU8NQN8EVPMYG">
<input type="image" src="https://www.endersouls.us/img/buynow.png" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!" width="200px">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</center>
</body>
</html>
Here is my paypal ipn.php
<?php
header('HTTP/1.1 200 OK');
$resp = 'cmd=_notify-validate';
foreach ($_POST as $parm => $var) {
$var = urlencode(stripslashes($var));
$resp .= "&$parm=$var";
}
$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'];
$record_id = $_POST['custom'];
$httphead = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$httphead .= "Content-Type: application/x-www-form-urlencoded\r\n";
$httphead .= "Content-Length: " . strlen($resp) . "\r\n\r\n";
$errno ='';
$errstr='';
$fh = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fh) {
die("Connection to and from PayPal has bee lost");
} else {
fputs ($fh, $httphead . $resp);
while (!feof($fh)) {
$readresp = fgets ($fh, 1024);
if (strcmp ($readresp, "VERIFIED") == 0) {
$command = "warp ranks Hayno";
require_once("WebsenderAPI.php"); // Load Library
$wsr = new WebsenderAPI("*****","*****","*****"); // HOST , PASSWORD , PORT
if($wsr->connect()){ //Open Connect
$wsr->sendCommand($command);
}
$wsr->disconnect(); //Close connection.
} else if (strcmp ($readresp, "INVALID") == 0) {
}
fclose ($fh);
}
}
?>
I think your URL is wrong. try to put
$fh = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
instead of `$fh = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
in your test pay now button also put sandbox.paypal.com/blahglah`
so put sandbox.paypal.com..... instead of paypal.com....
// 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'); // 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 accordinglyq
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 variablesq
$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'];
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "*****";
$nizz = (explode('|', $custom));
$var1 = $nizz[0];
$var2 = $nizz[1];
$var3 = $nizz[2];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// DO YOUR QUERY HERE OR WHATEVER YOU WANT
// --------------------
if ($conn->query($sql) === TRUE) {
$email_from = 'mymail#example.com';
//send mail from here to notify yourself
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
Sorry i'm a newbie at this PAYPAL IPN
so i got my IPN file.
so my question is, once the user has paid gets redirected to the success/ipn page my script updates the records. but what if the user didnt get redirected, i tested it myself paypal redirects me to the PAYPAL THANK YOU ORDER page and then mozilla pops up a window alert saying that "your connecting to an insecure site bla bla CLICK (yes) or (cancel)" if i click yes then i get redirected to my success/ipn page, but if i click cancel i will stay on the PAYPAL THANK YOU PAGE so im worried that the user might click cancel and he wont get redirected and the data wont be updated
so how do i update the database without paypal redirecting me to my success/ipn page
Please advise, and dont vote down please,
$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.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,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
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);
// WRITE LOG
$fh = fopen('result.txt', 'w');
fwrite($fh, $res .'--'. $req);
fclose($fh);
// 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'];
// Insert your actions here
if(($payment_status == 'Completed') && ($receiver_email == 'paypal-test#bolddata-ap.com')){
include('php/config.php'); //Open Database connection
$check = $dbo->prepare('SELECT * FROM order_bytes WHERE trans_id = ?');
$check->execute(array($txn_id));
if($check->rowCount() >= 1){
die('ERROR FOUND SAME TXN ID IN DATABASE');
}else{
/*Data token = EAZZn0OkC2zo4H3CF9vrrSlU-grBGr0oQzE8NZ6jnYGRTuJkJS0howDNK48*/
$stmt = $dbo->prepare("UPDATE `order_bytes` SET stat=? ,paid=?, trans_id=? WHERE `tracker`=? AND `user_id`=?");
/*$stmt->bindValue(":stats", 'PAID', PDO::PARAM_STR);
$stmt->bindParam(":pay", $item_price, PDO::PARAM_STR);
$stmt->bindParam(":it", $item_transaction, PDO::PARAM_STR);
$stmt->bindParam(":trackers", $_SESSION['random_id'], PDO::PARAM_STR);
$stmt->bindParam(":uid", $_SESSION['byte_user'], PDO::PARAM_STR);*/
if(!$stmt->execute(array($payment_status,$payment_amount,$txn_id,$_SESSION['tracker'],$_SESSION['byte_user']))){
//print_r($stmt->errorInfo());
}else {
if($stmt->rowCount() == 1){
notify(getbyteuser($item_no),'A User Ordered your Byte<br />Tracker ID: '.$_SESSION['tracker'].'','NEW ORDER');
//mail_booked($item_transaction);
echo "<div class=\"alert alert-success\"><h3>Thank you<br>Your payment has been successfull</h3>
<p>Keep track of your order in your Dashboard</p>
</div>";
echo 'Done';
}else{
print alert_danger('Error');
}
}
}
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
echo "The response from IPN was: <b>" .$res ."</b>";
}
?>
You are confused about IPN and return page.
This is wrong:
so my question is, once the user has paid gets redirected to the success/ipn page
IPN is not a success page. It is a page that PayPal calls in the background to notify you about a transaction status. It is independent of the user session. (notify_url)
The page that PayPal redirects the user after complete (or cancel) a payment is different from the IPN. This is related to the user session (return_url)
Update - I removed the validation, and added an $item_id = $_POST['option_selection1']; to my field, and suddenly it worked!
I have a website for a photographer, and she is selling time slots throughout the day. I am trying to set her up so that someone chooses a time slot, purchases it through paypal, and then when the data is returned via IPN, I capture the email address used to make the purchase, as well as an id that I have associated with the time slot. With that ID, I am setting a toggle in the database that causes that time slot to no longer populate on the form, so others can't purchase the same time slot. Every time I make a test transaction, the database doesn't update, and I don't know why. When I manually set the values of the variables $payer_email and $item_number, the database does what I would expect it to do. From this, I'm under the impression that PayPal isn't validating the data, or it isn't sending the data in a way I'd expect it to.
Here is my code for the form that is running through PayPal:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id,hour,minute,toggle FROM mini ORDER BY id ASC";
$result = $conn->query($sql);
echo '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">';
echo '<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="B6XDLRPVAUBQJ">
<input type="hidden" name="on0" value="item_number">
<select name="os0">';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["toggle"] == 0){
echo '<option value="'.$row["id"].'">'.$row["hour"].':'.$row["minute"].' '; //id is what I'm trying to extract from paypal via IPN
if ($row["id"] < 13){echo 'AM';}else{echo 'PM';}; //if-then statement determines if it is AM or PM based on id
echo '</option>';
};
}
} else {
echo "Sorry, I'm fully booked!";
}
?>
</select>
<input type="submit" name="submit" value="Book Your Session">
</form>
Here is my code for the IPN
<?php
// STEP 1: read POST data
// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: POST IPN data back to PayPal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// The IPN is verified, process it:
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process the notification
// 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'];
// IPN message values depend upon the type of notification sent.
// To loop thffrough the &_POST array and print the NV pairs to the screen:
foreach($_POST as $key => $value) {
echo $key." = ". $value."<br>";
}
} else if (strcmp ($res, "INVALID") == 0) {
// IPN invalid, log for manual investigation
echo "The response from IPN was: <b>" .$res ."</b>";
}
//database credentials intentionally omitted :)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE mini SET toggle='1',email='".$payer_email."' WHERE id=('".$item_number."')";
if ($conn->query($sql) === TRUE) {
echo "<br/> - Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
?>
I'd suggest you to try using PaymentDetails API to debug the payment statuses that you are testing.
https://developer.paypal.com/docs/classic/api/adaptive-payments/PaymentDetails_API_Operation/
Also with PayPal sandbox is a little bit different, slower and buggier - so you should employ some logging. Log everything that is posted and the validation response. After having that you could focus on the app's logic.
I'm using paypals IPN for players to purchase points from my game. Once they purchase them it should update the users table where their Id is and give them points and energy, and then insert into a different table named transactions. I've tested it and the IPN is sending but it's not updating the database or inserting into the table. Here's the code:
<?php session_start() ?>
<?php require 'connect.php' ?>
<?php
// check if logged into PsychoWars
if(!$id) {
die('Error: Not Logged In! Contact Us With The Transaction ID!');
}
// 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://sandbox.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) {
// The IPN is verified, process it:
// check whether the payment_status is Completed (Done)
// check that txn_id has not been previously processed ()
// check that receiver_email is your Primary PayPal email (Done)
// check that payment_amount/payment_currency are correct (Done)
// process the notification
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
// Checking if package exists
$get_points = mysql_query("SELECT * FROM buying_offers WHERE id=".$item_number."");
if(mysql_num_rows($get_points) == 0) {
die('Error: Boss Point Offer Doesn\'t Exist!');
}
// Get Points Info
$points_info = mysql_fetch_array($get_points);
$points_cost = $points_info['cost'];
$points_amount = $points_info['points'];
$points_energy = $points_info['energy'];
$points_name = $points_info['package'];
// check that payment_amount/payment_currency are correct
if($payment_amount != $points_cost) {
die('Error: Payment Doesn\'t Equal Package Cost!');
}
if($receiver_email != 'bad.karma12323#gmail.com') {
die('Error: Paypal Email Doesn\'t Match!');
}
// checking payment status
if($payment_status == 'Completed'){
echo 'Success: You Were Rewarded '.$points_amount.' Boss Points And '.$points_energy.' Energy!';
$update_user = mysql_query("UPDATE users SET points=(points+".$points_amount."),energy=(energy+".$points_energy.") WHERE id=".$id."");
$add_trans = mysql_query("INSERT INTO transactions (user_id,txn_id,item_name,payment_status,cost,time) VALUES ('$id','$txn_id','$points_name','$payment_status','$payment_amount','".time()."')");
}
elseif($payment_status == 'Denied' || $payment_status == 'Failed' || $payment_status == 'Refunded' || $payment_status == 'Reversed' || $payment_status == 'Voided'){
die('Error: There Was An Issue With The Transaction!');
}
elseif($payment_status == 'In-Progress' || $payment_status == 'Pending' || $payment_status == 'Processed'){
//Do something
}
elseif($payment_status == 'Canceled_Reversal'){
die('Error: The Transaction Was Cancelled!');
}
// IPN message values depend upon the type of notification sent.
// To loop through the &_POST array and print the NV pairs to the screen:
foreach($_POST as $key => $value) {
echo $key." = ". $value."<br>";
}
} else if (strcmp ($res, "INVALID") == 0) {
// IPN invalid, log for manual investigation
echo "The response from IPN was: <b>" .$res ."</b>";
}
echo mysql_error();
?>
The IPN Message from paypal shows all of the variables going through, but like I said, Nothing's updating. Any help would be appreciated!
The paypal IPN doesn't enter the data into the mysql database for some reason!!
I am using paypal sandbox and the payments go through and they show in my sandbox account but the details wont show in the mysql!!
this is my IPN file. although I called it payments.php and I also used the IPN simulator to point to it and it did it said the IPN sent succesfully. So I don't know what the issue is here:
<?php
// Database variables
$host = "localhost"; //database location
$user = "my details"; //database username
$pass = "pass"; //database password
$db_name = "my details"; //database name
// PayPal settings
$paypal_email = 'MYSANDBOXEMAIL#PAYPAL.COM';
$return_url = 'http://some site/';
$cancel_url = 'http://some site/';
$notify_url = 'http://some site/thanks.php';
$item_name = 'Test Item';
$item_amount = 5.00;
// Include Functions
include("functions.php");
//Database Connection
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db_name);
// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
// Firstly Append paypal account to querystring
$querystring .= "?business=".urlencode($paypal_email)."&";
// Append amount& currency (£) to quersytring so it cannot be edited in html
//The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
$querystring .= "item_name=".urlencode($item_name)."&";
$querystring .= "amount=".urlencode($item_amount)."&";
//loop for posted values and append to querystring
foreach($_POST as $key => $value){
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
// Append paypal return addresses
$querystring .= "return=".urlencode(stripslashes($return_url))."&";
$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
$querystring .= "notify_url=".urlencode($notify_url);
// Append querystring with custom field
//$querystring .= "&custom=".USERID;
// Redirect to paypal IPN
header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
exit();
}else{
// 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 = 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'];
// 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)) {
$res = fgets ($fp, 1024);
if (strcmp($res, "VERIFIED") == 0) {
// Used for debugging
//#mail("you#youremail.com", "PAYPAL DEBUGGING", "Verified Response<br />data = <pre>".print_r($post, true)."</pre>");
// 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){
$orderid = updatePayments($data);
if($orderid){
// Payment has been made & successfully inserted into the Database
}else{
// Error inserting into DB
// E-mail admin or alert user
}
}else{
// Payment made but data has been changed
// E-mail admin or alert user
}
}else if (strcmp ($res, "INVALID") == 0) {
// PAYMENT INVALID & INVESTIGATE MANUALY!
// E-mail admin or alert user
// Used for debugging
//#mail("you#youremail.com", "PAYPAL DEBUGGING", "Invalid Response<br />data = <pre>".print_r($post, true)."</pre>");
}
}
fclose ($fp);
}
}
?>
Updated: Here is the function.php.. i hope this helps someone to help me resolve this!
<?php
// functions.php
function check_txnid($tnxid){
global $link;
return true;
$valid_txnid = true;
//get result set
$sql = mysql_query("SELECT * FROM payments WHERE txnid = '$tnxid'", $link);
if($row = mysql_fetch_array($sql)) {
$valid_txnid = false;
}
return $valid_txnid;
}
function check_price($price, $id){
$valid_price = false;
//you could use the below to check whether the correct price has been paid for the product
/*
$sql = mysql_query("SELECT amount FROM `products` WHERE id = '$id'");
if (mysql_numrows($sql) != 0) {
while ($row = mysql_fetch_array($sql)) {
$num = (float)$row['amount'];
if($num == $price){
$valid_price = true;
}
}
}
return $valid_price;
*/
return true;
}
function updatePayments($data){
global $link;
if(is_array($data)){
$sql = mysql_query("INSERT INTO payments (txnid, payment_amount, payment_status, itemid, createdtime) VALUES (
'".$data['txn_id']."' ,
'".$data['payment_amount']."' ,
'".$data['payment_status']."' ,
'".$data['item_number']."' ,
'".date("Y-m-d H:i:s")."'
)", $link);
return mysql_insert_id($link);
}
}
?>
It looks as if you are working a bit 'blind' because this is a 'headless' script and you don't know where it is failing.
Add some error_log lines at various points so that you can check the flow through the script. In particular, adding error_log($sql) just before you execute the DB query will print the statement to the error log. Take this and try to run it independently in the DB. It could be that some table constraints are failing rather than being an error in the PHP
Adding log lines at various points through the flow and printing out variables at those points will also help you diagnose where failure is happening and hopefully let you pinpoint the error more precisely.
Try Printing or echoing these values replacing - // Payment has been made & successfully inserted into the Database
print $data['item_name'];
print $data['item_number'];.......
And from there I could update till where it is correct and from where it is wrong.