Process Payments Promptly

Use Free PayPal-compatible Web Controls to Add E-Commerce Capabilities to Your Web Site

ControlFreak

LANGUAGES: VB.NET | C#

ASP.NET VERSIONS: 2.0+

 

Process Payments Promptly

Use Free PayPal-compatible Web Controls to Add E-Commerce Capabilities to Your Web Site

 

By Steve C. Orr

 

Over the years, many Web development tasks have become easier to implement. For example, HTML is generated with drag and drop simplicity, basic state management is now virtually automatic, and user profile data management is nearly as simple as getting and setting variables.

 

One thing that remains relatively laborious, however, is payment processing. In an attempt to quench the thirst for simpler e-commerce capabilities, I ve assembled two ASP.NET Web controls that will empower any user to donate money or buy a basic product or service from your Web site.

 

In the following paragraphs I ll show you how easy it is to use these controls from an ASP.NET application. Following that, I ll show you how the controls were designed so you can extend them or learn how to make similar Web controls.

 

Accept Donations

The Donate control allows users to give money in a simple and intuitive way. When the user clicks it at run time, they are led through PayPal s payment system that accepts credit card payments and other common payment options. End users do not necessarily need to be PayPal members, but Web sites will need a basic account with PayPal in order to accept such payments. Setting up a PayPal account is free, although they typically take a small specified amount from each transaction as their fee. When the transaction is complete, users are optionally redirected automatically back into the specified flow of your Web site.

 

The default user interface of the Donate button is shown in Figure 1. An alternative button image may be specified by adjusting the ImageUrl property.

 


Figure 1: The Donate control provides a simple and familiar way for users to contribute to your cause.

Present Purchases

The BuyNow control has a nearly identical design and a similar one-button user interface. It is intended to be associated with a specific product or service so users may purchase it. Like the donation control, the user s initial button click leads them through PayPal s intuitive payment processing system. When the transaction is complete, PayPal provides multiple options for transferring the flow back to your Web site and allowing your Web site to verify the completed payment.

 

The default user interface of the Buy Now button is shown in Figure 2. An alternative button image may be specified by adjusting the ImageUrl property.

 


Figure 2: The Buy Now button allows a user to purchase a particular product or service.

 

Common Properties

The two controls present slightly different user interfaces to the user, but they share the same set of public properties. Some of the properties are likely more relevant for the Buy Now button than the Donate button, but all the properties can be useful for both controls in certain situations.

 

If you re familiar with the standard ASP.NET ImageButton control, you ll find most of the properties to be familiar because both controls ultimately inherit from it. Here I ll cover the unique properties the controls offer (see Figure 3).

 

Property

Value Type

Description

SuccessReturnUrl

String

The public URL to which PayPal should return the user upon successful payment.

FailReturnUrl

String

The public URL to which PayPal should return the user upon aborted payment.

NotifyUrl

String

The URL to which PayPal posts information about the transaction via Instant Payment Notification. Must be URL-encoded.

BusinessEmail

String

The registered e-mail address of your PayPal account.

CustomData

String

Passthrough variable never presented to the customer. May be useful for associating custom state or identifier data with the transaction.

Invoice

String

Passthrough variable you can use to identify your invoice number for this purchase.

ItemName

String

Description of item. If omitted, customers can enter an item name at time of purchase.

ItemNumber

String

Passthrough variable for you to track purchases or donations, passed back to you at payment completion.

CurrencyCode

String

Defines the currency of the payment. Default is USD.

Price

Single

The required payment amount. (Leave blank to allow the user to choose the payment amount.)

PostReturn

Boolean

Return method GET or POST: the FORM METHOD used to send data to the URL specified by the return variable after payment completion. Default: false.

RequireShippingAddress

Boolean

Prompts customer for a shipping address. Default: false.

RequireNote

Boolean

Prompts customer to include a note with payment. Default: false.

Figure 3: These are the unique public properties of the Donate and BuyNow controls.

 

Perhaps the most important property is the BusinessEmail string. This must be set to the e-mail address associated with your registered PayPal account. If this property is not set correctly, you will not receive payments that were intended for you.

 

The Price property is also of notable functionality. For the Buy Now button you ll almost certainly want to set this property to the amount of the associated product or service. For the Donate button, you might choose to leave this property value unspecified. In either case, if the property is left blank, PayPal will prompt the user to specify their desired payment amount.

 

The CurrencyCode property is only relevant when the price property has been set. The default currency code is USD, which specifies that the Price property contains a United States Dollar amount. Any other standard currency code can be specified for this property value.

 

The ItemName property should be filled with the name of the product or service with which the Buy Now button is associated. PayPal presents this name to the user so they can rest assured they are purchasing the correct item. This property is clearly optional for the Donate button, although you might (in some cases) choose to associate a donation with a particular item of some sort. If the ItemName property value is omitted, PayPal typically allows the user to enter a free-form item name with which their payment is associated.

 

Similarly, the ItemNumber property can be filled with any custom identifier that you may have associated with the specified product or service. This passthrough variable is never shown to the user, but is saved along with the transaction to help identify what was purchased. Taking this concept one step further, the Invoice and CustomData properties also can be filled with personalized passthrough identifiers of some sort to help identify particular purchases.

 

The Boolean RequireNote property can be set to true to force users to include a note along with their payment. The default value of this property is false.

 

You can avoid having to manually collect shipping address information for purchases that must be physically shipped to a user simply by setting the Boolean RequireShippingAddress property to true. This will prompt PayPal to collect the shipping address information, thus simplifying your own input requirements.

 

Transaction Complete

If you want the user to return to the flow of your Web site after they ve completed their interaction with PayPal, you must set the SuccessReturnUrl and FailReturnUrl properties. The SuccessReturnUrl property should be set to the absolute public Web address of the page intended to accept the user back into your site. If the user cancels out of the PayPal transaction, the FailReturnUrl page accepts the redirection instead.

 

All these transaction variables will be posted to the above specified ReturnUrl if the Boolean PostReturn property is set to true. This allows the page to potentially contain custom logic to recognize the incoming transaction data and respond intelligently to the success or failure of that transaction. For example, a custom function could be called to order the shipment of the product associated with a successful transaction. The relevant form variables are documented on PayPal s Web site at https://www.paypal.com/IntegrationCenter/ic_std-variable-ref-buy-now.html.

 

However, instead of blindly trusting any data claiming to be from PayPal that is posted to this page, you might want to take a more secure approach by verifying the data with one of PayPal s other payment notification services. These services also can be useful if you choose to leave the PostReturn property at its default value of false.

 

For example, their Instant Payment Notification System (IPN) can post a special message to your server when a transaction has been successfully completed. The NotifyUrl property of the controls can be used to specify the full public Web address of the page that accepts such messages. This and other types of automated and manual PayPal verification systems are documented at https://www.paypal.com/IntegrationCenter/ic_button-encryption.html.

 

How It Works

Because the Donate and Buy Now buttons have such a similar design, it makes sense to have them inherit from the same base class. This technique maximizes code reuse and reduces maintenance. The custom abstract base class from which both controls are inherited is named aspaypal_base. It, in turn, inherits from the standard ASP.NET ImageButton Web control.

 

The aspaypal_base class primarily collects the previously noted properties and renders them into the page as hidden form fields that are recognized by PayPal. It then posts these values into PayPal s payment processing system. This requires a few hundred lines of fairly boilerplate code, examples of which are listed in Figure 4 and Listing One.

 

(requires reference to System.Design)

GetType(System.Drawing.Design.UITypeEditor)), _

Bindable(True), Category("Behavior"), _

DefaultValue(""), Localizable(True)> _

Property SuccessReturnUrl() As String

 Get

   Dim s As String = CStr(ViewState("SuccessReturnUrl"))

   If s Is Nothing Then

       Return String.Empty

   Else

       Return s

   End If

 End Get

 Set(ByVal Value As String)

   ViewState("SuccessReturnUrl") = Value

 End Set

End Property

Figure 4: This is an example of one of the properties from the aspaypal_base class.

 

The SuccessReturnUrl property listed in Figure 4 is a little more interesting than most of the other properties because it is decorated with the Editor attribute. This design-time feature tells Visual Studio to show the ellipsis (...) button in the properties window for this property. When clicked, the standard Visual Studio Select URL dialog box appears (see Figure 5).

 


Figure 5: Visual Studio s Select URL dialog box.

 

Listing One lists the aspaypal_base class internal CreateHiddenFields subroutine, which is called from the Render method. The actual Donate and BuyNow controls (listed in Figures 6 and 7, respectively) contain very little code, because most of the functionality is implemented via inheritance.

 

Imports System.ComponentModel

Imports System.Web.UI

ToolboxData("<{0}:Donate runat=server>")> _

Public Class Donate

 Inherits aspaypal_base

 Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

  MyBase.OnInit(e)

  Dim u As String

  u = "http://www.paypal.com/en_US/i/btn/btn_donate_LG.gif"

  Me.ImageUrl = u

  Me.cmd = "_donations"

 End Sub

End Class

Figure 6: This is the complete code for the Donate class found in the file Donate.vb.

 

Imports System.ComponentModel

Imports System.Web.UI

ToolboxData("<{0}:BuyNow runat=server>")> _

Public Class BuyNow

 Inherits aspaypal_base

 Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

  MyBase.OnInit(e)

  Dim u As String

  u = "http://www.paypal.com/en_US/i/btn/btn_buynow_LG.gif"

  Me.ImageUrl = u

  Me.cmd = "_xclick"

 End Sub

End Class

Figure 7: This is the complete code for the BuyNow class found in the file BuyNow.vb.

 

As you can see by the code listings in Figures 6 and 7, the controls differ only by a couple properties that have distinctive default values set in their initialize events. The underlying ImageButton s ImageUrl property is assigned a standard button image from PayPal s site. Additionally, the custom cmd property is set to a value that reflects the button s type to PayPal s Web site.

 

Conclusion

Payment processing no longer needs to be an ominous development chore. By dropping one of these free controls on a Web page, basic e-commerce functionality can be enabled simply by setting a property or two. You ve seen how easy it is to use these controls, examined their properties, and explored much of the source code.

 

I encourage you to download the complete source code, available in both VB.NET and C#, to more thoroughly explore their inner workings. With this knowledge you can extend these controls with custom functionality, or create entirely new controls of similar design.

 

C# and VB.NET source code accompanying this article is available for download.

 

Steve C. Orr is an ASPInsider, MCSD, Certified ScrumMaster, Microsoft MVP in ASP.NET, and author of Beginning ASP.NET 2.0 AJAX by Wrox. He s been developing software solutions for leading companies in the Seattle area for more than a decade. When he s not busy designing software systems or writing about them, he often can be found loitering at local user groups and habitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:[email protected].

 

Begin Listing One The aspaypal_base class hidden field rendering

Protected Sub CreateHiddenFields(ByVal _

 writer As System.Web.UI.HtmlTextWriter)

   'Create common hidden fields...

   Dim h As HiddenField

   h = New HiddenField()

   h.ID = "business"

   h.Value = Me.BusinessEmail

   h.RenderControl(writer)

   If Me.Invoice.Trim.Length > 0 Then

       h = New HiddenField()

       h.ID = "invoice"

       h.Value = Me.Invoice

       h.RenderControl(writer)

   End If

   If Me.ItemName.Trim.Length > 0 Then

       h = New HiddenField()

       h.ID = "item_name"

       h.Value = Me.ItemName

       h.RenderControl(writer)

   End If

   If Me.ItemNumber.Trim.Length > 0 Then

       h = New HiddenField()

       h.ID = "item_number"

       h.Value = Me.ItemNumber

        h.RenderControl(writer)

   End If

   If Me.Price > 0 Then

       h = New HiddenField()

       h.ID = "amount"

       h.Value = Me.Price

       h.RenderControl(writer)

   End If

   If Me.CurrencyCode.Trim.Length > 0 Then

       h = New HiddenField()

       h.ID = "currency_code"

       h.Value = Me.CurrencyCode

       h.RenderControl(writer)

   End If

   If Me.CustomData.Trim.Length > 0 Then

       h = New HiddenField()

       h.ID = "custom"

       h.Value = Me.CustomData

       h.RenderControl(writer)

   End If

   If Me.NotifyUrl.Trim.Length > 0 Then

       h = New HiddenField()

       h.ID = "notify_url"

       h.Value = Me.NotifyUrl

       h.RenderControl(writer)

   End If

   If Me.FailReturnUrl.Trim.Length > 0 Then

        h = New HiddenField()

       h.ID = "cancel_return"

       h.Value = Me.FailReturnUrl

       h.RenderControl(writer)

   End If

   If Me.SuccessReturnUrl.Trim.Length > 0 Then

       h = New HiddenField()

       h.ID = "return"

       h.Value = Me.SuccessReturnUrl

       h.RenderControl(writer)

       If Me.PostReturn Then

           h = New HiddenField()

           h.ID = "rm"

           h.Value = "2"

           h.RenderControl(writer)

       End If

   End If

   If Me.RequireShippingAddress = False Then

       h = New HiddenField()

       h.ID = "no_shipping"

       h.Value = "1"

       h.RenderControl(writer)

   End If

   If Me.RequireNote = False Then

       h = New HiddenField()

       h.ID = "no_note"

       h.Value = "1"

       h.RenderControl(writer)

   End If

   h = New HiddenField

   h.ID = "cmd"

   h.Value = Me.cmd

   h.RenderControl(writer)

End Sub

End Listing One

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish