Paypal умножает сумму на количество, поэтому его вставка правильных данных в таблицу с помощью ipn.php
Теперь на странице success.php можно получить количество в этой строке URL, чтобы яможно разделить ее на базовую цену и получить цену, хранящуюся в базе данных, чтобы она возвращала значение true, а платеж успешно напечатан на странице success.php.
Возможно ли получить количество в приведенном ниже URL-адресе или в базе данныхединственный способ сохранить количество в таблице платежей с помощью ipn.php?
http://localhost/x/success.php?amt=4.00&cc=USD&item_name=Battery%204000MAh&item_number=1&st=Completed&tx=3HW78993GG9423304
Products.php
<?php
//Include DB configuration file
include 'dbConfig.php';
//Set useful variables for paypal form
$paypalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; //Test PayPal API URL
$paypalID = '*****tator@gmail.com'; //Business Email
?>
<?php
//Fetch products from the database
$results = $db->query("SELECT * FROM products");
while($row = $results->fetch_assoc()){
?>
<img src="images/<?php echo $row['image']; ?>"/>
Name: <?php echo $row['name']; ?>
Price: <?php echo $row['price']; ?>
<form action="<?php echo $paypalURL; ?>" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="<?php echo $paypalID; ?>">
<!-- 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="<?php echo $row['name']; ?>">
<input type="hidden" name="item_number" value="<?php echo $row['id']; ?>">
<input type="hidden" name="amount" value="<?php echo $row['price']; ?>">
<input type="hidden" name="quantity" value="2">
<input type="hidden" name="currency_code" value="USD">
<!-- Specify URLs -->
<input type='hidden' name='cancel_return' value='http://localhost/x/cancel.php'>
<input type='hidden' name='return' value='http://localhost/x/success.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>
<?php } ?>
Success.php
<?php
include 'dbConfig.php';
//Get payment information from PayPal
$item_number = $_GET['item_number'];
$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];
//Get product price from database
$productResult = $db->query("SELECT price FROM products WHERE id = ".$item_number);
$productRow = $productResult->fetch_assoc();
$productPrice = $productRow['price'];
if(!empty($txn_id) && $payment_gross == $productPrice){
//Check if payment data exists with the same TXN ID.
$prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");
if($prevPaymentResult->num_rows > 0){
$paymentRow = $prevPaymentResult->fetch_assoc();
$last_insert_id = $paymentRow['payment_id'];
}else{
//Insert tansaction data into the database
// $insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
// $last_insert_id = $db->insert_id;
}
?>
<h1>Your payment has been successful.</h1>
<h1>Your Payment ID - <?php echo $last_insert_id; ?></h1>
<?php }else{ ?>
<h1>Your payment has failed.</h1>
<?php } ?>
ipn.php
<?php
//Include DB configuration file
include 'dbConfig.php';
/*
* 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
*/
$paypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
$ch = curl_init($paypalURL);
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_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close', 'User-Agent: company-name'));
$res = curl_exec($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 || strcasecmp($res, "VERIFIED") == 0) {
//Payment data
$item_number = $_POST['item_number'];
$txn_id = $_POST['txn_id'];
$payment_gross = $_POST['mc_gross'];
$item_quantity = $_POST['quantity'];
$currency_code = $_POST['mc_currency'];
$payment_status = $_POST['payment_status'];
//Check if payment data exists with the same TXN ID.
$prevPayment = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");
if($prevPayment->num_rows > 0){
exit();
}else{
//Insert tansaction data into the database
$insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status,item_quantity) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."','".$item_quantity."')");
}
}