You are on page 1of 7

Version 1.

0
Create a site for e-commerce
Release Date: 2/14/2005
with PHP, MySQL, and PayPal

Copyright 2005 CNET Networks, Inc. All rights reserved.
To see more downloads and get your free TechRepublic membership, please visit
http://techrepublic.com.com/2001-6240-0.html

By Phillip Perkins


Takeaway
Adding e-commerce capabilities to your existing Web site does not necessarily require extensive
development time. This download shows you one way to add commercial functionality without a major
allocation of scarce resources.


This article was originally published on Builder.com in the February 3, 2004, Web Development Zone
newsletter, and was written by Phillip Perkins. Keep your developer skills sharp by automatically signing up
for TechRepublic's free Web Development Zone newsletter, delivered each Tuesday.



Table of Contents
CREATE A SITE FOR E-COMMERCE..........................................................................................................................................................2
SETTING UP THE SITE .........................................................................................................................................................................................2
GETTING DONATIONS (PAYMENTS) VIA PAYPAL................................................................................................................................................2
CREATING THE SITE...........................................................................................................................................................................................2
Listing A.......................................................................................................................................................................................................3
Listing B.......................................................................................................................................................................................................4
DESCRIPTION.....................................................................................................................................................................................................7
VERSION HISTORY .............................................................................................................................................................................................7
1.0............................................................................................................................................................................................................7
o Bug fixes .............................................................................................................................................................................................7
o Feature changes .................................................................................................................................................................................7
TECHREPUBLIC SITE FEATURES.........................................................................................................................................................................7


Page 1 of 7
Version 1.0
Create a site for e-commerce
Release Date: 2/14/2005
with PHP, MySQL, and PayPal

Copyright 2005 CNET Networks, Inc. All rights reserved.
To see more downloads and get your free TechRepublic membership, please visit
http://techrepublic.com.com/2001-6240-0.html
Create a site for e-commerce
A friend recently asked me to coordinate his bachelor party, so I decided to apply some of my developer
skills to help organize this soiree.
I'm going to set up a public Web site to collect attendees' names, addresses, phone numbers, and e-mail
addresses. And, rather than driving around town to pick up any financial contributions for the evening, I'm
going to collect donations by pointing the guys to PayPal.
Setting up the site
The first order of business was to find a cheap hosting service. I chose Sureshot Hosting, which provides
PHP and MySQL support. Other details include 1 GB of space, 10-GB data transfer, unlimited e-mail
addresses, and other niceties such as some acceptable administrative tools. With a few clicks, I have a
pretty inexpensive hosting service.
Since I'm more of a business application designer, the hardest part of this project was getting some form of
graphical design. Also, I have limited time for this project, so I opted to leave the graphic design to two of
my friends. This way, I can focus on the more important parts of the sign-up process.
When partygoers visit the site, they'll receive specific information regarding the event, such as time,
location, and an estimation of the party's cost. The user must fill out their first name, last name, and e-mail
address; optional fields include address and phone number(s). The data is stored in a MySQL database for
later access. After invitees sign up to go to the party, they're presented with an option to donate to the
event. This is the most exciting part (at least in geek terms).
Getting donations (payments) via PayPal
PayPal provides the ability to set up an e-commerce site for people who don't have the infrastructure to
support e-commerce. You can do this by signing up for either a Premier or Merchant account with PayPal.
Once you have an account, you can receive payments for a reasonable fee per transaction.
You can also create a method for customizing your own site to handle payments through PayPal. (PayPal's
site offers more information about this capability.) These tools allow you to create a button for your site so
you can forward visitors to PayPal to make payments to your account. You have the option of choosing to
include return URLs for completed or cancelled transactions. And, you can get payment notifications
instantly through PayPal's Instant Payment Notification (IPN). With IPN, you can track payments made to
your account.
Since I'm only collecting money in simple transactions, I'm going to make a Donation button on my site.
However, there are tools for creating a full-fledged shopping cart application with the PayPal tools.
Creating the site
I'll collect information from the attendees of my friend's bachelor party by using PHP and MySQL. Then, I'll
forward the guys to PayPal so they can make a donation to help cover the party's expenses. I'm using an
inexpensive hosting service that features support for PHP and MySQL, so the only thing I have left to do is
set up the site. (Note: You should take great care when setting up any e-commerce site in order to protect
your users from data theft. Since I'm using PayPal, that overhead is part of the PayPal service.)
Page 2 of 7
Version 1.0
Create a site for e-commerce
Release Date: 2/14/2005
with PHP, MySQL, and PayPal

Copyright 2005 CNET Networks, Inc. All rights reserved.
To see more downloads and get your free TechRepublic membership, please visit
http://techrepublic.com.com/2001-6240-0.html
The first page will collect the user information (i.e., first names, last names, e-mail addresses, and the
amount they plan to donate, along with optional fields for addresses and phone numbers) so that I can
store it on MySQL.
The next page will store the user information into a MySQL table and create another page that will forward
them to PayPal. This page will provide a text <input>for the donation amount. The necessary information
is then forwarded to PayPal. (Listing A)
Listing A
<html>
<body>
<?php
$connection = mysql_connect("localhost", " dbuser", "dbuserpass");
mysql_select_db("PRIMARY");
$result = mysql_query("SELECT * FROM GUEST_LIST WHERE email = '" .
$_POST["email"] . "'");
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
echo "This email address has already been registered.<br>";
} else {
$sql = "INSERT INTO GUEST_LIST (first_name, last_name, email) VALUES ('" .
$_POST["fname"] . "', '" . $_POST["lname"] . "', '" . $_POST["email"] . "')";
$result = mysql_query($sql) or die("Cannot do this query: " .
mysql_error());
if (mysql_affected_rows() > 0) {
$result = mysql_query("SELECT LAST_INSERT_ID()");
$row = mysql_fetch_array($result);
$guest_id = $row[0];
?>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="myemail@mysite.com">
<input type="hidden" name="custom" value="<?= $guest_id ?>">
<input type="hidden" name="return" value="http://www.mysite.com/thankyou.php">
<input type="hidden" name="item_name" value="Bill's Party">
Donation Amount:
$<input type="text" name="amount">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cancel_return"
value="http://www.mysite.com/cancel.php">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="tax" value="0">
<input type="image" src=https://www.paypal.com/en_US/i/btn/x-click-but04.gif
name="submit">
</form>
<?php
} else {
echo "There was an error writing to the database.";
}
}
mysql_close($connection);
?>
</body>
</html>
Page 3 of 7
Version 1.0
Create a site for e-commerce
Release Date: 2/14/2005
with PHP, MySQL, and PayPal

Copyright 2005 CNET Networks, Inc. All rights reserved.
To see more downloads and get your free TechRepublic membership, please visit
http://techrepublic.com.com/2001-6240-0.html
First, the e-mail address is checked to see if it's already registered. If it is, the page simply outputs that it's
been registered. If not, the data is stored, the auto ID generated by the table is returned, and a form is
produced that points to PayPal. The form values that PayPal expects are all included for the donation. The
custom form element is used to store the auto ID so that when PayPal returns the donation information,
this value can be used to coordinate the donation amounts. PayPal will return the information to the
thankyou.php page as POST data. This is denoted by the rm form element set to 2.
The user enters the donation amount and is taken to PayPal, where he logs in and signs up (if necessary).
After a successful payment, the user is directed to thankyou.php. You can use this page to update the
payment information on the local database but, since I'm going to be using PayPal's Instant Payment
Notification (IPN), I'll just present the user with a simple thank you and a link back to the home page. This
is the same for the cancel page.
When a payment is made successfully, PayPal's IPN will send a notification to another page called
paypalipn.php, which is set up in the Profile area of your PayPal account. And when a payment notification
is received, I want to update my database to confirm the donation amount. Creating the code doesn't take
much work because PayPal's site provides sample code. I've taken the sample code and added a little of
my own custom code as you can see in Listing B.
Listing B
<?php
// read the post from PayPal system and add 'cmd'
set_error_handler("errorHandler");

$header = "";
$connection = mysql_connect("localhost", "dbuser", "dbuserpass");
mysql_select_db ("PRIMARY");
$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}

error_log("$req \r\n", 3, realpath("paypal.log"));
// 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("www.paypal.com", 80, $errno, $errstr, 60);
// 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) {
// HTTP ERROR
error_log("Could not connect to PayPal.\r\n$errstr", 3, realpath("paypal.log"));
} else {
Page 4 of 7
Version 1.0
Create a site for e-commerce
Release Date: 2/14/2005
with PHP, MySQL, and PayPal

Copyright 2005 CNET Networks, Inc. All rights reserved.
To see more downloads and get your free TechRepublic membership, please visit
http://techrepublic.com.com/2001-6240-0.html
fputs ($fp, $header . $req);
$status = socket_get_status($fp);
$bytes_left = $status['unread_bytes'];
while (!feof($fp) || $bytes_left > 0) {
$res = fgets ($fp, 1024);
$status = socket_get_status($fp);
$bytes_left = $status['unread_bytes'];
if (strcmp ($res, "VERIFIED") == 0) {
// check the payment_status is Completed
if (strcmp ($payment_status, "Completed") == 0) {
// check that txn_id has not been previously processed
$result = mysql_query("SELECT * FROM PAYPAL WHERE transaction_id = '$txn_id'");
if (mysql_num_rows($result) == 0 && strcmp($receiver_email, "myemail@mysite.com") == 0) {
// check that payment_amount/payment_currency are correct
// process payment -- write donation in MySQL table
$result = mysql_query("SELECT guest_id FROM GUEST_LIST WHERE email =
'$payer_email'");
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$guest_id = $row["guest_id"];
$result = mysql_query("INSERT INTO PAYPAL (guest_id, transaction_id, amount)
VALUES
($guest_id, '$txn_id', $payment_amount)");
if (mysql_affected_rows() == 0) {
//log error.
error_log("Could not insert $payment_amount into PAYPAL with $payer_email
\r\n", 3,
realpath("paypal.log"));
}
}
} else {
error_log("Possible problems\r\nTransaction ID: $txn_id\r\nReceiver Email:
$receiver_email\r\n", 3, realpath("paypal.log"));
}
mysql_free_result($result);
}
} else {
// log for manual investigation
}
}
fclose ($fp);
}
mysql_close($connection);

function errorHandler($errno, $errstr, $errfile, $errline) {
$d = getdate();

error_log($d['mon']."/".$d['mday']."/".$d['year']."T".$d['hours'].":".$d['minutes'].":".$d['seconds']."
Error:
$errno in $errfile\nLine:$errline $errstr \n\n", 3, realpath("errlog.log"));
mail("phillip@phillipweb.com", "Error In $errfile", "Error: $errno\n$errstr\nin
$errfile\nLine:$errline");
exit;
}

?>
Page 5 of 7
Version 1.0
Create a site for e-commerce
Release Date: 2/14/2005
with PHP, MySQL, and PayPal

Copyright 2005 CNET Networks, Inc. All rights reserved.
To see more downloads and get your free TechRepublic membership, please visit
http://techrepublic.com.com/2001-6240-0.html
Also, when I receive the payment notification, I must send all the information back to PayPal to verify the
payment as a security measure. PayPal will respond with either VERIFIED or INVALID. If the payment is
verified, you can trust that the payment notification you received is authentic. Once the payment is verified,
I place an entry in my PAYPAL table for the guest_id. (Any database errors are written to a paypal.log log
file.) I can then use the amount information to display a total amount donated on another Web page.
If you'd like more information on the tools PayPal offers, then visit the site and look under the Merchant
Tools tab. (For some functionality, such as the button wizard, you need to log in.)
Page 6 of 7
Version 1.0
Create a site for e-commerce
Release Date: 2/14/2005
with PHP, MySQL, and PayPal

Copyright 2005 CNET Networks, Inc. All rights reserved.
To see more downloads and get your free TechRepublic membership, please visit
http://techrepublic.com.com/2001-6240-0.html
Description
The techniques outlined in this download show how to implement the basic principles of commerce using a
distinct method and programming language. The method has advantages and disadvantages, but it will
achieve the basic goal of recording a transaction. Using the lessons learned in this download will provide
you a platform from which you can launch your Web-based e-commerce application development project.
Version history
1.0
o Bug fixes
o Feature changes
TechRepublic communities engage IT professionals in the ultimate peer-to-peer experience, providing
actionable information, tools, and services to help members get their jobs done. TechRepublic serves the
needs of the professionals representing all segments of the IT industry, offering information and tools for IT
decision support and professional advice by job function.
TechRepublic site features
Free newsletters: Keep up-to-date with the IT industry with our newsletters, which cover various topics
including disaster recovery, Internet security, Microsoft Office, e-mail administration, management advice,
and much more.
Free downloads: We've collected resources to make your job easier, including ready-to-use IT forms and
templates, checklists, tools, executables, Gartner product analyses, and white papers.
TechRepublic's books and CDs: Find the latest books and CDs about today's critical IT topics, including
PC troubleshooting, VPN, TCP/IP, Windows client and server issues, and Cisco administration.
Discussion center: Open a discussion thread on any article or column or jump into preselected topics:
career, technology, management, and miscellaneous. The fully searchable Discussion Center brings you
the hottest discussions and threads and allows you to sort them by topic. Our online IT community provides
real-world solutions and the latest articles, resources, and discussions affecting frontline IT pros. Get
access to more than 250 full-text IT books, along with exclusive downloads and in-depth articles on
network and system administration, PC troubleshooting, help desk and support issues, and more.
Page 7 of 7

You might also like