create a web storefront using php, derby and paypal, part 2: … · 2010. 1. 15. · paypal, part...

40
Create a Web storefront using PHP, Derby and PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with Derby Skill Level: Intermediate Tyler Anderson ([email protected]) Freelance Writer Stexar Corp. 15 Nov 2005 This series chronicles the building of a Web storefront in PHP using PHP Data Objects to access a Derby database. The storefront includes a user manageable shopping cart that allows item purchases using PayPal, and includes the ability for merchants to notify customers via e-mail on successful orders automatically. Part 2 covers creating shopping carts and making payments via PayPal. Section 1. Before you start This series is for those interested in expanding the storefront created in Part 1 of this three-part series by integrating a fully functional shopping cart in PHP with Derby and making payments with PayPal. This tutorial assumes knowledge of PHP, including PHP data objects and user sessions, as covered in Part 1. About this series Our hypothetical situation for this series is Ghastly Computers, a computer hardware and software shop. Its owners want to set up a presence online, and for obvious reasons, they want the online store to be constructed and managed with minimal fuss. This three-part series covers the whole process, from creating a storefront with an integrated shopping cart from scratch in PHP to using PayPal for payment. With Collecting payments © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 40

Upload: others

Post on 22-Aug-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Create a Web storefront using PHP, Derby andPayPal, Part 2: Collecting paymentsAlso, creating shopping carts and storing their data with Derby

Skill Level: Intermediate

Tyler Anderson ([email protected])Freelance WriterStexar Corp.

15 Nov 2005

This series chronicles the building of a Web storefront in PHP using PHP Data Objectsto access a Derby database. The storefront includes a user manageable shopping cartthat allows item purchases using PayPal, and includes the ability for merchants tonotify customers via e-mail on successful orders automatically. Part 2 covers creatingshopping carts and making payments via PayPal.

Section 1. Before you start

This series is for those interested in expanding the storefront created in Part 1 of thisthree-part series by integrating a fully functional shopping cart in PHP with Derbyand making payments with PayPal. This tutorial assumes knowledge of PHP,including PHP data objects and user sessions, as covered in Part 1.

About this series

Our hypothetical situation for this series is Ghastly Computers, a computer hardwareand software shop. Its owners want to set up a presence online, and for obviousreasons, they want the online store to be constructed and managed with minimalfuss. This three-part series covers the whole process, from creating a storefront withan integrated shopping cart from scratch in PHP to using PayPal for payment. With

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 40

Page 2: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

e-commerce booming and a growing number of online shoppers using PayPal andother forms of payment to make purchases, creating an online storefront is a goodway to attract customers from around the world. The benefit of creating a shoppingcart from scratch is the absolute control it gives programmers.

Part 1 focuses on setting up a Derby database and creating the basic storefront. Youwill access Derby through PHP data objects. User sessions are started to help setup for this part of the series, where a shopping cart will be associated with a user'ssession ID.

Part 2 covers creating and managing the shopping cart. The shopping cart will bestored in the Derby database, and the user's session id will become the id of theircart. The shopping cart, if containing any items, will be shown under the listing ofcategories in the storefront with Manage cart and Checkout links. Checking out willinvolve taking a users bill-to/ship-to information, which will be submitted for paymentto PayPal. After completing the payment to PayPal, the user is then shown athank-you page, and is given a new session ID.

Part 3 will cover viewing orders, shipping, and e-mail notification. Transactions usingPHP data objects will also be introduced. Adding shipping to the checkout processwill be incorporated via UPS, offering real-time shipping prices. E-mail notificationwill be sent to the customer showing an order summary. PayPal, by default, alsosends a payment confirmation e-mail to the user and the merchant.

About this tutorial

This tutorial details the creation of a shopping cart, and the added ability of users tomake payments using PayPal. You will create new tables for the database that willhold shopping cart, and customer and order information. Then you will create theshopping cart and display it in the side panel. A page to manage the shopping cartwill also be created. Checking out is a five-step process:

1. User will enter bill-to/ship-to information.

2. User will view a summary and "confirm order" page.

3. User will be taken to PayPal for payment.

4. User is returned to the Web site to a thank-you page.

5. PayPal notifies the storefront of successful payment.

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 2 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Prerequisites

To follow along, you will need to install and test the following tools:

Web serverPick any Web server and operating system. Feel free to use Apache V2.X, orthe IBM HTTP Server.

PHPDue to the use of PHP data objects, the latest version, PHP V5.1, is necessaryto fully follow along in this tutorial. Note that V5.1 is is a release candidate (RC)and is not yet an official release. Be sure to configure PHP with the followingoption to include support for Derby:--with-pdo-odbc=ibm-db2,/home/db2inst1/sqllib. See Resourcesfor information about configuring Apache or the IBM HTTP Server with PHP.

DatabaseThis tutorial uses Derby. Download Derby V10.1, the current IBM DB2 JDBCUniversal Driver, and the DB2® run-time client from IBM. Be sure to follow theinstructions on each page carefully. Follow either the Linux® or Windows®instructions for downloading and installing the DB2 run-time client.You may also use Cloudscape for this tutorial. The internals of Cloudscape arethe same as Derby. However, the DB2 JDBC Universal Driver and other thingsare packaged into Cloudscape, and it is supported by IBM. DownloadCloudscape V10.1, and the DB2 run-time client from IBM.

Java™Derby requires Java technology. I have found the gcj provided in Red Hat Linuxdistributions insufficient. Download Java technology from Sun.

Section 2. Setting up

Introducing the new database tables

Now we will set up the shopping cart for Ghastly Computers, as well as provide formaking and paying for orders. This requires more tables to facilitate suchfunctionality:

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 40

Page 4: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

CustomersEveryone who wants to make a purchase needs to enter his personalinformation. This table will hold all the necessary billing and shippinginformation, including e-mail, first name, last name, street address, city, state,ZIP code, and phone number.

Shopping cartsEvery customer gets a shopping cart. This table keeps track of a shopping cartuntil the customer pays. The following fields are necessary for this table:cartid and email. The email field corresponds to the email field in thecustomer table, and will be empty until a customer checks out and enters in hispersonal information.

Shopping cart contentsEvery shopping cart contains items. This is the table that holds this information,including cartid, productid, quantity, and attribute value. The cartid fieldcorresponds to the cartid field in the shopping cart field. Thus, the two canbe joined on cartid to determine the contents of a user's shopping cart. Theproductid field corresponds to the productid field of the products fieldcreated in Part 1 of this series. The details of a product can be retrieved byjoining this table and the products table. The attribute value is simply a textvalue describing the chosen attribute, followed by its value, and does notcorrespond to any of the other tables. A possible extension to the storefrontapplication would be to further parameterize this table to allow more attributesper product.

OrdersThe orders table will hold information about the status of current orders,including cartid, email, amount due, and status. The cartid fieldcorresponds to the shopping cart table, and so the two tables can be joined onthis field. The email field corresponds to the email field in the customer table,and so these two tables can be joined on the two email fields. The amountdue will contain how much the customer owes on the order, and the status fieldwill hold the result from PayPal's Instant Payment Notification: Pending onINVALID responses and Processing on VERIFIED responses.

Creating the tables

The customer table is essential for logging ship-to and contact information forcustomers. Create this table at an ij prompt, as you did in Part 1.

Listing 1. Creating the customer table

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 4 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

create table customers(email varchar(256) primary key,first_name varchar(30),last_name varchar(30),street_address varchar(100),city varchar(30),state varchar(30),zipcode varchar(5),phone_number varchar(30));

The following output reveals success every time a table is created:

0 rows inserted/updated/deleted

Create the shopping cart table at the ij prompt:

create table shopping_carts(cartid integer primary key,email varchar(256));

This table connects to the next table, the shopping cart contents table.

Listing 2. Creating the shopping cart contents table

create table shopping_cart_contents(cartid integer,productid integer,qty integer,attribute_value varchar(30));

The next table, the orders table, connects to the shopping carts.

Listing 3. Creating the orders table

create table orders(cartid integer primary key,email varchar(256),amount_due decimal(10,2),status varchar(20));

Notice that the orders table connects to the other three tables. It connects toshopping carts and shopping cart contents using cartid; it uses email to connectto customers.

New constants

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 40

Page 6: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

The following new constants are important as you connect to PayPal:

Listing 4. Defining new constants

define('IMAGEURL', "images/");define('MY_EMAIL', "[email protected]");define('PAYPAL_URL',"www.sandbox.paypal.com");define('MY_URL',"localhost.localdomain");

function db_connect($dbname='PAYPAL',$username='paypaluser',

MY_EMAIL is the e-mail you entered when you registered for a PayPal account onPayPal or on PayPal Developer Central. PAYPAL_URL is the PayPal URL you willconnect users to for payment. It's currently set to the PayPal Sandbox because thePayPal Sandbox doesn't support real payments, making it a good testingenvironment for your application. MY_URL is the domain name of your Web site.

Section 3. The shopping cart

Ghastly Computers wants users to see their shopping carts at all times in the sidepanel, tempting them to check out and purchase the items. This section coverscreating and viewing the shopping cart.

Setting up for adding items

Here, you will create a form on the viewItem page that contains a button, whichadds the current item to the shopping cart. Modify the printViewItemHelper()in shared_functions.php:

Listing 5. Displaying an Add to cart button

...if($admin == 1)

$imageURL = "../".$imageURL;

$str = "";if($admin == 0)

$str .= "<formaction='storeFront.php?".

processGETString("")."'method='post'>";

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 6 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

$str .="<center><h3>$name</h3></center>";...

$str .= "<font size='-1'>Price:$price</font><br>";

if($admin == 0){$str .= "<input name='submit'

type='submit' ";$str .= "value='Add to Cart' />";$str .= "<input name='addCart' \type='hidden' value='$id' />";$str .= "<input name='qty' \type='hidden' value='1' />";

}$str .= "</td></tr>";

...$str .= "</table>";if($admin == 0)

$str .= "</form>";print($str);

}

The first section in bold starts off the form. The middle section creates the button,followed by a couple hidden inputs that will pass through the quantity of the item toadd, as well as the productid. The productid is the ID of the item being addedto the cart, which is used to search the database to pull up information about theproduct. Quantity, named qty above, is hard-coded to a 1. The next section goesover managing the shopping cart, which will allow a user to increase or decrease theqty of a product in his shopping cart. See the Add to cart button.

Figure 1. Displaying the Add to cart button

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 40

Page 8: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Processing Add to cart requests

Once an item has been selected to add to the cart, your script needs to capture therequest and process it. Modify the user section of the storefront (./storefront.php):

Listing 6. Processing an Add to cart request

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 8 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

...include('includes/user_functions.php');include('includes/shared_functions.php');$pdo = db_connect();

if($_POST['addCart'] != ''){addItemToCart($pdo);

}

$title="Welcome to ".STORE_NAME;require('header.php');...

Thus when the addCart variable is set in the POST array, your script will call theaddItemToCart() function.

Adding items to the cart

Once an add to cart request has been successfully submitted and processed, youneed to save it in the database and associate with the appropriate cartid. Create aaddItemToCart() function, add it to user_functions.php, and define it:

Listing 7. Processing an Add to cart request

function addItemToCart($pdo){$id = $_POST['addCart'];$qty = $_POST['qty'];if(!isset($_POST['attribute']))

$attribute = 'none';else

$attribute = $_POST['attribute'];$cartid = $_SESSION['sessid'];$_SESSION['cartid'] = $cartid;$sql = "select cartid from shopping_carts

where cartid=$cartid";$result = $pdo->query($sql);if(!$result || !$result->fetch()){

$sql = "insert into shopping_carts (cartid) values ($cartid)";$pdo->exec($sql);

};

$sql = "select productid from shopping_cart_contentswhere cartid=$cartidand productid=$id"and attribute_value='$attribute';

$result = $pdo->query($sql);if(!$result || !$result->fetch())

$sql = "insert into shopping_cart_contents values($cartid,$id,$qty,'$attribute')";

else$sql = "update shopping_cart_contents

set qty=$qtywhere cartid=$cartidand productid=$id ";

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 40

Page 10: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

$pdo->exec($sql);}

First, the item's productid and qty are saved in local variables, $id and $qty,respectively. Next, the appropriate attribute is retrieved, none for no attribute. Theattribute is retrieved from the radio buttons that allow a user to select the color of theitem. Then, the session ID, sessid, a SESSION variable, is saved as $cartid andis also saved as a SESSION variable, cartid. Your application then checks if anentry exists for this shopping cart in the shopping cart table and inserts it into thetable, leaving the email field blank. Next, the shopping cart contents table isqueried to see if the product and accompanying attribute value already exist as anitem in the given shopping cart; it is inserted into the table if it doesn't exist.Otherwise, it will update the qty of the item.

The side panel: Setting up for viewing the cart

Since you have already created the shopping cart, we display it to the users at alltimes. Modify the header.php file:

Listing 8. Displaying an existing shopping cart

...</tr>

</table>');

if($_SESSION['cartid'] != '' &&$_GET['manageCart'] != "true" &&$_GET['checkout'] != "true" &&$_GET['checkout2'] != "true"){printCart($pdo);

}

print('</td></tr></table></td><td valign="top" width="100%">');?>...

The above code checks to make sure the cartid exists as a SESSION variable,and if it does, displays it to the user. The other variables, manageCart, checkout,and checkout2, will be discussed in Managing the shopping cart and Checking out.Basically, the shopping cart will not be displayed in the shopping cart while a user ismanaging it or checking out.

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 10 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

The side panel: Viewing the shopping cart

An item already exists in your user's shopping cart, so now you will query thedatabase for the item. Create a printCart() function, add it to theuser_functions.php file, and define it:

Listing 9. Querying the database for shopping cart contents

function printCart($pdo, $full=0){$cartid = $_SESSION['cartid'];$str = "<center><h3>Shopping Cart</h3></center>";$str .= "<table width='100%' border='0' ";$str .= "cellspacing='5' cellpadding='0'>";

$pdo = db_connect();$sql = "select productid, qty, attribute_value

from shopping_cart_contentswhere cartid=$cartid";

$result = $pdo->query($sql);if(!$result || !$result->fetch())

return;

$str .= "<font size='-3'>";$totalPrice = 0;foreach ($pdo->query($sql) as $row){

if($row['QTY'] <= 0)continue;

$arrayVals = printCartItem($row['PRODUCTID'], $row['QTY'],$row['ATTRIBUTE_VALUE'], $full, $pdo);

$totalPrice += $arrayVals['totalPrice'];$str .= $arrayVals['str'];

}

$str .= "<b>Total: $$totalPrice</b><br>";$str .= "</font>";$str .= "</table>";if($totalPrice > 0)

print($str);}

First, capture the cartid SESSION variable, followed by some HTML that lets thecustomer know what is being displayed. Next, query the shopping cart contents tablein the Derby database for all items whose cartid matches the SESSION variable.If nothing exists, return and display nothing. Otherwise, loop through all the itemsthat have a quantity greater than 0. Next, the printCartItem() function is called.This function returns an array containing the price for the item and the HTML datafor display. After all the items have been processed, the accumulated total isdisplayed, and if the price is greater than 0 (at least one item exists with qty greaterthan 0), the shopping cart data will be displayed.

The side panel: Displaying items in shopping cart

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 40

Page 12: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

This panel goes over the display HTML for individual items in the shopping cart.Create a printCartItem() function, add it to user_functions.php, and define it:

Listing 10. Collecting the HTML display data for individual items in the cart

function printCartItem($id, $qty, $attribute, $full, $pdo){$sql = "select * from products

where productid=$id";$result = $pdo->query($sql);if(!$result || !($row = $result->fetch()))

return array('totalPrice' => 0,'str' => '');

$str = $row['NAME']." x $qty : $".$row['PRICE']."<br>";return array('totalPrice' => $row['PRICE'] * $qty,

'str' => $str);}

First, connect to the database and query it for the product whose productidmatches the passed in $id variable. If none exists, return 0 for the price and theempty string '' for the HTML display data. Next, collect the HTML data and set upthe array, setting the price to the price of the item multiplied by qty. See theshopping cart:

Figure 2. Displaying the shopping cart

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 12 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

You have successfully created the shopping cart, and can view it! Now find out howto manage it.

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 40

Page 14: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Section 4. Managing the shopping cart

The gang at Ghastly Computers was wondering how the shopping cart data could bemodified. Here's the solution: Manage cart. This section covers creating the pagewhere users can manage the items in their shopping carts by increasing ordecreasing the quantities.

Setting up functionality

Before the shopping cart can be managed, you need to add a link to the shoppingcart to allow for it. Modify the printCart() function:

Listing 11. Displays a Manage cart link in the shopping cart

...$str .= "<b>Total:

$$totalPrice</b><br>";

$str .= "<ahref='storeFront.php?manageCart=true".

processGETString("cavi").\"'>Manage cart</a><br>";

$str .= "</font>";$str .= "</table>";

This link, when clicked, starts the request to manage the cart to your storeFront.phpscript by setting the manageCart variable in the URL to true.

Figure 3. Displaying a Manage cart link

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 14 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Processing Manage cart requests

When a Manage cart request is issued, the manageCart variable gets set in theGET array. Modify the user section of the storeFront (./storeFront.php), and capturethe value of manageCart:

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 40

Page 16: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Listing 12. Processing a Manage cart request

...$title="Welcome to ".STORE_NAME;require('header.php');

if($_GET['manageCart'] == 'true'){printCart($pdo, 1);

}else if($_GET['viewItem'] != ''){

printViewItem();}...

If the manageCart variable exists and is true, call the printCart() function,passing in 1. This value communicates to the printCart() function that the fullshopping cart should be shown.

Displaying the cart for managing

This takes the printCart() function previously defined and modifies it fordisplaying the full shopping cart so users can manage it. If this function is called fromthe header.php file, the value of $full is 0. Otherwise, it is 1 as called fromstoreFront.php to make the function configurable, allowing you to use the function fordisplaying the shopping cart in the side panel and allowing a user to manage theshopping cart. Modify this function as shown:

Listing 13. Displaying the shopping cart for managing

function printCart($pdo, $full=0){...

if(!$result || !$result->fetch())return;

if($full == 0)$str .= "<font size='-3'>";

else if($full == 1){$str .= "<table><tr width='100%'><td

width='35%'>Name</td>";$str .= "<td width='25%'>Attribute</td>";$str .= "<td width='12%'>Price</td>";$str .= "<td width='13%'>Qty</td>";$str .= "<td width='15%'>Update</td></tr>";

}$totalPrice = 0;foreach ($pdo->query($sql) as $row){

...}if($full == 1)

$str .= "</table>";

$str .= "<b>Total: $$totalPrice</b><br>";

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 16 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

if($full == 0)$str .= "<a href='storeFront.php?manageCart=true".

processGETString("cavi")."'>Manage cart</a><br>";

if($full == 0)$str .= "</font>";

...}

If the value of $full is 0, the shopping cart is displayed. Otherwise, a table is set upin the new code in bold, and the font size is increased.

Displaying items in shopping cart for managing

This function modifies the printCartItem() for displaying individual items in theshopping cart that provides functionality for a user to manage the cart by increasingor decreasing the quantity of items in the shopping cart:

Listing 14. Displaying individual items in the cart for managing

function printCartItem($id, $qty, $attribute, $full, $pdo){...

if($full == 1){$str .= "<form action='storeFront.php?".

processGETString()."' method='post'>";$str .= "<tr><td><a href='storeFront.php?viewItem=$id".

processGETString("ma")."'>".$row['NAME']."</a></td>";$str .= "<td>$attribute</td>";$str .= "<td>$".$row['PRICE']."</td>";$str .= "<td>X <input name='addCart' type='hidden' ";$str .= "value='$id'>";$str .= "<input name='attribute' type='hidden' ";$str .= "value='$attribute'>";$str .= "<input name='qty' value=$qty size='2'/></td>";$str .= "<td><input type='submit' ";$str .= "value='Update'></td></tr></form>";

}else

$str = $row['NAME']." x $qty : $".$row['PRICE']."<br>";return array('totalPrice' => $row['PRICE'] * $qty,

'str' => $str);}

If the value of $full is 0, the shopping cart will remain unchanged and will bedisplayed as usual in the side panel. Otherwise, if its value is 1, the new code in boldcreates a form, sets the item's ID in the URL, and displays the name, attribute, price,and qty of the item. A text box is used to display the qty of the item, which can bemodified, followed by pressing the accompanying Update button. Notice that thisform sets the same values as the Add to cart button created in Listing 5. Users canremove items by setting the quantity value to 0.

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 40

Page 18: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Figure 4. Managing the shopping cart

Notice that the quantity of the monitor has been set to 0, removing it from theshopping cart. See Figure 5 for the results.

Figure 5. Removing the monitor from the shopping cart

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 18 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Your users can now manage the shopping cart by removing items and modifying thequantity.

Section 5. Checking out

A shopper now has a shopping cart with items to purchase. This is good news forGhastly Computers. This section covers the checkout process from start to finish.Making payments with PayPal is covered in the next section.

Setting up checkout functionality

Let's start by setting up the checkout link in the shopping cart. ModifyprintCart(), as shown:

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 40

Page 20: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Listing 15. Displaying a checkout link

...if($full == 0)

$str .= "<ahref='storeFront.php?manageCart=true".processGETString("cavi")."'>Managecart</a><br>";

$str .= "<ahref='storeFront.php?checkout=true".

processGETString("macavi").\"'>Checkout</a><br>";

if($full == 0)$str .= "</font>";

The code adds a checkout link to the shopping cart.

Figure 6. Displaying a checkout link

Clicking the checkout link sets the checkout variable in the URL to true.

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 20 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Processing checkout requests

The checkout sequence has been initiated. Now you need to take the request in theuser section of the storefront (./storeFront.php) and modify it, as shown:

Listing 16. Processing the checkout request

...$title="Welcome to ".STORE_NAME;require('header.php');

if($_GET['checkout'] == 'true'){printCheckout_1($pdo);

}else if($_GET['manageCart'] == 'true'){

printCart($pdo, 1);}...

Capture the value of the checkout variable in the GET array. If true, display thebill-to/ship-to page, shown next.

Checkout: Querying the database

This is the first page in the checkout sequence. It will collect and save a customer'spersonal data into the database. Create a printCheckout_1() function, add it touser_functions.php, and define it, as shown:

Listing 17. Determines if this shopping cart is already connected to acustomer

function printCheckout_1($pdo){$cartid = $_SESSION['cartid'];

$sql = "select customers.* from shopping_carts, customerswhere cartid=$cartid";

$result = $pdo->query($sql);try{

$row = $result->fetch();$first_name = $row['FIRST_NAME'];$last_name = $row['LAST_NAME'];$email = $row['EMAIL'];$street_address = $row['STREET_ADDRESS'];$city = $row['CITY'];$state = $row['STATE'];$zipcode = $row['ZIPCODE'];$phone_number = $row['PHONE_NUMBER'];

} catch(Exception $e){}...

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 40

Page 22: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

The code in Listing 17 takes the cartid SESSION variable and stores it as a localvariable. Next, the database is queried to determine if this shopping cart is alreadyconnected to a customer. If so, then that customer's information will be used toinitialize the HTML form.

Checkout: Collecting personal data

New customers can enter their information at the checkout. Returning customerscan edit their information here, too. Continue to define the printCheckout_1()method:

Listing 18. Form for users to enter or edit their information

...$phone_number = $row['PHONE_NUMBER'];

} catch(Exception $e){}$str = "<center><h3>Ship to/Bill to Information</h3></center>";$str .= "

<table width='100%' border='0' cellspacing='5' cellpadding='0'>";$str .= "

Please enter your information:<br><form action='storeFront.php?checkout2=true' method='post'><input type='hidden' name='cartid' value='$cartid' />First Name: <input name='first_name' value='$first_name'><br>Last Name: <input name='last_name' value='$last_name'><br>Email: <input name='email' value='$email'><br>Street Address: <input name='street_address' value='$street_address'><br>City: <input name='city' value='$city'><br>State: <input name='state' value='$state'><br>Zip Code: <input name='zipcode' value='$zipcode'><br>Phone Number: <input name='phone_number' value='$phone_number'><br><input name='submit' type='submit' value='Submit' /></form>";

$str .= "</table>";print($str);

}

This displays the form for the bill-to/ship-to page. It will be initialized with theinformation the customer previously entered if the shopping cart is already tied to acustomer. Otherwise, a user will be able to enter his information with this form. SeeFigure 7 for sample browser output.

Figure 7. Displaying the first page of the checkout process

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 22 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Clicking Submit submits the data to the storefront, setting the checkout2 variableto true in the URL.

Processing checkout2 requests

The second phase of the checkout process must be initiated. Modify the user sectionof the storefront (./storeFront.php), as shown:

Listing 19. Processing a checkout2 request

...$title="Welcome to ".STORE_NAME;

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 40

Page 24: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

require('header.php');

if($_GET['checkout2'] == 'true'){printCheckout_2($pdo);

}else if($_GET['checkout'] == 'true'){

printCheckout_1($pdo);}...

This code captures the checkout2 variable in the GET array. If its value is true, theprintCheckout_2() function is called.

Checkout2: Saving customer data

The second page of the checkout sequence has been initiated. The purpose of thispage is to save the data taken from step one of the checkout process, create apending order entry in the database, and display an order summary, which is aconfirmation that your customer is purchasing the items. Here, you'll save the datapreviously entered by the customer. Create a printCheckout_2() function andbegin to define it, as shown:

Listing 20. Saving customer data into the database

function printCheckout_2($pdo){$cartid = $_POST['cartid'];$first_name = $_POST['first_name'];$last_name = $_POST['last_name'];$email = $_POST['email'];$street_address = $_POST['street_address'];$city = $_POST['city'];$state = $_POST['state'];$zipcode = $_POST['zipcode'];$phone_number = $_POST['phone_number'];

$sql = "select email from customerswhere email='$email'";

$result = $pdo->query($sql);if(!$result || !$result->fetch())

$sql = "insert into customers values ('$email','$first_name','$last_name','$street_address','$city','$state','$zipcode','$phone_number')";

else$sql = "update customers set

first_name='$first_name',last_name='$last_name',street_address='$street_address',city='$city',state='$state',zipcode='$zipcode',phone_number='$phone_number'

where email='$email'";$pdo->exec($sql);

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 24 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

$sql = "update shopping_carts setemail='$email'where cartid=$cartid";

$pdo->exec($sql);...

First, the code saves the POSTed data as local variables. Next, it queries thecustomer database for existing customers and inserts a new entry if an existingcustomer with the same e-mail was not found. Otherwise, it updates the existingentry with the values stored in the local variables. Next, the shopping cart table isupdated by setting the empty email field to the e-mail address the customerentered on the bill-to/ship-to page. This enables you to look up the customer's e-mailif the user goes back to shopping and comes back so that he doesn't have to enterhis personal information all over again.

Checkout 2: Saving an order

The next stage of step two in the checkout process is to save an order entry in thedatabase. Continue to define printCheckout_2(), as shown:

Listing 21. Saves or updates an order entry in the database

...$sql = "update shopping_carts set

email='$email'where cartid=$cartid";

$pdo->exec($sql);

$sql = "select products.price, shopping_cart_contents.qtyfrom shopping_cart_contents, productswhere products.productid=

shopping_cart_contents.productidand cartid=$cartid";

$total = 0;foreach ($pdo->query($sql) as $row){

$total += $row['PRICE'] * $row['QTY'];}

$sql = "select customer_email from orderswhere customer_email='$email'and cartid=$cartid";

$result = $pdo->query($sql);if(!$result || !$result->fetch())

$sql = "insert into orders values ($cartid,'$email',$total,'Pending')";

else{$row = $pdo->query($sql)->fetch();!($row['STATUS'] == 'paid') or

die("This shopping cart has already been paid for!");$sql = "update orders set

status='Pending',amount_due=$totalwhere customer_email='$email'and cartid=$cartid";

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 40

Page 26: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

}$pdo->exec($sql);

...

The new code in bold starts off by joining the shopping cart contents and productstables on the productid field, totaling the value of each item, multiplied by itsquantity, and stored as a local variable in $total. Next, the code queries thedatabase for order entries with the same cartid and email. If one doesn't exist, anew entry is inserted, with $total and Pending as the values of amount due andstatus, respectively. The value of $total indicates the amount that is due topurchase the items in the shopping cart. Pending indicates that the item has notbeen bought yet via PayPal.

Checkout2: Order summary

Now you finish off step two of the checkout process by displaying a summary with alink that confirms the order. Finish off printCheckout_2(), as shown:

Listing 22. Displaying an order summary

...and cartid=$cartid";

}$pdo->exec($sql);

$str = "<center><h3>Order Summary</h3></center>";$str .= "<table width='100%' border='0' cellspacing='5' \cellpadding='0'>";

$str .= "<b>Bill to/Ship to:</b><br>";$str .= "$first_name $last_name<br>$street_address<br>";$str .= "$city, $state&nbsp;&nbsp;$zipcode<br>";$str .= "$phone_number<br>$email<br>";$str .= "<b>Order total: $$total</b><br>";

$str .= "<a href='storeFront.php?thankyou=true'>";$str .= "Confirm your order</a>";$str .= "</table>";print($str);

}...

The new code in bold displays the order summary using the variables passed infrom step one of the checkout process and $total, the payoff amount for theshopping cart. Then a link is display that confirms the order, sending the customer tothe final page in the checkout process: the thank-you page. The Making paymentswith PayPal section will instead take a user to PayPal to purchase the shopping cart.See Figure 8 to see sample browser output of the order summary page.

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 26 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Figure 8. Displaying the second page of the checkout process

Clicking on Confirm your order takes the user to the thank-you page of the checkoutprocess.

Processing confirmation requests

This is the final phase of the checkout process, which displays a thank-you page.Create a printThankyou() function, add it to the user_functions.php file, anddefine it, as shown:

Listing 23. Processing a thankyou request

<?phpsession_start();if($_GET['thankyou'] == 'true'){

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 40

Page 28: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

$_SESSION['sessid'] = rand(1002842140, 1410065407);$_SESSION['cartid'] = '';

}else if(isset($_GET['sessid']))

$_SESSION['sessid'] = $_GET['sessid'];...require('header.php');

if($_GET['thankyou'] == 'true'){printThankyou();

}else if($_GET['checkout2'] == 'true'){

printCheckout_2($pdo);}

If the thankyou variable is set in the GET array and has a value of true, a newsessid SESSION variable gets issued, and the current cartid SESSION variablegets invalidated. Next, the thank-you page is displayed.

Displaying the thank-you page

The final thank-you page displays a confirmation to the user that acts as a way ofbringing closure to the checkout process by communicating "That's it! You're done."Create a printThankyou() function, add it to user_functions.php, and define it, asshown:

Listing 24. Displaying the thank-you page

function printThankyou(){$str = "<center><h3>Thank You for Choosing ".$str .= STORE_NAME."!</h3></center>";$str .= "Thank you for your order!!!<p>";$str .= "<p>Come again soon!";print($str);

}

This function simply defines the HTML that displays the final page in the checkoutprocess. See Figure 9 for sample output.

Figure 9. Displaying the thank-you page

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 28 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

The next section covers the Making payments section of the checkout process,which brings home the bacon for the folks at Ghastly Computers.

Section 6. Making payments with PayPal

You now have the infrastructure of the entire checkout process in place, exceptmaking payments. This section adds to the checkout process by introducingPayPal's Instant Payment Notification (IPN) and making payments with PayPal.

PayPal Instant Payment Notification

PayPal's IPN allows you to know for sure if a payment was made from the storefrontby verifying it with PayPal. This completely streamlines the checkout process,making it easy for the administrator to look up orders that have been successfullypaid for.

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 40

Page 30: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

All of the items are going to be lumped into a single purchase to PayPal, in a singlepayment amount.

There are several variables you are going to forward onto PayPal in the paymentprocess, all of which are passed through to the notification URL you specify. Table 1contains the variables to send to PayPal with their values and short descriptions.

Table 1. Variables to be sent to PayPal

Variable name Value Description

cmd _ext-enter This is the type ofcommand that tellsPayPal what is beingrequested

email The e-mail of thecustomer (sender'se-mail address)

amount Amount the customer ispaying

item_name The name of your store

item_number 1 The number of the itembeing purchased, alwaysone

notify_url URL that PayPal willsend notification to,which you define in theIPN handler panels

cancel_return URL that PayPal willredirect a user to on acanceled checkout, backto the order summarypage

return URL that PayPalredirects users to afterPayment, the thank-youpage

rm 2 Specifies that PayPalshould send data viaPOST

currency_code USD The currency of themoney being sent, inU.S. dollars

business MY_EMAIL The e-mail addressassociated with yourPayPal account; this is

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 30 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 31: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

where the money theuser sends gets sent to

lc US Defines the language ofthe customer

shipping 0.00 The shipping charge,always 0.00. In Part 3 ofthis series, you willsimply add the shippingamount to the above,amount, variable.

custom cartid A custom pass-throughvariable used to updateorders in the databasewith successful payments

upload 3 Indicates that theshopping cart is not beinguploaded to PayPal; onlypayment for the specifiedamount, specified by theamount variable, is beingcollected

country US Country associated withthe sender

There are several other variables. Check out Resources for more PayPal IPNdocumentation.

The following variables are defined so the customer doesn't have to re-enter themduring in the payment process, and have already been collected in step one of thecheckout process (see Checkout: Collecting personal data):

• redirect_cmd => _xclick

• Needs to be set when prepopulating your customer's PayPal payment

• first_name

• last_name

• address1

• city

• state

• zip

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 40

Page 32: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

On a successful payment, PayPal asynchronously sends notification to a URL youspecify; asynchronous, in this case, means that the notification gets sent outside ofnormal flow. You specify the URL PayPal should send notification to, then PayPal,sometime after a successful payment, sends a notification to this URL. You thenprocess this notification, resend the POSTed variables to PayPal, which then sendsyou a final message. Success is defined as VERIFIED in the message, and failure isdefined as INVALID in the message.

Creating the button

Here, we create the button needed to submit all the information to PayPal forpayment. Modify printCheckout_2(), as shown:

Listing 25. The Pay with PayPal button

...$str .= "$phone_number<br>$email<br>";

$str .= "<b>Order total: $$total</b><br>";

$str .= "Confirm your order:";$str .= "

<form action='https://www.sandbox.paypal.com/cgi-bin/webscr'method='post'><input type='hidden' name='cmd' value='_ext-enter'><input type='hidden' name='redirect_cmd' value='_xclick'><input type='hidden' name='email' value='$email'><input type='hidden' name='amount' value='$total'><input type='hidden' name='item_name' value='".STORE_NAME."'><input type='hidden' name='item_number' value='1'><input type='hidden' name='notify_url'value='http://".MY_URL."/paypal_part2/paypal_ipn_handler.php'><input type='hidden' name='cancel_return'value='http://".MY_URL."/paypal_part2/storeFront.php?checkout2=true'><input type='hidden' name='return'value='http://".MY_URL."/paypal_part2/storeFront.php?thankyou=true'><input type='hidden' name='rm' value='2'><input type='hidden' name='currency_code' value='USD'><input type='hidden' name='business' value='".MY_EMAIL."'><input type='hidden' name='first_name' value='$first_name'><input type='hidden' name='last_name' value='$last_name'><input type='hidden' name='address1' value='$street_address'><input type='hidden' name='city' value='$city'><input type='hidden' name='state' value='$state'><input type='hidden' name='zip' value='$zipcode'><input type='hidden' name='country' value='US'><input type='hidden' name='lc' value='US'><input type='hidden' name='shipping' value='0.00'><input type='hidden' name='custom' value='$cartid'><input type='hidden' name='upload' value='3'><input name='submit' type='submit' value='Pay with PayPal' />";

$str .= "</table>";print($str);

}

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 32 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 33: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

This form displays a Pay with PayPal button and sets up all the variables, asdescribed in this section, to be submitted to PayPal for payment (see Figure 10).

Figure 10. Displaying the Pay with PayPal button

Clicking the Pay with PayPal button takes your customers to PayPal to purchase theshopping cart. See Figure 11 for sample browser output.

Figure 11. Paying via PayPal

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 40

Page 34: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

This is the page on PayPal Sandbox that lets you test your application. Follow thescreens for making payment, and remember that even if you enter a real credit card,nothing happens because no payment made in the PayPal Sandbox is real.

Once the payment process is completed, PayPal returns your customer to your Website at the thank-you page, just as before.

IPN handler: Retrieving variables

After a payment has been made, PayPal sends a notification to the URL specified inthe notify_url variable you sent to PayPal's server via POST. The script specifiedabove is paypal_ipn_handler.php, so create this file, and begin to define it as

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 34 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 35: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

specified:

Listing 26. Saving the POSTed results as local variables

<?phpinclude('includes/user_functions.php');include('includes/shared_functions.php');

// assign posted variables to local variables$payment_status = $_POST['payment_status'];$amountDue = $_POST['mc_gross'];$txn_id = $_POST['txn_id'];$payment_currency = $_POST['mc_currency'];$cartid = $_POST['custom'];$my_email = $_POST['business'];$email = $_POST['payer_email'];...

First, save the important variables PayPal has sent to you via POST into localvariables.

IPN handler: Verifying payment

Verifying payment works by collecting the variables sent to you from PayPal andresending them via POST. Continue defining the paypal_ipn_handler.php by addingthe following code:

Listing 27. Returning POSTed variables to PayPal

...$my_email = $_POST['business'];$email = $_POST['payer_email'];

$req="";foreach ($_POST as $key => $value) {

$req .= $key."=".urlencode($value) . "&";}$req .= 'cmd=_notify-validate';

$fp = fsockopen (PAYPAL_URL, 80, $errno, $errstr, 30);if (!$fp)

die();fputs($fp, "POST /cgi-bin/webscr HTTP/1.1\r\n");fputs($fp, "Host: ".PAYPAL_URL."\r\n");fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");fputs($fp, "Content-length: ".strlen($req)."\r\n");fputs($fp, "Connection: close\r\n\r\n");fputs($fp, $req . "\r\n\r\n");$info = "";while(!feof($fp)) {

$info .= @fgets($fp, 1024);}...

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 40

Page 36: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

The foreach statement takes all the variables in the POST array and saves them inanother variable, $req, adding the command _notify-validate. This commandasks PayPal to verify the payment. This is done so that not anyone can simply POSTdata to this URL because you are going to re-POST all the variables back to PayPal,making the whole process very secure. PayPal issues another notification that youcollect in the while loop using $info and @fgets.

IPN handler: Processing the second notification

Up to this point, you have received POSTed variables from PayPal, and you havesent them back to PayPal via POST. PayPal is now going to send a secondnotification. Continue defining the paypal_ipn_handler.php by adding the followingcode:

Listing 28. Interpreting PayPal's final response

...while(!feof($fp)) {

$info .= @fgets($fp, 1024);}if(strstr($info, "VERIFIED") != ''){

if($payment_currency == "USD" &&$payment_status == "Completed" &&$my_email == MY_EMAIL) {

$pdo = db_connect();$sql = "select amount_due from orders

where cartid=$cartid";$row = $pdo->query($sql)->fetch();$balance = $row['AMOUNT_DUE']-$total;

$sql = "update orders setstatus='Processing',amount_due=$balancewhere cartid=$cartid";

$pdo->exec($sql);}

}else{

// log for manual investigation}fclose ($fp);?>

If the data returned in the $info variable contains the word VERIFIED, the paymentis a success! Verify the correct currency as U.S. currency, that the payment statusreturned as "Completed," and that the e-mail the money went to you, stored in theconstant variable you defined, MY_EMAIL.

This completes Part 2 of this series. Part 3 will explain viewing completed orders,

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 36 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 37: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

transactions of PHP data objects, adding shipping to the checkout process, andsending out e-mail notifications on successful orders.

Section 7. Summary

Congratulations! You have completed the shopping cart and can now acceptpayments with PayPal. Shoppers can view and add items to their shopping carts justlike any other storefront. They can also manage their carts by adding or removingitems and check out by e-mailing you money for the goods via PayPal, which notifiesyour storefront of successful payments.

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 40

Page 38: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Downloads

Description Name Size Download method

Source code for Part 2 os-paypal2code.zip11KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 38 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 39: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

Resources

Learn

• For an excellent article on integrating PHP with Derby/Cloudscape, see"Connecting PHP applications to Apache Derby."

• Learn how to configure IBM Cloudscape V10.0 and IBM DB2 Universal Database(DB2 UDB) V8.2 servers for access from PHP V4.x and PHP V5.x "Develop IBMCloudscape and DB2 Universal Database applications with PHP."

• For a document that describes the PayPal features for managing orders,including Instant Payment Notification, see the PayPal Order ManagementIntegration Guide.

• For more information about Instant Payment Notification, read the PayPalWebsite Payments Standard Checkout Integration Guide.

• Try hosting your cart with PayPal Shopping Cart, instead of in a local database.

• Check out PayPal's Testing Instant Payment Notification.

• Visit PayPal Developer Central to access the PayPal Sandbox test environment,Website Payments testing, Instant Payment Notification, and Payment DataTransfer.

• To access the PayPal Sandbox, log in to PayPal Developer Central first.

• Consider using this PayPal IPN handler for a different style of Instant PaymentNotification handler.

• Test your Instant Payment Notification handler if you're running inside a networkor behind firewall at EliteWeaver UK.

• To learn about the differences between the open source Apache Web server andIBM's version, and view demonstrations of IBM's version running a well-knownPHP application, see the developerWorks article "Hosting PHP applications onthe IBM HTTP Server."

• For information about getting Apache V2 and PHP V4.x to work together onLinux, read the Apache 2 and PHP Installation guide.

• Learn more about PHP data objects and their capabilities in the PHP Manual.

• Various HTML form input data you may want to use for representing attributesare available at w3.org.

• Visit the IBM Tivoli information center to learn more about the SQL syntax anditems.

ibm.com/developerWorks developerWorks®

Collecting payments© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 40

Page 40: Create a Web storefront using PHP, Derby and PayPal, Part 2: … · 2010. 1. 15. · PayPal, Part 2: Collecting payments Also, creating shopping carts and storing their data with

• For a series of tutorials designed to broaden your PHP skills, see "Learning PHP,Part 1," Part 2, and Part 3.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologies anduse them with IBM's products.

Get products and technologies

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• Get involved in the developerWorks community by participating indeveloperWorks blogs.

About the author

Tyler AndersonTyler Anderson graduated with a degree in computer science from Brigham YoungUniversity in 2004 and is currently in his last semester as a master's student incomputer engineering. In the past, he worked as a database programmer forDPMG.com, and he is currently an engineer for Stexar Corp., based in Beaverton, Ore.

developerWorks® ibm.com/developerWorks

Collecting paymentsPage 40 of 40 © Copyright IBM Corporation 1994, 2008. All rights reserved.