Kentico CMS 7.0 E-commerce Guide

Example - Integrating a custom payment gateway as a library

Example - Integrating a custom payment gateway as a library

Previous topic Next topic Mail us feedback on this topic!  

Example - Integrating a custom payment gateway as a library

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

Here's a general overview of the process of integrating a custom payment gateway as a dynamic-link library:

 

1.Create a payment gateway form with your custom controls to enable customers to enter their payment data such as credit card number; see the Creating a custom payment gateway form section.

2.Create your custom payment gateway class and override required methods for payment processing, see the Creating a custom payment gateway class section.

3.Go to CMS Desk -> E-commerce -> Configuration -> Payment methods.

4.Create a new payment method and register your custom payment gateway.

 

Creating a custom payment gateway form

 

1.Create a new web user control (*.ascx) and place it into your site folder which is located in the root of your web project. Since the control is located in the site folder, it is included in the export package of your site.

2.Set the control class to inherit from the abstract CMS.EcommerceProvider.CMSPaymentGatewayForm class.

3.There are several methods you need to override to reach your required functionality:

 

LoadData() - initializes form controls with customer payment data.

ValidateData() - validates customer payment data.

ProcessData() - processes customer payment data and saves it to the ShoppingCartInfo object.

 

4.There are several properties to get or set the required information:

 

ShoppingCartControl - the parent shopping cart control to which the current shopping cart step belongs.

ShoppingCartInfoObj - the shopping cart object which stores all data during the checkout process.

 

 

InfoBox_Note

 

Please note

 

Payment data, such as credit card numbers, credit card codes and others are not saved into the database due to security reasons.

 

 

Creating a custom payment gateway class

 

1.Create a new library (assembly) as part of your solution and a new class in this library.

2.Add a reference to the System.Web assembly in the project with the payment gateway (right-click the References folder, choose Add reference, select .NET -> System.Web).

3.Set your class to inherit from the CMS.EcommerceProvider.CMSPaymentGatewayProvider abstract class.

4.There are several methods you can override to reach the required functionality:

 

AddCustomData() - adds payment gateway custom controls to the current shopping cart step. By default the CMSPaymentGatewayForm control is added to the payment data container and its data is loaded.

RemoveCustomData() - removes payment gateway custom controls from the current shopping cart step. By default all controls from the payment data container are removed.

ValidateCustomData() - validates payment gateway custom data of the current shopping cart step. By default the CMSPaymentGatewayForm control data is validated.

ProcessCustomData() - processes payment gateway custom data of the current shopping cart step. By default the CMSPaymentGatewayForm data is processed.

ProcessPayment() - processes payment; you need to override this method to process payment by your payment processor.

GetPaymentDataForm() - loads the payment gateway form with custom controls; you need to override this method to get your own payment gateway form.

 

5.There are several properties to get or set the required information:

 

ShoppingCartControl - a parent shopping cart control to which the current shopping cart step belongs.

ShoppingCartInfoObj - a shopping cart object which stores all data during the checkout process. If OrderId is set, it is created from the existing order, otherwise it is returned from the current shopping cart control.

OrderId - a unique identifier (ID) of the currently processed order.

PaymentDataContainer - the payment gateway custom controls container of the current shopping cart step control.

PaymentResult - the result of the currently processed payment.

IsPaymentCompleted - indicates whether order payment is already completed. It is determined by the order payment result.

InfoMessage - the payment result message displayed to the user when payment succeeds.

ErrorMessage - the payment result message displayed to the user when payment fails.

 

6.Compile the library.

7.Ensure the library file (*.dll) is included in the <your web project folder>/Bin directory.

 

Example

 

The following example shows a custom payment processor implementation. It allows customers to pay for their orders using an external payment gateway similar to PayPal; we can call it e.g. Custom Gateway. The customer is asked for their credit card number in the last step of the checkout process. The credit card number is validated for emptiness and processed after the Finish payment button is clicked. If successful, the payment process is performed – required payment data is attached to the payment URL and the customer is redirected to the Custom Gateway. If the payment process fails (payment gateway URL is not defined), the order payment result is updated and an appropriate error message is displayed. Notice that the order is saved before the customer is asked to pay for it. Specifically, this happens immediately after the Order now button is clicked.

 

 

InfoBox_Note

 

Please note

 

It is not secure to send credit card information as a part of payment gateway URL. Customers are usually asked for their credit card number after they have been redirected to the payment gateway itself. Otherwise, another way of sending credit card information should be used instead.

 

 

 

For more details about how payment gateways can inform merchants about the results of payments finished outside their websites, please see the IPN (Instant Payment Notification) section in the PayPal topic.

 

On the following screenshot you can see an example of a custom payment gateway definition.

 

ecommerceguide_clip0192

 

Custom payment gateway form

 

It is a simple form with one input field to enter customer credit card number, see image bellow.

 

ecommerceguide_clip0193

 

CustomGatewayForm.ascx

 

If you installed the Kentico CMS project as a web application, you need to rename the CodeFile property on the first line to Codebehind for the code example to be functional.

 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CustomGatewayForm.ascx.cs" Inherits="CMSEcommerce_Example_CustomGatewayForm" %>

<asp:Label ID="lblTitle" runat="server" EnableViewState="false" CssClass="BlockTitle" />

<asp:Label ID="lblError" runat="server" EnableViewState="false" CssClass="ErrorLabel" Visible="false" />

<asp:Label ID="lblCardNumber" EnableViewState="false" runat="server" />

<asp:TextBox ID="txtCardNumber" runat="server" />

 

CustomGatewayForm.ascx.cs

 

[C#]

 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

using CMS.EcommerceProvider;

using CMS.GlobalHelper;

 

public partial class CMSEcommerce_Example_CustomGatewayForm : CMSPaymentGatewayForm

{

 

  protected void Page_Load(object sender, EventArgs e)

   {

      // Initialize label    

       lblTitle.Text = "Your credit card details";

       lblCardNumber.Text = "Credit card number:";

   }

 

 

  /// <summary>

  /// Initializes form controls with customer payment data.

  /// </summary>

  public override void LoadData()

   {

      // Display customer credit card number

       txtCardNumber.Text = ValidationHelper.GetString(this.ShoppingCartInfoObj.PaymentGatewayCustomData["CustomGatewayCardNumber"], "");

   }

 

 

  /// <summary>

  /// Validates customer payment data.

  /// </summary>

  /// <returns></returns>

  public override string ValidateData()

   {

      if (txtCardNumber.Text.Trim() == "")

       {          

           lblError.Visible = true;

           lblError.Text = "Please enter your credit card number";

          return lblError.Text;

       }

      return "";

   }

 

 

  /// <summary>

  /// Process customer payment data.

  /// </summary>

  /// <returns></returns>

  public override string ProcessData()

   {

      // Save credit card number

      this.ShoppingCartInfoObj.PaymentGatewayCustomData["CustomGatewayCardNumber"] = txtCardNumber.Text.Trim();

      return "";

   }

}

 

Custom payment gateway class

 

The following example uses the CMS.CustomProvider assembly name and the CMS.CustomProvider.CustomGateway class, however, you will need to use your own names.

 

CustomGateway.cs

 

[C#]

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Web;

using System.Collections;

 

using CMS.EcommerceProvider;

using CMS.GlobalHelper;

using CMS.UIControls;

using CMS.ExtendedControls;

 

namespace CMS.CustomProvider

{

  /// <summary>

  /// Class representing Custom Gateway processor.

  /// </summary>

  public class CustomGateway : CMSPaymentGatewayProvider

   {

      /// <summary>

      /// Returns payment gateway form with custom controls.

      /// </summary>

      /// <returns></returns>

      public override CMSPaymentGatewayForm GetPaymentDataForm()

       {

          try

           {

              return (CMSPaymentGatewayForm)this.ShoppingCartControl.LoadControl("~/CMSEcommerce/Example/CustomGatewayForm.ascx");

           }

          catch

           {

              return null;

           }

       }

 

 

      /// <summary>

      /// Process payment.

      /// </summary>

      public override void ProcessPayment()

       {          

          // Get payment gateway url

          string url = this.GetPaymentGatewayUrl();

 

          if (url != "")

           {

              // Initialize payment parameters

               Hashtable parameters = InitializePaymentParameters();

 

              // Add required payment data to the url

               url = GetFullPaymentGatewayUrl(url, parameters);

 

              // Redirect to payment gateway to finish payment

              this.ShoppingCartControl.Page.Response.Redirect(url);

           }

          else

           {              

              // Show error message - payment gateway url not found

              this.ErrorMessage = "Unable to finish payment: Payment gateway url not found.";

 

              // Update payment result

              this.PaymentResult.PaymentDescription = this.ErrorMessage;

              this.PaymentResult.PaymentIsCompleted = false;

 

              // Update order payment result in database

              this.UpdateOrderPaymentResult();

           }

       }

 

 

      /// <summary>

      /// Returns table with initialized payment parameters.

      /// </summary>

      /// <returns></returns>

      private Hashtable InitializePaymentParameters()

       {

           Hashtable parameters = new Hashtable();

 

           parameters["orderid"] = this.ShoppingCartInfoObj.OrderId;

           parameters["price"] = this.ShoppingCartInfoObj.TotalPrice;

           parameters["currency"] = this.ShoppingCartInfoObj.CurrencyInfoObj.CurrencyCode;

           parameters["cardnumber"] = Convert.ToString(this.ShoppingCartInfoObj.PaymentGatewayCustomData["CustomGatewayCardNumber"]);

 

          return parameters;

       }

 

 

      /// <summary>

      /// Returns payment gateway url with payment data in query string.

      /// </summary>

/// <param name="url">Payment gateway url.</param>

      /// <param name="parameters">Initialized payment paremeters.</param>

      /// <returns></returns>

      private string GetFullPaymentGatewayUrl(string url, Hashtable parameters)

       {

          foreach (DictionaryEntry parameter in parameters)

           {

              // Add payment data to the url

               url = URLHelper.AddParameterToUrl(url, Convert.ToString(parameter.Key), HttpUtility.UrlEncode(Convert.ToString(parameter.Value)));

           }

          return url;

       }

   }

}

 

For further details on how to create your custom payment gateway, please see the Developing Custom Payment Gateway webinar.