This content is archived. See latest version here

Last updated: Oct 21 2014

In this document we will provide an example of how to create a payment provider for purchasing gift cards. Functionality to deduct or add to the balance of the gift card is not included here, that will need to be added. We will also create a new Business Foundation object and tie that to the existing Contact object. With this in place we can create a gift card and assign that to a contact (customer). To be able to use the gift card payment provider we will create classes and user controls. A back-end customization and setup must also be done.

Classes referred to here are available in the following namespaces:

Creating classes

In these steps we will create a class which implements the IPaymentGateway interface.

1. In Visual Studio, create a new project named for instance GiftCardPaymentProvider.

2. Delete the app.data folder and the files web.config and Default.aspx as these are not required.

3. From the root of the site, create the folder structure: this adheres to Commerce Manager.

4. Create a new class GiftGateway.cs. This class will do the following:

  • Return the configuration data associated with a gateway.
  • Set the configuration gateway data. This data typically includes information like gateway URL, account info and so on.

5. In the class add: using Mediachase.Commerce.Orders; Resides in Mediachase.Commerce.Orders.IPaymentGateway.

6. Add a reference to the assembly Mediachase.Commerce.dll.

7. Implement the interface IPaymentGateway.

Example: implementing the payment gateway interface

C#
public class GiftGateway : IPaymentGateway
            {
            #region IPaymentGateway Members
            IDictionary<string, string> _ConfigData;
            public bool ProcessPayment(Payment payment, ref string message)
            {
            OtherPayment p = (OtherPayment)payment;
            if (!String.IsNullOrEmpty(p.ValidationCode))
            {
            GiftManager.DeactivateGiftCard(Settings["GiftCardMetaClass"]
            , PrimaryKeyId.Parse(p.ValidationCode));
            p.Status = "Processed";
            }
            return true;
            }
            /// <summary>
            /// Returns the configuration data associated with a gateway.
            /// Sets the configuration gateway data. This data typically includes
            /// information like gateway URL, account info and so on.
            /// </summary>
            /// <value>The settings.</value>
            /// <returns></returns>
            public virtual IDictionary<string, string> Settings
            {
            get
            {
            return _ConfigData;
            }
            set
            {
            _ConfigData = value;
            }
            }
            #endregion
            }

Note that error messages occurring at this step can be ignored.

8. Create a new class GiftManager.cs (public static class GiftManager), see the code comments below.

Example: creating the GiftManager

C#
public static class GiftManager
            {
            public const string ContactIdFieldName = "ContactId";
            public const string AmountFieldName = "Amount";
            public const string BalanceFieldName = "Balance";
            public const string ContactFieldName = "Contact";
            public const string IsActiveFieldName = "IsActive"
            public const string RedemptionCodeFieldName = "RedemptionCode";
            public const string TitleFieldName = "Title";
            public static EntityObject[] GetClientGiftCards(string giftCardMetaClass, PrimaryKeyId contactId)
            {
            return BusinessManager.List(giftCardMetaClass,
            new FilterElement[]
            {
            FilterElement.EqualElement(ContactIdFieldName, contactId),
            FilterElement.EqualElement(IsActiveFieldName, true)
            });
            }
            public static void DeactivateGiftCard(string giftCardMetaClass, PrimaryKeyId giftCardId)
            {
            // Load Gift Card
            EntityObject giftCard = BusinessManager.Load(giftCardMetaClass, giftCardId);
            // Update field
            giftCard[IsActiveFieldName] = false;
            // Save Changes
            BusinessManager.Update(giftCard);
            }
            }

9. Build the project.

Creating user controls

In these steps we will create the user controls needed for the gift card payment provider.

ConfigurePayment

Firstly, create a user control called ConfigurePayment.ascx. This user control will need to inherit from System.Web.UI.UserControl, IGatewayControl. See code comments in the examples below.

Example: creating the ConfigurePayment user control (part 1)

C#
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ConfigurePayment.ascx.cs"
             Inherits="GiftCardPaymentProvider.ConfigurePayment" %>
            <div id="DataForm">
            <table cellpadding="0" cellspacing="2">
            <tr>
            <td class="FormLabelCell" colspan="2"><b>Configure Gift Card</b></td>
            </tr>
            </table>
            <br />
            <table class="DataForm">
            <tr>
            <td class="FormLabelCell"><asp:Literal ID="Literal4" runat="server" Text="MetaClass name" />:</td>
            <td class="FormFieldCell"><asp:TextBox Runat="server" ID="MetaClassName"
             Width="230"></asp:TextBox><br>
            <asp:RequiredFieldValidator ControlToValidate="MetaClassName" Display="dynamic"
             Font-Name="verdana" Font-Size="9pt" ErrorMessage="'MetaClass name' must not be left blank."
            runat="server" id="RequiredFieldValidator2"></asp:RequiredFieldValidator>
            </td>
            </tr>
            </table>
            </div>

Example: creating the ConfigurePayment user control (part 2)

C#
public partial class ConfigurePayment : System.Web.UI.UserControl, IGatewayControl
            {
            string _ValidationGroup = String.Empty;
            private PaymentMethodDto _PaymentMethodDto = null;
            private const string _MetaClassParameterName = "GiftCardMetaClass";
            /// <summary>
            /// Handles the Load event of the Page control.
            /// </summary>
            /// <param name="sender">The source of the event.</param>
            /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
            protected void Page_Load(object sender, System.EventArgs e)
            {
            BindData();
            }
            /// <summary>
            /// Binds a data source to the invoked server control and all its child controls.
            /// </summary>
            public override void DataBind()
            {
            //BindData();
            base.DataBind();
            }
            /// <summary>
            /// Binds the data.
            /// </summary>
            public void BindData()
            {
            // fill in the form fields
            if (_PaymentMethodDto != null && _PaymentMethodDto.PaymentMethodParameter != null)
            {
            PaymentMethodDto.PaymentMethodParameterRow param = null;
            param = GetParameterByName(_MetaClassParameterName);
            if (param != null)
            MetaClassName.Text = param.Value;
            }
            else
            this.Visible = false;
            }
            #region IGatewayControl Members
            /// <summary>
            /// Saves the object changes.
            /// </summary>
            /// <param name="dto">The dto.</param>
            public void SaveChanges(object dto)
            {
            if (this.Visible)
            {
            _PaymentMethodDto = dto as PaymentMethodDto;
            if (_PaymentMethodDto != null && _PaymentMethodDto.PaymentMethodParameter != null)
            {
            Guid paymentMethodId = Guid.Empty;
            if (_PaymentMethodDto.PaymentMethod.Count > 0)
            paymentMethodId = _PaymentMethodDto.PaymentMethod[0].PaymentMethodId;
            PaymentMethodDto.PaymentMethodParameterRow param = null
            param = GetParameterByName(_MetaClassParameterName);
            if (param != null)
            param.Value = MetaClassName.Text;
            else
            CreateParameter(_PaymentMethodDto, _MetaClassParameterName, MetaClassName.Text, paymentMethodId);
            }
            }
            }
            /// <summary>
            /// Gets the name of the parameter by.
            /// </summary>
            /// <param name="name">The name.</param>
            /// <returns></returns>
            private PaymentMethodDto.PaymentMethodParameterRow GetParameterByName(string name)
            {
            PaymentMethodDto.PaymentMethodParameterRow[] rows = 
            (PaymentMethodDto.PaymentMethodParameterRow[])
            _PaymentMethodDto.PaymentMethodParameter.Select(String.Format("Parameter = '{0}'", name));
            if (rows != null && rows.Length > 0)
            return rows[0];
            else
            return null;
            }
            /// <summary>
            /// Creates the parameter.
            /// </summary>
            /// <param name="dto">The dto.</param>
            /// <param name="name">The name.</param>
            /// <param name="value">The value.</param>
            /// <param name="paymentMethodId">The payment method id.</param>
            private void CreateParameter(PaymentMethodDto dto, 
            string name, string value, Guid paymentMethodId)
            {
            PaymentMethodDto.PaymentMethodParameterRow newRow = 
            dto.PaymentMethodParameter.NewPaymentMethodParameterRow();
            newRow.PaymentMethodId = paymentMethodId;
            newRow.Parameter = name;
            newRow.Value = value;
            // add the row to the dto
            if (newRow.RowState == DataRowState.Detached)
            dto.PaymentMethodParameter.Rows.Add(newRow);
            }
            /// <summary>
            /// Loads the object.
            /// </summary>
            /// <param name="dto">The dto.</param>
            public void LoadObject(object dto)
            {
            _PaymentMethodDto = dto as PaymentMethodDto;
            }
            /// <summary>
            /// Gets or sets the validation group.
            /// </summary>
            /// <value>The validation group.</value>
            public string ValidationGroup
            {
            get
            {
            return _ValidationGroup;
            }
            set
            {
            _ValidationGroup = value;
            }
            }
            #endregion
            }

PaymentMethod

Create another user control. In this user control we will render a radio button for the Gift Card payment option. Call this user control PaymentMethod.ascx.

1. Add a reference to the assembly Mediachase.Commerce.Website.dll (IPaymentOption) in the project.

2. Inherit BaseStoreUserControl, IPaymentOption.

3. Add the following using directives:

C#
using Mediachase.BusinessFoundation.Data;
    using Mediachase.BusinessFoundation.Data.Business;
    using Mediachase.Commerce.Website.BaseControls;
    using Mediachase.Commerce.Website;
    using Mediachase.Commerce.Security;
    using Mediachase.Commerce.Orders.Dto;
    using Mediachase.Commerce.Orders.Managers;
    using Mediachase.Commerce.Orders;
    using System.Threading;

4. Add an ASP.NET RadioButton with ID="rbList"

Example: adding a radio button

C#
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PaymentMethod.ascx.cs"
             Inherits="GiftCardPaymentProvider.PaymentMethod" %>
            <asp:RadioButtonList runat="server" ID="rbList">
            </asp:RadioButtonList>
            <br />
            <asp:Label ID="Label1" runat="server" Text="RedemptionCode: "></asp:Label>
            <asp:TextBox ID="TextBox1" runat="server" BackColor="White"
            BorderStyle="Dashed"></asp:TextBox>

Example: adding a payment method

C#
public partial class PaymentMethod : BaseStoreUserControl, IPaymentOption
            {
            private void Page_Load(object sender, System.EventArgs e)
            {
            EntityObject[] objs = GiftManager.GetClientGiftCards(GetGiftCardMetaClassName()
            , (PrimaryKeyId)SecurityContext.Current.CurrentUserId);
            foreach (EntityObject obj in objs)
            {
            rbList.Items.Add(new ListItem((string)obj[GiftManager.TitleFieldName],
            obj.PrimaryKeyId.ToString()));
            }
            }
            private string GetGiftCardMetaClassName()
            {
            string GiftCardMetaClass = "GiftCard";
            PaymentMethodDto method = PaymentManager.GetPaymentMethodBySystemName
            ("GiftCard", Thread.CurrentThread.CurrentCulture.Name);
            PaymentMethodDto.PaymentMethodParameterRow[] rows =
            (PaymentMethodDto.PaymentMethodParameterRow[])
            method.PaymentMethodParameter.Select("Parameter = 'GiftCardMetaClass'");
            if (rows.Length > 0)
            {
            GiftCardMetaClass = rows[0].Value;
            }
            return GiftCardMetaClass;
            }
            #region IPaymentOption Members
            public bool ValidateData()
            {
            this.Page.Validate(this.ID);
            return this.Page.IsValid;
            }
            public Payment PreProcess(OrderForm form)
            {
            OtherPayment otherPayment = new OtherPayment();
            otherPayment.BillingAddressId = form.BillingAddressId;
            otherPayment.ValidationCode = rbList.SelectedValue;
            return (Payment)otherPayment;
            }
            public bool PostProcess(OrderForm form)
            {
            return true;
            }
            #endregion
            }

Deployment

In these steps we will deploy the GiftCardPaymentProvider assembly to the Commerce Manager and the EPiServer Commerce sites. We also deploy the user controls into specific folders.

  1. Deploy your files by copying the GiftCardPaymentProvider to the sample project website and Commerce Manager website.
  2. The configured system keyword of the payment provide will be GiftCard, and therefore folders with that name must be created in the Payment\Plugins folder of respectively Commerce Manage and the front end website.
  3. Create a folder in the payment plugin folder of Commerce Manager, with the name GiftCard and put the ConfigurePayment.ascx there. The path would resolve to the following: [~CommerceManagerSite]\Apps\Order\Payments\Plugins\GiftCard\
  4. Create a folder in sample site payment plugin folder with the name GiftCard and put the PaymentMethod.ascx there. That path would result in the following: [~Commerce SampleSite]\Templates\Sample\Units\CartCheckout\GiftCard\

Adding the gift card in Commerce Manager

Adding a business object

1. Go to Commerce Manager and Administration, navigate to the Business Foundation option, select Create New and then New Business Object.

2. Name the new object Gift Card, notice the Plural name. Leave the field info section entries to their defaults.

Gift card payment provider configuration

3. Add a new field to the Gift Card object called Amount. Note that the data type is Currency.

Gift card payment provider configuration

4. Add a new field to the Gift Card object called Balance, data type Currency.

Gift card payment provider configuration

5. Add a new field to the Gift Card object called IsActive, data type Boolean.

Gift card payment provider configuration

6. Add a new field to the Gift Card object called RedemptionCode.

Gift card payment provider configuration

7. Your Gift Card object should now look like this:

Gift card payment provider configuration

Making the gift card available

To make the gift card available to customers and to create easy management from back-end, we will use the Relationship feature another feature of Business Foundation. In order to track and record relevant data, business objects must be related to other objects, whether they are "1 to many," "many to 1","many to many."

Note that the Related Object will have the Primary Object appear under the opposite relationship (N:1) on its configuration form.

1. From the main Business Foundation menu, select the Contact object, click the tab for 1:N Relations, and then click the New Relation link in the right area of the screen.

2. Fill in the information.

Gift card payment provider configuration

3. Click the dropdown Related Object and select Gift Card. Also; Display Region should be set to Information.

4. Save your settings.

5. Click Back To List and select the Gift Card object, the N:1 tab should look like this.

Gift card payment provider configuration

Creating a payment method

In these steps we will create a new payment method by using the Gift Card object.

1. In Commerce Manager/Administration, navigate to the folder for the language of choice, for instance English (United States).

Gift card payment provider configuration

2. Click New and enter information as follows: (remember to switch to Markets tab, then select markets that this payment should be available on)

Gift card payment provider configuration

3. When done click OK.

4. Open up the new Payment Method again and go to the Parameters tab to enter GiftCard.

Gift card payment provider configuration

5. Click OK to finalize.

6. Navigate to the customer management section and select Contacts, open up the contact admin and give admin an instance of the newly created Gift Card. The Gift Card is found under the Information section, as we choose that during the setup of the relation between Contact and Gift Card objects.

7. Click Add Items and then New. Enter values as the image below

Gift card payment provider configuration

Verifying the result

Browse to the EPiServer Commerce site and login as admin. Purchase an item and when you reach the Payment Page in the Checkout wizard select the Gift Card payment and also select the child instance radio button.


Do you have feedback on this documentation? Send an email to documentation@episerver.com. For development-related questions and discussions, refer to our Forums on https://world.episerver.com/forum/