PayPal with ASP.NET MVC

November 29, 2011

PayPal is a cheap and easy solution for taking payments and is quick to implement in ASP.NET MVC. We will look at a simple scenario of taking a user to a PayPal payment page to checkout. There is not much information on the PayPal website about using MVC, so hopefully this should get you started. This post deals with the express checkout, but the same principle applies to the normal checkout process.

Creating a PayPal Account

You will need a sandbox account to test your transactions. The sandbox account is separate from a regular account and is all you need to sign up to before you develop and test your code.

PayPal Account Settings

It's good practice to put things like account settings in the web.config. The code in this article will access these settings. You must change the sandbox setting to False when using regular account details:

PayPal Checkout Button

We won’t discuss the ins and outs of implementing the shopping cart functionality for adding/removing products, and will get straight onto the “buy” button. You will need to place a checkout or buy button on your page (you must use the ones PayPal provide).

Here’s how this should look in ASP.NET MVC using the Razor engine (which I’m a big fan of):

The checkout button posts back to your controller and then you do a server side call to PayPal. This is the only API call you need to make to get the simplest of transactions going and in fact you don’t need to make this call if you're not using the express checkout, however, the nice part about doing this server side interaction is you get some feedback from PayPal which you can log (logging the interaction with a payment provider in this way for trouble shooting purposes is heavily advised) before taking the user to the PayPal website. The MVC redirect mechanism makes this quite easy in your controller. Once this redirect happens the user can pay and the transaction is complete.

Further Investigation

There are facilities for PayPal to notify your website that the transaction was successful (you get emailed so this isn’t entirely necessary) and there are numerous other features, but hopefully this should get you started on the path to using PayPal with ASP.NET MVC.