Advertisement
PHP

Using PayPal's Instant Payment Notification with PHP

by

Hi there! Today we are going to combine Paypal with PHP to allow for the easy processing of payments on your website.

Finished Product: Preview

Step 1 - Creating a PayPal Account

For this tutorial you will need a Premier PayPal Account and an online website. Begin by going to paypal.com and click "signup" at the top of the page.

Step 1

Click Get Started under the Premier Title; you will be redirected to a signup form. Please fill in all necessary information. When your account has been created, login and move on to step 2.

Step 2 - Enable IPN

In this step we are going to enable Instant Payment Notification (IPN), so while logged in, please click Profile and then choose Instant Payment Notification

Step 2

Now on the next screen you will see that IPN is set to "off"; click "Edit" to change that.

At the start of this tutorial, I mentioned that you would need an online website. Why? Well we are going to ask PayPal to send us data when a payment is complete. PayPal can't reach local hosted websites unless you have all settings configured correctly. (This involves opening ports on your router). So, I'll enter the url to my validation script for example http://www.yourdomain.com/PayPal/ipn.php. PayPal will then post a notification to my server, at the URL I've specified.

Step 3 - Building a Simple HTML Page

Okay, now we need a simple and basic html page where your visitor can buy access to your download area.
I'm not going to explain all the HTML because i think you should know the basics of HTML before you start with PHP.

index.php - A simple HTML page with a stylesheet.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Nettuts.com | Purchase access to download area</title>
<link rel="stylesheet" type="text/css" media="All" href="css/style.css" />
</head>
<body>

	<div id="wrap">
		<h3>Purchase Access</h3>
		<p>Please click the button below to receive login details for the download area. <br />
		   Already have an account? <a href="login.php">Login</a> here.</p>
		   <!-- Paste your PayPal button code here (That you will get in the next step) -->
	</div>

</body>
</html>

css/style.css - A simple stylesheet for our HTML Page.

body{
	background: #2D2D2D; /* Set Website Background Color */
	font: 11px 'Verdana'; /* Set Website Font Size & Font Type */
}

#wrap{
	margin: 0 auto; /* Center Our Content */
	width: 500px; /* Set The Width For Our Content */
	background: #FFF; /* Set Content Background Color */
	padding: 10px; /* Set Padding For Content */
	border: 1px solid #000; /* Add A Border Around The Content */
}
step 3

Step 4 - Building a PayPal Button

We need to create a purchase button, so please click Merchant Services, and then chooseWebsite Payments Standard

You may choose three types of buttons, Sell single items, Sell multiple items and, Subscription. Now in this tutorial we are going to create a single item. When someone purchases this single item, in this case access to a download area. Once the payment has been validated, an email will be sent with there details.

Step 4

Let's enter some information for our purchase button; you may leave the rest as it is.

Step 4 Settings

When you have finished filling in each section, generate the code. Copy this code to your clipboard, and then paste it insideindex.php - where I added the comment in the html page. Please review step 3, if needed.

This should work perfectly. Users can click the button and complete their purchase.

Step 5 - Writing ipn.php

First, create ipn.php so we can start writing. We'll use a small snippet that I made from a larger snippet that you can get from Paypal's website.
Please note that there is no reason to learn this code out of your head! Snippets are handy and save time. I will break it down below.

<?php

mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("PayPal") or die(mysql_error());

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
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";

$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) {

// PAYMENT VALIDATED & VERIFIED!

}

else if (strcmp ($res, "INVALID") == 0) {

// PAYMENT INVALID & INVESTIGATE MANUALY!

}
}
fclose ($fp);
}
?>

Please fill in the correct credentials for your database so we can insert data in the next step.

PayPal POSTS data to the url we specified. In this example we only need the email address from the buyer, so that we may send him his login information. This code above will read the data PayPal sends and return the info to PayPal. I've added two comments where the code should come if its validated. Additionally, I've also added a comment that specifies what should be done if it's not validated.

Step 6 - Creating the Database

Now we are going to focus on what should happen if the payment is verified. First, we need to build a MySQL table where we store the users information. Just a simple one with an id, email and password field.

Next, we must enter our table details; we need an ID with a primary key selection and it should auto increment; next an email and password field.

For those of you don't have the time to enter all of this information, below is a small MySQL Dump code to recreate the table.

CREATE TABLE `users` (
  `id` int(10) NOT NULL auto_increment,
  `email` varchar(50) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Step 7 - Account Creation

Open ipn.php again. We are going to write the following code below the "// PAYMET VALIDATED" line.

Our first step is to retrieve the email address of the buyer; PayPal sends all of this info over to ipn.php.


// PAYMENT VALIDATED & VERIFIED!

$email = $_POST['payer_email'];

We must create one last variable - which is the password that we will generate using php.

// PAYMENT VALIDATED & VERIFIED!

$email = $_POST['payer_email'];
$password = mt_rand(1000, 9999);

As you can see, we used mt_rand to generate a random password - in this case a numeric value between 1000 and 9999. Next, we need to insert this data into our database. To do so, we'll use the mysql insert query.

// PAYMENT VALIDATED & VERIFIED!

$email = $_POST['payer_email'];
$password = mt_rand(1000, 9999);

mysql_query("INSERT INTO users (email, password) VALUES('". mysql_escape_string($email) ."', '".md5($password)."' ) ") or die(mysql_error());

Here we tell our script to insert the email and the password into our database. I've added a mysql_escape_string to ensure that mysql injection isn't possible. I've also added the md5 function to our password so that it will be stored as a 32-character hash. Now the account is created; let's move on to the next step.

Step 8 - Emailing the Login Credentials

We need to write some code that will email the login information to the buyer. To accomplish this, we will use the php mail function.

// PAYMENT VALIDATED & VERIFIED!

$email = $_POST['payer_email'];
$password = mt_rand(1000, 9999);

mysql_query("INSERT INTO users (email, password) VALUES('". mysql_escape_string($email) ."', '".md5($password)."' ) ") or die(mysql_error());

$to      = $email;
$subject = 'Download Area | Login Credentials';
$message = '

Thank you for your purchase

Your account information
-------------------------
Email: '.$email.'
Password: '.$password.'
-------------------------
            
You can now login at http://yourdomain.com/PayPal/';
$headers = 'From:noreply@yourdomain.com' . "\r\n";

mail($to, $subject, $message, $headers);

Let's break this email function down. We use the variable $email to get the user's email address and assign it to the $to variable.
The variable $subject is the title/subject that you will see in your email program. After this, we have our message, which will contain a thank you note as well as the account information. The $email and $password variables in the message will change to the correct information once the email has been sent. We also have set a custom header. When the user receives the email, the "from" address will display as "noreply@yourdomain.com".

Step 9 - Invalid Payment Email

An invalid payment might occur because of fraud, but also because of a problem with PayPal; so we want to make sure that our customer gets what he paid for.
So we are going to send an email to our site administrator, telling him to contact the buyer for more information. Simply copy the email code we used before and then make the changes listed below.

// PAYMENT INVALID & INVESTIGATE MANUALY!

$to      = 'invalid@yourdomain.com';
$subject = 'Download Area | Invalid Payment';
$message = '

Dear Administrator,

A payment has been made but is flagged as INVALID.
Please verify the payment manualy and contact the buyer.

Buyer Email: '.$email.'
';
$headers = 'From:noreply@yourdomain.com' . "\r\n";

mail($to, $subject, $message, $headers);

This code is nearly the same as above, only we made some changes to the receiver, subject and message.

Step 10 - User Login

This is our final step, where we build a simple login form for our buyers. Make a new php file, and name it login.php. We'll use the same HTML page as used for the index.php, only we will make some adjustments to the content of the page, and of course add a bit of styling to our login form.

login.php - This is the page where our buyers can login.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Nettuts.com | Login</title>
<link rel="stylesheet" type="text/css" media="All" href="css/style.css" />
</head>
<body>

	<div id="wrap">
		<h3>Login</h3>
		<p>Please enter your login credentials to get access to the download area</p>
		
		<form method="post" action="" >
			<fieldset>
				<label for="email">Email:</label><input type="text" name="email" value="" />
				<label for="password">Password:</label><input type="text" name="password" value="" />
				<input type="submit" value="Login" />
			</fieldset>
		</form>
		   
	</div>

</body>
</html>

Add to style.css

label{
	display: block; /* Make sure the label is on a single line */
	margin: 3px; /* Create some distance away from the input fields */
}

input{
	padding: 3px; /* Give the text some more space */
	border: 1px solid gray; /* Add a border around the input fields */
	margin: 3px; /* Create some distance away from the labels */
}

Now that we've made our form, we need to check if the login credentials are correct. I made a few changes to login.php so we can get started:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Nettuts.com | Login</title>
<link rel="stylesheet" type="text/css" media="All" href="css/style.css" />
</head>
<body>

	<div id="wrap">
		
		<?php 
		
		mysql_connect("localhost", "paypalUser", "test123") or die(mysql_error());
                mysql_select_db("PayPal") or die(mysql_error());

		
		if(isset($_POST['email']) && isset($_POST['password'])){
			// Verify
		}else{
		?>
	
		<h3>Login</h3>
		<p>Please enter your login credentials to get access to the download area</p>
		
		<form method="post" action="" >
			<fieldset>
				<label for="email">Email:</label><input type="text" name="email" value="" />
				<label for="password">Password:</label><input type="text" name="password" value="" />
				<input type="submit" value="Login" />
			</fieldset>
		</form>
		
		<?php
		}
		?>
		   
	</div>

</body>
</html>

The code above will check if email and password are both posted. If true, we can verify the credentials. If not, we return a error. The next code we are going to write will be placed below "// Verify". First we need to turn the post variables into local variables.

$email = mysql_escape_string($_POST['email']);
$password = md5($_POST['password']);

I've added an escape function to prevent mysql injection and have transformed the posted password into a md5 hash. Because we did this in our database, we must also hash the user's password to compare the two values correctly. Now it's time to verify the data.

$email = mysql_escape_string($_POST['email']);
$password = md5($_POST['password']);
			
$gUser = mysql_query("SELECT * FROM users WHERE email='".$email."' AND password='".$password."' LIMIT 1") or die(mysql_error());
$verify = mysql_num_rows($gUser);
			
if($verify > 0){
	echo '<h3>Login Complete</h3>
		  <p>Click here to download our program</p>';
}else{
	echo '<h3>Login Failed</h3>
		  <p>Sorry your login credentials are incorrect.';
}

As you can see, we are running a mysql query, and are selecting all the data from our user table - but only the row where the user's email address matches the one from the database.
mysql_num_rows checks if a match has been found: 1 = true; 0 = false.

That's All!

And that's the end of this tutorial. I hope you enjoyed it, and feel free to leave a comment with your thoughts. Have any tips that might help?

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Related Posts
  • Code
    Web Development
    Securely Handling User's Login CredentialsSecure wide retina preview
    Consider the following tips on how to properly secure your user's login credentials.Read More…
  • Web Design
    HTML/CSS
    Creating Friendlier, “Conversational” Web FormsForm retina
    Web forms are constantly a hot topic when it comes to web design and user interaction. The reasons for this are vast, but one of the more obvious reasons is that forms are the most basic way for a user to input information into your application. In this article, we'll discuss a few techniques that allow your forms to respond to the user's input, while helping to obscure unnecessarily confusing or overwhelming elements.Read More…
  • Web Design
    HTML/CSS
    The Truth About Multiple H1 Tags in the HTML5 EraH1 retina
    Whether you're a webmaster or a web designer, there's a question you've most likely either asked or answered many times over the years. That question is, "How many <h1> tags can I use per page, and how exactly should I implement them?"Read More…
  • Code
    PHP
    Authentication With Laravel 4Laravel 4 auth retina preview
    Authentication is required for virtually any type of web application. In this tutorial, I'd like to show you how you can go about creating a small authentication application using Laravel 4. We'll start from the very beginning by creating our Laravel app using composer, creating the database, loading in the Twitter Bootstrap, creating a main layout, registering users, logging in and out, and protecting routes using filters. We've got a lot of code to cover, so let's get started!Read More…
  • Code
    Scala
    Building Ribbit in ScalaRibbit scala retina preview
    In this tutorial we will implement the Ribbit application in Scala. We'll be covering how to install the Play web framework, a NetBeans plugin for it, and finally the code in Scala. If you are new to Scala, check out this previous tutorial which will help you set up your environment and provides you with a general platform that you can build upon. Even though the essence of Ribbit is to create/send/read Ribbits (our version of tweets), we will spend a large part of this tutorial explaining how Play works, authentication, and persistence. After these are in place, the rest becomes much easier. We will also implement ribbit creation, submission and listing out all ribbits. Following someone, advanced user settings, and direct messages will be an extra assignment for you to complete on your own. I am sure if you manage to follow along with this tutorial and create Ribbit as explained below, these three functionalities will be easily accomplished as homework.Read More…
  • Code
    JavaScript & AJAX
    Adding Bitcoin Payment Processing to Your WebsiteBitcoin retina preview
    Bitcoin has definitely started to become more mainstream, and with its global reach and minimal fees, it is a payment method worth considering. In this article, we will take a look at what Bitcoin is, as well as how to start accepting them in your applications.Read More…