Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Online Credit Card Transaction in ASP.NET Using PayPal Payflow Pro

0.00/5 (No votes)
8 Feb 2011 4  
This article shows you how to implement the online credit card transaction in ASP.NET using .NET SDK for PayPal Payflow Pro

Introduction

To do an online credit card transaction in ASP.NET using PayPal Payflow Pro, you’ll need to set up a Payflow Pro online payment gateway account at PayPal.com, download and install .NET SKD for Payflow Pro, and create an ASP.NET application that sends a transaction request to and receives a transaction response from Payflow Pro.

Payflow Pro Online Payment Gateway Account

At the time of writing this article, the account creation link is: https://registration.paypal.com/welcomePage.do?producttype=C2&country=US&mode=try. PayPal documentation indicates that a testing account can be created, which can then be activated as a production account if needed. Upon the completion of an account setup, you’ll have four user parameters as login credentials to access the account, as shown in the table below.

PayPal_PayflowPro/UserLogin.jpg

Using these credentials, you are able to log into https://manager.paypal.com to manage your account settings, to view/manage transactions, and to generate reports, etc. These same user parameters are also required for online transaction in your ASP.NET application.

.NET SDK for Payflow Pro

PayPal SDK download page is https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks&fli=true#PayflowPro. Scroll down to near bottom of the page, you’ll see the download link for .NET SDK for Payflow Pro v4.31 released in January, 2009. At this time, this is the most current version available.

Download and install the package to your local development machine. By default, it is installed at C:\Program Files\Payflow SDK for .NET\. Browse to the folder, you’ll see two DLLs: Payflow_dotNET_1.1.dll and Payflow_dotNET_2.0.dll which are, as their names imply, for .NET Framework 1.1 and 2.0 respectively. Choose the version you need and RENAME it to Payfow_dotNET.dll before adding a reference to your web application in Visual Studio. As you can see, the SDK has not been updated to the current .NET Framework 4. However, it works fine in the application coded in .NET Framework 4 using Visual Studio 2010.

How Online Transaction Works

Utilizing .NET SDK for Payflow Pro classes, your application sends a transaction request to a Payflow Pro host, where Payflow Pro server processes the request and then sends back a transaction response to your application to notify you of the transaction status. In the request and response cycle, a credit card transaction is accomplished and funds are moved in or out of your bank account that is linked to your Payflow Pro payment gateway account.

Host Name

The host name is a URL for the Payflow Pro server. Payflow Pro provides one for testing and another for production.

  • For testing : pilot-payflowpro.paypal.com
  • For production: payflowpro.paypal.com

Please note that both testing transaction and production transaction go through the same Payflow Pro account. When you log into https://manager.paypal.com, you are able to search, view and manage both.

Transaction Request

A transaction request consists of a string of name value pairs concatenated with a “&”, which contains all payment information needed in a transaction, such as transaction type, payment method, credit card information, user parameters (credentials) for Payflow Pro account, etc. Some are required, and some optional. Here is an example of a transaction request string:

TRXTYPE=S&TENDER=C&ACCT=5105105105105100&EXPDATE=1209&CVV2=123&AMT=99.00
&FIRSTNAME=John&LASTNAME=Smith&STREET=123 Main St.&CITY=SanHose
&STATE=CA&ZIP=12345&COMMENT1=Reservation&USER=MyUser&PWD=MyPassword
&VENDOR=MyVendor&PARTNER=MyPartner

In which, TRXTYPE=S indicates it is a sale transaction type and TENDER=C shows that a credit card is used as the method of payment. The tables below lists common parameters and their descriptions used in a transaction request.

PayPal_PayflowPro/Request_1.jpg
PayPal_PayflowPro/Request_2.jpg

If a parameter is marked as required, it has to be included in a transaction request to get accepted by Payflow Pro server.

Transaction Response

Similarly, a transaction response that your application receives from Payflow Pro is also a string of name value pairs. It provides transaction results including status, transaction number, authorization code, or errors. The string shown below is an example.

RESULT=0&PNREF=EFHP0D426A53&RESPMSG=APPROVED&AUTHCODE=25TEST&
AVSADDR=Y&AVSZIP=N&CVV2MATCH=Y

RESULT=0 means that the transaction is approved. Any value that is greater than 0 indicates a decline or an error. RESPMSG (response message) gives a brief description for an approved transaction, a declined transaction, or an error corresponding to a result code. The table below displays typical parameters in a Payflow Pro response.

PayPal_PayflowPro/Response.jpg

ASP.NET Application

Now let’s take a look at how we can implement the transaction process discussed above in an ASP.NET application using .NET SDK for Payflow Pro. A demo application has been prepared for download. It is coded in Visual Studio 2010, .NET Framework 4 using Payflow_dotNET.dll for Framework 2.0.

The application has only one ASP.NET page that collects payment amount and credit card information, constructs a transaction request string, sends the request to and receives a transaction response from Payflow Pro, and then displays the data on the page.

PayPal_PayflowPro/Submit.jpg

The above screen shot illustrates the web interface for collecting the required data. Upon clicking the Submit button, the transaction request string is constructed and sent to Payflow Pro host, and a response string is then received from the host. The screen shot below displays the name values pairs of the request and the response respectively.

PayPal_PayflowPro/PayPal_data.jpg

When you run this application, you may not see a successful transaction but a failed status. This is because invalid user parameters (USER, VENDOR, PARTNER and PWD) are used in the transaction request. You’ll need to update the user parameters stored in the <appSettings> section of the web.config with valid values associated with your Payflow Pro account.

In the application, the Payflow_dotNET_2.0.dll that came with the .NET SDK for Payflow Pro installation was renamed to Payflow_dotNET.dll and then added to the Visual Studio project as a reference.

Let’s have a look at the code listing:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Configuration;
using PayPal.Payments.Common.Utility;
using PayPal.Payments.Communication;
using PayPal.Payments.DataObjects;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            return;
        }

        //populate month
        string[] Month = new string[] 
	{ "", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
        ddlMonth.DataSource = Month;
        ddlMonth.DataBind();
        //pre-select one for testing
        ddlMonth.SelectedIndex = 4;

        //populate year
        ddlYear.Items.Add("");
        int Year = DateTime.Now.Year;
        for (int i = 0; i < 10; i++)
        {
            ddlYear.Items.Add((Year + i).ToString());
        }
        //pre-select one for testing
        ddlYear.SelectedIndex = 3;
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string PayPalRequest = "TRXTYPE=S" //S - sale transaction
                 + "&TENDER=C" //C - Credit card
                 + "&ACCT=" + txtCardNumber.Text //card number
                 + "&EXPDATE=" + ddlMonth.SelectedValue + 
			ddlYear.SelectedValue.Substring(2, 2)
                 + "&CVV2=" + txtCvv.Text   //card validation value (card security code)
                 + "&AMT=" + txtAmount.Text
                 + "&COMMENT1=My Product Sale"
                 + "&USER=" + ConfigurationManager.AppSettings["USER"]
                 + "&VENDOR=" + ConfigurationManager.AppSettings["VENDOR"]
                 + "&PARTNER=" + ConfigurationManager.AppSettings["PARTNER"]
                 + "&PWD=" + ConfigurationManager.AppSettings["PWD"];

            // Create an instance of PayflowNETAPI.
            PayflowNETAPI PayflowNETAPI = new PayflowNETAPI();

            // RequestId is a unique string that is required for each & every transaction. 
            // The merchant can use her/his own algorithm to generate 
            // this unique request id or use the SDK provided API to generate this
            // as shown below (PayflowUtility.RequestId).
            string PayPalResponse = PayflowNETAPI.SubmitTransaction
				(PayPalRequest, PayflowUtility.RequestId);
            
            //place data from PayPal into a namevaluecollection
            NameValueCollection RequestCollection = 
		GetPayPalCollection(PayflowNETAPI.TransactionRequest);
            NameValueCollection ResponseCollection = GetPayPalCollection(PayPalResponse);

            //show request
            lblResult.Text = "<span class=\"heading\">
		PayPal Payflow Pro transaction request</span><br />";
            lblResult.Text += ShowPayPalInfo(RequestCollection);

            //show response
            lblResult.Text += "<br /><br /><span class=\"heading\">
		PayPal Payflow Pro transaction response</span><br />";
            lblResult.Text += ShowPayPalInfo(ResponseCollection);
                
            //show transaction errors if any
            string TransErrors = PayflowNETAPI.TransactionContext.ToString();
            if (TransErrors != null && TransErrors.Length > 0)
            {
                lblResult.Text += "<br /><br /><span class=\"bold-text\">
				Transaction Errors:</span> " + TransErrors;
            }

            //show transaction status
            lblResult.Text += "<br /><br /><span class=\"bold-text\">
		Status:</span> " + PayflowUtility.GetStatus(PayPalResponse);
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message.ToString();
        }
    }

    private NameValueCollection GetPayPalCollection(string payPalInfo)
    {
        //place the responses into collection
        NameValueCollection PayPalCollection = 
		new System.Collections.Specialized.NameValueCollection();
        string[] ArrayReponses = payPalInfo.Split('&');

        for (int i = 0; i < ArrayReponses.Length; i++)
        {
            string[] Temp = ArrayReponses[i].Split('=');
            PayPalCollection.Add(Temp[0], Temp[1]);
        }
        return PayPalCollection;
    }
    private string ShowPayPalInfo(NameValueCollection collection)
    {
        string PayPalInfo = "";
        foreach (string key in collection.AllKeys)
        {
            PayPalInfo += "<br /><span class=\"bold-text\">" + 
				key + ":</span> " + collection[key];
        }
        return PayPalInfo;
    }
}

Three “using Directives” are required in order to use .NET SDK for Payflow Pro: PayPal.Payments.Common.Utility, PayPal.Payments.Communication and PayPal.Payments.DataObjects.

The transaction related code is shown inside the btnSubmit_Click event handler.

First of all, a string of name value pairs is concatenated and assigned to the variable PayPalRequest. This string includes transaction type (TRXTYPE=S: sale), payment method (TENDER=C: credit card), credit card number, expiration date, amount to charge, user parameters (credentials) for Payflow Pro account, etc. More may be added as needed.

Secondly, an instance of PayflowNETAPI is created so that its properties and methods are exposed to our application.

Thirdly, the method PayflowNETAPI.SubmitTransaction() is called to perform the transaction. This method requires two parameters, a transaction request string built earlier and a RequestId that is an unique ID generated by PayflowUtility object. The return type of the method is a string (stored in the variable PayPalResponse), which is the response from Payflow Pro, consisting of name value pair for transaction results. That is all for a transaction cycle. The rest of the code displays the transaction data on the page, which can be handled differently depending on the requirements in a real world business application.

You may have noticed that in the code sample, Payflow Pro host name is not used anywhere. This is because the host name is placed in the <appSettings> section of web.config file. The SDK knows where to retrieve it directly during a method call. The listing below shows the standard settings provided by the SDK. Some are related to tracing and logging tasks that the SDK also does. These are not turned on in the demo.

    <appSettings>       
        <!-- Payflow Pro Host Name. This is the host name for the PayPal Payment Gateway.
 
      For testing:  pilot-payflowpro.paypal.com.
      For production: payflowpro.paypal.com
     -->
        <add key="PAYFLOW_HOST" value="pilot-payflowpro.paypal.com" />
        <!-- TRACE value when set to ON will show the 
       complete exception stack trace in the response message, if any.
        Change TRACE value to "ON" to switch on the stack trace in response message.-->
        <add key="TRACE" value="OFF" />
        <!-- This is a LOG level tag.To switch on logging change the 
		logger level from "OFF" to any of the following:
     a. DEBUG
     b. INFO
     c. WARN
     d. ERROR
     e. FATAL
     -->
        <add key="LOG_LEVEL" value="OFF" />
        <!-- Relative path for LOG file. -->
        <add key="LOG_FILE" value="logs\PayflowSDK.log" />
        <!-- Log file filesize constant. -->
        <add key="LOGFILE_SIZE" value="102300" />
    </appSettings>

Summary

This article takes a sale credit card transaction as an example to demonstrate how to use .NET SDK for Payflow Pro in ASP.NET. There are other types of transaction, such as Authorization, Void, Delayed Capture, etc. that can all be done using the SDK. No matter what transaction type is involved, in general, it is a similar process of sending a transaction request to a Payflow Pro host and receiving a transaction response from the host, as illustrated in our demo application.  

Reference

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here