Paypal IPN with PhP

Wraping it together

Now that we have a verification and data insertion function, we need to actually wrap the two together. A simple set of lines like this would suffice.

 $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";
$fp = fsockopen ('ssl://', 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'];
if (!$fp) {
} else {
	fputs ($fp, $header . $req);
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0) {
			// check 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
		else if (strcmp ($res, "INVALID") == 0) {
			// log for manual investigation
	fclose ($fp);

The “BLANKED OUT” portion is for your secure merchant ID, this can be seen on your profile page
of your PayPal account, such as this example:
Secure Merchant ID

Checking against your Merchant ID is more secure because the number is not stored in your buy now form, nor is it made known to the buyer. It also prevents a potential buyer from paying themselves and using your notification url in order to fake a “valid” transaction that never made it to your own account. Because essentially if someone did pay themselves on paypal, it would be a valid transaction according to paypal’s IPN script if you did not check against the receiver email or secure merchant ID.

It is also usually a good idea to notify yourself of any irregularities or unexpected settings in the transaction, such as receiving funds in a currency you are not familiar with. If so decided you can also check against a buyer’s verified status by looking at $_POST[‘payer_status’] which will return either verified, or unverified.

A successful transaction will have $_POST[‘payment_status’] set to “Completed”.

For a list of more IPN variables such as transaction type, have a look at this page: IPN and PDT Variables.

Comments are closed.