Creating a Paypal IPN System in PHP – Part Two

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.

Create “Buy Now” Buttons

The first step in this process is to create “Buy Now” buttons.

1. Log in to the PayPal Sandbox: https://developer.paypal.com/

2. Click “Test Accounts.”

3. Check the radio button for your test and verified “Business” account.

4. Click “Enter Sandbox Test Site.”

5. Log in using your “Business” account credentials, which you created in the first part of this series.

6. Click “Merchant Services.”

7. Under “Create Buttons,” click “Buy Now.”

8. Fill in "Item name," e.g Codex Ebook, "Price," e.g 30 and "Currency," e.g. USD.

The Item ID and the rest, which are not specified above, are optional. However, make sure “use my secure merchant account ID” is selected.

9. Click “Step 2,” and uncheck “Save Button at PayPal.”

10. Click “Step 3,” and since this tutorial is for selling digital products such as downloads (e.g ebook, mp3, etc) using the PayPal IPN system, set the answer to “NO” for the following items:

  • Do you want to let your customer change order quantities?
  • Can your customer add special instructions in a message to you?
  • Do you need your customers shipping address?

11. Check “Take customers to this URL when they cancel their checkout.” For the purpose of this tutorial, it will be set to:

http://www.php-developer.org/paypal_ipn_demo/

12. Check “Take customers to this URL when they finish checkout.” In this tutorial, this URL will be used:

http://www.php-developer.org/paypal_ipn_demo/customerdownload.php

13. Check “Add advanced variables,” and add the following:

cbt=CLICK HERE TO DOWNLOAD YOUR EBOOK
invoice=1
custom=1

Some of those values will be changed later. Finally, click “Create Button.” Click “Remove code protection” and click “select code.” Copy the resulting HTML code to a text editor and save it. Since your button is not protected, you will rely on IPN and PHP validation to authenticate and validate a customer transaction.

Create a Shopping Page for Your Products

Now that you have created the “Buy Now” buttons, you can create the shopping page for your products.

Let’s name this file index.php; you will place it inside a folder named ”paypal_ipn_demo” in your test server.

Here is the complete working HTML code and script (index.php):

<html>
<head>
<title>Example Shopping Page-PayPal IPN Demo</title>
</head>
<body>
<h3>Buy my ebook</a>
A newly released ebook that I wrote, Codex ebook for $30:
<br />
<br />
<?php
//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’;
?>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="6GTE64BZPKGFG">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item_name" value="Codex Ebook">
<input type="hidden" name="amount" value="30.00">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="http://www.php-developer.org/paypal_ipn_demo/customerdownload.php">
<input type="hidden" name="cancel_return" value="http://www.php-developer.org/paypal_ipn_demo/">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest">
<input type="hidden" name="cbt" value="CLICK HERE TO DOWNLOAD YOUR EBOOK">
<input type="hidden" name="invoice" value="<?php invoicenumber(); ?>">
<input type="hidden" name="custom" value="<?php echo $_SERVER["REMOTE_ADDR"]; ?>">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
<br /><br />
Or my previous book entitled "How to behave like a child" for $15.
<br /><br />
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="6GTE64BZPKGFG">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item_name" value="How to behave like a child">
<input type="hidden" name="amount" value="15.00">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="http://www.php-developer.org/paypal_ipn_demo/customerdownload.php">
<input type="hidden" name="cancel_return" value="http://www.php-developer.org/paypal_ipn_demo/">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted">
<input type="hidden" name="cbt" value="CLICK HERE TO DOWNLOAD YOUR EBOOK">
<input type="hidden" name="invoice" value="<?php invoicenumber(); ?>">
<input type="hidden" name="custom" value="<?php echo $_SERVER["REMOTE_ADDR"]; ?>">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
<br /><br />
You can pay safely with PayPal. Thank you for your interest in my books.
<?php
//close database connections
mysql_close($dbhandle);
?>
</body>
</html>

{mospagebreak title=Explaining the Code}

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:

<?php
//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:

<?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
$generatedinvoicenumber=$numbergenerator.$invoicerandom;

//Sanitize
$generatedinvoicenumber=mysql_real_escape_string($generatedinvoicenumber);

//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);
$generatedinvoicenumber=$numbergenerator.$invoicerandom;
}

//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:

<?php
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.

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan