Last active
June 6, 2022 08:34
-
-
Save sanjaybhowmick/5b3279b3e26dbef78bd7193ef6143e35 to your computer and use it in GitHub Desktop.
PayPal IPN Integration - PHP & MySQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE IF NOT EXISTS `payments` ( | |
`id` int(6) NOT NULL AUTO_INCREMENT, | |
`txnid` varchar(20) NOT NULL, | |
`payment_amount` decimal(7,2) NOT NULL, | |
`payment_status` varchar(25) NOT NULL, | |
`itemid` varchar(25) NOT NULL, | |
`createdtime` datetime NOT NULL, | |
PRIMARY KEY (`id`) | |
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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_num_rows($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); | |
} | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Paypal IPN Integration Web Form</title> | |
</head> | |
<body> | |
<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="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" /> | |
<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="[email protected]" /> | |
<input type="hidden" name="item_number" value="123456" / > | |
<input type="submit" name="submit" value="Submit Payment"/> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Payment Cancelled</title> | |
</head> | |
<body> | |
<h1>Payment Cancelled</h1> | |
<p>Your payment was cancelled.</p> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Payment Successful</title> | |
</head> | |
<body> | |
<h1>Thank You</h1> | |
<p>Your payment was successful. Thank you.</p> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Database variables | |
$host = "localhost"; //database location | |
$user = ""; //database username | |
$pass = ""; //database password | |
$db_name = ""; //database name | |
// PayPal settings | |
$paypal_email = '[email protected]'; | |
$return_url = 'http://domain.com/payment-successful.html'; | |
$cancel_url = 'http://domain.com/payment-cancelled.html'; | |
$notify_url = 'http://domain.com/payments.php'; | |
$item_name = 'Test Item'; | |
$item_amount = 5.00; | |
// 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)."&"; | |
//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 { | |
//Database Connection | |
$link = mysql_connect($host, $user, $pass); | |
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.1\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('[email protected]', '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 | |
} else { | |
// Error inserting into DB | |
// E-mail admin or alert user | |
// mail('[email protected]', '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("[email protected]", "PAYPAL DEBUGGING", "Invalid Response<br />data = <pre>".print_r($post, true)."</pre>"); | |
} | |
} | |
fclose ($fp); | |
} | |
} | |
?> |
I'm having trouble for the data inserting to the database
insert to DB code are not working
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for your recommendation. I have updated the gist.