Home arrow PHP arrow Page 2 - Creating a Paypal IPN System in PHP - Part Two

Explaining the Code - PHP

This is the start of the actual creation of the PayPal IPN system using PHP. If you are looking for the entire script, you can download it at the end of this tutorial series. It is recommended that you read and understand the concept behind those scripts before testing the script on your own server. As noted in the title, this is the second part of a series.

  1. Creating a Paypal IPN System in PHP - Part Two
  2. Explaining the Code
By: Codex-M
Rating: starstarstarstarstar / 3
January 11, 2011

print this article



First, you need to state the product name, price and describe your product a little. This is a significant factor for your website conversion rate. Below is a screen shot showing what the test shopping page will look like (using the above source code) in the browser:

Second, you need to generate an invoice number, which is a long string of alphanumeric keys with which you need to associate each customer transaction. This invoice number will be used by the customer to validate the transaction and download the digital product. This invoice number should be unique for each customer and will be stored in the customer records database. The PHP script will ensure that the generated invoice number has not been used before.

The script below will connect to the MySQL database and then generate the invoice number:

//connect to MySQL database
include '/home/www/php-developer.org/paypal_ipn_demo/connect.php';
//invoice number and random key generator function
include '/home/www/php-developer.org/paypal_ipn_demo/invoicenumbergenerator.php';

Discussion of the invoice number generation function (invoicenumbergenerator.php) and database connection script (connect.php) will be covered in later sections.

You will notice that the shopping page is selling two products which are ebooks. The HTML code for the buttons, which are contained between <form> and </form> tags, are similar; they differ only in product name, product price and invoice number.

Now the interesting part is how the generated invoice number is added to the  PayPal Button HTML:

<input type="hidden" name="invoice" value="<?php invoicenumber(); ?>">

A PHP function named invoicenumber () is called, which will do the actual job of generating the invoice number on the server side, which will become the value of the invoice field.

Also, after the customer has paid in PayPal, a button will be shown to them, which will take them to "Click here to download your ebook."

<input type="hidden" name="cbt" value="CLICK HERE TO DOWNLOAD YOUR EBOOK">

This is done by defining the cbt field. When they click this button (with the above value) at the PayPal site, they will taken to the customer download page.

Finally, the customer IP address is also recorded, and passed to the PayPal IPN:

<input type="hidden" name="custom" value="<?php echo $_SERVER["REMOTE_ADDR"]; ?>">

This IP address will be saved in the customer records (IPN) database. When the customer lands on the download page (customerdownload.php) after successful payment in PayPal, the IP address of the customer will be recorded in the download page script. This IP address is then compared to the IP address associated with the invoice number (stored in the database) from the successful PayPal IPN transaction.

This will ensure that the correct customer can download the purchased product, and that it cannot be downloaded from other machines in case the invoice number is compromised.

For best security, the download page (customerdownload.php) should use SSL (https://) as well as the shopping page to prevent others from eavesdropping on this information.

Since everything is in PayPal's test environment, the button's HTML uses https://www.sandbox.paypal.com, instead of the actual PayPal URL: https://www.paypal.com/. You will be switching to the latter, actual URL once your entire PayPal IPN PHP application is fully working and tested.

Invoice Number Generator PHP Function (invoicenumbergenerator.php)

The following is the complete PHP script for the invoice number generator function, which will be used by your shopping page and PayPal buttons. This script is an included file from the index.php shopping page discussed in the previous section. The name of this file is invoicenumbergenerator.php:


//Since this is an included script, it needs to be protected with direct file access, so that the public users cannot just execute this script using a web browser

if ('invoicenumbergenerator.php' == basename($_SERVER['SCRIPT_FILENAME'])) {
die ('<h2>Direct File Access Prohibited</h2>');
else {
function invoicenumber(){

//generate invoice numbers between 1000 and 10000000000

//mt_rand function is recommended for producing more random results

$numbergenerator = mt_rand(1000,10000000000);

//generate invoice random key,credits:ripat at lumadis dot be

$chars = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789';

$max = strlen($chars)-1;
$invoicerandom = null;
for($i=0; $i < 15; $i++) {
$invoicerandom .= $chars{mt_rand(0, $max)};

//Now combine the generated numbers and the randomly generated alphanumeric keys to define the final invoice number


//Check that the invoice number has not been used before
 by comparing the generated numbers with those stored in MySQL database

while($fetch = mysql_fetch_array(mysql_query("SELECT `InvoiceNumber` FROM `customerrecords` WHERE `InvoiceNumber`='$generatedinvoicenumber'"))) {

//Invoice number already exists, generate another invoice number

$numbergenerator= mt_rand(1000,10000000000);

//echo the results

echo $generatedinvoicenumber;

MySQL database connection script (connect.php)

This is an include script in index.php, which also needs to be protected from direct file access:

if ('connect.php' == basename($_SERVER['SCRIPT_FILENAME'])) {
die ('<h2>Direct File Access Prohibited</h2>');
else {
$username = "Your MySQL database username";
$password = "Your MySQL database password";
$hostname = "Your MySQL hostname";
$database = "Your MySQL database name";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");

In the third part of the tutorial, you will learn to create the MySQL database tables, as well as other, related scripts that are needed in your PayPal PHP IPN application.

>>> More PHP Articles          >>> More By Codex-M

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: