Hey everyone!
I'm using PayPal 'buy it now' buttons on my website to sell products. Because I keep track of the number of units in stock for each product in a MySQL database and I'd like the inventory tracking in the system to be automated, I am using PayPal's Instant Payment Notification functionality to let me know when a purchase has been completed. When Paypal notifies my handler that a valid purchase has been made, the script updates my MySQL database by subtracting '1' from the inventory of the product purchased.
I've attached my IPN PHP code below that works successfully with Paypal buy it now buttons (one purchase at a time).
My Question is: I would like to substitute 'buy it now' buttons with PayPal's 'add to cart' buttons so that customers can purchase more than one product at a time. I'm unsure how I have to alter my code below to let it loop through all items purchased and update my database accordingly. Any help would be greatly appreciated!
The Code:
// Paypal POSTs HTML FORM variables to this page
// we must post all the variables back to paypal exactly unchanged and add an extra parameter cmd with value _notify-validate
// initialise a variable with the requried cmd parameter
$req = 'cmd=_notify-validate';
// go through each of the POSTed vars and add them to the variable
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.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
// In a live application send it back to www.paypal.com
// but during development you will want to uswe the paypal sandbox
// comment out one of the following lines
$fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30);
//$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
// or use port 443 for an SSL connection
//$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) {
$item_name = stripslashes($_POST['item_name']);
$item_number = $_POST['item_number'];
$item_id = $_POST['custom'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross']; //full amount of payment. payment_gross in US
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id']; //unique transaction id
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$size = $_POST['option_selection1'];
$item_id = $_POST['item_id'];
$business = $_POST['business'];
if ($payment_status == 'Completed') {
// UPDATE THE DATABASE
}