Articles


 

Crystal Report

 

This is the first article in a series focusing on programming with Crystal Reports with ASP.NET 2.0. In this article, we will focus on adding a Crystal Report to an ASP.NET 2.0 web site and displaying the same using the CrystalReportViewer control in a number of different ways.

The entire solution (source code) for this article is available as a free download (in the form of a zip). The source code in this article has been developed using Microsoft Visual Studio 2005 Professional Edition on Microsoft Windows Vista Ultimate Edition with Microsoft SQL Server 2005 Express Edition. I used the same version of Crystal Reports which comes with Visual Studio 2005 Professional Edition. I didn’t really test any of the code in any other tools/IDEs/servers/editions/versions. If you have any problems, please feel free to post in the discussion area.

I contributed two articles focusing on the capabilities of ASP.NET 2.0’s built-in reporting. If you are new to the built-in reporting (also called local reporting),

Starting an ASP.NET 2.0 Web Site Project

The following are the steps necessary to create a new ASP.NET 2.0 web site:

  • Open Microsoft Visual Studio 2005 Professional Edition
  • Open File || New || Web Site
  • Select “ASP.NET Web Site” in templates, select “File System” as the location, provide the website name “SampleWebSite01”  and finally click on OK.
  • Right click on “SampleWebSite01” available in Solution Explorer and select “Add New Item.”

The next section walks you through adding a Crystal report to the project.

Programming Crystal Reports with ASP.NET 2.0 – Adding a Crystal Report to the Project
(Page 2 of 6 )

In the previous section, a new ASP.NET web site was created. In this section, we shall walk through the creation of a Crystal report. The following are the steps you need to take; they pick up from where we left off in the previous section:

In the “Add New Item” dialog box, select “Crystal Report” as the template, provide the name “SampleRpt01.rpt” and click on the “Add” button.

You should see “SampleRpt01.rpt” added to the “Solution Explorer” and the “Crystal Reports Gallery” dialog will be shown (Fig 05). Select “Standard” in “Choose an Expert” and click OK (Fig 05).

Next, you will be taken to provide details for the Data Source. In the “Available Data Sources,” open “Create New Connection” and open “OLE DB (ADO).” It brings up another dialog box to let you select the OLEDB Provider. Select “Microsoft OLEDB Provider for SQL Server” in the list of Providers and click on “Next” as shown below.

Provide the db connection information to connect to the Northwind database and click on “Finish.”

A new connection gets added to the “OLEDB (ADO)” group. Open the added connection and further drill down to Northwind || dbo || Tables, add the “Orders” table to the “Selected Tables” list (by selecting it and clicking on the greater than arrow), and click on “Next” as shown below.

In the next screen of the wizard, you will be provided with all the fields (or columns) to include in the report. Add OrderID, CustomerID, EmployeeID and OrderDate to the “Fields to Display” section by double clicking each of those fields in the “Available Fields” list and click on “Finish” as shown below.

Programming Crystal Reports with ASP.NET 2.0 – Crystal Report Components
(Page 3 of 6 )

In the previous section, we added a new Crystal Report to the web site. Once the report gets added, you should be able to see the Visual Studio layout with “Field Explorer,” the new “Crystal Reports” menu and an “Embedded Crystal Report Designer” with two modes (“Main Report” and “Main Report Preview” at the bottom) as shown below.

The “Field Explorer” can be used to drag and drop the columns onto the report, add new, add new tables to the report, add new formula oriented columns, running totals, and so on.

The report designer is initially divided into five sections (Report Header, Report Footer, Page Header, Page Footer and Details). Report Header gets displayed only on the first page. Report Footer gets displayed only on the last page. Page Header gets displayed on top of every page. Page Footer gets displayed at the bottom of every page. The Detail section is the body of the report where all of the rows get displayed.

Using the formatting toolbar, properties windows and tools in toolbox, we can format the report in the required manner. Try playing with formatting the report (and preview it simultaneously without executing the project).

Displaying Crystal Report on the ASP.NET 2.0 web page

To display the report on the web page, we need to work with Crystal Report Viewer control. The following are the steps required to attach the Crystal Report to the ASP.NET 2.0 web page:

Using the ToolBox, drag and drop the CrystalReportViewer control.

Using the Smart tag of the CrystalReportViewer control, select “New Report Source.”

This leads you to a new dialog box, “Crystal Report Source.” Every CrystalReportViewer gets associated with the CrystalReportSource control. You can directly drag and drop the CrystalReportSource control from the toolbox as well and assign the same in a smart tag. Provide the details and click OK.

The moment you hit OK, you should be previewing the report. Just hit F5 to execute your web site. Once the web page gets displayed, provide logon information for the report and click on “Logon.”

Programming Crystal Reports with ASP.NET 2.0 – Providing Login information for the CrystalReportViewer control dynamically
(Page 4 of 6 )

The CrystalReportViewer control needs to be provided with database logon information to execute and show the report. At the same time, it is a bit awkward to have the database login page displayed for every Crystal Report. No end user likes it (and of course, it is dangerous too!).

To solve this problem, we can provide database logon information to the CrystalReportViewer control dynamically at runtime. The following is the code to achieve the same:

Imports CrystalDecisions.Shared

Partial Class _Default

Inherits System.Web.UI.Page

Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load

Dim ConnInfo As New ConnectionInfo

With ConnInfo

.ServerName = “.sqlexpress”

.DatabaseName = “Northwind”

.UserID = “sa”

.Password = “eXpress2005”

End With

For Each cnInfo As TableLogOnInfo In Me.CrystalReportViewer1.LogOnInfo

cnInfo.ConnectionInfo = ConnInfo

Next

End Sub

End Class

You must observe that the CrystalDecisions.Shared namespace is added to the top. In the above code, the database connection information is stored in ConnInfo and is defined as follows:

Dim ConnInfo As New ConnectionInfo

With ConnInfo

.ServerName = “.sqlexpress”

.DatabaseName = “Northwind”

.UserID = “sa”

.Password = “eXpress2005”

End With

The above connection information is assigned to CrystalReportViewer control using the following code:

For Each cnInfo As TableLogOnInfo In Me.CrystalReportViewer1.LogOnInfo

cnInfo.ConnectionInfo = ConnInfo

Next

Programming Crystal Reports with ASP.NET 2.0 – Hiding the toolbar and adding First, Last, Next and Previous page buttons to the report
(Page 5 of 6 )

By default, CrystalReportViewer automatically displays toolbar at the top. Not every end user uses all features. At the same time, some end users may not like the toolbar.

To hide the toolbar, modify the CrystalReportViewer code (in Source mode) as follows:

<CR:CrystalReportViewer ID=”CrystalReportViewer1″ runat=”server”AutoDataBind=”True” ReuseParameterValuesOnRefresh=”True”DisplayToolbar=”False” EnableDatabaseLogonPrompt=”False”EnableParameterPrompt=”False” DisplayGroupTree=”False”

Height=”1064px” ReportSourceID=”CrystalReportSource1″Width=”928px” />

Add First, Last, Next and Previous page buttons to the web page and modify the code behind with new events as follows:

Protected Sub btnFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFirst.Click

Me.CrystalReportViewer1.ShowFirstPage()

End Sub

Protected Sub btnLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLast.Click

Me.CrystalReportViewer1.ShowLastPage()

End Sub

Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click

Me.CrystalReportViewer1.ShowNextPage()

End Sub

Protected Sub btnPrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrevious.Click

Me.CrystalReportViewer1.ShowPreviousPage()

End Sub

Programming Crystal Reports with ASP.NET 2.0 – Enhancing the report with run-time binding along with session handling
(Page 6 of 6 )

In all of the above sections, the CrystalReportViewer worked with CrystalReportSource. Now, let us dynamically add a report source to the CrystalReportViewer and bind it at runtime. This gives us the flexibility to use the same viewer for different reports (showing one at a time).

Add a new web page to the project, add the four buttons (First, Previous, Next and Last) and a CrystalReportViewer control. Modify the CrystalReportViewer control, so that it looks like the following:

<CR:CrystalReportViewer ID=”CrystalReportViewer1″ runat=”server”AutoDataBind=”True” ReuseParameterValuesOnRefresh=”True”DisplayToolbar=”False” EnableDatabaseLogonPrompt=”False”EnableParameterPrompt=”False” DisplayGroupTree=”False”

Height=”1064px” Width=”928px” />

In the code-behind, add the following at the top:

Imports CrystalDecisions.Shared

Imports CrystalDecisions.CrystalReports.Engine

Add a new method as follows:

Private Sub BindReport()

If Session(“Rep”) Is Nothing Then

Dim ConnInfo As New ConnectionInfo

With ConnInfo

.ServerName = “.sqlexpress”

.DatabaseName = “Northwind”

.UserID = “sa”

.Password = “eXpress2005”

End With

Dim rep As New ReportDocument

rep.Load(Server.MapPath(“SampleRpt01.rpt”))

Me.CrystalReportViewer1.ReportSource = rep

Dim RepTbls As Tables = rep.Database.Tables

For Each RepTbl As Table In RepTbls

Dim RepTblLogonInfo As TableLogOnInfo = RepTbl.LogOnInfo

RepTblLogonInfo.ConnectionInfo = ConnInfo

RepTbl.ApplyLogOnInfo(RepTblLogonInfo)

Next

Session(“Rep”) = rep

End If

Me.CrystalReportViewer1.ReportSource = Session(“Rep”)

Me.CrystalReportViewer1.DataBind()

End Sub

Add the following code to bind the report for every button click and also during the page load event:

Protected Sub btnFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFirst.Click

BindReport()

Me.CrystalReportViewer1.ShowFirstPage()

End Sub

Protected Sub btnLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLast.Click

BindReport()

Me.CrystalReportViewer1.ShowLastPage()

End Sub

Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click

BindReport()

Me.CrystalReportViewer1.ShowNextPage()

End Sub

Protected Sub btnPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrev.Click

BindReport()

Me.CrystalReportViewer1.ShowPreviousPage()

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not IsPostBack Then

BindReport()

End If

End Sub

================************************===================================

Pay Pal Integration

Index

PayPal Introduction
Getting Started with PayPal
Setting up a Test Account
Website Payments Standard (HTML)
PostPayment processing
AutoReturn
Direct Payment (PDT)
Instant Payment Notification (IPN)
PayPal API
Express Checkout
Direct Payment (Website Payments Pro)
Conclusion
History
Introduction

PayPal is probably one of the first things that gets mentioned once you start discussion on online payments. It’s not so without reason – in 2008, PayPal moved over 60 billion dollars between accounts which is, you’ll agree, a respectable amount. And also, all trends show that this growth will continue – with huge number of new accounts (over 184 million accounts in 2008 compared to 96.2 million in 2005), with a new platform named PayPal X, and with more cool applications that involve paying (like Twitpay), you can bet that PayPal is here to stay. So, how can you join the whole PayPal Development movement?

Unfortunately, I would say – not so easily. When I first started with PayPal integration – it was hard, really hard. If you wish to see what I mean, just jump to the PayPal Developer Center. There is no way you’ll easily fish out what you need from that site if you are a PayPal newbie; simply – there are too many links, too many resources, and too many mixings of important and not-so-important information. So, how should you start?

Getting Started with PayPal

To those who really want to get into PayPal, and are willing to shell out some buck, I would recommend the Pro PayPal E-Commerce book – that’s how I eventually got into understanding the concepts behind PayPal integration. For those who are not so eager to pay – don’t worry, that’s why this article is here… I’ll go over most of the stuff that book covers, but in a more brief and concise manner.

First and foremost – understanding what kinds of integration PayPal offers is, I would say, the most important thing in order to successfully start your development journey. A common mistake, that happened to me also, is to start at once with the PayPal API and Express Checkout. I mean it’s natural – we are developers, and when they tell us to integrate with something, the first thing we look for is the SDK & API… the PayPal API comes up as a result… we say “That’s it” to ourselves… and start working. The problem is – the majority of payment scenarios can be handled with a way simpler approach – HTML forms that are part of the Website Payments Standard.

So, without further ado, here is a classification of PayPal integrations:

Website Payments Standard (HTML)
Postpayment Processing
AutoReturn
Payment Data Transfer (PDT)
Instant Payment Notification (IPN)
PayPal API
Express Checkout
Direct Payment (Website Payments Pro)
Payflow Gateway
Items in classification are also ordered in a way I would suggest for everyone to follow. So, if you are new to PayPal – first learn all of the options that you have with the Website Payments Standard (HTML). Then, if you need to add some basic post-payment processing, see if Auto-Return or PDT will solve your problem… if not, IPN is a more robust option you have at your disposal.

The next level would involve the PayPal API and implementing the Express Checkout, which is the most flexible PayPal integration solution. And finally, if you long for the ability to directly process credit cards on your website, you’ll pay a monthly fee to PayPal and implement Direct Payment (effectively getting what is called Website Payments Pro).

The last item from our classification – the Payflow Gateway is, on the other hand, a different beast. It doesn’t “update the stack” in a way the previously mentioned technologies do. It is a solution aimed specifically at those businesses that have/want an Internet Merchant Account (IMA) and just need the payment gateway. In order to keep the article consistent, I’ll skip explaining the details of the Payflow Gateway. However, if you have any questions related to it, feel free to leave a message in the comments section and I’ll try to answer.

That said, let’s get to setting up a test PayPal account, and then we’ll delve deeper into describing the mentioned integrations.

Setting up a Test Account

Word of notice – you’ll want to follow this step even if you already have a live PayPal account. There are two reasons for using test accounts:

you don’t want to test and play with real money
you want to have access to different types of PayPal accounts
Personal account – most people have these; just an account that allows you to use PayPal when paying for stuff online. Theoretically, you can use a Personal account to accept money; just know that you’ll be severely constrained – there is a $500 receiving limit per month, and you are only able to accept one time payments using the Website Payments Standard (HTML). The big advantage of a Personal account is that you don’t need to pay any transaction fee when receiving money. Note, however, that if you receive more than $500 in one month, you’ll be prompted to either upgrade to a Premier/Business account or reject the payment.
Premier account – step up from a personal account; for anyone who wants to run a personal online business. This type of account has all of the integration options (accepting credit cards, recurring payments, PayPal API). However, most people skip directly from Personal to Business account as Premier account has the same transaction fees (in most cases, 2.9% + $0.30 per transaction) while lacking reporting, multi-user access, and other advanced merchant services of the Business account.
Business account – it has all of the features of the Premier account plus a few more (ability to operate under your business’s name is one of them). If you are developing a website that needs to accept payments in 99% of situations, you’ll go with this type of account.
To start, visit the PayPal Sandbox and sign-up for a new account. The process is straightforward, and most developers should have no trouble finishing it. However, here are the pictures that will help you navigate through the process:

Signing up for a Sandbox account

Filling in the details of your Sandbox account
Once done with entering the details for your Sandbox account, you’ll need to check the email you provided in order to complete the registration. After that, you’ll be able to login and start creating Sandbox PayPal accounts. Clicking on Test Accounts (menu on the left), and then Create Account: Preconfigured – will get you a form like the one on the image below:

Creating a Sandbox test account
Clarification of Account Type radio buttons: by selecting Buyer, you’ll create a Personal account, and by selecting Seller, you’ll create a Business account. For testing most integration scenarios, you’ll need both accounts, so be sure to create them. Here is what you should eventually have on your screen after you click on Test Accounts:

Overview of your testing accounts
Checking the radio button next to any of the accounts from the list and clicking on Enter Sandbox Test Site should bring up the Sandbox PayPal site which will allow you to login and administer your account in the same way as with a regular PayPal account. The only difference is that you’ll have a huge PayPal Sandbox header and text that displays the email address of your developer account. To see what I’m talking about, check the image below:

Administering a PayPal Sandbox account
Last but not least – in order to use your Sandbox account for testing, you need to be logged in with your developer account. If you are not logged in and you follow some payment link, you’ll get the following screen:

Login to use the PayPal Sandbox features
Website Payments Standard (HTML)

In this section, I’ll provide you with a number of examples that will show how to create your own HTML form for receiving money over PayPal. You’ll see how to use different variables in order to influence payment details. Before we delve into details, let’s take a look at the two most basic variables:

form’s action attribute – in most cases, it should be https://www.paypal.com/cgi-bin/webscr. If you are using Sandbox for testing payments, you’ll change it to https://www.sandbox.paypal.com/cgi-bin/webscr – effectively, you just insert the word sandbox into the URL (this is also true for some other integrations; e.g., the PayPal API). For upcoming examples, I won’t be using the Sandbox URL because most of you would just get that “Login to use the PayPal Sandbox features” screen (look up for the image).
form’s business child – I’ll use youremailaddress@yourdomain.com for most examples; if you copy-paste the code, you’ll want to replace that with the email of your PayPal account.
Basic Payment

OK, let’s say you have an opened PayPal account and you just wish to be able to accept a $10 payment for a painting you are selling through your site. Just insert the following HTML into your page and you are set to go:

Collapse

Shipping & Handling

The next thing that comes to mind is that you’ll wish to add shipping and/or handling fees to your form. It’s easy – just add more parameters:

Collapse

Donations & Textual Links

If you aren’t selling anything but rather accepting donations for some cause – you’ll just need to change the value of the cmd variable to _donations. If we combine this with a common requirement to have a hyperlink instead of a button – we get the following URL (of course, you can use this method of URL creation for other PayPal payment types):

https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=youremailaddress@yourdomain.com&item_name=Save Polar Bears!&amount=10.00
Result:

Save Polar Bears!
Cart System

If you have a bunch of different products to offer and you just want a simple cart system without implementing anything, PayPal has you covered. Basically, you’ll just play with the cmd variable while keeping the rest of the form same as for the Basic Payment. Let’s see how you should do this for two products; one priced at $10 without shipping fees, and one priced at $5 with $1 shipping fee. We will also need a View Cart button:

Collapse
My Cart Item 1:

My Cart Item 2:

View Cart:

Recurring Payments

If you are selling a monthly service rather than a product, you’ll be interested in the recurring payment options PayPal provides. Again, it’s playing with different variables that have different meaning. Let’s say you wish to set a 3 day free trial after which the user will have to pay you $10.00 per month to keep using the service. The following HTML form should do the trick:

Collapse

HTML Variables & Resources

After reading the previous example, you may be wondering what certain variables do (a1? p1? srt?). Luckily, PayPal provides an “HTML Variables for Website Payments Standard” page on which you can read about any variable that you are interested in.

Also, another great resource (to which I wish someone pointed me when I first started with PP integration) is “skier’s PayPal examples”. You’ll find examples for almost all payment scenarios you can think of – so instead of cluttering this article with more examples, I’ll encourage you to visit that page should you wish to implement some more advanced PayPal HTML form.

PostPayment Processing

When you setup your PayPal HTML form, the first question you’ll probably ask is – after user pays, can I have some post-payment processing logic? It is not so without reason; there are numerous post-payment scenarios we can think of – from sending a simple “Thank you” email to updating the site database and allowing user access to restricted resources for which he paid. Depending on your knowledge and the desired level of robustness for post-processing logic, there are three ways you can go; and the good thing is you can combine them.

AutoReturn

AutoReturn is the simplest PostPayment processing solution that you have – after the user pays, he is automatically* redirected to a specified page on your website on which you can display some confirmation text. If you carefully went through “HTML Variables for Website Payments Standard”, you know that you can use a return variable to specify the AutoReturn URL in the HTML form. If you wish to have the default AutoReturn URL, follow these steps:

Log in to your Premier or Business account
Click the Profile subtab
Click the Website Payment Preferences in the Selling Preferences column
Click the On radio button next to the Auto Return label
Enter the URL where you want your users to return in the text box labeled Return URL
Click the Save button at the bottom of the page

Providing the AutoReturl URL in your PayPal profile
Know that if you have both AutoReturn URL in your profile and provide a return variable in your HTML form, the return variable will overwrite the profile URL value.

Now, when your return page is hit, you’ll be getting variables that should allow you to customize the page display and log payment:

tx – Transaction ID
st – Payment status
amt – Payment amount
cc – Currency code
Before closing this section, one more thing. The reason why I’ve italicized the word “automatically” in the first sentence is: if the user uses a credit card to pay you, he won’t be automatically redirected to your return URL; he’ll rather need to click on the “Return to Merchant” button. If this sounds weird to you, know that you’re not alone; however, because of legal issues, PayPal refused and still refuses to change the way credit card payments are handled with AutoReturn.

Payment Data Transfer (PDT)

After looking over the list of variables that AutoReturn provides, you probably wondered – can I get more details about the transaction that occurred? This is exactly where PDT jumps in – building on the AutoReturn functionality. For that reason, you’ll need to enable both AutoReturn and then PDT in your profile; here is how to do that:

Log in to your Premier or Business account
Click the Profile sub tab
Click Website Payment Preferences in the Selling Preferences column
Click the On radio button next to the Auto Return label
Enter the URL of the script that will process the PDT HTTP request sent from PayPal
Under Payment Data Transfer, click the On radio button
Click Save.
After following these steps, you should get a PDT Identity Token that is needed for querying PayPal. If you don’t copy-paste the token after clicking Save, know that you can always see it in your Website Payment Preferences:

Payment Data Transfer and Identity Token
Now that you have the Identity Token, you can query PayPal for more details after your return URL has been hit. Here is how things flow when utilizing PDT:

User pays and is redirected to your AutoReturn page, for example: http://www.yourdomain.com/Thanks.aspx?tx=%5BTransactionID%5D.
From the code-behind of Thanks.aspx, you’ll parse the tx value and make an HTTP POST to https://www.paypal.com/cgi-bin/webscr with the following parameters: cmd=_notify-synch&tx=[TransactionID]&at=[PDTIdentityToken]. (If you are using Sandbox, you’ll of course make an HTTP POST to https://www.sandbox.paypal.com/cgi-bin/webscr.)
PayPal will respond to your HTTP POST in the following format:
Collapse
SUCCESS
first_name=Firstname
last_name=Lastname
payment_status=Completed
payer_email=firstname%40lastname.com
payment_gross=50.00
mc_currency=USD
custom=Custom+value+you+passed+with+your+HTML+form
etc.
Do whatever you wish with the data.
Here is how what was said in the previous few lines looks in C# code:

Collapse
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
authToken = WebConfigurationManager.AppSettings[“PDTToken”];

//read in txn token from querystring
txToken = Request.QueryString.Get(“tx”);

query = string.Format(“cmd=_notify-synch&tx={0}&at={1}”,
txToken, authToken);

// Create the request back
string url = WebConfigurationManager.AppSettings[“PayPalSubmitUrl”];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

// Set values for the request back
req.Method = “POST”;
req.ContentType = “application/x-www-form-urlencoded”;
req.ContentLength = query.Length;

// Write the request back IPN strings
StreamWriter stOut = new StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
stOut.Write(query);
stOut.Close();

// Do the request to PayPal and get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();

// sanity check
Label2.Text = strResponse;

// If response was SUCCESS, parse response string and output details
if (strResponse.StartsWith(“SUCCESS”))
{
PDTHolder pdt = PDTHolder.Parse(strResponse);
Label1.Text =
string.Format(“Thank you {0} {1} [{2}] for your payment of {3} {4}!”,
pdt.PayerFirstName, pdt.PayerLastName,
pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);
}
else
{
Label1.Text = “Oooops, something went wrong…”;
}
}
}
In the code I’m attaching with the article, under the PDT directory, you’ll see more classes that will help you out in following the previously mentioned flow.

And, as with AutoReturn, one notice before closing the subject – take a look at the custom variable in PayPal’s response to your HTTP POST. You’ll probably want to utilize this variable as it allows you to pass some information from your payment page to your post-processing page without presenting it to the user. To name one use, in some of my PayPal implementations, I track the user with it – when he started payment process, and when/if he finished it.

Instant Payment Notification (IPN)

One big shortcoming of PDT is that it is a user-driven process, meaning – if the user closes the browser after performing a payment and before being redirected to your site, you’ll lose the opportunity to run your post processing logic. That’s why you are advised to combine the PDT with IPN for any serious integration with PayPal.

IPN is a back-end mechanism that makes HTTP POSTs to your page, notifying you of important events. It is used not only for PostPayment processing, but also for things that come after, like handling user cancelation of recurring payments.

Being a back-end technology, it is somewhat harder to implement and debug than PDT. There are a couple of things you should be aware of before starting to implement IPN:

IPN messages can be delayed sometimes. I know, I know… that beats the word “Instant” in IPN, but that’s how things are.
There is a known history of problems with the IPN service; two latest incidents happened on October 2nd 2009 (2 hour delay) and on September 6th 2009 (6 hour delay).
Whenever you have problems with IPN, be sure to check the Live Status page and see if there is an incident notification before digging into debugging and changing your script. There is also a similar page for Sandbox Status.
Before being able to receive IPN messages, you’ll need to activate this service; follow these steps:

Log in to your Premier or Business account
Click the Profile sub tab
Click Instant Payment Notification in the Selling Preferences column
Click the ‘Edit IPN Settings’ button to update your settings
Select ‘Receive IPN messages’ (Enabled) and enter the URL of your IPN handler
Click Save, and you should get a message that you have successfully activated IPN

Activating Instant Payment Notification
As with AutoReturn, you can overwrite the IPN handler URL set in the profile in individual forms by adding the notify_url variable (see the HTML Variables reference). Know that this will influence not only the initial IPN message but all future messages related to that transaction (they will all go to notify_url).

To handle IPN messages, you’ll need to create an HTTP handler somewhere on your website. When a significant event occurs (e.g., user performs payment), following flow takes place:

PayPal will send an HTTP POST to your IPN handler with a number of variables.
After receiving HTTP POST and parsing it, you need to submit the complete body of the message back to https://www.paypal.com/cgi-bin/webscr (or https://www.sandbox.paypal.com/cgi-bin/webscr for a Sandbox account). When you are doing this, be sure to send a message back in the exact format in which you received it; the only thing you are allowed to do is adding cmd=_notify-validate. This is all done in order to verify that HTTP POST was authentic and sent from PayPal.
PayPal will respond with either VERIFIED or INVALID. After you receive this response, be sure to send 200 OK to prevent additional attempts from PayPal to send an IPN. If you don’t close the loop with a 200 OK, PayPal will start resending IPN (starting from 4 seconds and doubling – 8 seconds, 16 seconds, 32 seconds… up to 4 days).
Here is a generic C# IPN handler (for more code, check the zip attached to the article):

Collapse
protected void Page_Load(object sender, EventArgs e)
{
string postUrl = ConfigurationManager.AppSettings[“PayPalSubmitUrl”];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postUrl);

//Set values for the request back
req.Method = “POST”;
req.ContentType = “application/x-www-form-urlencoded”;
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
string ipnPost = strRequest;
strRequest += “&cmd=_notify-validate”;
req.ContentLength = strRequest.Length;

//for proxy
//WebProxy proxy = new WebProxy(new Uri(“http://url:port#&#8221;));
//req.Proxy = proxy;

//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();

StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();

// logging ipn messages… be sure that you give write
// permission to process executing this code
string logPathDir = ResolveUrl(“Messages”);
string logPath = string.Format(“{0}\\{1}.txt”,
Server.MapPath(logPathDir), DateTime.Now.Ticks);
File.WriteAllText(logPath, ipnPost);
//

if (strResponse == “VERIFIED”)
{
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
}
else if (strResponse == “INVALID”)
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
}
If you have received an INVALID response, that could mean two things:

Someone tried to send a malicious message to your IPN handler.
Your implementation isn’t perfect.
In case of a malicious message, you’re on your own (log IP, take appropriate action), but for imperfect implementations, visit this IPN troubleshooting topic on PayPal Developer Forums; it is full of useful tips that should help you solve INVALID responses.

Also, before going online with your IPN handler, be sure to test it thoroughly with the Instant Payment Notification (IPN) simulator. As an IPN handler will work in the background, you’ll want to test it as much as you can before going live and relying on its processing.

Another thing you’ll want to visit if you are implementing IPN is ScriptGenerator2 page… it can quickly generate an IPN handler in the language of your choice. Funny thing – they are missing a generator for ASP.NET/C#; for that, check out the IPN directory in the code-archive I’ve attached to this article and these Code Samples.

Finally, on PayPal Developer Center, there is this nice page that lists most of the IPN and PDT variables. I’m saying most because there are some variables missing on it (check comments on this page), but the list is far beyond being useless.

PayPal API

As said in the introduction, most developers, even if they have no previous experience with PayPal, start directly with the API. Google search brings up either API Reference or the SDKs and Downloads page and then browsing through Documentation starts. I don’t want to say that there is something wrong with using PayPal API for payments; I want to say that in most of the cases, it’s not necessary to go down that path.

PayPal API is much more than just a mechanism for payment – if you look at the provided API Reference page, you’ll see that there are lots of methods not tied directly to “user performing payment”. You can use the API to browse through the history of your transactions, issue a refund, or update a recurring payments profile. So how do you start using it?

First and foremost, you’ll need to enable API access in your account; follow these steps:

Log in to your Premier or Business account
Click the Profile sub tab
Click the API Access link under the Account Information header
Click the link that says Request API Credentials / View API Certificate
Select either API Signature or API Certificate

Step 5 from activating API Access
I recommend that you select API Signature, and the examples that follow will assume you made this choice. There is nothing wrong with selecting API Certificate; I just find it more demanding from a setup perspective.

Now that you have credentials to make API calls, how do you perform them? The approach that will work equally well with all platforms is to download the SDK, target the appropriate API endpoint, and start making HTTP calls with either Name-Value pairs or SOAP.

However, for .NET developers, I recommend a different approach. Considering that Visual Studio has an awesome WSDL parser, I urge you to just add a Web Service Reference to https://www.paypal.com/wsdl/PayPalSvc.wsdl. After a few moments, you’ll have an up-to-date class ready to serve you with all the benefits of strong typing – no building of HTTP requests, no copy-pasting field names, and no cumbersome parsing of responses. You have the same thing available for Sandbox at: https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl.

Express Checkout

Express Checkout is the most flexible PayPal integration solution. The user is redirected to PayPal just for authentication and confirmation that he wants to pay for your services, and after that, everything is done on your website; you’ll make calls to the PayPal API in the background. The following picture describes the process (taken from this page):

Express Checkout flow
You’ll add a PayPal Checkout button that invokes the SetExpressCheckout method of the PayPal API after it is clicked.
If you are invoking this method for one time payment, it’ll be valid if you include only the required fields. Setting the NOSHIPPING variable to 1 is important if you are selling some online service (it’ll help you skip the Shipping info page).
If you are invoking this method in order to set recurring payments, be sure to set L_BILLINGTYPE0 to RecurringPayments and L_BILLINGAGREEMENTDESCRIPTION0 to a valid description of your service.
SetExpressCheckout will return a 20 char token that will uniquely identify your transaction. This token is valid for 3 hours. After you receive it, redirect the user to https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=%5BTOKEN%5D (you can guess what the URL for Sandbox is, right?).
The user will review payment information, and if everything is OK, enter the login credentials. After this, PayPal will redirect him to the URL you specified with RETURNURL when you called SetExpressCheckout.
When your RETURNURL is hit, you need to invoke the GetExpressCheckoutDetails method and see the details of the actual transaction; verify that everything is in order.
Now, all that is left is to commit the transaction. Depending on what you did in step 1, there are two things that can be done.
For one time payments, you’ll just invoke DoExpressCheckoutPayment and forward the appropriate variables.
For recurring payments, you’ll invoke the CreateRecurringPayments method. It is required that you include the DESC field and match it to the value entered in L_BILLINGAGREEMENTDESCRIPTION0 when you called SetExpressCheckout.
In a nutshell – that’s it. Again, I have provided code examples that follow the previously specified flow in the archive accompanying this article (under the API directory). If you wish, you can also use the PayPal Express Checkout Integration Wizard for generating the reference code.

Direct Payment (Website Payments Pro)

Most developers aren’t aware that the PayPal platform can be used for just Credit Card processing. This part of the PayPal API is called Direct Payment, and when combined with Express Checkout (which only services customers with PayPal accounts), you get what is referred to as Website Payments Pro on the PayPal Developer Center.

To be able to call methods that are part of Direct Payment (DoDirectPayment and CreateRecurringPayments), you first need to satisfy some conditions:

Have a Business account that is based in US, UK, or Canada
Oblige that you’ll implement both Express Checkout and Direct Payment on your website
Submit application for Website Payments Pro through your PayPal account and have it approved
Pay monthly fee (currently $30 per month)
After you have a Website Payments Pro account in place, calling Direct Payment methods is pretty straightforward – if in doubt, either visit the API Reference page, or look at the code attached to this article. Just know that if you try to call any Direct Payment method on an account that doesn’t have Pro enabled, you’ll get an error with code 10501 (this is one of the most common problems reported in the Sandbox forum).

Lastly, once you start dealing with credit cards, you’ll need to take care of PCI Compliance; here is a nice forum thread that provides more information on that.

Conclusion

My hope is that this article gave you good overview of PayPal integration options. If it did that, I’ll be at peace – as once you have an understanding of the concepts laid out in this article, you’ll easily fetch the needed details from the provided links. Sure, there are some topics we haven’t touched, like Encrypted Website Payments, PayPal API Certificates, or Payflow Gateway, but I think you can tackle even that on your own once you fully understand all things written here.

If you get stuck on anything, I suggest that you first visit the PayPal Developer Community and ask your question in the appropriate forum. A number of great, knowledable developers monitor those forums, and it’s highly probable that you’ll receive an answer to almost any PayPal issue within an hour. I also have an account on that site (lepipele) and try to answer questions whenever I have time; so feel free to send me a private message if you drop by or run into trouble.

3 thoughts on “Articles

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s