Integration with PayPal

The final success of an e-commerce site is getting the money into the bank. For this purpose you must integrate your site with a credit card processing service. This service handles all the details of interacting with your customers over a secure connection, collecting credit card information, interfacing with the Federal banking system to debit and credit bank accounts, and notifying your site of the success of the transactions.

There are numerous commercial services available at various setup costs, transaction fees, and volume limits. For instance, a popular online payment service has entry-level costs including a $179 set-up fee and a $20 per month transaction fee for up to 500 transactions per month. Other fees are applicable for additional customer and merchant support services. In contrast, a payment service such as PayPal can be joined at no set-up cost and very modest transaction fees of around 3.5% of sales. Since this latter service is widely popular, the steps involved in integrating your e-commerce site with PayPal are summarized below. They are typical of integration with most commercial services.

Handling HTML Forms

Most online payment services work by placing a short HTML form on your Web page. This form links to the payment service through the action attribute of the <form> tag. Hidden textbox fields on the form are populated with transaction information—at minimum with your membership identification with the service, a customer identification, the total amount of the order, and the URL of your site page to which work flow will return when credit processing is completed.

The problem is that ASP.NET pages are forms themselves, surrounded by a single <form Runat="Server"> tag that automatically posts back to itself. Therefore, you cannot embed an HTML form inside this server form.

If you are not using master pages, you can get around this limitation by placing the HTML form outside the server form. The setup looks something like that shown below, similar to the example CreditCheck.aspx page explained in the "Credit Card Processing" section of this tutorial.

<form Runat="Server">

  ...page content

</form>

<form action="credit card processing URL" method="post">

  ...transaction data fields

</form>
Listing 13-52. Web page layout with two separate forms.

Posting of the HTML form takes place outside the context of the server form. Transfer is made to the action URL without involving post-back of the separate server form.

If, however, you are using master pages then it is impossible to place an HTML form outside the server form. The master page containing the <form Runat="Server"> control always encompasses the entire content page. An HTML form coded on a content page is always inside the server form. In this situation you will need to place the HTML form on a separate page from a master/content page and transmit it behind the scenes, using a technique like that explained in the "Checkout Processing" section of this tutorial. An alternative is to configure a stand-alone Web page that resembles the layout of the master/content pages. In this latter case the page layout can appear like the two forms coded above.

Setting Up an Account with PayPal

You must have an account with PayPal before conducting online business. This is a relatively simple process.

  1. Go to the PayPal site (https://www.paypal.com) and click on the Sign Up Now link at the top of the page.

  2. Choose an account type. A Premier account is sufficient for conducting personal business and handling most credit cards. A Business account permits you to conduct sales under a business name and to handle all payment types. You can decide which account best fits your purpose.

  3. You are asked to enter personal information (and business information for a Business account) including an email address as your account identification and a password.

  4. After submitting this information, you will receive an email from PayPal confirming your account.

Additional set-up steps are completed after you received the email account confirmation. At that time you return to PayPal and log in under your private member account—your confirmed email address and password.

  1. Add a Bank Account. You must add a bank account through which customer payments are received and refunds are returned. This is your personal or business bank account indicated by bank name, account type, routing number, and account number, the latter two taken from the numbers appearing at the bottom of your checks.

  2. Confirm a Bank Account. After you add a bank account, PayPal makes two small deposits into the account. After getting the deposit amounts from your bank, return to PayPal and enter these amounts to confirm your bank account. You will not be able to conduct business until after the account is confirmed.

  3. Add a Credit Card. You can add a personal or business credit card to your account. This is optional but necessary if you intend to use the card for you own purchases. Incidentally, you cannot use this card to test your system by purchasing your own products. You cannot purchase and receive payment under the same card.

You may find that it takes several days to get your account set up and functioning. However, this gives you time to explore the PayPal site to become familiar with personal and merchant services. You should probably download relevant documentation and guides at https://www.paypal.com/us/cgi-bin/webscr?cmd=_resource-center. Make sure you spend time reading the documentation. You will discover useful features and service descriptions beyond the summary coverage provided here.

Developer Site

As a site developer you may wish to join as a member of PayPal Developer Central. As a member you have free access to a "Sandbox" development environment in which you can test your pages prior to their full integration with online PayPal. It works exactly like normal PayPal without risk of introducing buggy code into the real world. Check out this site at https://developer.paypal.com/.

PayPal "Buy Now" Buttons

Make payments with PayPal - it's fast, free and secure! The most basic way to interact with PayPal is through a "Buy Now" button. A click on this button links from your site to PayPal where the purchase transaction for a single product is completed. This method requires no scripting; plus, the button code can be generated automatically by filling in forms at the PayPal site.

Your setup work with PayPal is through their "Merchant Services" site section. The first step in creating a "Buy Now" button is to enter details about the item for sale.

Figure 13-15. Entering product information for a PayPal "Buy Now" button.

Next, you choose a button style for display on your site. As an option, you can provide a link to your own graphic image for use as the button.

Figure 13-16. Choosing a button style for a PayPal "Buy Now" button.

Then, you provide return URLs for linking back to your site following the PayPal transaction. Different pages can be specified for a successful purchase versus a cancelled purchase.

Figure 13-17. Configuring return URLs for a PayPal "Buy Now" button.

Other optional steps include indicating whether multiple items can be purchased and whether to collect shipping information.

Figure 13-18. Selecting multiple quantities and shipping information options for a PayPal "Buy Now" button.

Finally, code for the form needed to connect to and transmit this information to PayPay is generated. This code is copied and pasted onto your page at the display location of the "Buy Now" button, usually next to a picture and description of the item for sale. When this button is clicked, transfer is made immediately to the PayPal site where the customer is walked through the purchase transaction. After completion of the purchase, or its cancel, transfer returns to your site. Both you and the customer receive email confirmations of the purchase.

Figure 13-19. Generated code for a PayPal "Buy Now" button.

Shown below is typical code for a PayPal "BuyNow" button. Once you have produced this first button, you can modify it for use in purchasing other products at your site.

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="dradams@dradamsweb.com">
<input type="hidden" name="item_name" value="ASP.NET 2.0 Tutorial">
<input type="hidden" name="item_number" value="WDS03">
<input type="hidden" name="amount" value="52.00">
<input type="hidden" name="return" 
  value="http://www.dradamsweb.com/default.aspx">
<input type="hidden" name="cancel_return" 
  value="http://www.dradamsweb.com/default.aspx">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-BuyNowBF">
<input type="image" border="0" name="submit"
  src="https://www.paypal.com/en_US/i/btn/x-click-but01.gif" 
  alt="Make payments with PayPal - it's fast, free and secure!">
</form>
Listing 13-53. Form code for a PayPal "Buy Now" button.

Customer Interaction with PayPal

When your site visitor clicks the "Buy Now" button to purchase an item, the enclosing form transfers to the PayPal site, carrying with it the information coded on the form. The initial page is shown in Figure 13-19. From here, several screens lead the purchaser through the steps necessary to indicate payment method, enter credit card information, and confirm and finalize the transaction. At the end, transfer returns to the merchant site at one of the pages designated by the return URLs associated with the "Buy Now" button.

Figure 13-20. Customer interaction with PayPal.

With a merchant account, you can always log on to PayPal to review sales transactions. Summaries are provided along with options to transfer funds from your PayPal account to your bank account, to initiate shipping, or to return refunds to customers.

PayPal Shopping Cart

Make payments with PayPal - it's fast, free and secure!

Make payments with PayPal - it's fast, free and secure!
Normally, in running a commercial site, you will not wish to have a checkout procedure associated with each individual item for sale. The usual approach is to maintain a shopping cart of items and, at the end, perform checkout processing for the total amount of the order. PayPal permits you to integrate your own or a third-party shopping cart, or to use it's built-in shopping cart feature.

To use PayPal's shopping cart, and in the same manner for creating "Buy Now" buttons, you create "Add to Cart" and "View Cart" buttons. The former are associated with each product for sale, the latter for viewing the current contents of the shopping cart and initiating the checkout process.

Figure 13-21. Viewing the PayPal shopping cart.

Using a Merchant Shopping Cart

It is a little more problematic to integrate your own site's shopping cart with PayPal. It involves utilizing the Instant Payment Notification (IPN) service. You can log on to PayPal and select this option. In this case, the Auto Return option—the default option in which you provide a return URL for buy-now and shopping-cart purchases—must be turned off for replacement by a different method of returning to your site.

The IPN feature permits you to know immediately the success or failure of the sale and to take action with your customer such as producing a sales order or otherwise corresponding online with the customer. Still, there are follow-up emails generated by PayPal confirming and summarizing the transaction.

This option also requires you to produce a special page to interact with IPN notification. This page contains only script (it has no visual presence) and performs the following tasks.

  1. Receives information from PayPal with data fields summarizing the transaction.

  2. Echoes the received information back to PayPay as security confirmation that the information was actually and accurately sent by PayPal.

  3. Receives verification back from PayPal on the success of the transaction.

  4. On the basis of the returned "VERIFIED" or "NOT VERIFIED" flag, redirects to a local page for follow-up interaction with the customer.

With IPN as the chosen return option, the URL designated in the form's "return" field is a script page to receive, echo back, and receive processing verification from PayPal. The script is a bit unusual in that it receives a "form" from PayPal, posts a "form" back to PayPal, and receives another "form" back from PayPal, all without using HTML forms. The technique involves posting form information through the HttpWebRequest class, effectively posting forms through script rather than through HTML forms. An example page to perform this processing is shown below.

<%@ Page Language="vb" Debug="True" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Net" %>

<SCRIPT Runat="Server">

Sub Page_Load

  '-- Capture posted form values from PayPal
  Dim FormValues As String = Request.Form.ToString()

  ' Create the postback to PayPal to verify sent information
  Dim PostBackRequest As HttpWebRequest 
  PostBackRequest = WebRequest.Create("https://www.paypal.com/cgi-bin/webscr")
  PostBackRequest.Method = "POST"
  PostBackRequest.ContentType = "application/x-www-form-urlencoded"
  Dim PostBackString As String = FormValues + "&cmd=_notify-validate"
  PostBackRequest.ContentLength = PostBackString.Length

  ' Send the postback reply to PayPal
  Dim PostBackWriter As StreamWriter 
  PostBackWriter = New StreamWriter(PostBackRequest.GetRequestStream(), Encoding.ASCII)
  PostBackWriter.Write(PostBackString)
  PostBackWriter.Close()
	
  ' Receive final verification from PayPal
  Dim ResponseReader As StreamReader 
  ResponseReader = New StreamReader(PostBackRequest.GetResponse().GetResponseStream())
  Dim ResponseString As String = ResponseReader.ReadToEnd()
  ResponseReader.Close()

  If ResponseString = "VERIFIED" Then
    'Set a flag and transfer to sales success page
    Session("Verified") = "OK"
    Response.Redirect("SalesConfirmation.aspx")
  Else
    'Set flag and transfer to sales failure page
    Session("Verified") = ""
    Response.Redirect("NoSalesConfirmation.aspx")
  End If

End Sub

</SCRIPT>
Listing 13-54. Example receive and post-back page.

When this page is called by PayPal as your return URL page, it receives transaction information collected at the PayPal site. This information includes billing and shipping information and numerous other items of information pertaining to the sale. Your script receives this information just as it would a standard HTML form, through the Request.Form collection. Notice the first line in the script.

Dim FormValues As String = Request.Form.ToString()
Listing 13-55. Receiving a form as a string.

Here, the entire form is assigned to a string variable, FormValues, for post-back to PayPal to validate the transmission. If you need to capture this information for your own purposes, such as saving any shipping and billing information collected by PayPal, you can parse the Request.Form collection into its individual fields.

Dim Items As String
For Each Item in Request.Form
  Session(Item) = Item
Next
Listing 13-56. Capturing form fields returned by PayPal IPN notification.

The main purpose for the returned form string, however, is for echo back to PayPay for verification. The next section of script composes this Web request and sends it to PayPal.

' Create the postback to PayPal to verify sent information
Dim PostBackRequest As HttpWebRequest 
PostBackRequest = WebRequest.Create("https://www.paypal.com/cgi-bin/webscr")
PostBackRequest.Method = "POST"
PostBackRequest.ContentType = "application/x-www-form-urlencoded"
Dim PostBackString As String = FormValues + "&cmd=_notify-validate"
PostBackRequest.ContentLength = PostBackString.Length

' Send the postback reply to PayPal
Dim PostBackWriter As StreamWriter 
PostBackWriter = New StreamWriter(PostBackRequest.GetRequestStream(), Encoding.ASCII)
PostBackWriter.Write(PostBackString)
PostBackWriter.Close()
Listing 13-57. Posting received order information back to PayPal.

Discussion of the coding details is beyond the purpose of these tutorials. Suffice it to say that the post-back returns to the PayPal site accompanied by the information previously received. PayPal verifies that this is, indeed, the information it sent, using this echo as a means to verify that the transmission was not intercepted and changed nor was the original transmission a "spoof" of PayPal.

The script then waits for a second transmission from PayPal, this time a final verification of the order. A single data item is received, the string value "VERIFIED" if payment is verified. In the above script, this string value is received in variable ResponseString.

' Receive final verification from PayPal
Dim ResponseReader As StreamReader 
ResponseReader = New StreamReader(PostBackRequest.GetResponse().GetResponseStream())
Dim ResponseString As String = ResponseReader.ReadToEnd()
ResponseReader.Close()
Listing 13-58. Receiving final post from PayPal.

At this point, your script does whatever it needs to do depending on whether "VERIFIED" was received or not. Normally, on a verified order, you will want to redirect to a page at your site to handle final order processing.

Other PayPal Options

The above discussion only scratches the surface of payment options available through PalPal. If wanted, you can produce invoices, handle subscriptions, recurring payments or donations, and initiate shipments through UPS or the postal service; plus, there is a wealth of merchant services for managing your account. The best way to learn about these features is to visit the site and, at no cost, establish an account. Then you can nose around before making a commitment, and even cancel your account if you decide not to proceed.