# Wednesday, 10 April 2013

imageIn some cases though you might need to leverage the API outside a web context for automated integration between systems, for custom web services, or integration of uCommerce functionality directly in other custom applications such as point of sale- or kiosk apps.

This article outlines the steps required to get the API going for uCommerce 3.

Running uCommerce 2? Please refer to Enable the uCommerce E-commerce API Outside the Web Context instead.

Create New Console Application Project

Open Visual Studio and create a new console application project in the usual way. We’ll use that as a basis for getting the APIs up and running.

My usual project structure has a folder for the project source and any libraries required to build it like below.

image

Copy uCommerce Assemblies to Project

You’ll find the assemblies in your website under /bin.

Copy the following assemblies to /lib in your project.

  • Castle.Core
  • Castle.Windsor
  • FluentNHibernate
  • Iesi.Collections
  • log4net
  • NHibernate.ByteCode.Castle
  • NHibernate.Caches.SysCache2
  • UCommerce
  • UCommerce.Infrastructure
  • UCommerce.Pipelines
  • UCommerce.Transactions.Payments
  • UCommerce.Presentation
  • UCommerce.Umbraco
  • interface
  • umbraco
  • businesslogic
  • ClientDependency.Core
  • Umbraco.Core


image

Copy the Configuration and Pipelines Folders to the Project

You’ll want the core configuration and the pipelines as part of your project to be able to use the API fully.

Copy these folders to the project folder of your solution.

image

To project:

image

Include Configuration and Pipelines in Project

image

Set Configuration and Pipelines Folders to Copy to Output Folder

For uCommerce to able to pick up the configuration they need to be copied to the output folder of the compiled application.

Select all the config files and press F4 to bring up the properties for the files.

Set “Copy to Output Directory” to “Copy if newer”.

image

Reference the Assemblies in Your Project

Next reference the assemblies you copied to the /lib folder in Visual Studio.

image

Modify App.Config

Next up we need to modify the application config with settings to enable the final bits of uCommerce to run.

Open up web.config of your Umbraco site and locate the configSections element. Copy the sectionGroups called “commerce” and “systemcache” to the coonfigSections element of App.config.

<sectionGroup name="commerce" 
type="System.Configuration.ConfigurationSectionGroup">
<section name="syscache" 
type="NHibernate.Caches.SysCache.SysCacheSectionHandler, 
NHibernate.Caches.SysCache2" requirePermission="false" />

Finally we need the actual sections from web.config copied to app.config.

<commerce>
<syscache>

 

With all that in place your App.config file should look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
   <sectionGroup name="commerce" type="System.Configuration.ConfigurationSectionGroup">
       <section name="catalogConfiguration" type="UCommerce.Infrastructure.Configuration.CatalogConfigurationSection, UCommerce.Infrastructure" />
       <section name="runtimeConfiguration" type="UCommerce.Infrastructure.Configuration.RuntimeConfigurationSection, UCommerce.Infrastructure" />
       <section name="securityConfiguration" type="UCommerce.Infrastructure.Configuration.SecurityConfigurationSection, UCommerce.Infrastructure" />
       <section name="amazonPaymentMethodService" type="UCommerce.Transactions.Payments.Amazon.Configuration.AmazonPaymentMethodServiceConfigurationSection, UCommerce.Transactions.Payments" requirePermission="false" />
       ...
      </sectionGroup>
    <section name="syscache" type="NHibernate.Caches.SysCache.SysCacheSectionHandler, NHibernate.Caches.SysCache2" requirePermission="false" />
  </configSections>
 
  <commerce>
    <runtimeConfiguration enableCache="false" cacheProvider="NHibernate.Caches.SysCache2.SysCacheProvider, NHibernate.Caches.SysCache2" connectionString="(auto)" />
    <catalogConfiguration defaultCultureCode="en-US" enforceCategoryNameUniquenessWithinCatalogs="true" />
    <securityConfiguration enable="true" />
    <amazonPaymentMethodService configSource="umbraco\ucommerce\configuration\payments\Amazon.config" />
    ...
  </commerce>
 
  <syscache>
    <!-- Cache catalog objects for 60 mins before refreshing -->
    <cache region="CatalogFoundation" expiration="3600" priority="5" />
    <cache region="MarketingFoundation" expiration="3600" priority="5" />
    <cache region="SecurityFoundation" expiration="3600" priority="5" />
  </syscache> 
</configuration>

Modify Connection String

Finally you need to point the connection string at your database. Simply replace the (auto) values with an actual connection string and you’re good to go.

<runtimeConfiguration ... connectionString="server=(local);database=Umbraco;user id=umbraco;password=1234567890" />

Summary

Leveraging uCommerce outside a web site makes for some interesting use cases. Foremost is automated integration with other systems, but you could use this method to establish an offline Point of Sale or Kiosk-type system with a completely different frontend done in Windows Presentation Foundation for a rich in store experience.

posted on Wednesday, 10 April 2013 16:36:31 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Wednesday, 17 October 2012

At uCommerce we’re fortunate in many ways: We get to build products that customers actually use and love and most importantly we get to work with some pretty amazing people.

What we didn’t see coming is the amount of excitement and involvement in uCommerce from our partners and customers. From helping out in the support forums, building extensions, providing key insights and feedback for uCommerce, blogging about uCommerce, to creating full open source projects around uCommerce.

The involvement is truly amazing to see and we want to recognize the people who go above and beyond and thus 2013 is the year for a grand new tradition: uCommerce MVPs (uCommerce Most Valuable Professionals).

How To Become An MVP

uCommerce MVPs are a small, select group of the professionals in the uCommerce community, outliers with the ability to highlight solutions and helping out in the community making the community a better place for everybody.

We select MVPs from the community in a very unscientific way each year in October based on their contributions. Once selected the MVP title is good for the coming year and will be reviewed each year.

MVPs are honored with the “king” Hoptimist to proudly display in their desks :)

Hoptimist-yellow

Sounds like something for you? Here are some pointers if you’d like be considered for MVP next year:

  • If you do something cool with uCommerce blog about
  • Help out in the uCommerce forum
  • Do a talk for your local user group
  • Host a uCommerce code camp
  • Build a package for Umbraco using uCommerce
  • Share your uCommerce extensions like payment providers, shipping providers, etc.
  • Make some noise about uCommerce :)

And now for the most important part of this post: The uCommerce MVPs for 2013.

Tim Gaunt, The Site Doctor, UK

Avatar-Tim-Drinking-Tea

Tim has been around the uCommerce community from the very beginning. He initially got on board after Codegarden 09 when we introduced uCommerce 1.0 and has since been active in the uCommerce community; blogging, providing valuable feedback for uCommerce itself, and recently with his heavy involvement in the development of Avenue Clothing, the new Razor store. He even came up with the name Avenue Clothing :)

His company The Site Doctor builds amazing uCommerce stores. The work TSD does is second to none.

Christian Wendler, Byte5, DE

Christian Wendler, Byte5

Christian popped up in the community in 2011 with his company byte5 immediately producing high quality stores with uCommerce.

His insights and willingness to help out in the Germany with community activities are remarkable, but his work on the uCommerce Data Types for Umbraco package is really what puts him over the top.

In Summary

uCommerce MVPs are a great asset for the community as a whole. With the 2013 MVPs we’re recognizing the first uCommerce MVPs ever who have gone above and beyond in making the uCommerce community a better place.

We’re proud and honored to work with these people!

posted on Wednesday, 17 October 2012 08:27:11 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Sunday, 13 May 2012

tomboy-128uCommerce is designed to run in one of two scenarios: Standalone or integrated. When running in an integrated scenario you’ll typically need to import information from other systems like SKUs, preexisting accounts, etc..

If you need to import large amounts of data from external systems you’ll want to the stateless API uCommerce provides for just this type of scenario.

You can skip the background portion if you’re just looking for the quickest way to import data into uCommerce. If not read on and get the inside scoop on uCommerce data access.

Background

uCommerce uses NHibernate for data access a handy way of querying the underlying database and converting the relational data into the e-commerce objects you know and love.

To provide a more convenient way of working with the data access APIs NHibernate will build up a large map of every object ever loaded into memory, which is awesome for caching scenarios and for figuring out which objects require updates and in which order when a write command is issued to the data access engine, but not so much for bulk imports.

As it turns out this is not really what you want for bulk scenarios as the object map tends to slow down writes quite a bit after only a few database operations. This slows bulk import scenarios quite noticeably; even a few hundred write commands.

Luckily you have at your disposal an API optimized for bulk import scenarios called the stateless API.

The Stateless API

The stateless API is named so because it doesn’t maintain the memory map of objects, which is exactly what we want for bulk imports because generally we’re just inserting and updating each object once. We don’t really need L1 or L2 caching, nor identify map tracking and that good stuff.

Using the stateless API offers awesome performance for writes compared to the default one, but it does come with a couple of drawbacks as well, which means there are a couple of areas you’ll have to handle yourself:

  • Lazy loading child collections is disabled
  • ModifiedBy, ModifiedOn, CreatedBy, and CreatedOn properties are not automatically updated
  • Cascades for saves and deletes are disabled
  • Auto soft delete is disabled – everything is deleted permanently
  • Save is disabled and replaced by manual Insert/Updates operations

Fear not the rest of the article describes how to accomplish these operations in a straightforward manner.

First things first: To use the stateless API you need an implementation of ISessionProvider, which is obtained with the following code:

ISessionProvider sessionProvider = ObjectFactory.Instance.Resolve<ISessionProvider>();
IStatelessSession statelessSession = (sessionProvider as SessionProvider).GetStatelessSession();

With the session you’re ready to start issuing commands to the data access layer in a stateless fashion.

Eager Loading Child Collections

By default uCommerce will automatically load any child collections you access, which is very convenient when you want something up and running rapidly. This capability  however is not available when working with the stateless API, so you’ll have to initialize any collection you need manually.

QUICK TIP: This is actually the way to get the best level of performance from your queries too.

Here’s how you eager load order lines for a purchase order.

var purchaseOrder = statelessSession
    // The Query method is an extension method found in the NHibernate.Linq namespace
    .Query<PurchaseOrder>()
    // The fetch method receives a lambda which tells if which child collection to initialize
    .Fetch(x => x.OrderLines)
    // You can use ThenFetch to initialize subsequent child collections on the same parent
    .ThenFetch(x => x.OrderAddress)
    // Loads the first parent
    .SingleOrDefault(x => x.OrderNumber == "WEB-001");

The code above will issue one query batch to the database instead of opening and closing a connection for each round trip as is the case for lazy initialization, so much more efficient all around.

Updating ModifiedOn, ModifiedBy, CreatedBy, CreatedOn Properties

These properties are required by objects implementing the IAuditCreatedEntity and IAuditModifiedEntity. You just need to make sure that they are set for any objects you insert.

Handling Delete Cascades

When you delete an object which has relationships with other objects using the default API uCommerce will handle removing or updating the related objects, e.g. PurchaseOrder.Delete() also deletes associated order lines, customer, addresses, etc..

With the stateless API, however, you have to delete the objects yourself in the correct order to avoid foreign key constraint errors in the database. It works exactly as if you’re deleting directly from the database using T-SQL.

This means that for our order from before you’ll have to delete the order lines and customer before deleting the parant order, which both the order lines and the customer a link to in the underlying data structure.

using (var transaction = statelessSession.BeginTransaction())
{
    var purchaseOrder = statelessSession.Query<PurchaseOrder>()
        .Fetch(x => x.OrderLines)
        .ThenFetch(x => x.OrderAddresses)
        .ThenFetch(x => x.Customer)
        .ThenFetch(x => x.Payments)
        .ThenFetch(x => x.Shipments)
        .SingleOrDefault(x => x.OrderNumber == "WEB-001");
    
    // Issue a delete for each shipment
    // The ForEach method is just for convenience
    purchaseOrder.Shipments.ForEach(x => statelessSession.Delete(x));
    
    // Issue a delete for all child objects of order until they're all deleted
    
    // Finally delete the order itself
    statelessSession.Delete(purchaseOrder);
 
    transaction.Commit();
    
}

Handling Saves

With the default API uCommerce will figure out whether to insert or update an object when you issue a save. This is not the case with the stateless API so you’ll have to issue an insert or update depending on whether you’re updating an existing object or adding a completely new one.

using (var transaction = statelessSession.BeginTransaction())
{
    // Update an existing order
    var purchaseOrder = statelessSession.Query<PurchaseOrder>()
        .SingleOrDefault(x => x.OrderNumber == "WEB-001");
 
    purchaseOrder.ModifiedBy = "Søren";
    purchaseOrder.ModifiedOn = DateTime.Now;
 
    // Save to the database
    // Notice the explicit use of Update for
    // the existing object
    statelessSession.Update(purchaseOrder);
 
    // Create a new order
    var newOrder = new PurchaseOrder();
    newOrder.CreatedOn = newOrder.ModifiedOn = DateTime.Now;
    newOrder.CreatedBy = newOrder.ModifiedBy = "Søren";
    newOrder.BillingCurrency = statelessSession.Query<Currency>()
        .Single(x => x.ISOCode == "EUR");
    
    // Save to the database
    // Notice the use of Insert for the new object
    statelessSession.Insert(newOrder);
 
    transaction.Commit();
}

Handling Soft Deletes

Some entities are marked with the ISoftDeletable interface, which indicates that they never really disappear from the database. The stateless API will permanently delete data from the database. If you want to preserve soft delete behavior you just have to set the “Deleted” property to “true” on objects which have it and issue a save like above.

In Summary

While there are some aspects you have to manually handle when using the stateless uCommerce API for bulk updates it’s still a convenient way to stay in the object oriented world while keeping decent write performance.

Of course all the uCommerce information is stored in standard SQL tables so you can just as well use a tool like SQL Server Integration Services, which bypass the API completely and go straight to the database. This is by far the fastest way to import, but bear in mind that integrations done directly against the database might break when you upgrade to newer versions of uCommerce.

posted on Sunday, 13 May 2012 23:03:55 (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Wednesday, 21 March 2012

In many cases we come across companies who operate a separate discounting system from their e-commerce platform. In these cases it’s convenient to be able to import external campaigns into uCommerce via code.

This article outlines how you can create campaigns, campaign items, and associated advertising and discounts from code.

If you’re unfamiliar with uCommerce Marketing Foundation you can watch a quick video tour on uCommerce.tv.

Also before you continue you might want to take a look at Marketing Foundation Explained: Targeted Advertisements and Discounts, which explains the terminology of uCommerce Marketing Foundation and Extending Marketing Foundation- Adding A New Advertise and Act Target, which deals with added new targets and awards to Marketing Foundation.

A Bit Of Background

A discount in uCommerce requires a couple of moving parts to get going:

  1. A campaign to group marketing activities aka campaign items
  2. A campaign item to aggregate targets and awards
  3. One or more targets to determine when the campaign item is displayed to the customer, e.g. Customer is looking at the Clothing category
  4. One or more targets to determine when an award is triggered, e.g. Buy for more than 400€
  5. One or more awards, e.g. 10% off unit price

Let’s dive into each of the points individually.

Adding a Campaign

All of the classes below are available from the UCommerce.EntitiesV2 namespace found in the UCommerce.dll.

// Create a campaign to group campaign items
var campaign = new Campaign
                {
                    Name = "My Awesome Custom Campaing",
                    StartsOn = DateTime.Now,
                    EndsOn = DateTime.Now.AddDays(30),
                    Enabled = true
                };
 
campaign.Save();

Adding a Campaign Item

Campaign items require a definition, which determines which fields are available as part of it. We’re using the default campaign item definition in this case, but you can add your own with the fields and multilingual fields matching your requirements. You can learn more about definitions in Catalog Foundation Explained: Product Definitions.

Also worth noting is the “AllowNextCampaignItems” property, which is a way to tell uCommerce to stop evaluating campaign items if the current one is awarded to the customer. This is handy if you wish to limit the number of discounts awarded to the customer. Marketing Foundation Explained: Targeted Advertisements and Discounts describes this in more detail.

// Find a definition for the item to determine which fields are available
var definition = Definition.SingleOrDefault(x => x.Name == "Default Campaign Item");
 
// Create the campaign item to tie targets and awards to
var campaignItem = new CampaignItem
                {
                    Name = "Summer offers",
                    Enabled = true,
                    Definition = campaignItemDefinition,
                    AllowNextCampaignItems = true
                };
 
// Add campaign item to our campaign
campaign.AddCampaignItem(campaignItem);
campaign.Save();

Adding a Target for Advertise and Act

There a many different types of targets you can use. In this case it’s a product target, but you could go with “ProductCatalogGroupTarget” to target a specific store, “ProductCatalogTarget” to target a specific catalog, “CategoryTarget” to targat a specific category, “VoucherTarget” to require a specific voucher- or promo code, “OrderAmountTarget” to target a specific order total, etc. You get the idea :)

It’s important to note that if a target you need is not built-in you can extend uCommerce with your own targets as described in Extending Marketing Foundation- Adding A New Advertise and Act Target.

“EnabledForDisplay” and “EnabledForApply” determines whether the target is used for advertising, act, or both.

// add a product target
var productTarget = new ProductTarget
                {
                    CampaignItem = campaignItem,
                    Sku = "100-000-001",
                    VariantSku = "001", // this guy is optional
                    EnabledForApply = true, // use it for Act
                    EnabledForDisplay = true // use it for Advertise
                };
 
productTarget.Save();

Adding an Award

Here we’re using a discounted unit price award, but again there a many different types of awards you can add like AmountOffOrderTotalAward, AmountOffOrderLinesAward and so on. Remember if the award you’re looking for is not there you can extend uCommerce with your own types.

// Add a unit price discount award
var amountOffUnitPrice = new AmountOffUnitAward
                {
                    CampaingItem = campaignItem,
                    AmountOff = 10
                };
 
amountOffUnitPrice.Save();

Summary

One of the best features of uCommerce is that everything you can do from the UIs you can do from code. This enables developers to do some awesome automated things with uCommerce and it doesn’t take a whole lot of code to do either.

In the article we discussed how to create new campaigns, add marketing activities to them in the form of campaign items, and configure those campaign items with targets and awards to set up actual customer discounts.

posted on Wednesday, 21 March 2012 10:47:56 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Thursday, 15 March 2012

imageA great tool for converting a customer is to display items they’ve previously looked at. One way to do it is by using persistent baskets, i.e. the basket contents remain the same even if a customer leaves and later returns to the store.

But what about the cases where the customer didn’t actually put anything in the basket, but we still want to be able to show some of the items she browsed recently?

Approaches

The most obvious approach is to store SKUs in a cookie and present that list to the customer, but it makes for some pretty trivial use cases down the road, so let’s explore a different way of doing it: A custom basket.

uCommerce comes with the ability to handle as many baskets per customer as you like so why not leverage this to create almost a wish list-like scenario. After all the recently browsed list is just a list of products that sure sounds like a basket?

Creating a New Basket

First up we need to create a new basket. By default uCommerce will do one default basket where every item goes into, but we’ll need a second basket, which we can maintain ourselves.

Let’s do a little Razor, which will create that custom basket and tie it to the customer using a cookie:

   1: @using UCommerce.Runtime;
   2: @using UCommerce.EntitiesV2;
   3: @using System.Web;
   4:  
   5: @{
   6:   ProductCatalogGroup catalogGroup = SiteContext.Current.CatalogContext.CurrentCatalogSet;
   7:   ProductCatalog catalog = ProductCatalog.All().Single(x => x.Name == SiteContext.Current.CatalogContext.CurrentCatalogName && x.ProductCatalogGroup == catalogGroup);
   8:   
   9:   Guid basketId = Request.Cookies["viewedProductsList"] != null ? new Guid(Request.Cookies["viewedProductsList"].Value) : Guid.Empty;
  10:  
  11:   PurchaseOrder viewedProductsList = basketId != Guid.Empty 
  12:                                         ? PurchaseOrder.All().SingleOrDefault(x => basketId != Guid.Empty && x.BasketId == basketId)
  13:                                         : new PurchaseOrder();
  14:  
  15:   // Initialize new order
  16:   if (basketId == Guid.Empty)
  17:   {
  18:     viewedProductsList.OrderStatus = OrderStatus.Get((int)PurchaseOrder.StatusCode.Basket);
  19:     viewedProductsList.ProductCatalogGroup = catalogGroup;
  20:     viewedProductsList.BillingCurrency = catalog.PriceGroup.Currency;
  21:     viewedProductsList.BasketId = Guid.NewGuid();
  22:     viewedProductsList.CreatedDate = DateTime.Now;
  23:  
  24:     HttpCookie cookie = new HttpCookie("viewedProductsList", viewedProductsList.BasketId.ToString());
  25:     cookie.Expires = DateTime.Now.AddDays(30);
  26:     Response.Cookies.Add(cookie);
  27:   }
  28: }

Adding a Product To The List

Once we have the custom basket set up we’ll just start adding items to it in the usual manner from the product page or whenever you deem that the customer showed enough interested to have a product on the recently browsed list.

   1: // Add product being displayed
   2: Product product = Product.All().Single(x => x.Sku == "100-000-001" && x.VariantSku == "003");
   3:  
   4: viewedProductsList.AddProduct(catalog, product, 1);
   5:  
   6: viewedProductsList.Save();

Displaying The Recently Browsed Items List

The third and final piece is to display the list. The code will basically have to look up the cookie tying the list to the customer, load the basket with contents, and display individual order lines to the customer. Simple stuff and here’s how to do it:

   1: @using UCommerce.EntitiesV2;
   2: @using System.Web;
   3:  
   4: @{
   5:   // Find the cookie containing the basketId
   6:   Guid basketId = Request.Cookies["viewedProductsList"] == null 
   7:                     ? Guid.Empty
   8:                     : new Guid(HttpContext.Current.Request.Cookies["viewedProductsList"].Value);
   9:  
  10:   // Load the list
  11:   PurchaseOrder viewedProductsList = basketId != Guid.Empty 
  12:                                 ? PurchaseOrder.SingleOrDefault(x => x.BasketId == basketId) 
  13:                                 : new PurchaseOrder();
  14: }
  15:  
  16: @foreach (var orderLine in viewedProductsList.OrderLines.OrderBy(x => x.Quantity))
  17: {
  18:     <h3>@orderLine.ProductName</h3>
  19:     <p>Bought @orderLine.Quantity times.</p>
  20: }

In Summary

We took a look at what it takes to maintain a separate custom basket for handling a recently browsed items type list. Using a custom basket instead of storing SKUs in a cookie has the added advantage of the extra information available when displaying the list to a customer.

Best of all it takes a trivial amount of code to get it up and running.

The code above sorts the list by quantity; the premise being that the product will have its quantity increased every time the customer looks at it thus we have a handy mechanism for determining the most popular items on the list. You can expand this to look at last modified dates on order lines to see when the customer was last interested in the product and so forth.

Finally the technique outline here is handy for scenarios like gift registries, wish lists, standard recurring orders, and other cases which require a custom list of products maintained either by the customer herself or by the store.

posted on Thursday, 15 March 2012 00:06:46 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, 13 February 2012

uCommerce comes with built-in support for Ogone payments. This guide will walk you through getting uCommerce to work with Ogone for payment processing.

With the Ogone payment provider you can do authorization of payments, instant acquire, acquire and perform refunds both via our automatic uCommerce solution and manually via the back-end office of your Ogone subscription.

Settings in uCommerce

Add a new payment method, under “uCommerce à Settings à Orders à Payment Methods”, by right clicking the “Payment Methods” leaf and use “Create”. You can use any name you like; I have used “Ogone”.

clip_image001

Now we’re ready to configure your new payment method. Click the newly created node and select “Ogone” in the Service drop down list and select “Checkout” in the pipeline drop down list. Remember to fill out the rest of the required information in the rest of the Tabs.

When you’re done, click the save icon. That’s everything in the uCommerce interface.

clip_image002

Settings in Your Back-end Office at Ogone

First you need to log in with your “pspid” and password.

clip_image004

Click “Technical information” at the menu to the left of the page. At the center screen 7 tabs is displayed. Use the settings as used on the screenshots representing each tab.

1. Global Security Parameters

Set the first hash algorithm to SHA-1 as our system uses this hash algorithm for payment requests and maintenance requests.

Set the character encoding to the first option.

clip_image006

2. Data and origin verification

You need a password in this field. This password is used in the communication between your uCommerce shop and Ogone payment provider for security reasons. This pass phrase is used when the system requests a payment at Ogone.

The password must follow rules given by Ogone. Press the blue information button for information regarding those rules.

clip_image008

3. Transaction feedback

The first four URLs in the “http redirection in the browser” section can be left blank, as we configure this in our configuration file later on.

The next step is to link from the secure payment page to your page which processes the payment.

Please note that “/<PARAMVAR>/PaymentProcessor.axd” is required at the end of your URL.

clip_image010

Next step is to tell Ogone which parameters they need to send back to our site. There’s quite a few available, just select them all. This is a good idea as that information is logged, should any problem occur, problem solving is made a lot easier.

clip_image012

The last part in this section is to put in the SHA-OUT pass phrase. This is the same method as before but for security reasons you should use another phrase this time.

When Ogone makes the callback to our server, this pass phrase is used in a hash algorithm in order to test for corrupt requests.

Now we need to make an “admin without user management” but with access rights to make direct link requests.

Click Users at the back end office menu to the left and click new users in that section.

clip_image014

clip_image015

Fill out the required fields and put your PSPID password in the password field and click create. At the next page you’ll get a password.

Now we need to change the password to something that doesn’t contain special characters (use “a-z” and/or “0-1”.

clip_image017

Under the password section, simply select the user you’ve just created and put in the old password and together with the new you want and click submit.

This is it in the back-end office at your configuration.

Configuring Acquire and Cancel Payments

The Ogone payment provider comes with the ability to do automatic acquire and cancel payments. In order to make this work you need to enable a pipeline task.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

clip_image018

Simply remove “<!-- “ and “-->” at the highlighted line. These are HTML comment sections.

Configuring the “Ogone.config” File

Now we need to edit the ”Ogone.config” file in order to match your environment.

You’ll find the configuration file at “rootdir\umbraco\UCommerce\Configuration\Ogone.config” where rootdir is the location on your computer, where Umbraco is installed.

Some values need to be found in the back-end office. All of those can be found under technical information.

clip_image003

Parameter list for the configuration file:

Parameter name

Value

pspid

The pspId of your Ogone account.

Find it at the bottom of the menu to the left at the back-end office.

Userid

The Userid of the user you’ve just made.

Password

The password for the user you’ve just made.

acceptUrl

The URL the customer is redirected to after an accepted payment.

cancelUrl

The URL the customer is redirected to after a canceled payment.

backUrl

The URL the customer is redirected to if the customer clicks the back button on the payment page.

declineUrl

The URL the customer is redirected to if the payment is declined.

exceptionUrl

The URL the customer is redirected to if a problem occours in the payment process .

All the urls are a local webs in your website such as “yourshop.com/orderconfirmation.aspx”.

Debug

Tells the system weather this is in debug mode. This should be set to false.

shaSignOut

The shaSign used when Ogone redirects to the payment processor.

Under technical information, go to the bottom of the “transaction feedback” tab to find the SHA-OUT pass phrase

shaSignIn

The shaSign used when your uCommerce website requests a payment at Ogone.

Under technical information, go to the “Data and origin verification” tab to find the SHA-IN pass phrase

language

Must follow the right language codes otherwise it’s set to the default value “en_US”.

instantAcquire

Is set to “true” if you want instant acquire.

Is set to “false” if you want to only authorize a payment.

testMode

Tells the system weather this is in test mode. This should be set to false.

Congratulations - your website now includes payments with the Ogone payment provider.

posted on Monday, 13 February 2012 16:47:18 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with buil-in support for MultiSafepay. This guide will walk you through getting uCommerce working with MultiSafepay for payment processing.

Settings in uCommerce

Add a new payment method, under “uCommerce -> Settings -> Orders -> Payment Methods”. You can call it whatever you like, here I have used “MultiSafepay”.

clip_image001

Click the newly created node and select “MultiSafepay” in the Service drop down list. Choose Checkout ast he pipeline. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When you are done click “Save”.

clip_image002

That’s everything in the uCommerce interface.

Settings in MultiSafepay back office.

Create a back office at MultiSafepay with the MultiSafepay Connect.

Create a new website under Setttings -> Sites.

clip_image004

Category

Choose the category your site belongs to

Description

Can be anything, just a name you give your website.

Base URL

The URL for your website

Notification URL

clip_image006

MultiSafepay notifies uCommerce about new payments and changes to existing payments using the notification URL. The URL you receive notifications from MultiSafepay will be in the format https://www.mystore.com/id of your payment method/PaymentProcessor.axd

To find the PaymentMethodId you need to search the database. If you used the name “MultiSafepay” for the payment method name, you can run this SQL query in the SQL Server Management Studio:

select PaymentMethodId from uCommerce_PaymentMethod where Name='MultiSafepay'

A sample URL for a payment method with an ID of 10 would be https://www.mystore.com/10/PaymentProcessor.axd

PrivatePay

An option so MultiSafepay won’t give you information regarding the consumer. Name and address will be excluded.

SecondChance

Should the consumer cancel midway, they will receive an email giving them a second chance to complete the process.

Editing the MultiSafepay.config file

Now we need to edit the MultiSafepay.config file.

You will find the MultiSafepay.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\ MultiSafepay.config”. Usually “rootdir” is c:\inetpub.

image

TestMode

If set to “True” the MultiSafepay test site will be used, not their live site. If not testing, this should be set to “False”.

Account Id

Your account ID from the MultiSafepay back office. (See picture below)

SiteId

The ID provided by MultiSafepay when creating a new site. (See picture below)

SiteSecurityCode

The SiteSecureCode provided by MultiSafepay when creating a new site. (See picture below)

CallbackUrl

Leave setting at (auto) unless you want to handle callbacks yourself.

Accept

The URL you return to when completing a payment.

CancelUrl

The URL you return to when cancelling a payment.

Click Settings è Websites to find the screen below.

clip_image009

MultiSafepay back office

In the MultiSafepay back office you have options to refund and cancel, this cannot be done without using the MultiSafepay back office.

clip_image011

Use the green refund button to start a refund or the red cross to cancel a pending payment.

Please note that any changes to a payment in the back office will cause a notification to be sent to uCommerce. The notification will cause uCommerce to update the status of the order the payment belongs to to “Requires Attention”.

posted on Monday, 13 February 2012 16:43:08 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for iDEAL (ING) payments. This guide will walk you through getting uCommerce to work with iDEAL (ING) for payment processing.

With iDEAL (ING) only authorization with instant acquire is available. To cancel or refund a transaction you will have to use the iDEAL (ING) Dashboard. This is implemented with iDEAL (ING) Basic.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “iDEAL (ING)”.

clip_image002

Click the newly created node and select “iDEAL (ING)” in the Service drop down list. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When you are done click “Save”.

clip_image003

That’s everything in the uCommerce interface.

Settings in iDEAL Dashboard

Changes needed in the iDEAL (ING) Dashboard, so it will work with uCommerce.

Configure Secret Key

On the Menu on the left side, click “Signup process –> Configuration”. Make sure that there is a key in the “Secret key” field and the click “Start upload”. The “Certificate upload successful” should be marked with a green sign upon success.

clip_image005

Configure Return URLs

uCommerce performs validation of the payment information when iDEAL (ING) performs the callback. To get the callback, for verify the payment, you need the set the “Notification” to XML and the “Notification URL” to you shops URL ending with “/PaymentMethodId/PaymentProcessor.axd”.

To find the PaymentMethodId you need to search the database. If you used the name “iDEAL (ING)” for the payment method name, you can run this SQL query in the SQL Server Management Studio:

select PaymentMethodId from uCommerce_PaymentMethod where Name='iDEAL (ING)'

The URL could be then end with: “/10/PaymentProcessor.axd”.

clip_image007

Click “Start Upload” when you are done.

Editing the Ideal_Ing.config File

Now we need to edit the Ideal_Ing.config file.

You will find the Ideal_Ing.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\Ideal_Ing.config”. Usually “rootdir” is c:\inetpub.

clip_image009

Some of the below information are found in the iDEAL (ING) Dashboard, so start by logging in you aren’t already.

Finding secretKey

On the Menu on the left, click “Signup process” –> “Configuration”, here you will find the secretKey. Make sure that the “Certificate upload successful” is marked with a green sign, before you use it.

clip_image011

Finding merchantId

On the Menu on the left, click “Signup process” –> “Application”, here you will find the Merchant ID.

clip_image013

Finding subId

Unless agreed otherwise with the acquirer, you should use “0”(zero).

Finding successUrl, cancelUrl and errorUrl

To get the customer redirected back to your page after the payment is completed, you have to specify a return URL depending on payments result: Success, Error and Cancel.

Finding debug

If set to “True” you will be prompted to click a button before posting the information to “iDEAL” otherwise it will do an autosubmit using Javascript. When running in production, you will want this set to “false”.

Finding testMode

Test mode will toggle the payment method service to use a test environment where applicable. Usually this implies working against another URL.

Valid values “true” or “false”.

Finding language

Set preferred language, currently only “Dutch”(nl) is supported by remote gateway.

Excecuting a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, open Umbraco click “Commerce” select the payment method (“iDEAL (ING)”). In the pipeline drop down list select Checkout and then click “Save”.

clip_image014

Now the default pipeline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

Configuring Auto Acquire and Cancel Payments

Authorize.Net comes with the ability to do automatic acquire and cancel payments. In order to make this work you need to enable a pipeline task.

To enable auto acquire edit the “ToCompletedOrder” pipeline.

To enable auto void/refund edit the “ToCancelled” pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

clip_image015

Simply remove “<!-- “ and “-->” at the highlighted line. These are HTML comment sections.

FAQ

  • Test mode – Make sure test mode if turned off when going live.
  • You can simulate different payment statuses by using special amount on your payment. Please note that success payments can only be made with a payment total of 1 EUR.

Transactions made with any other amount than the ones below will result in an error:

    • Successful transaction: 1 EUR in test mode
    • Cancelled transaction: 2 EUR in test mode
    • Expired transaction: 3 EUR in test mode
    • Open transaction: 4 EUR in test mode
    • Format error: 7 EUR in test mode.
posted on Monday, 13 February 2012 16:37:11 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for Google Checkout payments. This guide will walk you through getting uCommerce to work with Google checkout for payment processing.

With the Google Checkout you can do authorization of payments, acquire payments, refund and cancellation of payments both via uCommerce and the back end office of your Google checkout subscription.

Settings in uCommerce

Add a new payment method, under “uCommerce à Settings à Orders à Payment Methods”, by right clicking the “Payment Methods” leaf and use “Create”. You can use any name you like; I have used “Google Checkout”.

clip_image001

Now we’re ready to configure your new payment method. Click the newly created node and select “Google Checkout” in the Service drop down list and select “Checkout” in the pipeline drop down list. Remember to fill out the rest of the required information in the rest of the Tabs.

When you’re done, click the save icon. That’s everything in the uCommerce interface.

clip_image002

Settings in Your Google Checkout Back-end Office

First you need to log in to your back end office at: https://sandbox.google.com/checkout/sell/settings?upgrade%3Dtrue&hl=da&nui=1&ltmpl=seller

Now click integration in the left panel. You should get to a page looking like this:

clip_image004


API Callback URL

In the API callback URL: you need to put “http://yoursite.com/10/PaymentProcessor.axd”.

You’ll need to replace “10” in the URL with another number that we’re going to find now.

Open “Microsoft SQL Server Manangement Studio” and log in to the database for your site.

Open a new query document by clicking the “New Query” button.

clip_image006

Write this line:

SELECT PaymentMethodId FROM uCommerce_Paymentmethod where name = 'Google Checkout'

and then click the execute button.

You’ll now need to replace the number the management studio gives you with the number “10” in the URL.

Callback Contents

Now set the radio button at the callback contents to: Notification as XML.

API Version

The API Version must be set to “Version 2.5”

Notification Filtering

The notification filtering must be checked

Configuring Acquire and Cancel Payments

Google Checkout comes with the ability to do automatic acquire and cancel payments. In order to make this work you need to enable a pipeline task.

To enable auto acquire edit the “ToCompletedOrder” pipeline.

To enable auto void/refund edit the “ToCancelled” pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

clip_image007

Simply remove “<!-- “ and “-->” at the highlighted line. These are HTML comment sections.

Configuring the “GoogleCheckout.config” File

Now we need to edit the ”GoogleCheckout.config” file in order to match your environment.

You’ll find the configuration file at “rootdir\umbraco\UCommerce\Configuration\ GoogleCheckout.config” where rootdir is the location on your computer, where Umbraco is installed.

Parameter list for the configuration file:

Parameter name

Value

merchantID

This is the identification of your google checkout account. When logged in at: https://sandbox.google.com/checkout/sell/settings?upgrade%3Dtrue&hl=da&nui=1&ltmpl=seller

Find it at the top right corner of the page.

merchantKey

This is a passphrase needed in the communication between your shop and google checkout.

Find it on the integration page in the back end office at “Google Checkout”, at the right side of the page.

successUrl

This URL redirects your customer back to a specific page at your site after a successful authorization.

editBasketUrl

This URL redirects your customer to the basket on your site.

testMode

Tells our system weather the application is in test mode or not. This must be set to false.

debug

Tells our system weather the application is in debug mode or not. This must be set to false.

clip_image009

 

clip_image010

FAQ

Ensure that uCommerce uses the same currency as your Google Checkout seller account

During our test of Google Checkout we found that transactions made with currencies other than the main currency of the seller account will always result in rejected authorizations. If you create the seller account with GBP please make sure that any test transactions are made with the same currency.

Failed transaction will appear with the message ”Cancelled by Google: Payment declined” in the seller account and the messages ”Cancelled” and ”Your order has been cancelled.” in the buyer account.

Please note that this applies to the sandbox only.

Ensure that “testMode” is set to “true” when using the Google Checkout sandbox for testing

If your GoogleCheckout.config is set to testMode=”false” Google Checkout will return HTTP code 400 bad request when accessing sandbox. Make sure that you’re operating in test mode when calling the sandbox.

posted on Monday, 13 February 2012 16:33:38 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for eWAY payments. This guide will walk you through getting uCommerce to work with eWAY for payment processing.

At the moment, the eWAY API only supports instant payment, which means that refunds or cancel payments is not possible.

Settings in uCommerce

Add a new payment method, under “uCommerce à Settings à Orders à Payment Methods”, by right clicking the “Payment Methods” leaf and use “Create”. You can use any name you like, I have used “EWay”.

clip_image001

Now we’re ready to configure your new payment method. Click the newly created node and select “Eway” in the Service drop down list and select “Checkout” in the pipeline drop down list. Remember to fill out the rest of the required information in the rest of the Tabs.

When you’re done, click the save icon. That’s everything in the uCommerce interface.

clip_image003

Please not that eWAY only supports Australian dollars (“AUD”).

clip_image005

if AUD does not appear under the pricing tab follow the next step ”Setting up Australian dollars at currencies” to add Australian dollars under currencies. Otherwise click the save icon and you’re done.

Setting up Australian Dollars at Currencies

clip_image007

Right click the currencies leaf and click create. The ISO code for Australian dollars is “AUD”. When you’re done, click the save icon. That’s everything in the uCommerce interface. Proceed to “2.0 Editing the EWay.config file”

Editing the EWay.config file

Now we need to edit the EWay.config file in order to match your environment.

You’ll find the config file at “rootdir\umbraco\UCommerce\Configuration\EWay.config” where rootdir is the location on your computer, where umbraco is installed.

image

customerId: must be found at your sandbox environment at the bottom of the page after you have logged in using your account credentials :

clip_image010

username: corresponds to your eWAY account username

debug: no need to configure

callbackUrl: no need to configure

cancelUrl: this is the page the customer would be redirected to after a cancellation at the secure payment page at eway.

acceptUrl: this is the page the customer would be redirected to after a successful payment at the secure payment page at eway.

Both the cancelUrl and acceptUrl is a local web in your website such as “orderconfirmation.aspx”

Now everything is configured to your webpage and should work as intended.

posted on Monday, 13 February 2012 16:30:30 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for Braintree payments. This guide will walk you through getting uCommerce to work with Braintree for payment processing.

With Braintree you are responsible for hosting the payment form. A simple form is provided by uCommerce, but it will need a better look and feel. Acquire, cancel, and refund are available. This is implemented with the Transparent Redirect method.

A wide range of currencies available, but you decide which currency to use when you create a merchant account. Each merchant account can only process a single currency.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “Braintree”.

clip_image002

Click the newly created node and select “Braintree” in the Service drop down list. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When you are done click “Save”.

clip_image003

That’s everything in the uCommerce interface.

Optional Settings in Braintree gateway

All those settings in the Braintree gateway are optional.

You log into your account at https://www.braintreegateway.com/login and sandbox at

Configure Validation Rules

On the Menu at the top, click “Processing” and the click “Add/Edit” in the CVV line.

clip_image005

Make sure that all is checked, and “For Any Transaction” is selected, to get CVV validation enabled. End by clicking “Save”.

clip_image007

Editing the Braintree.config File

Now we need to edit the Braintree.config file.

You will find the Braintree.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\Braintree.config”. Usually “rootdir” is c:\inetpub.

clip_image009

Some of the below information are found in the Braintree gateway, so start by logging in you aren’t already.

Finding merchantId

On the Menu at the top, click “Account” -> “My User” –> “API Keys”.

clip_image011

Here you find “merchantId”:

clip_image012

Finding publicKey

In the Menu at the top, click “Account” -> “My User” –> “API Keys”. Here you find the “publicKey”.

clip_image013

Finding privateKey

On the Menu at the top, click “Account” -> “My User” –> “API Keys” -> “View”. Here you find the “privateKey”.

clip_image014

Finding callbackUrl

Unless you have implemented your own version of the callback handling, this should be set to “(auto)”.

Finding paymentFormUrl

You can optionally host the payment form inside your own pages. To do this override the value “(auto)” with the URL on which the payment form is rendered.

Remember to use the CommerceLibrary:RenderPaymentForm or the RenderPage of the IPaymentWindow. Please find code samples in a later section.

Finding paymentFormTemplate

Path to the paymentFormTemplate. The default paymentFormTemplate BraintreePaymentForm.htm is located in the Configuration folder under uCommerce.

Finding acceptUrl and declineUrl

To get the customer redirected back to you page after ended payment, you have to specify a return url depending on payments result: Accept or decline.

Finding debug

If set to “True” you will be prompted to click a button before posting the information to “Braintree” otherwise it will do an autosubmit using Javascript. When running in production, you will want this set to “false”.

Finding testMode

Test mode will toggle the payment method service to use a test environment. A sandbox account is used in testMode.

Valid values “true” or “false”.

Excecuting a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, open Umbraco click “Commerce” select the payment method (“Braintree”). In the pipeline drop down list select Checkout and then click “Save”.

clip_image016

Now the default pipeline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

Set Look and Feel on the Payment Form

The payment form is populated with the contents of paymentFormTemplate file chosen in the config file, no matter which way you choose to integrate it.

The HTML inputs that have a name specified in the default file are needed to submit the form to Braintree. It is possible to changes types of the fields, add other attributes and move the fields around, but they must retain the names assigned to them.

The Braintree provider will insert values at runtime by replacing placeholder values, e.g. “##XX##” tags. You can safely remove these placeholders if you wish to handle the form values yourself.

Integrate the Payment Form into Your Own Page

If you want to integrate the payment form into one of your pages you’ll want to modify the template HTML to include only the form element and get rid of the html and body tags.

Integrate the form using Razor

Sample code:

@using UCommerce.EntitiesV2;
@using UCommerce.Transactions.Payments;
 
@{
 
    var paymentGuid = HttpContext.Current.Request["paymentGuid"];
    
    var payment = Payment.All().Single(x => x.PaymentProperties.Where(y => y.Key == "paymentGuid" && y.Value == paymentGuid).Count() > 0);
    
    var paymentMethod = payment.PaymentMethod;
    
    var paymentWindow = paymentMethod.GetPaymentMethodService() as IPaymentWindow;
 
}
 
@Html.Raw(paymentWindow.RenderPage(new PaymentRequest(payment.PurchaseOrder, payment)))

Integrate the form using XSLT

Sample code:

<xsl:variable name="paymentGuid" select="umbraco.library:RequestQueryString('paymentGuid')"/>
<xsl:value-of select="CommerceLibrary:RenderPaymentForm($paymentGuid)" disable-output-escaping="yes"/>

Optional: Enable Acquire, Cancel, and Refund in uCommerce Back Office

To be able to acquire, cancel, and refund payments you need to enable two pipeline tasks in the ToCompletedOrder pipeline and ToCancelled pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

ToCancelled.config

clip_image018

ToCompletedOrder.config

clip_image020

FAQ

· Test mode – Make sure test mode if turned off when going live.

posted on Monday, 13 February 2012 16:23:41 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for Authorize.Net payments. This guide will walk you through getting uCommerce to work with Authorize for payment processing.

With the Authorize.Net you can do authorization of payments, acquire payments and cancellation of payments both via uCommerce and the back end office of your Authorize.Net subscription.

Settings in uCommerce

Add a new payment method, under “uCommerce => Settings => Orders => Payment Methods”, by right clicking the “Payment Methods” leaf and use “Create”. You can use any name you like; I have used “Authorizedotnet”.

image

Now we’re ready to configure your new payment method. Click the newly created node and select “Authorizedotnet” in the Service drop down list and select “Checkout” in the pipeline drop down list. Remember to fill out the rest of the required information in the rest of the Tabs.

When you’re done, click the save icon. That’s everything in the uCommerce interface.

image

Settings in Your Back-end Office at Authorize.NET

You log in using the “Merchant Log In” page.

First you need to log in to your back end office at: http://Authorize.net

We need to configure your MD5-Hash used for secure communication between your server and Authorize.NET. Click MD5-Hash and create and submit. You need to have this ready by your hand in one of the following steps.

image

Next we need to configure the payment form.

image

Click “Form fields” in the page you enter after clicking “Payment Form” on the page above.

Check the following boxes off:

image

Now we need to visit “API Login ID and Transaction key” section.

image

Now you need to create a Transaction Key by answering your secret question which you created upon creating your Authorize.NET account.

Make sure you have the “API Login ID” and “Transaction Key” by your hand as you need them in the last step on configuring your configuration file.

image

Configuring Auto Acquire and Cancel Payments

Authorize.Net comes with the ability to do automatic acquire and cancel payments. In order to make this work you need to enable a pipeline task.

To enable auto acquire edit the “ToCompletedOrder” pipeline.

To enable auto void/refund edit the “ToCancelled” pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

image

Simply remove “<!-- “ and “-->” at the highlighted line. These are HTML comment sections.

Configuring the “Authorizedotnet.config” File

Now we need to edit the ”Authorizedotnet” file in order to match your environment.

You’ll find the configuration file at “rootdir\umbraco\UCommerce\Configuration\authorizedotnet.config” where rootdir is the location on your computer, where Umbraco is installed.

Parameter list for the configuration file:

Parameter name

Value

apiLogin

The API login ID from the backend. Please refer to section of settings in Authorize.NET backend

TransactionKey

The transaction key you’ve created in the back-end configuration.

Md5Hash

You’ll have to define this hash key yourself. Please refer to section of settings in Authorize.NET backend

acceptUrl

This URL redirects your customer back to a specific page at your site after a successful authorization.

declineUrl

This URL redirects your customer back to a specific page at your site if an authorization is declined.

payType

Tells our system what command to send to Authorize.NET

testMode

Application is in test mode. This must be set to false.

debug

Application is in debug mode or not. Set to false for live environments

instantAcquire

Perform instant capture on payment or authorization of a payment.

sandboxMode

Set to true for the sandbox environment and false for test/live environments.

 

image

Congratulation - your website now includes payments with the Authorize.NET.

Important: When authorization has been succesfully completed, Authorize will redirect the customer to the acceptpage but notice this page will be under the Authorize.Net’s URL. This is not an error.

posted on Monday, 13 February 2012 16:15:48 (Romance Standard Time, UTC+01:00)  #    Comments [1] Trackback

uCommerce comes with built-in support for Amazon FPS payments. This guide will help you to setup your installation to use Amazon FPS as payment.

Settings in uCommerce

To add a new payment method to uCommerce, go to the Commerce section in your Umbraco installation.

clip_image002

Navigate to “uCommerce => Settings => Orders => Payment Methods”. Right click on the node “Payment Methods” and click “Create”.

clip_image004

A box will appear. Here you can enter any name you like but it’s recommended to use “Amazon FPS” so you easily can find it again.

Now we have to configure the payment method. Click on the node with the name you have chosen. In the service dropdown list you choose “Amazon FPS” and select “Checkout” in the Pipeline dropdown list. Remember to give the service a “Display name” which you find in your language tab in the same window.

clip_image006

Amazon FPS does only support US Dollars at this point, so if USD doesn’t appear under the “Pricing” tab you have to follow the next step “Setting up US Dollars at currencies”. Otherwise click the save icon and skip the next step.

clip_image008

Setting up US Dollars in Currencies

clip_image010

Right click the currencies leaf and click create. The ISO code for Australian dollars is “USD”. When you’re done, click the save icon.

Signing up for a Amazon FPS account

To use the Amazon FPS with uCommerce you have to register first. Go to https://payments.amazon.com and go to the “Developer” tab in the top menu. Under the “Developer” tab click “Sign Up For Amazon FPS”. Create a new account or use an existing account if you already got one you wish to use.

clip_image011

Follow the instructions on the screen to complete the registration. When the registration is complete you receive a confirmation to the e-mail address you used for the registration.

Setting up the Amazon FPS config file

Now we need to edit the Amazon.config file in order to match your environment. You will find the config file at “(root dir)\umbraco\UCommerce\Configuration\Amazon.config” where “root dir” is the location on your computer where umbraco is installed.

clip_image013

debug: Not used by this provider.

testMode: Indicates whether the Amazon FPS is using the Sandbox or production environment. If you want to test your payment service this setting MUST be set to “True” otherwise the Amazon FPS will be in production environment and will charge a customer.

debug=”True” – For sandbox environment

debug=”False” – For production environment

awsAccessKey: This key is used to identify the account. You can find this key here: http://aws.amazon.com/security-credentials. If you’re not logged in you will be asked to do so.

awsSecretKey: This key is used to create your signature and it’s important to keep this secret from people who is not in need of this. You can also find this key at the security credentials at amazon. Use the same link above.

acceptUrl: This is the page the customer will be redirected to after a payment has been authorized at Amazon. In the picture above there is an example how it can look like.

cancelUrl: This is the page the customer will be redirected to if the customers abandons payment at Amazon.

callbackUrl: this need to be configured. You need to know what id the payment method has in the database. Look at the next step to see how to find this id. The URL should be on the form of: http://(domain name)/(id)/PaymentProcessor.axd

How to find your payment method id in your database

To find your payment method id you need to make a query. One way to make this query is using SQL Mangement Studio. Connect to your SQL server. In SQL Management click “New Query” in the tools menu right under the file menu. Choose the database where you have your umbraco/uCommerce installed.

clip_image014

In the text editor in write the following:

SELECT * FROM ucommerce_paymentmethod WHERE Name = 'Amazon FPS'

The text between ‘’ is the name of the service you choose in step 1.1. Then press “F5” on your keyboard to execute the query. In the bottom of the text editor window a result window should appear.

clip_image015

The number which is in the column “PaymentMethodId” is the number you need in your Amazon.config file.

Setting up the Instant Payment Notification messages in Amazon FPS.

Amazon FPS sends notifications when a status on a transaction changes. That can be when a transation is changing from “Pending” to “Success”. To setup this you need to go to your account management. Navigate to https://payments.amazon.com in your browser. Click on “Your Account” tab and type in your login credentials.

In your control panel go to “Edit My Account Settings à Manage Developer and Seller Preferences”. In the textbox right for “URL for Instant Payment Notification” type in the url in the following format: http://(domain name)/(paymentmethodId)/PaymentProcessor.axd

clip_image017

Note: The URL you type in this field has to match the callbackUrl in the Amazon.config file or Amazons signature will be rejected and payments will not be available.

Configuring Auto Acquire and Cancel Payments

The Amazon FPS  provider comes with the ability to do automatic acquire and cancel payments. In order to make this work you need to enable a pipeline task.

To enable auto acquire edit the “ToCompletedOrder” pipeline.

To enable auto void/refund edit the “ToCancelled” pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

clip_image018

Simply remove “<!-- “ and “-->” at the highlighted line. These are HTML comment sections.

posted on Monday, 13 February 2012 16:08:55 (Romance Standard Time, UTC+01:00)  #    Comments [1] Trackback
# Tuesday, 18 October 2011

Foundation-logouCommerce comes with a bunch of built-in targets that you can use to set up new campaign items, but you can extend Marketing Foundation with your own targets as well.

To build a new target you have to deal with three concerns:

  • Business logic, this is the target itself
  • User interface, the UI a customer will use to configure your target
  • Data access, creating new instances of your target and loading existing ones

“Buy More Than”-target

In this article you will learn how to extend Marketing Foundation with a “Buy more than”-target, which is what uCommerce calls an Act target. The “Buy more than”-target will be an order line level target, which will be combined with a “Buy product”-target to create a discount triggered.

It can be used stand-alone as well in which case the customer just needs to “Buy more than” of whatever product she decides. Not the most common discount type, but it does show the power of being able to combine targets.

image

Advertise and Act Targets

uCommerce supports two kinds of targets: The advertise target and the act target. Display targets are used in the process of targeting campaign items for specific customers, i.e. these are the ones you set up under the “Advertise” section of a campaign item.

Act targets are evaluated against a cart to determine whether the customer actually “acted” the way we wanted them to and thus trigger an award.

A target might be either an advertise target, an act target, or both, e.g. a product target is actually both an advertise target and an act target as it works for both scenarios.

As mentioned advertise targets are used to determine which campaign items a customer should see using the XSLT extension:

<xsl:variable name="targetedCampaignItems" select="CommerceLibrary:GetTargetedCampaignItems()"/>

Or via .NET

var targetingService = ObjectFactory.Instance.Resolve<ITargetingService>();
IList<CampaignItem> targetedCampaignItems = targetingService.GetTargetedCampaignItems();

Act targets are executed by the basket pipeline using the pipeline task Basket.ApplyAwards.

Our “Buy more than”-target will be an act target targeting individual order lines. Before we get to that though let’s take a look at what’s required to create an advertise target or IDisplayTarget as they’re called internally in uCommerce.

Implementing IDisplayTarget

image

To implement a display target you’ll implement the interface called IDisplayTarget, which has a single method called IsSatisfiedBy. This is the method invoked by uCommerce to determine whether the target is satisfied by the current targeting context.

Basically you’ll evaluated the targeting context and see if it fits with what you want your target to do, e.g. is the customer viewing a particular product, is the customer logged, etc..

Pretty simple.

A Word On The TargetingContext

image

The targeting context is gathered by uCommerce during runtime and tells you all manner of interesting information about what the customer is currently viewing, e.g. what’s the current page, store, catalog, category, list of products being viewed, etc.. You can add your own information to the targeting context if you require additional information. We’ll cover that in another article.

Implementing An Act Target: IPurchaseOrderTarget, IOrderLineTarget

image

Act targets are evaluated against the customer’s cart to verify that the customer actually bought or did what we wanted her to do. You can opt into two interfaces depending on whether you’re targeting the entire order or individual order lines: IPurchaseOrderTarget and IOrderLineTarget.

For our “Buy more than” target we’ll implement the IOrderLineTarget because that’s where we’ll find the quantity of a particular item. Our new “Buy more than”-target would probably be combined with a “Buy this product”-target in most cases, which would require a customer to buy a certain amount of the product.

image

As you can see the logic is pretty simple. We’re receiving an order line from Marketing Foundation and our job is to figure our whether the target is satisfied by this particular order line. In our case the customer just needs to buy more than the configured quantity on the our target.

This leads us to the next question: How do we actually configure a target? Enter the ITargetUi and IConfigurable…

Implementing Configuration UI for the Target

The configuration UI for our new target is responsible for creating a new instance of our particular target and saving it the data store of your choice. Also it serves to reconfigure existing targets of the type that we’re working with; in this instance QuantityTarget.

To add a config UI for our new target we need to create a new user control in .NET. Let’s put it in /umbraco/ucommerce/marketing/targets, which is where the standard target UIs are located. Also remember to put the generated DLL in the /bin folder.

Our user control needs to plugin into the UI framework defined by uCommerce. All that’s required to do so is to inherit ViewEnabledControl<IEditCampaignItemView> and implement IConfigurable.

image

Inheriting ViewEnabledControl<IEditCampaignItemView> gives us access to the context in the UI, i.e. the campaign item currently being configured.

IConfigurable is the interface which lets uCommerce create your target and subsequently reconfigure it when a user wants to edit it.

image

For our target we need a specialized version of IConfigurable called ITargetUi. This is due to the fact that the target might be used as both an advertise target, an act target, or both.

uCommerce will tell you whether it’s one context or the other by assigning the EnabledForDisplay and EnabledForApply values on your UI.

image

So our user control ends up looking like this. Please note that the New() method acts not only as a factory method for our target, but has the responsibility for storing that instance in the data store also. If this doesn’t happen the instance is lost and won’t be displayed as part of the campaign item.

image

Before we can actually use the control we need to register it with uCommerce.

Register Target Configuration UI

To add the target UI to uCommerce we’ll add it to the table called uCommerce_EntityUi. This table holds the mapping between the type, which is to be configured, i.e. our QuantityTarget, and our UI to do the configuration, i.e. our QuantityUi.ascx user control.

image

Because uCommerce is multilingual we’ll want to add a description of the new UI in the table uCommerce_EntityUiDescription otherwise the target UI will show up blank in the drop down lists.

image

When the “Add” button is clicked our new target UI is added to the campaign item and the New() method is called on our user control thus creating a new instance of the target we’re configuring.

image

image

With that in place our new UI is now available when setting up new campaign items and we can create new quantity targets, so we’re ready to move on to dealing with existing targets.

Feeding Marketing Foundation with Targets using TargetAggregator

With the previous steps complete we need to deal with existing targets so Marketing Foundation can find them and evaluate them for customers entering the site: Enter the TargetAggregator.

TargetAggregator is responsible for finding targets for any given campaign item configured in Marketing Foundation.

var targetAggregator = ObjectFactory.Instance.Resolve<ITargetAggregator>();
IList<ITarget> targets = targetAggregator.GetTargets(campaignItem);

TargetAggregator relies on individual TargetResolvers to find targets for a campaign item, e.g. uCommerce has a single target resolver called DefaultTargetResolver, which handles the built-in targets.

We’ll build a custom target resolver by implemeting the ITargetResolver. It will handle our Quantity target and any other future targets.

image

Thus our QuantityTargetResolver ends up looking like this:

image

Register Custom Target Resolver with TargetAggregator

At this point uCommerce doesn’t know about our custom target resolver yet so we’ll have to tell it about it. This is done using the Marketing configuration file found in /ucommerce/configuration/Marketing.config.

We’ll have to register a new component and add it to the target aggregator registration.

First the new component

image

And finally grab the id from the component and add it to the target aggregator registration in the same file.

image

That’s it. Our new target is good to go and will act exactly as the built-in targets, which ship with uCommerce.

In Summary

image

This article showed you how to add custom targeting logic to uCommerce, the user interface to configure it, and how to handle data access for it as well. When you think about it each target is a mini-application hosted inside uCommerce dealing with all the usual concerns of a full-blown  app.

Some of the concerns like the resolver need only be implemented once while others like the UI and the target itself are highly specific to the task they’re trying to accomplish and require a new implementation for each new type you need.

Marketing and particularly discounting are areas, which often come with very specific business rules highly different dependent on the individual business. uCommerce ships with a bunch of useful targets, but having the ability to add your own ensures that you can accommodate any targeting scenario.

posted on Tuesday, 18 October 2011 17:13:10 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback

Foundation-logoMarketing Foundation introduced with uCommerce 2.0 adds rich marketing capabilities, which can be used to stimulate customers to buy. It’s built based on three simple principles: Advertise, Act, and Award.

Advertise

One of the common issues with discounts is that customers are never told about them thus a discount does not work its full effect. Basically the customer is only made aware of the discount once they actually trigger it, which is akin to throwing marketing dollars out the window as the customer was likely to buy anyway.

That’s why we built each campaign item in uCommerce to include the “Advertise” component so marketers actively have to decide whether to advertise or not; at the end of the day why wouldn’t you?

When doing advertisements in uCommerce you will select a number of targets, which are to be satisfied in order for the campaign item to be displayed. You can think of them in terms of, “Customer is viewing this category”, “Customer is viewing this page”, “Customer is in this particular store or catalog”.

If multiple targets are configured in the “Advertise” section the campaign item will be displayed if any of the targets are satisfied.

Once a campaign item is targeted for the current customer its contents can be displayed, which includes rich text, video, HTML, and even the actual targets and awards inside the campaign item. What this boils down to is that you can display banners, which feature video, sound, or HTML content and you can take this a step further by actually telling the customer what she needs to do in order to receive a particular discount.

image

Say you have a campaign item set up called “Free shipping for orders over 400€”. The intent is clear enough, but what if you could actually tell the customer how close she is to get that discount? It just so happens that you can.

Using the information produced by Marketing Foundation you can tell the customer exactly what she must do to trigger the discount.

Say she’s got items in the cart with a total value of 350€. You’d pop up a message telling her that by buying for 50€ more she’d get free shipping; oh and by the way here are some products which 50€ or more making it easy for the customer to take the action we want her to.

Act

image

The act section of a campaign item is the thing we want the customer to do to trigger a discount. When you think about it a discount is actually composed of two things: The thing we want the customer to do; the act part, and the thing the customer gets; the award part.

Think of “Act” as “The customer must buy this particular product”, “The customer must buy for more than x amount”, “The customer must buy something from this particular store, catalog, or category”, etc.

Targets can be combined to form even more powerful campaign items such as a product bundle or kit depending on which side of the pond you’re on.

If multiple targets are set up in the “Act” section of the campaign item they must all be satisfied in order to trigger the discount. Say you want to the customer to buy two products to get a discount. You’ll set up two targets: One for each of the products in involved. uCommerce will look for these products in the cart of they are both found will trigger the discount.

Award

AwardThe final piece of the puzzle is the “Award”, i.e. the thing the customer gets. The award is completely separate from the rest of the campaign item and thus can be reused for many different types of discounts, e.g. “Buy for more than 400€ and get free shipping ” could also be “Enter this promo code and get free shipping”. The only difference is that the “Buy for more than 400€” act section is substituted with “Enter this promo code”. The award remains the same.

Types of awards include “Get amount of unit price”, “Get amount off order total”, “Get amount off order lines total”, “Get percentage off shipping”. Awards can be combined like targets and effectively gives you a discount for each of the awards configured.

It’s important to distinguish between order discounts and order line discounts. The difference being that order level discounts are typically applied only once per order, e.g. “Get amount off order total” will only add a single discount to the order as you’d expect.

Order line discounts on the other hand can involve multiple order lines as in the case of the bundle or kit. Here two or more order lines are involved in the discount thus each of lines will have the order line discount applied, e.g. “Get 10% off unit price” will produce two discounts; one for each order line satisfied by the Act section.

Campaign Items

image

The campaign item ties together our “Advertise”, “Act”, and “Award” sections and is the unit, which can be thought of as a “Discount”.  However, the campaign item does more than just set up a discount, it serves as the content for the advertisement as well.

A campaign item is assigned a “definition” when it’s created. The definition determines the content that the marketer can add to the advertisement. So this is basically where you’d add all the rich content we discussed in the beginning of the article.

image

You can read more about definitions in Catalog Foundation Explained: Product Definitions. The basic concept of the definition is the same for campaign items as for products although obviously a campaign item definition does not deal with variants.

Because the campaign items are configured using definitions you can add your own properties and multilingual properties effectively giving you multilingual marketing campaigns right there. No need to configure the same campaign item twice if you want to target different languages, just add the relevant multilingual properties and you’re done!

Multiple Discounts Per Order, Or No

image

In some cases you don’t want the customer to receive multiple discounts. That’s where the configuration of the campaign item comes in. Of course you can disable individual campaign items that you don’t customer to receive at all by removing the checkmark in the “Enabled” checkbox.

More interestingly you can configure a campaign item to not allow additional discounts if the “Act” section of current campaign item is satisfied. Combine this with the priority of individual campaign items and you can effectively control which discounts the customer is awarded based on your business rules.

You can prioritize campaign items by right-clicking the campaign and choosing “Prioritize campaign items” in the tree menu.

Campaigns

image

Finally we come to the top-most level of Marketing Foundation: The campaigns. A marketing campaign is a collection of campaign items grouped together under a name so each campaign will effectively hold all the planned marketing activities for a given period of time.

A marketing campaign is assigned an interval for which it is active. uCommerce will automatically activate campaign items within in the campaign once the activation period is reached and disabled them again once the activation period is done.

In Summary

uCommerce Marketing Foundation is a highly flexible way to set up marketing messages and discounts in your online store. Combined targets and awards make for interesting possibilities when it comes to different discount types and best of all you can let your customers know exactly what they need to do to get a discount, which is the way it should be.

More importantly Marketing Foundation is built-in from the ground up using our Framework First approach, which means that new targets and awards can easily be added. You can even go so far as to change the inner workings on Marketing Foundation. What this means for your online store is that marketing can be tailored to meet your needs exactly.

posted on Tuesday, 18 October 2011 13:34:57 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, 16 August 2011

imageIn a previous article we discussed 4 Steps to Building an Apple-style Product Configurator with uCommerce, which detailed how to piece together a complete product from multiple product options configured in the catalog.

This article will help you deal with those composite items as a unit rather than separate line items.

Step 1: Adding a Composite Product to Basket

When adding the main product and options to the basket we’ll need some way to tell the “master order line” from the “sub order lines”.

We’ll use dynamic order properties to enrich the order lines  for the required information linking each product option line to a master order line containing the main product; our MacBook Air 11 inch.

With that in mind here’s the Razor code in Umbraco to add all the selected options to the basket.

ProductCatalog catalog = ProductCatalog.All().Single(x => x.Name == SiteContext.Current.CatalogContext.CurrentCatalogName);
    
// Check if we're dealing with a post
if (!string.IsNullOrEmpty(Request["masterSku"]))
{
    var basket = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
        
    // Add the master order line
    var mainProduct = Product.All().Single(x => x.Sku == Request["masterSku"] && x.ParentProductId == null);
    var masterOrderLine = basket.AddProduct(catalog, mainProduct, 1, false);
        
    // Mark the master as such
    masterOrderLine["master"] = true.ToString();
 
    // Save basket to generate ids for the order line
    basket.Save();
        
    // Add each product option to the basket
    foreach (string key in Request.Params.AllKeys.Where(x => x.Substring(0, 3) == "SKU"))
    {
        // Split the value of the posted skus to get both sku and variant sku (where applicable)
        // Example Intel-Core-CPU,i7-1.7
        string[] skus = Request[key].Split(',');
        string sku = skus[0];
        string variantSku = skus.Length == 2 ? skus[1] : null;
            
        // Add the option order line
        var optionProduct = Product.All().Single(x => x.Sku == sku && x.VariantSku == variantSku);
        OrderLine subOrderLine = basket.AddProduct(catalog, optionProduct, 1, false);
 
        // Add a reference back to the master order line
        subOrderLine["masterOrderlineId"] = masterOrderLine.OrderLineId.ToString();
    }
 
    basket.Save();
 
    // Execute the basket pipeline to recalculate basket
    Library.ExecuteBasketPipeline();
}

Now we’ve got all the items added to the basket let’s move on to displaying the items in a nice way on the basket page.

Step 2:  Displaying the Composite Product

Now we’ll need to leverage that extra information we added in the previous step to group the items together.

@using UCommerce.EntitiesV2;
@using UCommerce.Runtime;
@{
    // Load basket
    var basket = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
}
 
@foreach (var masterOrderLine in basket.OrderLines.Where(x => x.OrderProperties.Where(y => y.Key == "master" && y.Value == true.ToString()).Count() > 0))
{
    <form method="post">
    <input type="hidden" name="masterOrderLineId" value="@masterOrderLine.OrderLineId"/>
    <div>
        <h4>@masterOrderLine.ProductName</h4>
        <ul>
            @foreach (var subOrderLine in basket.OrderLines.Where(x => x.OrderProperties.Where(y => y.Key == "masterOrderLineId" && y.Value == masterOrderLine.OrderLineId.ToString()).Count() > 0))
            {
                <li>@subOrderLine.ProductName</li>
            }
        </ul>
        <input type="submit" value="Remove" name="remove" />
    </div>
    </form>
}

Here’s what the basket looks like when Umbraco and Razor renders it:

image

Step 3: Remove a Composite Product

Next we’ll want to let the customer remove composite items from the basket by remove the master order line along with any sub order lines it might have.

@using UCommerce.EntitiesV2;
@using UCommerce.Runtime;
@using UCommerce.Xslt;
@{
    // Load basket
    var basket = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
 
    // Check for post
    if (!string.IsNullOrEmpty(Request["masterOrderLineId"]))
    {
        int masterOrderLineId = Convert.ToInt32(Request["masterOrderLineId"]);
 
        // Find all sub order lines for master
        var subOrderlines = basket.OrderLines.Where(x => x.OrderProperties.Where(y => y.Key == "masterOrderLineId" && y.Value == masterOrderLineId.ToString()).Count() > 0).ToList();
 
        // Remove sub order lines from basket
        foreach (var subOrderLine in subOrderlines)
        {
            basket.RemoveOrderLine(subOrderLine);
        }
 
        // Now remove the master order line
        OrderLine masterOrderLine = basket.OrderLines.Single(x => x.OrderLineId == masterOrderLineId);
 
        basket.RemoveOrderLine(masterOrderLine);
        basket.Save();
 
        // Recalculate basket
        Library.ExecuteBasketPipeline();
    }
  
}
 
@foreach (var masterOrderLine in basket.OrderLines.Where(x => x.OrderProperties.Where(y => y.Key == "master" && y.Value == true.ToString()).Count() > 0))
{
    <form method="post">
    <input type="hidden" name="masterOrderLineId" value="@masterOrderLine.OrderLineId"/>
    <div>
        <h4>@masterOrderLine.ProductName</h4>
        <ul>
            @foreach (var subOrderLine in basket.OrderLines.Where(x => x.OrderProperties.Where(y => y.Key == "masterOrderLineId" && y.Value == masterOrderLine.OrderLineId.ToString()).Count() > 0))
            {
                <li>@subOrderLine.ProductName</li>
            }
        </ul>
        <input type="submit" value="Remove" name="remove" />
    </div>
    </form>
}

Summary

Managing multiple items as one in the basket is handy when working with complex product options like we did for the MacBook Air just now. At all times should customers be certain as to what they’re buying and managing the items should be as straightforward as for “simple items”.

Combining multiple items into one visually is a matter of adding a bit of extra information to tie the items together and doing a clever presentation of the items.

All the internal calculations and stock management stay the same behind the scenes so you just have to worry about doing a nice presentation of the basket.

posted on Tuesday, 16 August 2011 22:55:31 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback

imageVariants is a great way to offer up products which have varying properties, but sometimes they are just not enough or it’s too cumbersome to maintain each and every variant combination you want.

In this article you’ll discover how to build an Apple-style product configurator with uCommerce.

There are two pieces to doing a highly flexible product configurator: The configurator itself and the subsequent presentation of the basket.

We’ll cover the configurator itself in this article and do a separate article for the basket itself.

Step 1: Product Definition for the Main Product

First we’ll need a main product which is the one that we want to configure. For the sake of concreteness let’s build a product configurator for an Apple MacBook Air.

We’ll build a definition to hold main products. Let’s call it “Configurable”. The product definition will hold information to present the main product unique selling proposition like what you see on the main product page on Apple.com.

We won’t be doing any variants for this product definition as the options will come from somewhere else.

Before we move on let’s create the MacBook Air in the product catalog.

image

Step 2: Add Options to the Catalog

For a MacBook Air we’ll need to be able to configure the CPU, the amount of storage, and a couple of add-ons like an external optical drive and display.

We’ll do the options as individual products, which incidentally they typically are anyway with their own inventory.

Let’s add a couple more product definition for the various types of options: CPU, Flash Storage, and Display.

We’ll do variants for the product options as they will become the actual choices the customer has to choose from when configuring the final product.

Here are the product options configured in a separate category for good measure. Note that each option has a number of variants configured.

image

image

I did go ahead and create a definition for each type of add-on, but that’s not a strict requirement. I’m just being a smartass and showing off some other features of uCommerce :)

Step 3: Configure Available Options

Now we’ve got a catalog of products and main products and now for the good stuff: Configuring the available options for each main product. Customers will be able to select CPU, Flash Storage, and optional optical drive or Display for our MacBook Air.

uCommerce supports related products, which is a handy way of building up a list of available options for a given product. So let’s see if we can make that work for our configurator.

First let’s set up a new relationship kind called “Option” to help us find available options later on.

image

And now let’s actually add the options to our MacBook Air.

image

Step 4: Build the Configurator

With the previous steps concluded we’ve got the required information set up in the catalog and now we’re ready to present the options to our rabid following; sorry, loyal customers :)

Enter Razor. Enter the code!

First we’ll load up the product that we wish to configure. Of course it would typically come from a listing, but we’ll just grab it directly to get to the point.

Finally we’ll grab the “Option” relations and present them in a list. Here’s what the Razor code in Umbraco will look like.

@using UCommerce.EntitiesV2;
@using UCommerce.Runtime;
@{
    // Check if we're dealing with a post
    if (!string.IsNullOrEmpty(Request["masterSku"]))
    {
        // Iterate the posted values and add each value to basket
        foreach (string key in Request.Params.AllKeys.Where(x => x.Substring(0, 3) == "SKU"))
        {
            Response.Write(Request[key]);
        }
    }
}
 
@{
    // Grab a price group to work from
    var priceGroup = ProductCatalog.All().Single(x => x.Name == SiteContext.Current.CatalogContext.CurrentCatalogName).PriceGroup;
 
    // Load MacBook Air product
    Product macbookAir = Product.All().Single(x => x.Sku == "MacBook-Air-11-inch");
 
    // Load options relationship kind
    ProductRelationType optionRelation = ProductRelationType.All().Single(x => x.Name == "Option");
 
    // Load the product options, "Option" relation kind only
    var options = macbookAir.GetRelatedProducts()[optionRelation];
}
 
<h1>@macbookAir.Name</h1>
<form>
<input type="hidden" name="masterSku" value="@macbookAir.Sku"/>
@foreach (Product option in options)
{
    <h2>@option.GetDescription("en-us").DisplayName</h2>
    if (option.ProductDefinition.IsProductFamily())
    {
        foreach (Product selectableOption in option.Variants)
        {
            <input type="radio" group="@option.Name" name="SKU,@option.Sku" value="@option.Sku,@selectableOption.VariantSku">@selectableOption.GetDescription("en-us").DisplayName</input>
            if (selectableOption.GetPrice(priceGroup).Price > 0)
            {
                <span>[Add $@selectableOption.GetPrice(priceGroup).Price.Value.ToString("#.00")]</span>
            }
            <br />
        }
    }
    else
    {
        <input type="radio" group="@option.Name" name="SKU,@option.Name" value="@option.Sku">@option.GetDescription("en-us").DisplayName</input>
        
        if (option.GetPrice(priceGroup).Price > 0)
        {
            <span>[Add $@option.GetPrice(priceGroup).Price.Value.ToString("#.00")]</span>
        }
        <br />  
    }
}
<br />
<input type="submit" value="Add to basket" />
</form>

And here’s what the product configurator looks like when the customer sees it in Umbraco. Add some CSS and images to the HTML and you’ve got your product configurator.

image

Summary

Creating and maintaining highly configurable products in uCommerce is a perfect way to offer up nice customization opportunities for customers.

By using the out of the box capabilities like product definitions, relationship kinds, and relationships combined with the API you can build a rich product configurator, which will present product options dynamically based on the options attached to any given product.

Also doing configurable products like this is a great way to manage inventory of individual components instead of complete product configurations. This means that less inventory is required because any given option might be part of multiple different product configurations thus inventory will seem higher with this approach.

In this article you saw how we can use uCommerce to build an Apple-style configurator, but this technique can be further extended to present even more complex decision trees if required.

Imagine building the options themselves with sub-options by doing deeper relationships. This way you can support some very complex scenarios and have complete decision trees for product with very different options, e.g. triple-play service providers of TV, phone, and internet services, which require very different configuration for each option.

posted on Tuesday, 16 August 2011 09:10:18 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Wednesday, 10 August 2011

imageWhen working with an e-commerce transaction system in an online store typically the information stored on the orders and order lines will come from the products themselves in the catalog system.

However, in some cases you might want to add custom information such as a personalized message, an indication whether gift wrapping is required, serial numbers, measurements, or something else entirely.

Enter Dynamic Order Properties

For this specific scenario uCommerce supports dynamic order properties, which is a way to add information to basket, orders, and individual order lines.

You can add as many as you want and you don’t have to stick with the same number of properties or even the same names across orders.

Using Dynamic Order Properties in Razor and .NET

// Grab the basket of the current customer
Basket basket = SiteContext.Current.OrderContext.GetBasket();
PurchaseOrder order = basket.PurchaseOrder;
 
//Add dynamic order property to the order
order["gift_message"] = "Happy birthday!";
order.Save();
// Grab the basket of the current customer
Basket basket = SiteContext.Current.OrderContext.GetBasket();
PurchaseOrder order = basket.PurchaseOrder;
 
//Add dynamic order property to an order line
OrderLine orderLine = order.OrderLines.First();
orderLine["serial_number"] = "ZX456-123";
 
order.Save();
PurchaseOrder purchaseOrder = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
 
// Reading the properties back is just as simple
string giftMessage = purchaseOrder["gift_message"];
string serialNumber = purchaseOrder.OrderLines.First()["serial_number"];
 

Using Dynamic Order Properties in XSLT

For convenience you can also work with dynamic order properties in XSLT courtesy the Commerce Library.

For order level properties you go:

<xsl:variable name="result" select="CommerceLibrary:SetOrderProperty('gift_message', 'Happy birthday!')"/>

For individual order lines you’ll refer to the index of the order line to target a specific one. That the first parameter. The index values will be part of the order XML produced by CommerceLibrary:GetBasket().

<xsl:variable name="basket" select="CommerceLibrary:GetBasket()"/>
 
<!-- Grab the index of the first line item -->
<xsl:variable name="firstLineItemIndex" select="$cart/purchaseOrder/lineItems/*[1]/@index"/>
 
<!-- Now set a dynamic order property on the line item with that index -->
<xsl:variable name="result" select="CommerceLibrary:SetOrderProperty(@firstLineItemIndex, 'serial_number', 'ZX456-123')"/>

Once set the dynamic order property will be outputted as part of the XML produced by GetBasket() or GetPurchaseOrder() in the orderProperties element under the order itself or under individual order lines.

<purchaseOrder index="0" orderNumber="WEB-20" orderGuid="62093368-877a-42d8-94c7-332f6f0031f1" status="New order" createdDate="8/10/2011 8:24:14 AM" completedDate="8/10/2011 8:25:10 AM" note="" vat="479.00" orderTotal="2874.00" discount="0.00" discountTotal="100.00" shippingTotal="0.00" paymentTotal="0.00" taxTotal="" subTotal="2395.00" lineItemCount="1" billingCurrency="EUR" productCount="1">
    <customer index="0" id="69" firstName="Søren" lastName="Spelling Lund" emailAddress="soren.spelling.lund@ucommerce.dk" phoneNumber="4540385659" mobilePhoneNumber="4540385659" umbracoMemberId="">
        <addresses />
    </customer>
    <discounts />
    <orderProperties>
        <orderProperty key="gift_message" value="Happy birthday!" />
    </orderProperties>
    <lineItems>
        <lineItem index="0" sku="100-000-001" variantSku="003" productName="uCommerce 1.0 RTM Go-Live" price="2495.00" quantity="1" discount="100.00" unitDiscount="100.00" vat="479.00" vatRate="0.20" total="2874.00">
            <orderProperties>
                <orderProperty key="serial_number" value="ZX456-123" />
            </orderProperties>
            <discounts>
                <discount index="0" campaignName="Default Campaign" campaignItemName="Discounted unit price" description="" amountOff="100.00" />
            </discounts>
        </lineItem>
    </lineItems>
    <shipments>
        <shipment index="0" shipmentId="17" name="Download" createdDate="8/10/2011 8:25:06 AM" shippingMethodId="8" deliveryNote="Download" trackAndTrace="" price="0.00" taxRate="0.20" tax="0.00" shipmentTotal="0.00">
            <address addressId="76" addressName="Shipment" index="0" firstName="Søren" lastName="Spelling Lund" emailAddress="" phoneNumber="" mobilePhoneNumber="" company="uCommerce ApS" line1="Ny Banegårdsgade 55" line2="" postalCode="8000" city="Aarhus C" state="" country="Denmark" attention="" />
        </shipment>
    </shipments>
    <payments>
        <payment id="27" index="0" transactionId="33c6e85e-05f5-41d1-b32e-8b57212883a2" name="Account" dateCreated="8/10/2011 8:25:08 AM" fee="0.00" feeTotal="0.00" feePercentage="0.0000" amount="2874.00" statusId="1" paymentMethodId="6" />
    </payments>
    <addresses />
    <billingAddress>
        <address addressId="75" addressName="Billing" index="0" firstName="Søren" lastName="Spelling Lund" emailAddress="soren.spelling.lund@ucommerce.dk" phoneNumber="+4561799997" mobilePhoneNumber="" company="uCommerce ApS" line1="Ny Banegårdsgade 55" line2="" postalCode="8000" city="Aarhus C" state="" country="Denmark" attention="" />
    </billingAddress>
</purchaseOrder>

Admin

Dynamic order properties will be displayed in uCommerce Admin as part of the order overview.

image

Summary

Dynamic order properties is a great way to add custom information to orders during checkout or indeed later in the order process if required. It can be used to capture customer choice for later use such as custom messages, newsletter sign up flags, and more.

Because they are automatically picked up by the order management interface in the backend they are useful for information store managers need to know during the order management process.

posted on Wednesday, 10 August 2011 08:40:08 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Wednesday, 03 August 2011

imageMore often than not you will leverage uCommerce in a web context either via the Commerce Library XSLT extensions or through .NET directly.

In some cases though you might need to leverage the API outside a web context for automated integration between systems, for custom web services, or integration of uCommerce functionality directly in other custom applications such as point of sale- or kiosk apps.

This article outlines the steps required to get the API going.

Reference uCommerce Assemblies

First you need to reference the uCommerce assemblies and their dependencies in your project.

You’ll need to add references to:

  • UCommerce.dll
  • UCommerce.Infrastructure.dll
  • UCommerce.Umbraco.dll
  • businesslogic.dll (Umbraco)
  • Castle.Core.dll
  • Castle.Windsor.dll
  • FluentNhibernate.dll
  • NHibernate.dll
  • Nhibernate.ByteCode.Castle.dll

Modify App.Config

uCommerce needs some configuration to run. You’ll find examples of the relevant groups in web.config in your Umbraco installation. You’ll want to copy the commerce sectionGroup, connectionStrings, and commerce sections.

Add configSection Element

<configSections>
    <sectionGroup name="commerce" type="System.Configuration.ConfigurationSectionGroup">
        <section name="runtimeConfiguration" type="UCommerce.Infrastructure.Configuration.RuntimeConfigurationSection, UCommerce.Infrastructure" />
    </sectionGroup>
</configSections>

Add connectionStrings Element
<connectionStrings>
    <add name="ucommerce" connectionString="Data Source=(local);Initial Catalog=Umbraco;integrated security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>

Add commerce Element

<commerce>
    <runtimeConfiguration componentsConfigurationFile="Components.config" enableCache="false" cacheProvider="" />
</commerce>

With all that in place your App.config file should look like this

<configuration>
    <configSections>
        <sectionGroup name="commerce" type="System.Configuration.ConfigurationSectionGroup">
            <section name="runtimeConfiguration" type="UCommerce.Infrastructure.Configuration.RuntimeConfigurationSection, UCommerce.Infrastructure" />
        </sectionGroup>
    </configSections>
    <connectionStrings>
        <add name="ucommerce" connectionString="Data Source=(local);Initial Catalog=Umbraco;integrated security=SSPI;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <commerce>
        <runtimeConfiguration componentsConfigurationFile="Components.config" enableCache="false" cacheProvider="" />
    </commerce>
</configuration>

Add Configs to Application Folder

Components.config holds information about all the various subsystems in uCommerce. Copy Components.config and Marketing.config from the website folder you installed Umbraco and uCommerce in, e.g. c:\inetpub\Umbraco\uCommerce\Configuration and copy them to your app folder.

Modify Components.config to Work Outside Web Context

The configuration files assume a web context so we’ll have to update them to work in a non web environment. Open up Components.config in your favorite editor and modify any life cycle with a value of “PerWebRequest” to “Thread”.

This tells uCommerce to create an instance of the object once per thread as opposed to once per request, which oviously doesn’t make sense for what we’re trying to do.

Do the same for Marketing.config if you intend to use that in your application.

Remove Includes in Components.config

Be sure to remove includes in components.config, which refer to Presenters.config and XmlRenderings.config.

Summary

Leveraging uCommerce outside a web site makes for some interesting use cases. Foremost is automated integration with other systems, but you could use this method to establish an offline Point of Sale or Kiosk-type system with a completely different frontend done in Windows Presentation Foundation for a rich in store experience.

posted on Wednesday, 03 August 2011 14:05:37 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, 07 June 2011

FoundationWhen we first conceived of uCommerce years ago there was no uCommerce HQ and no real plan for what uCommerce should become. When time came to choose a data access layer we went the RAD route and chose Subsonic for its productivity benefits. Since then Subsonic has been a blessing and a course.

A blessing because it got us off the ground rapidly as intended and it introduced some pretty cool concepts to the uCommerce API such as LINQ based Active Record.

What really hurt was the complete lack of options for tuning queries for optimum performance. Subsonic is great for throwing together custom queries, but is rather lacking in projecting the needed result into an existing model. Basically this means lots of lots of lazy loading, which hurts performance badly due to the many tiny SQL queries being issued to the database.

Thus we decided to switch to a more full featured ORM and the natural choice at the time was NHibernate.

NHibernate has been present in uCommerce since the very early days. In fact it was introduced in uCommerce 1.0.2 to improve performance when querying the catalog via the XSLT API. We’ve slowly migrated bits and pieces of uCommerce to NHibernate where it made sense over the years.

uCommerce 2.0

During the past two years we’ve kept uCommerce backwards compatible with previous versions to make it simple to upgrade to new versions of uCommerce. With version 2.0 we didn’t really have that option anymore as we reached the end of what was possible to achieve internally so we decided to migrate the final uCommerce .NET APIs to EntitiesV2 and NHibernate.

What this means for you and existing code written against UCommerce.Entities, UCommerce.Runtime, and  UCommerce.Pipelines will have to be migrated to UCommerce.EntitiesV2.

The following article describes changes required to make your code run against the new API. Completing the migration will give you several benefits:

  • A clearer API to work with
  • Less code to write
  • Better performance
  • Caching support
  • Single programming model for everything

Ids vs Entities

One of the common patterns you see in Subsonic is the use of id properties to tie object together. This is not possible in NHibernate, which has a more entity focused approach.

NHibernate moves the responsibility of handling the association to the “aggregate root” or in other words to the more logical owner of the child object, e.g. the order handles order line.

Subsonic

var purchaseOrder = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder();
var orderLine = new OrderLine();
orderLine.OrderId = purchaseOrder.OrderId;
orderLine.Save();

NHibernate

var purchaseOrder = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
var orderLine = new OrderLine();
// Notice that the purchase order is responsible for handling the operation
purchaseOrder.AddOrderLine(orderLine);
purchaseOrder.Save();

Three things are worth nothing here:

  1. We’re not setting any ids. It’s all handled behind the scenes by NHibernate.
  2. The order line is added via the AddOrderLine() method, which is a very common pattern in EntitiesV2.
  3. The purchase order is responsible for saving both the order itself and the order line.

Simple Deletes

More often than not you don’t want to delete an entire aggregate, but just a portion of it. Subsonic and NHibernate deal with this is different ways.

Subsonic

var orderLine = OrderLine.All().Single(x => x.OrderLineId == orderLineId);
orderLine.Delete();

NHibernate

var orderLine = OrderLine.All().Single(x => x.OrderLineId == myOrderLineId);
var purchaseOrder = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
// Notice the RemoveOrderLine patterns. Use it whenever you can to delete.
purchaseOrder.RemoveOrderLine(orderLine);
purchaseOrder.Save();

As you can see the order is still responsible for handling the delete of the order line. You simply remove the order line from the order with the RemoveOrderLine() method and it will get deleted automatically when the order is saved. Because the operations are not actually carried out until the Save is issued you get the benefit of bulk operations because they will be batched together once you save.

If you don’t use the method, but go the orderLine.Delete() route instead, you’ll often see the following error message, “deleted object would be re-saved by cascade (remove deleted object from associations)[UCommerce.EntitiesV2.OrderLine#2] ==> RemoveEntity”. This happens because the loaded order has a reference to the object and would re-save it to the database.

Deep Deletes

In Subsonic the pattern for deleting an object is very straightforward: You simply go order.Delete(). The issue with Subsonic is that it has no knowledge of relationships between objects so in many cases simply deleting an order would cause a SQL error because other data would be related to the order like order lines, properties, customer, shipments, addresses, etc.. So you have to know about these related objects and the order in which to delete them. Not very user friendly.

Subsonic

var purchaseOrder = PurchaseOrder.All().Single(x => x.OrderId == myPurchaseOrderId);
OrderAddress.Delete(x => x.OrderId == myPurchaseOrderId);
Shipment.Delete(x => x.OrderId == myPurchaseOrderId);
OrderProperty.Delete(x => x.OrderId == myPurchaseOrderId);
OrderLine.Delete(x => x.OrderId == myPurchaseOrderId);
// etc.
purchaseOrder.Delete();

NHibernate

var purchaseOrder = PurchaseOrder.All().Single(x => x.PurchaseOrderId == myPurchaseOrderId);
purchaseOrder.Delete();
// simple, no? :)

NHibernate is smart enough to know about the relationships between objects, so it’ll go ahead and delete related objects where it makes sense so you don’t have to think about it. These are called cascades and it’s the same mechanism, which ensured that our order line got saved in the previous example.

One to One Relationships

An interesting design decision with Subsonic is that it doesn’t expression one to one relationships, e.g. PurchaseOrder has one Customer. Instead Subsonic will treat all relationships as many to many, e.g. PurchaseOrder has many Customers, which makes sense from an ORM implementation point of view, but is very confusing for a developer trying to use an API built on this approach.

Of course NHibernate lets us map data exactly the way we want, which makes the API so much cleaner and simple to understand.

Subsonic

var purchaseOrder = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
// You have to know that there's only a single customer in the database explicitly.
var customer = purchaseOrder.Customers.Single();

NHibernate

var purchaseOrder = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
// With NHibernate the customer is mapped properly
var customer = purchaseOrder.Customer;

Many to Many Relationships

While Subsonic defines everything as a one to many relation it’s not so great a handling many to many relations. Typically these are implemented with a relation table to go between object A and B, like in the case of a category and product relationship where the same product might be present in multiple categories. Subsonic will map the go-between and require more code to handle the relationship.

Subsonic

// Grab a random product and category
var product = Product.All().First();
var category = Category.All().First();
 
// Create the relationship
var categoryProductRelation = new CategoryProductRelation();
categoryProductRelation.ProductId = product.ProductId;
categoryProductRelation.CategoryId = category.CategoryId;
categoryProductRelation.Save();

NHibernate

// Grab a random category and product
var category = Category.All().First();
var product = Product.All().First();
// Simply add the product to the category and you're done
category.AddProduct(product);
category.Save();

As you can see NHibernate completely eliminates the requirement to create the relation object yourself. It will handle the intricacies of the relationship behind the scenes for you.

LINQ to uCommerce

With the switch to NHibernate LINQ to uCommerce will gain new options as well. The most obvious change is that you can get away with writing less code than today when doing joins. In many cases you can even get rid of the join altogether.

Subsonic

var query = from product in Product.All()
            join categoryRelation in CategoryProductRelation.All() on product.ProductId equals categoryRelation.ProductId
            join category in Category.All() on categoryRelation.CategoryId equals category.CategoryId
            where category.Name = "My Category"
            select product;

NHibernate

var query = from category in Category.All()
            join categoryRelation in CategoryRelation.All() on category equals categoryRelation.Category
            join product in Product.All() on categoryRelation.Product equals product
            select product;
// Notice that ids are omitted from the query

Summary

As you can see there are significant changes between the Entities and EntitiesV2 APIs, but rest assured that migrating to the newer API is very straightforward. uCommerce Admin, which is a pretty significant codebase written entirely against the Entities API was migrated to EntitiesV2 in three days straight including testing. The benefits we’ve seen from the migration are significant. UIs are more responsive, code required to do a certain operation is clearer, and more often than not there’s less of it.

posted on Tuesday, 07 June 2011 11:38:33 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Wednesday, 18 May 2011

Baskets, carts, bags, whatever you want to call them, people have very different expectations of how they should work given the business they’re in. By default uCommerce uses cookies to find the basket for a given customer, which is handy because the basket automatically carries over if the customer logs in. No need to migrate it from an anonymous context to a customer context.

But what if you have scenario where multiple people use the same computer to shop from? Effectively they’d share the same basket because it’s effectively tied to the computer, not the customer.

Fortunately the uCommerce Foundation API makes it simple to override this behavior. So lets take a look at what’s required to change the default basket behavior.

IOrderContext

uCommerce uses the IOrderContext interface to determine the basket of the current customer, specifically the GetBasket() and GetBasket(Boolean) methods are used. Let’s take a look at what the IOrderContext interface contains.

image

To make things are little easier we’re not going to implement IOrderContext from scratch, rather we’ll modify the default implementation, which comes with uCommerce called OrderContext.

OrderContext

As mentioned we’re looking to change the behavior of loading a basket for a customer and OrderContext has two methods for this purpose: GetBasket() and GetBasket(Boolean). Basically what we’re going to do is use the default behavior when a customer is not logged in and use our custom behavior whenever a customer is logged in.

Overriding GetBasket(Boolean)

First we need a new class to inherit the existing OrderContext and second override the two GetBasket methods.

using System;
using System.Linq;
using UCommerce.Entities;
using UCommerce.Runtime;
using umbraco.cms.businesslogic.member;
 
namespace MyUCommerceApp.Library
{
    public class MyOrderContext : OrderContext
    {
        protected ICatalogContext CatalogContext { get; set; }
 
        public MyOrderContext(ICatalogContext catalogContext) : base(catalogContext)
        {
            CatalogContext = catalogContext;
        }
 
        public override Basket GetBasket(bool create) {}
 
        public override Basket GetBasket()
        {
            return GetBasket(false);
        }
    }
}

So right now it doesn’t do much, so lets make it behave like the existing OrderContext when a customer is not logged in. We’re going to use the Umbraco Member API to determine whether a customer is logged in.

using System;
using System.Linq;
using UCommerce.Entities;
using UCommerce.Runtime;
using umbraco.cms.businesslogic.member;
 
namespace MyUCommerceApp.Library
{
    public class MyOrderContext : OrderContext
    {
        protected ICatalogContext CatalogContext { get; set; }
 
        public MyOrderContext(ICatalogContext catalogContext) : base(catalogContext)
        {
            CatalogContext = catalogContext;
        }
 
        public override Basket GetBasket(bool create)
        {
            // Member is not logged on use default behavior
            if (!Member.IsLoggedOn()) return base.GetBasket(create);
        }
 
        public override Basket GetBasket()
        {
            return GetBasket(false);
        }
 
    }
}

Now we’re actually detecting whether the customer is logged in and use the default behavior of OrderContext for customers not logged in.

Right now that means that the code is going to fail if a customer logs in, so lets add the final piece where we load the basket basket based on the current member id. If we can’t find a basket like that we’ll have to create one. Here we go.

using System;
using System.Linq;
using UCommerce.Entities;
using UCommerce.Runtime;
using umbraco.cms.businesslogic.member;
 
namespace MyUCommerceApp.Library
{
    public class MyOrderContext : OrderContext
    {
        protected ICatalogContext CatalogContext { get; set; }
 
        public MyOrderContext(ICatalogContext catalogContext) : base(catalogContext)
        {
            CatalogContext = catalogContext;
        }
 
        public override Basket GetBasket(bool create)
        {
            // Member is not logged on use default behavior
            if (!Member.IsLoggedOn()) return base.GetBasket(create);
 
            // Otherwise try and load a basket for the current member, create one if it doesn't exist
            Basket basket = GetBasketForCurrentMember() ?? CreateBasket();
 
            return basket;
 
        }
        public override Basket GetBasket()
        {
            return GetBasket(false);
        }
 
        private Basket GetBasketForCurrentMember()
        {
            PurchaseOrder order = PurchaseOrder.SingleOrDefault(
                x => x.OrderProperties.Where(y => y.OrderId == x.OrderId && y.Key == "MemberId" && y.Value == Member.CurrentMemberId().ToString()).Count() > 0 
                    && x.OrderStatusId == 1);
 
            if (order != null) return new Basket(order);
 
            return null;
        }
 
        private Basket CreateBasket()
        {
            var catalogId = 0;
            int.TryParse(CatalogContext.CurrentCatalogName, out catalogId);
 
            var catalog = ProductCatalog.SingleOrDefault(c => c.Name.Equals(CatalogContext.CurrentCatalogName)) ??
                ProductCatalog.SingleOrDefault(c => c.ProductCatalogId == catalogId);
 
            if (catalog == null)
                throw new InvalidOperationException("Cannot create basket when not in product catalog. Make sure that SiteContext.Current.CatalogContext.CurrentCatalogName contains the name of the current product catalog.");
 
            return CreateBasket(catalog.PriceGroups.First().Currency);
        }
 
        private Basket CreateBasket(Currency currency)
        {
            var catalogGroup = ProductCatalogGroup.SingleOrDefault(g => g.Name.Equals(CatalogContext.CurrentCatalogGroupName));
 
            if (catalogGroup == null)
                throw new InvalidOperationException("Cannot create basket without product catalog group. Make sure that SiteContext.Current.CatalogContext.CurrentCatalogGroupName contains the name of the current product catalog group.");
 
            PurchaseOrder order = new PurchaseOrder();
            order.OrderStatusId = 1;// (int)PurchaseOrder.StatusCode.Basket;
            order.ProductCatalogGroup = catalogGroup;
            order.CurrencyId = currency.CurrencyId;
            order.BasketId = Guid.NewGuid();
            order.CreatedDate = DateTime.Now;
            order.Save();
 
            // Set the member id on the order so we can retrieve it later on
            order["MemberId"] = Member.CurrentMemberId().ToString();
 
            return new Basket(order);
        }
    }
}

The thing that makes the code above tick is the used of dynamic order properties. Basically a way of setting custom data on the order or individual order lines. Whenever a new basket is created by MyOrderContext it will store the current member id on the order itself and use that to load the basket the next time around.

Registering MyOrderContext with uCommerce

To test our new context class we’ll have to let uCommerce know it exists. The way to do this is to edit the components.config file, which holds information about all the components of uCommerce. You’ll the file in /umbraco/ucommerce/configuration/components.config and this is what it looks like.

image

We’re looking for the IOrderContext registration.

image

A registration basically refers to a service, typically an interface like IOrderContext, a type, which is the actual implementation to use for that particular interface, and a lifestyle, which is how long the object will live. You can read more about lifestyle if you’re interested, but for now just leave that attribute alone.

We’ll have to put in our type and assembly for IOrderContext. For this example my code compiles to MyUCommerceApp.Library.dll and the type is called MyUCommerceApp.Library.MyOrderContext, so that’s what we’re going to swap in to replace the current order context.

<component id="OrderContext"
    service="UCommerce.Runtime.IOrderContext, UCommerce"
    type="MyUCommerceApp.Library.MyOrderContext, MyUCommerceApp.Library" lifestyle="PerWebRequest"/>

What that we’re ready to test our site. The behavior you’ll see is that you’ll get one basket when you’re not logged in, the default behavior, and another basket when you log in, our new custom behavior.

In Summary

As you can see overriding the default basket behavior of uCommerce is straightforward and you can achieve exactly the behavior you want. You saw a couple of interesting pieces put together to make it work: The IOrderContext and OrderContext, which were overridden to inject our custom behavor, the dynamic order property for storing our member if, and finally the component registration to tell uCommerce about our custom component.

Components in particular is a useful thing to know about as there are many opportunities to override the default behavior almost any aspect of uCommerce in there.

Other interesting examples for overriding GetBasket() might be to:

  • Do individual baskets between stores when working with a multiple store setup in the same uCommerce installation to replace the default shared baskets.
  • Work with multiple baskets per customer for wishlist and gift registry scenarios.
  • Support impersonation to enable a customer representative take over the customer basket to help her through checkout.

The sky’s the limit.

posted on Wednesday, 18 May 2011 10:33:33 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, 10 March 2011

image

uCommerce 1.5 introduces nice URLs for catalogs, categories, and products. The basic idea is to provide keyword rich URLs for catalog items to increase page rank in search engines like Google and Bing. Really though, who are we kidding here? It’s just for Google  :)

Based on Existing Catalog Information

To keep maintenance low uCommerce generates URLs based on information already present in the catalog. To support multilingual sites display names are used when present otherwise standard internal names are used. This gives webshops built with uCommerce the ability to rank on search terms specific to the culture the online store services, e.g. English terms for English stores, Spanish terms for Spanish stores, etc..

URLs are structured in three parts:

  1. The domain name, which also determines the language to use as per Umbraco hostname
  2. The search engine friendly soft middle
  3. And finally the payload at the end, which enables uCommerce to figure which type of URL it’s dealing with

For a sample URL like www.myonlinestore.com/apparel/c-24 the three pieces are:

  1. “www.myonlinestore.com” – domain name of the store as set up in Umbraco
  2. “apparal” – search engine search term
  3. “c-24” – identifier of the catalog for uCommerce to use

Basically Umbraco and uCommerce only need the first and last pieces while the rest is all for Google.

Nice URLs from XSLT

To start using nice URLs in your own uCommerce solution you’ll need to use one of the following XSLT extensions:

GetNiceUrlForCatalog(string catalogName)
GetNiceUrlForCategory(string catalogName, string categoryName)
GetNiceUrlForProduct(string catalogName, string categoryName, string sku)
GetNiceUrlForProduct(string catalogName, string sku)
GetNiceUrlForVariant(string catalogName, string sku, string variantSku).

There are multiple extensions for each type of URL you’ll generate as they have slightly different needs for the final result. The method will generate the following URLs:

Catalog called “Apparel”

<xsl:variable name="catalogUrl" select="CommerceLibrary:GetNiceUrlForCatalog('Apparel')"/>

www.myonlinestore.com/apparel/c-24

Category called “T-shirts” nested in “Shirts” / “Men”

<xsl:variable name="categoryUrl" select="CommerceLibrary:GetNiceUrlForCategory('Apparel', 'TShirts')" />

www.myonlinestore.com/apparel/shirts/men/t-shirts/c-24/c-71

Product “Short sleeved green t-shirt

<xsl:variable name="categoryUrl" select="CommerceLibrary:GetNiceUrlForProduct('Apparel', 'TShirts', 'Green-TShirt')" />

www.myonlinestore.com/apparel/shirts/men/t-shirts/short-sleeved-green-t-shirt/c-24/c-71/p-107

<xsl:variable name="categoryUrl" select="CommerceLibrary:GetNiceUrlForProduct('Apparel', 'Green-TShirt')" />

www.myonlinestore.com/apparel/short-sleeved-green-t-shirt/c-24/p-107

Nice URLs from .NET

To generate those same URLs from .NET you’ll use the IUrlService. Using the ObjectFactory class you can resolve the configured instance for the interface. The default implementation is called UrlSerivce. More on that later.

IUrlService urlService = ObjectFactory.Instance.Resolve<IUrlService>();
 
ProductCatalog catalog = ProductCatalog.SingleOrDefault(x => x.Name == "Apparel");
string catalogUrl = urlService.GetUrl(catalog);
 
Category category = Category.SingleOrDefault(x => x.Name = "TShirts");
string categoryUrl = urlService.GetUrl(catalog, category);
 
Product product = Product.SingleOrDefault(x => x.Sku == "Green-TShirt" && x.ParentProductId == null);
string productIncludingCategoryInfoUrl = urlService.GetUrl(catalog, category, product);
string productUrl = urlService.GetUrl(catalog, product);

Building Your Own Nice URLs

image

If you wish to customize the default nice URLs you can go ahead and inherit the class UrlService and override any methods you’re not happy with. Should you need to replace the default nice URLs generated by uCommerce you can implement the IUrlService interface from scratch.

If for instance you need complete control over the keywords added to the URL your custom implementation might grab information not from the display name, but from a dedicated field on the category or product.

In any case you have to register your custom implementation via /umbraco/ucommerce/configuration/components.config. Just look for the existing registration of IUrlService.

URL Rewrite Rules

UrlRewriting.NET contains the set of rules, which define what URL the customer sees and what that URL should look like to the system.

You will not have to change the existing rules even if you implement your own UrlService as long as you keep the last part of the URL the same, i.e. the /c-xx/c-yy/c-zz part. This is the marker used for the rules to pick up a rewritten URL so you can include anything before that part. If you don’t want the marker as part of your URL you’ll have to modify the default rules.

Each rule is automatically deployed when uCommerce is installed and is found in /config/UrlRewriting.config in your website folder. If you wish to modify the default rules this is the place to do it.

Summary

Nice URLs help the search engine optimization process for webshops built with uCommerce and will make pages in your webshop rank higher. Any URL scheme is supported by overriding the default implementation found in UrlService.

posted on Thursday, 10 March 2011 22:32:35 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Thursday, 03 March 2011

Probably the most interesting new feature to come to Umbraco lately (for .NET developers anyway) is support for the Razor view engine. The Razor view engine was originally (sounds like it was year ago when in fact it only happened recently) introduced with MVC 3 to reduce friction when writing UI code.

XSLT, .NET, or Both

NET-logoXSLTOne of the first questions I’m asked when I demo uCommerce to new partners is, “should we use XSLT or .NET user control to build our uCommerce sites”.

My advice over the past couple of years has always been to use XSLT for static listings and roll out .NET for the more dynamic pieces like the check out flow or advanced product pickers.

It’s no secret that my background in .NET makes me whip out Visual Studio for almost everything, but XSLT does have some interesting attributes like the ability to build out a UI in no time and reskin existing UIs rapidly. That’s why we built the uCommerce Demo Store in XSLT exclusively and that’s why I originally invested some time in getting to know it.

Now, however, my advice might be about to change. Read on and find out why.

Introducing Razor, Macros on Steroids!

The answer to make .NET devs as efficient creating UIs as XSLT gurus is Razor. While it won’t make developers better designers it will enable them to roll out UIs very rapidly and in a more fluent manner to boot.

The Razor view engine is basically an advanced parser, which enables you to write code much more fluently than what was possible with the WebForms view engine. Gone are the days of <%%> replaced by @.

Basically you can now write code like this in your macros and it will render properly inside your templates.

@using umbraco.cms.businesslogic.member
 
@if (Member.GetCurrentMember() != null)
{
    @string.Format("Hello there, {0}, nice to see you again!", Member.GetCurrentMember().LoginName)
}

And this is what it looks like in Umbraco itself. Pretty straightforward, right? Create a new script file using CSHTML and then create a new macro, select the script you created previously, and you’re good to go.

image

image

uCommerce and Razor: Product Listing

So how does this work with uCommerce? As it turns out, quite well. The Active Record pattern combined with LINQ to uCommerce turns out to be a perfect fit for the Razor coding style. Lets see what it takes to get some products into the mix, shall we?

It’s very straightforward: Import the uCommerce entities and query away!

@using UCommerce.EntitiesV2
 
@foreach (var product in Product.All())
{
    <h1>@product.Name</h1>
}

image

Not surprisingly, the code produces the following result.

SNAGHTML1769ec5

But what’s with the 5, 10, and 15? Turns out that the list contains both product, product families, and variants. Lets expand on the query a bit and only display the top level products and families.

Notice how the following query now has a Where clause on the call. What we’re doing is filtering the result to only grab the products we want. See how easy that is? Common operations like filtering, grouping, and even joining is supported which opens up for some very interesting scenarios.

@using UCommerce.EntitiesV2
 
@foreach (var product in Product.All().Where(x => x.ParentProductId == null))
{
    <h1>@product.Name</h1>
}

SNAGHTML1704eb3

Simple Basket Page

How about another one just for kicks? What’s interesting here is that we’re leveraging the context aware API of uCommerce to determine the basket given the current customer. Because the API deals with context you don’t have to worry about getting the right data, it’s just there ready to be consumed.

@using UCommerce.Runtime
 
<table>
    <th>SKU</th><th>Name</th><th>Qty</th><th>Unit Price</th><th>Total</th>
    @foreach (var orderLine in SiteContext.Current.OrderContext.GetBasket().PurchaseOrder.OrderLines) 
    {
        <tr>
            <td>@orderLine.Sku</td>
            <td>@orderLine.ProductName</td>
            <td>@orderLine.Quantity</td>
            <td>@orderLine.Price</td>
            <td>@orderLine.Total</td>
        </tr>
    }
</table>

Again the code above is a full Razor macro in Umbraco, which is placed on a template to achieve the output below. With that we’ve got the beginnings of basket overview page. See how clean that is?

SNAGHTML30278e6

Summary

While Razor was introduced in Umbraco 4.6 it’s not really until 4.7 it’s become really usable. In testing uCommerce with Umbraco 4.7 I found the combination of Razor and LINQ to uCommerce to work surprisingly well. The flow inherent in Razor is carried over to the uCommerce API. As a result the code flows naturally just the way we like it.

With Razor .NET developers start to see the same level of productivity which has been exclusive to the XSLT gurus when creating UIs. Not only that but the UI code is very readable and the full .NET framework is available without having to resort to XSLT extensions as is the case with XSLT today.

posted on Thursday, 03 March 2011 22:05:36 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Wednesday, 02 March 2011

Social commerce is all about customers engaging each other helping online stores and webshops sell more by leveraging the high degree of credibility inherent in personal recommendations and getting the word out to a wider audience. Social commerce is available in many guises: At uCommerce we tend to think about it as internal- and external social commerce.

Reviews, Ratings, and Comments

The very first step in adopting social commerce is to enable customers to post reviews. As such we’re dealing with internal social commerce as everything happens in the webshop and doesn’t involve interaction with sites like Facebook and Twitter.

Even in online stores stores with product lines changing frequently there’s value to adding reviews to products as customers tend to skip past product information and dive straight into the user generated content to see whether or not a product is worth any further the attention.

Product Ratings

When a customers look at product information the very first thing that will catch her eye is the star rating of a product. uCommerce enables customers to post ratings. Each rating is aggregated into an average rating stored on each product, which can be used for searches, filtering, and custom product listings like “Most popular in this category”.

Ratings with no additional content require no approval and will be aggregated into the overall score by default. This behavior can be overridden by modifying the Product Review Pipeline.

Star Ratings in Google Search Results

Product review in Google Search

When searching for products online which link would you be more inclined to click? The one with no star rating or the one with star rating?  When searching on Google and Bing you’ve probably noticed that some search results are displayed with a star rating. This helps your search results stand out in the crowd and will bring in new customers.

The uCommerce Store supports this out of the box by leveraging a micro format that Google and Bing recognizes and will display as part of the search result bring more “foot traffic” into the webshop.

Product Reviews

SNAGHTML49abd9

uCommerce enables customers to add product reviews on individual products and submit them either directly to the site or, if enabled, for approval by store managers. Product reviews consists of a rating, a review headline, and a review body. If a customer is logged in the review can optionally be associated with that particular customer, which will make the reviews even more effective by letting you display information about the reviewer such as the first name. More on that later.

Because uCommerce supports multiple stores and languages each product review is associated with the store in which it was received, which makes it possible to display just the reviews received in a particular store.

Of course you’ll want to get as much review bang for your buck so more often than not reviews will be displayed from all stores, but you do have a choice.

SNAGHTML77c350

Comments and Helpful Reviews

SNAGHTML815d1fSNAGHTML7f7061SNAGHTML95d9ec

To further improve the value of having product reviews on a webshop you can open up for comments on existing reviews. The simplest form of commenting on a review is to indicate whether or not it was helpful, but the customer can go ahead and add a text comment as well to further explain her position or ask questions of the reviewer to get the conversation going.

Customer Information

As you can see in the previous screenshots information about the customer adding content is added to the review or comment. Customers are integrated with site members so you’re effectively free to add as much additional information to the customer profile and by extension the reviews themselves.

Optionally you can require the customer to log in before being able to comment as is the case on Amazon.com or just leave the floodgates open and let anyone comment if they provide an e-mail, which leads us to the next topic: Reporting Abuse.

Reporting Abuse

SNAGHTML9746c2

The internet can be a downright nasty place with scammers and spammers in abundance. When a site opens up to user generated content it better be prepared to deal with spam. Fortunately uCommerce supports multiple kinds of protection. You can enable customers to report abuse and thus bring any unsuitable content to your attention for approval. Abuse can be reported for both reviews and individual commets.

By default content reported as spam is still displayed on the site to prevent users from removing content from the site until it can be reviewed and approved. If content is to be removed from the site immediately you can do so as well by modifying the filters for user generated content which is not to be displayed.

Approval Workflow

SNAGHTML990bc5SNAGHTML9930b3

Once user generated content is reported as abuse it will show up in the administration backend where store owners and managers approve or unapprove content.

The approval workflow is available both on the product level and more importantly on the store level as well to make sure that the process of approving reviews is as efficient as possible. Reviews can be removed at any time at the store manager’s discretion.

When viewing the “Pending Reviews” tab on each store only reviews and comments, which require attention are displayed. While everything is displayed on the product level.

Should you want to have all reviews and comments screened before allowing them onto your website, you can indicate so on each of the stores by ticking the “Product reviews require approval” check box.

SNAGHTML9aa382

Automatic Workflow via Pipelines

As new ratings, reviews, and comments are received they are processed by uCommerce Pipelines, which enables automatic steps to be carried out for each piece of user generated content. Developers can extend these pipeline with custom logic to support custom requirements.

To give you an idea of what can be done using the pipelines here are some ideas:

You might want to check whether the customer has submitted a high number of reviews inside a short timeframe, which might indicate a spammer or you could notify store managers whenever new content requires attention.

This is also true whenever content is approved or unapproved in the backend. You might want to send an e-mail to the customer who submitted the review when it’s approved so they can see their handiwork on your site (thus bringing back the customer to the store) or you could post teasers from reviews on your Facebook fan page or to Twitter.

Please see uCommerce Pipelines Explained for detailed information on extending the Product Review and Product Review Comment pipelines.

Summary

Social commerce is many things to many people, but in the end a good place to start is by opening up for user generated content like ratings, reviews, and comments on your e-commerce site to increase conversion rates. Keep in mind that while user generated content will help sell more there are caveats associated with it. It’s important to ensure that only proper content makes it onto your site either by using an approval workflow like the one previously described, by requiring user login to be able to review, or by letting customers report abuse.

posted on Wednesday, 02 March 2011 11:15:03 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Thursday, 10 February 2011

One of my favorite features of uCommerce is the extensible framework lurking underneath the surface. Using the framework you have the opportunity to add, modify, or even completely the out of the box functionality of uCommerce. Shipping methods are no exception to this rule. Specifically you can build custom shipping method services to enable custom calculation of shipping costs during the checkout flow as discussed in Shipping Methods Explained.

This article covers adding a new shipping method service to uCommerce and having it show up the admin UI like so.

SNAGHTML9d935c

The Framework

Before you get into the nitty gritty of building your first custom shipping method service you’ll need a little background about the surrounding framework to understand what’s going on. Your shipping method service first needs to be configured in uCommerce via web.config (more on that later), once written the uCommerce pipelines will make sure and trigger your service when appropriate. By default shipping methods services are triggered in the Basket Pipeline by the task called CalculateShippingCostForShipments. If you’re interested in more information about pipeline please see the uCommerce Pipelines Explained article.

Notice that the tasks ends on Shipments plural. uCommerce supports multiple shipments per order and will call the proper shipping method service for each shipment based on the shipping method selected for it.

image

Pretty simple stuff. Now for the fun part: Writing your own shipping method service.

The IShippingMethodService Interface

image

This interface is what uCommerce uses to be able to calculate shipment costs. As you can see from the code it’s pretty simple. Basically you’ll receive the shipment as created using either the XSLT or .NET API and you’ll have the opportunity to loop through the relevant order lines, which are linked from the shipment. Lets see what’s involved to create a simple volume based IShippingMethodService.

Volume Based Shipping Method Service

Volume and weight based shipping pricing are probably the most common shipping scenarios for an online store so lets try and build one of them as an example. First you’ll need to create a new Visual Studio project and add a reference to the UCommerce.dll assembly. You will also need a reference to the Subsonic.Core.dll assembly. With that in place you’re ready to start implementing the service.

The Methods and Properties

image

As you can see you just need to implement two methods and a single property to get it going. The names of the methods should make it fairly obvious what they’re for. ValidateForShipping might require some explanation. As discussed in Shipping Method Explained each shipping method can be configured to available only to certain stores and for shipment only to certain countries. The ValidateForShipment enforces these rules. If you just need an unrestricted shipment you can go ahead and always return true, but be aware that users might be confused if they set up a shipping method in one way but it doesn’t actually check for the conditions thus behaving differently from what they expect.

CalculateShippingPrice Method

First up lets calculate the shipping price for the shipment:

public Money CalculateShippingPrice(Shipment shipment)
{
    // First sum up the total weight for the shipment.
    // We're assumning that a custom order line property 
    // was set on the order line prior when the product was added to the order line.
    decimal totalWeight = 0;
    foreach (OrderLine orderline in shipment.OrderLines)
        totalWeight += orderline.Quantity * Convert.ToDecimal(orderline["Weight"]);
 
    decimal shippingPrice = 0;
    if (totalWeight > 10)
        shippingPrice = 100;
    else if (totalWeight > 20)
        shippingPrice = 200;
    else
        shippingPrice = 300;
 
    // To instantiate a new Money object we need the currency,
    // which is set on the purchase order. To get the currency
    // we move through Shipment -> OrderLines -> PurchasrOrder -> Currency
    return new Money(shippingPrice, shipment.PurchaseOrder.BillingCurrency);
}

Of course the business rule in this particular case is very simplistic, but you get the idea.

ValidateForShipping Method

Next up is the ValidateForShippingMethod, which is actually called prior to CalculateShippingPrice to validate that the shipping method is validate for the current purchase order. The SinglePriceShippingMethod which comes out of the box has rules to ensure that the shipping method has a shipping address set and that the shipment is set to be delivered to one of the allowed countries for the shipping method.

public bool ValidateForShipping(Shipment shipment)
{
    if (shipment.ShipmentAddressId <= 0)
        throw new InvalidOperationException("Cannot validate shipment for country. Remember to set the shipping address for shipment.");
 
    var shippingMethod = shipment.ShippingMethod;
    if (shippingMethod == null)
        throw new InvalidOperationException(
            "Cannot validate destination country for shipment. It does not contain a shipping method. Remember to add a shipping method to your shipment before validating.");
 
    return ValidateShippingDestination(shipment.OrderAddress,
                                shippingMethod);
}
 
/// <summary>
/// Validates the order lines according to their desired destination and configured contries for shipping method
/// </summary>
/// <returns></returns>
protected virtual bool ValidateShippingDestination(OrderAddress shippingAddress, ShippingMethod shippingMethod)
{
    var eligibleCountries = shippingMethod.GetEligibleCountries();
 
    // No eligible countries exist - so the shipment isn't valid
    if (eligibleCountries == null) return false;
 
    return eligibleCountries.SingleOrDefault(x => x.Country == shippingAddress.Country) != null;
}

Name Property

I probably should have started out with the easier of the member to implement, but Name ended up with the shortest straw and got to go last. Name will be set externally based on the name used when the shipping method service is configured in web.config, which incidentally is the next topic of this article.

public virtual string Name
{
    get;
    set;
}

VolumeShippingMethodService

With the name property implemented our VolumeShippingMethodService looks like this:

public class VolumeShippingMethodService : IShippingMethodService
{
    public Money CalculateShippingPrice(Shipment shipment)
    {
        // First sum up the total weight for the shipment.
        // We're assumning that a custom order line property 
        // was set on the order line prior when the product was added to the order line.
        decimal totalWeight = 0;
        foreach (OrderLine orderline in shipment.OrderLines)
            totalWeight += orderline.Quantity * Convert.ToDecimal(orderline["Weight"]);
 
        decimal shippingPrice = 0;
        if (totalWeight > 10)
            shippingPrice = 100;
        else if (totalWeight > 20)
            shippingPrice = 200;
        else
            shippingPrice = 300;
 
        // To instantiate a new Money object we need the currency,
        // which is set on the purchase order. To get the currency
        // we move through Shipment -> OrderLines -> PurchasrOrder -> Currency
        return new Money(shippingPrice, shipment.PurchaseOrder.BillingCurrency);
    }
 
    public bool ValidateForShipping(Shipment shipment)
    {
        if (shipment.ShipmentAddressId <= 0)
            throw new InvalidOperationException("Cannot validate shipment for country. Remember to set the shipping address for shipment.");
 
        var shippingMethod = shipment.ShippingMethod;
        if (shippingMethod == null)
            throw new InvalidOperationException(
                "Cannot validate destination country for shipment. It does not contain a shipping method. Remember to add a shipping method to your shipment before validating.");
 
        return ValidateShippingDestination(shipment.OrderAddress,
                                    shippingMethod);
    }
 
    /// <summary>
    /// Validates the order lines according to their desired destination and configured contries for shipping method
    /// </summary>
    /// <returns></returns>
    protected virtual bool ValidateShippingDestination(OrderAddress shippingAddress, ShippingMethod shippingMethod)
    {
        var eligibleCountries = shippingMethod.GetEligibleCountries();
 
        // No eligible countries exist - so the shipment isn't valid
        if (eligibleCountries == null) return false;
 
        return eligibleCountries.SingleOrDefault(x => x.Country == shippingAddress.Country) != null;
    }
 
    public string Name
    {
        get; set;
    }
}

Registering Your ShippingMethodService with uCommerce

Your custom shipping method service needs to configured with uCommerce so users are able to set up new shipping methods which use your code. This happens in web.config. When uCommerce is rolled out a number of configuration sections are added to web.config one of which called ordersConfiguration.

<ordersConfiguration>
    <shippingMethodServices>
        <add name="SinglePriceService" type="UCommerce.Transactions.Shipping.SinglePriceShippingMethodService, UCommerce" />
        <add name="VolumeShippingService" type="MyUCommerceApp.VolumeShippingMethod, MyUCommerceApp" />
    </shippingMethodServices>
    <paymentMethodServices>
        <add name="DIBS" type="UCommerce.Transactions.Payments.DefaultPaymentMethodService, UCommerce" />
    </paymentMethodServices>
</ordersConfiguration>

With the web.config updated you’ll now be able to select your new shipping method service in the UI:

image

Summing It All Up

Creating your own shipping method service to handle custom calculations takes as little effort as implementing two methods and a property. Once it’s registered with uCommerce users take over and set up the shipping method to their liking. Becuase your shipping method service is rolled into a separate assembly it’s very straightforward to share between projects.

If you’d lie more information about Shipping Method please take a look at the article Shipping Methods Explained.

posted on Thursday, 10 February 2011 22:26:29 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

imageThe wonderful world of shipping is truly a tangle of complicated business rules and pricing. At uCommerce we realized this long ago thus we do not try to supply every single shipping method known to man in the box. Rather we built a framework to allow you, dear developer, to build to specification whatever you need. Indeed this is at the very core of our Framework First methodology.

The Shipping Method

A shipping method in uCommerce consists of two discrete parts: data for presenting the shipping method to the customer and calculating costs and logic to calculate costs based on whatever is in each shipment for an order. uCommerce supports multiple shipments per order and your shipping method will have the opportunity to calculate different shippings costs based on whats in each shipment.

As you can see in the screenshot above a shipping method contains a bunch of different information.

Common Tab

image

All the base information for your shipping method like the name, which will be used in code as well as on shipments created with this particular shipping method.

The default payment method in cases where your shipping method is also a payment like Collect on Delivery.

For developers the Service drop down list is of particular interest as this is where you can hook into the shipping system with your own code to calculate shipping costs. More on that in a separate article.

Access Tab

image

When running a multi store set up it’s often handy to be able to set up different shipping methods for different stores and determine which countries each shipping method is available to ship to. The access tabs lets you do just that.Pricing Tab

Pricing Tab

image

Here you’ll set up the pricing for your shipping method. By default each shipping method can have individual pricing in each price group, which means that you differentiate pricing in multi currency scenarios or even for individual customers if they’re working with individual price groups. The pricing strategy can be overridden by creating a custom shipping method service, which is covered in another article.

Multilingual Tabs (English)

image

The final tabs covers the multilingual capability of uCommerce. Most areas in the admin UI will have multilingual tabs assigned to them. uCommerce will pick of the configured languages in Umbraco and display a multilingual tabs for each of them where appropriate. For shipping methods this means that you can set up information about each shipping method to match whatever language your customers speak.

Summing It All Up

As you’ve seen uCommerce shipping methods are very straightforward to set up. You can have multiple shipping methods configured and you decide which stores each of the shippings method are available to. For each shipping method you can either use the out of the box shipping providers or you can roll your own to match customer requirements exactly.

You might also be interested in reading Building a Custom Shipping Method Service for Calculating Shipping Costs.

posted on Thursday, 10 February 2011 20:59:43 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Friday, 17 December 2010

When you delete something in uCommerce it doesn’t really go away. Rather uCommerce employs soft deletes on various data objects, particularly in the catalog, to enable you to query historical data. e.g. for reporting purposes.

Some times however you’d like to clear test data from your catalogs and you need to get a little heavy handed to do it by going directly to the database and deleting the data.

Of course you have to observe the relations between existing data and delete in the proper order to avoid breaking constraints in the database. The uCommerce product is a rather complex collection of tables, which hold your custom properties, language variations, prices, relations to other catalog items such as other products and categories, which means that getting it right might be a little tricky.

image

Fortunately we already did the script for you and it goes a little something like this:

-- PLEASE NOTE: If you run this script against your uCommerce database all products and related data will be deleted.
-- There's no way to get it back unless you keep a database backup handy.
BEGIN TRANSACTION
DELETE FROM uCommerce_PriceGroupPrice
DELETE FROM uCommerce_ProductRelation
DELETE FROM uCommerce_CategoryProductRelation
DELETE FROM uCommerce_ProductProperty
DELETE FROM uCommerce_ProductDescriptionProperty
DELETE FROM uCommerce_ProductDescription
DELETE FROM uCommerce_Product
COMMIT TRANSACTION
posted on Friday, 17 December 2010 11:09:01 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Wednesday, 01 December 2010

The basic process of updating uCommerce from one version to another is straightforward when you’re running a default setup: You install the new package on top of the existing one and uCommerce will figure out what needs to be migrated.

Database updates are handled automatically and will roll you forward without incident. XML files on the other hand are a little more tricky to merge so instead of trying to merge them uCommerce will overwrite existing config files with newer versions to ensure that the config matches the rolled out binary version of uCommerce; exactly as Umbraco does. This means that If you customized any of the uCommerce configuration files you will have to reapply those changes.

Not to worry though uCommerce will back up the files before resetting them. You’ll find the older versions sitting next the orignal file with a .backup extension.

Most of the time getting your settings back is a simple matter of copying back the backed up version of your configuration files and you’re done. The steps for manually reregistering your settings are outlined below.

image

Web.config

Web.config is an interesting file because it’s used by Umbraco and uCommerce itself. During installation uCommerce merges its configuration with the existing web.config contents preserving any settings not owned by uCommerce, i.e. Umbraco, .NET, basically anything not known by uCommerce.

Connection Strings

During install the Umbraco connection string is picked up and added to the uCommerce configuration section to enable running uCommerce in a separate database. If you’re running with a separate database you need to point uCommerce at the other database once the update is complete.

SNAGHTML3968cdd

Payment Method Services

Any custom payment method services for integrating payment gateways need to be registered in web.config. If you’ve created your own payment method service you’ll have to remember to reregister it once the update is complete. If you’re using the built-in ones you can omit this step. It’s important that you use the same name for your custom payment method service when you reregister it.

Payment method services are found in the <commerce> <ordersConfiguration> <paymentMethodServices> section in web.config.

image

Individual Payment Method Service Configurations

Each payment method service built into uCommerce comes with a configuration file. As these files are rolled out as part of the standard package install process they’re overwritten when you install a newer version of uCommerce. As with any other file you’ll find your old version of the file sitting next to the new one with a .backup extension.

image

Pipelines

Pipelines are basically XML configuration files which control the tasks executed in each pipeline and the order of execution as well. If you’ve added your own pipeline tasks to the standard uCommerce pipelines Basket, Checkout, ToCompletedOrder, ToCancelled, or SaveOrder you’ll have to add your custom tasks again after updating.

You’ll find the pipelines in the /umbraco/ucommerce/pipelines folder.

image

Components.config, Presenters.config, and XmlRenderings.config

All major components of uCommerce are configured in a central XML file, which lets you override any of the default uCommerce behavior by configuring your own components. While this is not the most common extension point used you’ll still have to reregister your custom components if you’ve extended uCommerce in this fashion.

Also web.config contains a reference to components.config in the <commerce> <runtimeConfiguration> which has to point at the correct file.

Presenters.config and XmlRenderings.config are referenced by Components.config and contains config for the UI pieces of uCommerce. Specically the backend (Presenters) and the frontend (XmlRenderings).

Wrap Up

uCommerce makes it very easy to update an existing installation provided that you’re running with a standard configuration. There are a couple of things you need to be aware of if you’ve customized the standard configuration files. This check list will make it easy to ensure that you didn’t miss anything when you update your existing site with a newer version of uCommerce.

posted on Wednesday, 01 December 2010 14:14:29 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Tuesday, 30 November 2010

uCommerce comes with built-in support for SagePay payments. This guide will walk you through getting uCommerce to work with SagePay for payment processing. uCommerce integrates with SagePay using server integration.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “SagePay”.

image

Click the newly created node and select “SagePay” in the Service drop down list. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When done click “Save”.

image

That’s everything in the uCommerce interface.

Settings in SagePay Administration Panel

You can learn more about how to configure SagePay in the SagePage Help Centre.

Editing SagePay.config

Now we need to edit the SagePay.config file.

You will find the SagePay.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\SagePay.config”. Usually “rootdir” is c:\inetpub.

image

Finding vender

Vendor is the name you use when you login with SagePay.

image

Finding debug

Debug mode indicates whether you want to have an intermediate page show up with the values, which will be posted to the payment gateway.

Finding testmode

Testmode indicates whether your site is in simulation mode (SIMULATOR), test mode (TEST),  or running in production mode (LIVE).

Finding successUrl

URL the customer is redirected to once the payment is accepted.

Finding abortUrl

URL the customer is redirect to if she cancels payment authorization.

Finding FailureUrl

URL the customer is redirect to if the payment could not be authorized.

Finding notificationUrl

uCommerce will generate a callback URL for internal use. Leave the setting at (auto) unless you need to handle callbacks yourself.

Executing a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, you need to modify the database. If you used the name “SagePay” for the payment method name, you can run this SQL query in the SQL Server Management Studio.

UPDATE uCommerce_PaymentMethod SET Pipeline = 'Checkout' WHERE Name = 'SagePay'

or just edit it manually in SQL Server Management Studio.

image

Now the default pipeline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

Optional: Enable Acquire, Cancel, and Refund in uCommerce Back Office

To be able to acquire, cancel, and refund payments you need to enable two pipeline tasks in the ToCompletedOrder pipeline and ToCancelled pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

ToCancelled.config

image

ToCompletedOrder.config

image

FAQ

  • Testmode – Make sure test mode if turned off when going live.
posted on Tuesday, 30 November 2010 10:26:11 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for RBS WorldPay payments. This guide will walk you through getting uCommerce to work with RBS WordPay for payment processing.

Authorization is available for all plans with RBS WorldPay. If you wish to acquire (capture) or refund payments you need to mail: support@rbsworldpay.com and ask them to setup “Remote Admin”. At the moment it’s not possible to cancel an authorization with the “Remote Admin”.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “WorldPay”.

image

Click the newly created node and select “Worldpay” in the Service drop down list. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When done click “Save”.

image

That’s everything in the uCommerce interface.

Settings in WorldPay Administration Panel

Changes needed in the WorldPay administration panel, so it will work with uCommerce. Make sure when you are logged in that you are in “Production” mode or else you want to able to save the changes. If you can see the “Switch to Test” link on the picture below, you are in “Production” mode.

image

Edit Payment Pages

This out of scope for this guide, however World Pay offers lots of possibilities for customizing the results pages. You can read more about it here.

image

Instant capture

In Denmark it is not allowed to capture a payment before the order is shipped, so we need to turn this off. This can different in other countries.

Settings

· “Off” means you need to manually capture the payment.

· “0” Means instant capture.

· “1-14” are delay in days before the capture happens.

Changing the setting

· Click “Profile” in the menu to the left.

· Click “Configuration Details”

· Capture Delay: Set the value as accordingly.

· Click “Save”

image

General changes to the account

  1. In the menu to the left click “Installations” and you should get a list like the one below.
  2. Then click the “Edit” button that are on the same line as the text: “Select Junior”, this is the primary account.

image

Settings

  1. Payment Response URL.
    • Put the following text there without the quotes: “<wpdisplay item=MC_callback>”
  2. “Payment Response enabled?
    • Make sure it’s checked.
  3. Payment Response failure email address.
    • Write your email address here, if you want to receive email notifications, when an error occurs with the “Payment Response”
  4. Check the option “Attach HTTP(s) Payment Message to the failure email?” if you want detailed information attached to the email.
  5. Payment Response password.
    • A password of your choice. In the next section this is referred to as the “callbackPW”, please take a note of this.
  6. MD5 secret for transations.
    • Custom text of your choice. But less than 32 characters. This is referred to as the “Signature” in the next section, so please take a note of it.
  7. SignatureFields
    • Type the following text below without the quotes, or you will get an “Invalid MD5” signature when trying to make a authentication.
    • “instId:amount:currency:cartId:MC_callback”
  8. Click “Save” and you are done in this section.

WorldPay-control-panel

Editing the Worldpay.config File

Now we need to edit the WorldPay.config file.

You will find the WorldPay.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\WorldPay.config”. Usually “rootdir” is c:\inetpub.

image

Some of the below information are found in the WorldPay administration panel, so start by logging in you aren’t already.

Finding debug

If set it to “True” you will be prompted to click a button before posting the information to “WorldPay” otherwise it will do an autosubmit using Javascript. When running in production, you will want this set to “False”.

Finding testMode

Set this value to “True” when testing the integration with WorldPay. When going live set this value to “False”.

Finding instId

Click “Profile” in the menu. The “instId” is the number (normally 6 digits) in the red cirkel.

image

Finding callbackPW

This is the “callbackPW” from the previous section.

Finding callback

Leave this at “(auto)” if in doubt.

Optional: Finding remoteInstId and authPW

Click the “Profile” link in the menu to the left. Then you will see a screen like the one below.

  1. This is the remoteInstId and is normally 6 digits.
  2. This is the authPW, random digits and letters

image

Finding instantCapture

True/False weather instant capture is On or Off. If you choose “Off” in the instantCapture in the previously section, this values needs to be “False” otherwise “True”.

Finding key

This is just a text string of your choice. Recommended is just using random digits/letters.

Executing a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, you need to modify the database. If you used the name “WorldPay” for the payment method name, you can run this SQL query in the SQL Server Management Studio.

UPDATE uCommerce_PaymentMethod SET Pipeline = 'Checkout' WHERE Name = 'WorldPay'

or just edit it manually in SQL Server Management Studio.

image

Now the default pipeline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

Optional: Enable Acquire, Cancel, and Refund in uCommerce Back Office

To be able to acquire, cancel, and refund payments you need to enable two pipeline tasks in the ToCompletedOrder pipeline and ToCancelled pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

ToCancelled.config

image

ToCompletedOrder.config

image

FAQ

  • Testmode – Make sure test mode if turned off when going live.
  • I get the error message “Cannot find an available route for the purchase. This may be caused by merchant configuration or remote systems failures.”
    The error messages might mean a number of different things. One of the meaning that we encountered during test is that our transaction amounts were greater than GBP 5,000.
  • Acquiring a payment and immediately cancelling the same payment moves the order to “Requires Attention”
    RBS WorldPay employs a queuing system for handling payments which means that when uCommerce asks WorldPay to acquire a payment we immediately get back a response which indicates that all went well, but in actuality the transaction is queue for acquire on their end.
    If a transaction is cancelled immediately after the state on the uCommerce end is different from RBS WorldPay thus an error message is logged in the following form: “Refund failed >> N,-1,PMPPI.invalidStatus”.
posted on Tuesday, 30 November 2010 09:34:23 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, 29 November 2010

uCommerce comes with built-in support for PayEx payments. This guide will walk you through getting uCommerce to work with PayEx for payment processing.

Authorization, acquire (capture), refund, or cancel (void) are available for all plans with PayEx.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “PayEx”.

image

Click the newly created node and select “PayEx” in the Service drop down list. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When you are done click “Save”.

clip_image002[4]

That’s everything in the uCommerce interface.

Settings in PayEx Merchant Admin Panel

Changes needed in the PayEx Merchant Admin, so it will work with uCommerce.

Ip filter

1. Click ”Merchant profile”.

2. Type in the external ip address of the webserver running the shop.

3. Click “Save”.

clip_image003[4]

Merchant access list

1. Click “Merchant access list” in the menu to the left.

2. Click the “PxOrder.PxOrder” link, so it will be expanded and make sure the following is checked. If they aren’t checked, please contact PayEx support and get them to do it.

· Cancel2

· Complete

· Capture3

· Credit3

clip_image005[4]

Editing the PayEx.config File

Now we need to edit the PayEx.config file.

You will find the PayEx.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\PayEx.config”. Usually “rootdir” is c:\inetpub.

clip_image006[4]

Some of the below information are found in the PayEx Merchant Admin, so start by logging in you aren’t already.

Finding debug

If set to “True” you will be prompted to click a button before posting the information to “PayEx” otherwise it will do an autosubmit using Javascript. When running in production, you will want this set to “False”.

Finding testMode

This will most likely be a “False” unless you are using a test account.

Finding callbackUrl

Leave this at “(auto)” if in doubt.

Finding acceptUrl

Url the user is returned to after successfully authorizing her credit card.

Finding cancelUrl

Url the user is returned to if she cancels a purchase.

Finding accountNumber

1. Click “Merchant profile”.

2. Copy the “Merchant account” number.

clip_image008[4]

Finding key

The Md5 key is created in the administration panel.

1. Click “Merchant profile” in the menu to the left.

2. Click “New encryption key”.

clip_image009[4]

1. Copy the encryption key.

2. If you click “Save encryption key”, please note that it will overwrite the old one. It’s not possible to get the old key from the admin interface, so keep it in a safe place.

clip_image010[4]

Executing a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, you need to modify the database. If you used the name “PayEx” for the payment method name, you can run this SQL query in the SQL Server Management Studio.

UPDATE uCommerce_PaymentMethod SET Pipeline = 'Checkout' WHERE Name = 'PayEx'

or just edit it manually in SQL Server Management Studio.

clip_image012[4]

Now the default piplline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

Optional: Enable Acquire, Cancel, and Refund in uCommerce Back Office

To be able to acquire, cancel, and refund payments you need to enable two pipeline tasks in the ToCompletedOrder pipeline and ToCancelled pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

ToCancelled.config

clip_image014

ToCompletedOrder.config

clip_image016

FAQ

· Test mode – Make sure test mode if turned off when going live.

posted on Monday, 29 November 2010 13:59:52 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for Payer payments. This guide will walk you through getting uCommerce to work with Payer for payment processing.

Authorization is available for all plans with Payer. Payer don’t support remote acquire (capture), refund, or cancel of payments. When an authorization is made the payment is automatically captured and cannot be overridden using configuration. To refund a payment, you must use the Adminwebb.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “Payer”.

image

Click the newly created node and select “Payer” in the Service drop down list. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When you are done click “Save”.

image

That’s everything in the uCommerce interface.

Settings in Payer Administration Panel

Changes needed in the Adminwebb, so it will work with uCommerce.

Payment Methods

1. Click “Inställningar”.

2. Click ”Betalsätt”.

3. Make sure the top radio button is selected. If it’s not, select it.

4. Click the “Spare” button.

image

Debug options

1. Click “Inställningar”.

2. Click ”Allmänt”.

3. Make sure all three checkbox’s are unchecked, if not do it.

4. Click “Spara”.

image

Editing the Payer.config File

Now we need to edit the Payer.config file.

You will find the Payer.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\Payer.config”. Usually “rootdir” is c:\inetpub.

image

Some of the below information are found in the Adminwebb, so start by logging in you aren’t already.

Finding agentId, key1 and key2

In the compressed starting package, "Startpaket", you can find the Agent ID and the keys beneath the catalog "Resources", in the files called "PayReadConf.*".

Finding debug

If set to “True” you will be prompted to click a button before posting the information to “ePay” otherwise it will do an autosubmit using Javascript. When running in production, you will want this set to “False”.

Finding testMode

This setting must match the configuration in the Adminwebb. If you followed the steps in “Debug options” above, you should set this to “False”, indicating that we are running in production.

Finding callback

Leave this at “(auto)” if in doubt.

Finding acceptUrl

Url the user is returned to after successfully authorizing her credit card.

Finding cancelUrl

Url the user is returned to if she cancels a purchase.

Executing a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, you need to modify the database. If you used the name “Payer” for the payment method name, you can run this SQL query in the SQL Server Management Studio.

UPDATE uCommerce_PaymentMethod SET Pipeline = 'Checkout' WHERE Name = 'Payer'

or just edit it manually in SQL Server Management Studio.

image

Now the default piplline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

posted on Monday, 29 November 2010 13:57:02 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, 22 November 2010

Once in a while a question turns up in the uCommerce support forum which has me stumped for while. As usual with LINQ once the solution presents itself it turns out to be quite simple, dare I say elegant?

So what was the question again? We need a way to find all products present in number of categories as specified by a customer, think search. So we only want products present in both categories A and B, but not products only present in only one or the other.

Here’s how you’d do that:

// These are the categories our products must be present in
string[] categoryNames = { "Software", "Support" };
 
var query = from product in Product.All()
         where product.CategoryProductRelations.Where(x => categoryNames.Contains(x.Category.Name)).Count() == categoryNames.Count()
         select product;

The idea here is to first find all products for the categories we’re looking for. With that done we compare the number of categories found for each product with the number of categories we’re looking for (in our categoryNames array). If they match we’ve got he result we were after in the first place.

The cool thing about this query is that everything is translated to SQL behind the scene so the end result is very efficient execution of the query.

posted on Monday, 22 November 2010 11:59:22 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Wednesday, 17 November 2010

To lead off the documentation on how to build the various pieces of a uCommerce based e-commerce site I wanted to first describe what those components are. Having worked with a multitude of clients and projects in my previous career as an e-commerce consultant I’ve come to take many of these things for granted, but as uCommerce grows in popularity I’ve come to realize that while many has a firm grasp of what an e-commerce project entails others are just starting out with e-commerce for the first time.

Most, if not all, e-commerce solutions consist of the same overall systems as a prelude to documenting how to actually build these systems using uCommerce I’ll outline what they are and which role they play.

This series will cover browse, marketing, checkout, customer service, and order processing.

First up the browse  portion of your webshop project.

Bulk of the Traffic

The customers coming to an e-commerce site start out not as a customer but as casual user of your site trying to find a suitable product for their needs. More than 90% of the traffic coming to your site will take place in the browse pieces with users looking through catalogs, categories, and products so you’ll want to make sure that this piece is as efficient as can be.

Tell the Story

The browse flow is all about telling the story about the products and convincing the user to become a customer. This is where integration between Umbraco and uCommerce comes into the picture because you can use the two to tell a very convincing story indeed using product pages, articles, blog entries, and rich media to grab the user’s interest and engage them to convert.

Shop in Shop

A scenario growing more common is to offer shop in shop functionality in e-commerce sites. It might be a company offering to run the platform for other companies offering each their own store with custom look and feel and even custom checkout flow. This is commonly found in B2B projects.

On the B2C side of things shop in shop is commonly used to give separate brands individual sites, which cater specifically to the target audience of that brand or for putting together micro branding sites for campaign activities. This is the e-commerce equivalent of throw-away marketing sites that you’ve probably done a lot of already.

You’ll also encounter the B2B-B2C combo from time to time. In this scenario the client needs to offer a sites which caters both their B2B customers as well as the B2C customers. Requirements vary wildly between a B2B and B2C site so a nice way to structure such a solution is to simply set up to stores, which might share some of the same products, but pricing will differ for individual customers and one site might require login where the other does not.

Catalog Structure

catalog-bookAn important part of putting together the browse flows is to decide on a catalog structure. Do you need to support international sites? Will they need to have different catalogs with a different range of products?

The nice thing about catalog structure is that you can easily change it or even leave the structure entirely in the hands of your client. What you can’t leave in the hands in your client though is the task of describing the data, which goes into the catalog system AKA establishing the taxonomy of your product catalogs.

One of the very first exercises that you’ll do is try to figure out what a customer means why their talking about their products. Do they need to operate with or without variants? Are they using a combination of products and product families? What information will they need to maintain on the product level? Brand? Supplier? MSRP?

Key Pieces of Information

These are your key pieces of information that as a minimum you absolutely want to display as part of the browse flow: Product name, high resolution images, product description, price, and inventory status.

A nice rule of thumb is that whenever you display any of this information you need to remember to include a “Add to cart” button. After all that’s what we’re here for, right?

Product Listings

7productYou’ll spend most of your time creating various product listings and taking special care that categories are presented in the best way possible.

The simplest product listings are the ones which simply pull products based on the contents of a category, but that’s seldom enough as we discuss in the next paragraph.

Store owners spend a lot for time gathering product data and getting that data shaped into product information ready to present to potential customers. That’s why you’ll spend time creating custom listings based on the information available on each product, e.g. a custom listing which shows the latest additions in the store, all products on sale. This will help automate some aspects of the maintenance in the store.

Catalogs and categories are a great foundation on which to build and you’ll get a lot of mileage out of them if you use them creatively, but if you truly want to make your client happy you need to pay special attention to the automated listings.

Do keep in mind the cardinal rule: Whenever you display product information remember to also display an “Add to cart” button.

The Product Page

I keep wondering why people pay so much attention to the design of “The Front Page”? It seems that in many cases we’re locked into conventional thinking when it comes to web design. “The Front Page is the first page we see, so why not give it special attention?”. It turns out that on the web this is not the case. The front page will actually receive only a tiny fraction of your overall website traffic as close to 80% of incoming traffic will be organic traffic coming from search engines like Google and Bing.

With this in mind every page turns into a landing page on your site in which case it makes sense to focus on the pages that you have a lot off: Product pages.

When creating your product page template you’ll want to keep in mind that this might be the first page that the customer sees thus you can add information which pertains to the overall value of shopping with your online store. Free shipping on everything? 30 return policy? Great, make sure that you say so on every page including the product page, because the customer might be coming here for the very first time.

Of course you need to present the customer with the actual product information as well. Keep in mind the key pieces of information and be aware of the fact that different products might require different presentation. Some products are visually oriented such as jewelry while others are more specification driven like TVs.

If you’re designing a site which will sell a very broad range of products you might need different templates to display product differently based on which type they are. One template might emphasize images and provide a gallery while another might bring the facts out a the primary selling point.

Guided Sales Funnels

Product listings will usually require custom filters for narrowing down the contents of a particular category or specialized category browse flows to enable the user to drill into the catalog by designing a browse flow which tries to anticipate the needs of the customer, e.g. the customer is looking for a shirt, so we might ask her a series of questions which will result in an ever narrower product listing:

Q: “What type of clothing are you looking for?”, A: “Women’s shirts”

Q: “To which occasion will you be wearing the shirt?”, A: “Casual home wear”

Q: “Will you be wearing the shirt inside or outside?”, A: “Outside"

The result might be that we’re displaying women’s fleeces.

The upside of a guided sales flow is that the customer is more likely to convert if we can accurately predict the circumstances which brought her to the site in the first place. The downside is that we might miss the mark completely in which case conversion is unlikely. The solution is simple: Build more guides sales flow and start asking questions at a higher level or be sure to try and grab her interest by displaying other products, which might grab her attention. That where related products come into play.

Related Products

The most common types of related products are your classic upsell-, cross sell-, and others bought relations, but other types of relations might be put into place to further enhance the probability of the macro conversion.

Once a user has decided on a product you’ll want to try and upsell them on an even better version. If you’re anything like me you’ve found yourself looking at one type of TV only to find yourself carrying home a more expensive model either due to a salesman doing his job a tad too well or in some cases because you upsold yourself, in any case that’s the upsell grab the users attention with one product and get them to choose a more expensive version.

You’ll be familiar with the cross sell as well. Sticking with the TV again the cross sell happens when you’re convinced that you need an HDMI cable, batteries for the remote, etc.. With that in place the upsell starts all over on the HDMI cable and the batteries. Round and round it goes.

As with automated product listings “others bought” relations are usually generated automatically, but not always. Sometimes you can get away with maintaining those types of relations manually if the store owner want a high degree of control. Keep in mind that whenever you’re dealing with automatically suggested data users usually want to be able to override the information.

There are a lot of opportunities to use related products for creating a better customer experience and optimizing conversion rates. Take for example a special set of products and display them during checkout or even after on the confirmation page or as part of the order confirmation e-mail.

Search

Search-Engine-MarketingSearch is an area becoming increasingly important to e-commerce sites. The options alone for doing search on an e-commerce site tell us as much. Customers expect to get Google-like results from the search engine on your e-commerce site. A feat which is very difficult to achieve even using something like the Google Search Appliance. The fact is that Google has vast quantities of statistic data available, which can’t be said for a single e-commerce site.

What we do have at our disposal is specific knowledge about the customers expected to come to the site. We can leverage that to adapt the site to the expected needs of the customer like what was described in the previous section dealing with Guided Sales. It also applies to search though as we’re able to create more specialized search experiences as we’ll dive into next.

You’ll usually see the simple- and advanced search. Simple search being your ubiquitous search box at the top of the site. Search suggestions might be a part of this, which enables customers to see possible search results as they type in their query.

What can trip you up is the advanced search as it might vary wildly from site to site. A site like ASOS.com is built with advanced search front and center powering the entire browse flow. More commonly though advanced search will present a bunch of options for the user to fill in and get more refined search results on. This is where your knowledge about the customers coming to the site comes into play as you’ll need to tailor these options to the expected needs of the customers.

Another variation on search is your specification search, which narrows down products in the store by searching for individual specifications one at a time, e.g. Car, Make, Year.

Keep the Customer in the Know

During the entire process it’s important to keep the customer up to date as to what’s going on. Customers these days are fickle and might leave your site for the slightest of reasons so you’ll want to keep their confidence high at all times by presenting them with the information they need when they need it.

Questions commonly posed by potential customers include, “what will shipping cost me?”, “can I have this item quickly?”, “what’s the difference between these similar items?”, “what’s my warranty like if I choose to buy?”, “what’s the return policy like?”.

Wrap Up

That’s it for an overview of the browse piece of an e-commerce site. As you can see browse is much, much more than simply slapping the products from a category onto the screen. The browse flow requires finesse to grab the customer’s attention and even more so to engage the customer further to convert. In your browse flow keep the micro conversion in mind as this persuades the customer to do the macro conversion over time.

When specifying an e-commerce project you’ll want to take special care with areas like advanced search, guided sales funnels, and any dynamic listings requested by the customer as these traditionally will cause you an extra bit of effort, but will pay off handsomely both for you and your client.

posted on Wednesday, 17 November 2010 10:57:31 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Tuesday, 09 November 2010

One of the common questions we get about uCommerce is, “how do I get rid of the Developer Edition banner on my site when I demo for the client?”. Before you get the answer a little background information.

uCommerce-Developer-Edition-banner

When we designed the uCommerce licensing system one of the requirements was to not get in the way of the developer so we wanted something which kept uCommerce running even though no license is present.

That’s how the uCommerce Development banner came to be and it works great. It’s only displayed when a user accesses the site from an external IP address so you’re free to develop and design your site without it interfering in any way.

But sometimes you really want to be able to demo your site without the banner. Until now the only way to do this was either to keep accessing your site locally, which is impractical if you’re doing onsite demoes for your client, or install a license, again impractical if you’re not ready to go live with the site.

Introducing Unlicensed URLs: Stage, Staging, and Preview

To make your life a little easier we introduced unlicensed URLs with uCommerce version 1.1.1.0, which are basically a bunch of words that you can add to your domain name to avoid the developer edition banner being rendered as part of your output.

To achieve this you simply set up your domains to include either of the words “stage”, “staging”, or “preview”. Whenever one of these words are found as part of your domain name the banner will not be displayed, e.g. stage.mysite.com, stagemysite.companyname.com, preview.mysite.com, staging.mysite.com will not show the banner.

uCommerce-Developer-Edition-without-banner

Wrap Up

Unlicensed URLs are a great way for designers and developers to demo their work without having that pesky banner show up to ruin the day. This way you hold off on acquiring a production license until your client needs to go live with the site.

Please remember that this is only supported by uCommerce 1.1.1.0 and later.

posted on Tuesday, 09 November 2010 09:25:14 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, 06 November 2010

The Challenge

In some scenarios you want to leave payment processing almost entirely up the remote payment gateway to avoid having to raise the PCI compliance level of your solution. The challenge then becomes to put in place infrastructure to handle the interactions between your server and the payment gateway server both when redirecting the customer to the payment gateway and handling any return traffic from the payment gateway to your server.

Basically the customer is redirected to the payment gateway to enter credit card information and is redirected back to your server once the process is done. Meanwhile the payment gateway will in some cases perform a callback to your server as well to notify you about the status of the payment.

image

Purchase Flow

These steps will be executed during the payment processing flow. Authorizations, captures, refunds, and voids (cancellation of a payment) are handled by the gateway. Follow the yellow boxes in the picture above.

  1. User arrives at the Store and gets a basket assigned.
  2. The user adds different products to the basket.
  3. User checks out and confirms the basket content.
  4. User types in buyer information (email, address, name, etc.).
  5. User selects a payment provider, e.g. PayPal, SagePay, WorldPay, PayEx, Payer.se, DIBS, or ePay.
  6. Process Payment will either result in a local store flow or a remote payment gateway flow. See the 2 different flows below. The only real difference is how the implementation of the request payment is done.
  7. The user gets directed to a form, which makes an auto postback with Javascript to the gateway with all the required information. This information might be the amount, key, order number, and more depending on the gateway.
  8. User chooses type of credit card.
  9. User types in credit card information.
  10. The payment gateway validates the information. When valid, it will make an asynchronous or synchronous callback back to the shop’s PaymentProcessor.axd (See the description of the class later in this guide). Depending on the payment gateway it will automatically redirect you back to the shop or present you with a “return to shop” button; you can click if you want to return to the shop, to get a receipt.
  11. The user gets an order receipt, optionally CC via email.

The Solution

To solve the problem of the customer leaving the store server to authorize credit cards an extended framework for handling payments is needed, which is used to accomplish the interaction between server in a structured and simple way.

This is a two-step process:

  1. We need to prepare the data to be sent to the payment gateway and then redirect or post that information to the gateway thus handing over the user to the gateway.
  2. Second we need to intercept the callback, so we can mark the payment as completed. If that was the last payment in a series the entire order needs to be marked as completed, usually by executing the checkout pipeline.

Payment Window Framework Explained

The IPaymentWindow is the main interface implemented to support the server to server interaction. It’s implemented by the class ExternalPaymentMethodService, which contains the methods for requesting payments, “RequestPayment”, which will redirect the customer to PaymentRequestForm which in turn redirect the customer to the payment gateway supported by the particular payment method service.

Passing the Customer to the Payment Gateway

image

Passing the Customer from the Payment Gateway

image

PaymentRequestForm

This class implements the IHttpHandler interface. In a default uCommerce installation its set up by default to intercept calls made to “PaymentRequest.axd”.

What it does
  • Tries to extract payment information from the URL using the PaymentUrlInformation helper class.
  • From the payment information it will try to find the payment in the system.
  • It will then lookup the payment method service assigned to the payment.
  • Cast the payment method service to an IPaymentWindow.
  • Calls RenderPage method on the IPaymentWindow instance just found.

image

PaymentProcessor

This class also implements the IHttpHandler interface. In a default uCommerce installation it’s set up by default to intercept calls made to “PaymentProcessor.axd”.

As PaymentProcessor is exposed as an HTTP endpoint it is important that all data it receives is validated. For many payment gateways this is done using MD5 hashes of the values passed to the gateway and back or two-encryption as is the case with PayPal.

What is does
  • Tries to extract payment information from the URL using the PaymentUrlInformation helper class.
  • From the payment information it will try to find the payment in the system, which has the status marked as “PendingAuthorization”.
  • It will look up the payment method service used to request this payment as passed in the URL.
  • Casts the payment method service to an “IPaymentWindow”.
  • Calls method ProcessCallback on the IPaymentWindow instance with the payment found earlier as the parameter.

IPaymentWindow

The “IPaymentWindow” represents a class that is able to render a page to the Response or to handle a callback from payment gateways.

Methods
  • RenderPage – This method should return a HTML page and return it. The page rendered will usually contain the HTML form, which needs to be posted to the payment gateway to initiate the payment processing flow on the remote end. It can however be used to redirect the user to another URL also. In these cases it will return an empty string.
  • ProcessCallback – This is called from the PaymentProcessor class and handles logic involved when a callback arrives. That could be getting the transaction id, setting the payment status as authorized, things like that.

IPaymentMethosService

Interface for implementing a Payment Method Service for payment processing. This interface is part of the ExternalPaymentMethodService. The IPaymentMethod service is documented in detail elsewhere, but holds the most basic interface for doing payment gateway integration like RequestPayment, AcquirePayment, Cancel, and Refund.

AbstractPageBuilder

This is an abstract base class for building a HTML page as most payment gateways expect a form POST to pass information to the service; this class eases the implementation.

Methods
  • BuildBody – Here goes all the HTML elements inside the <body /> tag, this is usually the form elements to represent the data.
  • BuildHead – Here goes all the HTML elements inside the <head /> tag. This is in most cases just used to put some javascript to make the form autosubmit.
What it does

When Build is called it will return the HTML page with the html, head, and body tag and all the custom tags that were added in the two abstract methods BuildHead and BuildBody.

image

ExternalPaymentMethodService

This is the base class when implementing an external payment gateway. Since this class implements the IPaymentWindow, you also need ProcessCallback and RenderPage. See the IPaymentWindow for a description.

Abstract methods

There are three methods that are required to be implemented. Acquire, Refund, and Cancel payment, if the gateway supports it. These are suffixed with internal, because they are protected and are only used by the base class “ExternalPaymentMethodService”.

  • AcquirePaymentInternal
  • CancelPaymentInternal
  • RefundPaymentInternal

image

Helper classes

PaymentUrlInformation

Class used when extracting payment information from a URL. This is primarily used by PaymentRequestForm and PaymentProcessor. It extracts information from the HttpRequest instance provided to the “ExtractInformation” method.

The method expects the URL to be in the following format:

· http://yoursite.com/{somedir}/{someotherdir}/{PaymentMethodName}/{PaymentId}/file.axd

· http://yoursite.com/{PaymentMethodName}/{PaymentId}/otherfile.axsd

The '/' is used as the spilt character, so only the imagination will limit you here.

image

AbstractMd5Computer

Abstract base class used when working with MD5 hashes. It contains one method to compute a hash from a string usually to validate information sent to the payment gateway and receive back on the local server to ensure that the values aren’t tampered with.

image

ExternalPaymentConfigurationSection

This is the base class for configuration files. It’s a convenient way to store user defined configuration, so it’s possible to change them at runtime instead of having to recompile the assembly.

image

Steps Required to Build Your Own

  • Configuration - ConfigurationSection
    • Recommended way as you can change settings during runtime.
  • The form builder
    • Create the PageBuilder that implements AbstractPageBuilder class. It contains some helper methods, which will ease the implementation.
  • Payment Method Service
    • Create a class that implements the ExternalPaymentMethodService class.
    • Implement the following abstract methods
      • RenderPage – method called to render the page to the Response stream.
      • ProcessCallback – Process a callback from a payment gateway.
      • CancelPaymentInternal – Gateway specific calls to cancel a payment.
      • AcquirePaymentInternal – Gateway specific calls to acquire a payment.
      • RefundPaymentInternal – Gateway specific calls to refund a payment.
    • Implement the following properties
      • Name – this is the name that is used in the web.config file, when registering the payment method service.

Register the payment method service in the web.config file.

You are now done implementing it and will now be able to select it from the uCommerce interface.

image

Summary

With the Payment Window Framework you have a nice way of creating the server to server interaction without having to do the supporting pieces yourself. More importantly the framework is used in a number of the payment providers supplied with uCommerce out of the box like PayPal, SagePay, RBSWorldPay, PayEx, DIBS, ePay, and Payer.se.

posted on Saturday, 06 November 2010 09:15:33 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Friday, 05 November 2010

When uCommerce was introduced to the world at Codegarden ‘09 one of the things we demoed was how to build simple inventory management using the API and pipelines.

The great thing about pipelines is that they’re very easy to extend so we didn’t think to actually include the inventory tasks; until now that is.

What does it do

The pipeline tasks are pretty simple and do one thing: During checkout one task looks for a field on your product definition called “InventoryOnHand” if found decrements that field with the quantity ordered by the customer. It’s that easy.

Now inventory management wouldn’t be complete if it didn’t support returns as well. So a second task is configured to run as part of the order processing flow in the backend of uCommerce. If an order is moved to a cancelled state the task looks for that same field once more and increments “InventoryOnHand” with the quantities found on each order line.

Setting it up

As mentioned the inventory tasks “DecrementInventoryOnHand” and “IncrementInventoryOnHand” looks for a field called “InventoryOnHand”. So you need to add to your product definitions for inventory management to kick in. You’re free to have the field only on some product and not on others. The tasks will adapt to whatever the case might be.

One thing to note is that if you’re operating with variants you want to add the “InventoryOnHand” field as a variant property otherwise uCommerce won’t pick it up.

If you don’t use variants just leave Variant Property off.

uCommerce-add-inventory-on-hand-field

Managing Inventory Levels

With the new field in place you can now manage inventory levels on products or variants as you would any other product property.

uCommerce-manage-inventory-on-hand-field

Cancelled Orders

The store owner might decide to cancel an order in which case the quantites ordered need to be returned as inventory. IncrementInventoryOnHand handles this for you.

uCommerce-inventory-return-order

Pipelines

Here’s what the pipelines look like in case you were wondering.

Checkout pipeline

uCommerce-inventory-checkout-pipeline

ToCancelled pipeline

uCommerce-inventory-to-cancelled-pipeline

Wrap Up

That’s it. With two pretty simple tasks uCommerce now has simple inventory management built right in.

posted on Friday, 05 November 2010 14:50:41 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, 01 November 2010

Any good e-commerce solution lets the store owner stay in contact with customers. One of the most well established ways of doing this is using the tried and true e-mail.

A strength of the integration between uCommerce and Umbraco is that Umbraco is particularly good at building nice looking pages so we thought, “why not use this to build e-mails as well?”, so that’s what we did. The great thing about this approach is that you don’t have to learn some obscure templating language to style your e-mails, you simply build your e-mail content like you would build any other page in your solution using XSLT or .NET user control, whichever suits you the best.

Steps Involved in Sending E-mail

To send e-mail you’ll need to:

  • Add the types of e-mails you’ll be working with in uCommerce
  • Set up a profile for your store to use
  • Configure the actual e-mails and their templates using Umbraco
  • Configure your store to use that profile
  • And finally trigger the e-mail from XSLT, a pipeline, or .NET

Adding a New E-mail Type

uCommerce employs the notion of E-mail Types, which are your basic kinds of e-mails that you’re working with. Out of the box a single type is supplied called “order confirmation”, but you can configure your own types as needed.

Other types might include “Welcome new customer”, “Thank you signing up to the newsletter”, or more business-like type e-mails like “Your items are shipping” or “Invoice”.

uCommerce-email-types

To set up a new e-mail type you need to go to Settings => E-mail => Types, right click Types, and click Create.

uCommerce-create-new-email-type

Add an E-mail Profile

“What’s an E-mail Profile and why do we need one?”, you might ask.

uCommerce supports multiple stores in a single installation and these stores might vary wildly in look and feel so we needed a way to set up multiple instances of the same e-mails on a per store basis to match that same look and feel from store on e-mails across different stores, e.g. an invoice for Store A might have a different look and feel than an invoice for Store B. Thus the notion of an E-mail Profile was introduced to group e-mail instances together for use on individual stores.

As you can see from the screenshot below the profile has an e-mail instance associated per e-mail type created previously. The difference being that for an E-mail Profile we’re dealing with an actual e-mail while an E-mail Type is a placeholder. The system basically ensures that we’re dealing with the same e-mail setup across all stores and makes it easier to deal with in code.

The process of creating a new profile is the same as you just used to create an E-mail Type.

uCommerce-email-profile

Create the E-mail Content in Umbraco

As mentioned previously e-mail is generated using Umbraco using content nodes, templates, macros, and/or user controls. uCommerce comes with a single Umbraco page out of the box: Order Confirmation, but really you can use any content node in Umbraco.

Each e-mail is language enabled so if you need multiple language variations of your e-mail you can set up a content node for each language you wish to support.

uCommerce-email-content-generated-by-umbraco

The template of your content node can be used to load information particular to the e-mail you’re sending by using macros. By use of a little magic uCommerce will provide the content page with a query string parameter named “orderGuid”, which will give you context information to load data.

Lets say that we’re building an order conformation e-mail and assume that we’re receiving the order guid in our query string. The code to load data would look as follows:

<!-- The query string param will always be 'orderGuid', but may contain additional parameters like a customer number or product id -->
<xsl:variable name="orderGuid" select="umbraco.library:RequestQueryString('orderGuid')"/>
<xsl:variable name="cart" select="CommerceLibrary:GetPurchaseOrder($orderGuid)"/>
<!-- code for formatting the contents of the $cart variable -->

Configure Contents of E-mail

Going back to uCommerce you need to specify which content node uCommerce is to use when generating the e-mail.

First you’ll set up the basics of the e-mail such as the name the e-mail is coming from and sender address and optionally whether the e-mail is to CC or BCC’d to anyone, e.g. stores owners like to get an e-mail notification when new orders roll in and this is the perfect use case for CC and BCC.

Sending-email-with-ucommerce-basics

Next up you’ll configure the multilingual pieces of the e-mail like the subject and the contents of the e-mail, which you set up in a earlier step.

Sending-email-with-ucommerce-configure-email-contents

Select the template in Umbraco using the content picker. Please note that this might be any content node in Umbraco; OrderConfirmation is used only as an example.

Sending-email-with-ucommerce-select-template

Configure Your Store to use an E-mail Profile

Once you’re happy with the e-mails in your installation you’re ready to tell your store to use those e-mails. To do so go to Product Catalog => <Your Store> and select your E-mail Profile.

With this step completed uCommerce will know which e-mail and template to select when you ask it to send a particular e-mail type in a given store. More on that in the next step.

uCommerce-configure-store-to-use-email-profile

Send the E-mail

Now you’re ready to tie it all together and send the e-mail to the customer. As with most APIs in uCommerce you can go with either XSLT or .NET when you want to trigger the e-mail. Use whatever makes sense in your particular scenario.

Using XSLT you can use the following to trigger our order confirmation template from before:

<xsl:variable name="orderGuid" select="CommerceLibrary:GetBasket()/purchaseOrder/@orderGuid"/>
<xsl:variable name="result" select="SendEmail('OrderConfirmation', $orderGuid)"/>

The XSLT extension “SendEmail” used above actually uses a class called EmailService to do its thing.

You can leverage this same class in .NET or pipeline yourself with the following code:

// Get the services required for sending e-mails
var emailService = ObjectFactory.Instance.Resolve<IEmailService>();
var localizationContext = ObjectFactory.Instance.Resolve<ILocalizationContext>();
 
// Find the relevant e-mail profile for the current store
var emailProfile = SiteContext.Current.CatalogContext.CurrentCatalogGroup.EmailProfile;
 
// Load information for e-mail personalization
var purchaseOrder = SiteContext.Current.OrderContext.GetBasket().PurchaseOrder;
 
// Set up personalization parameters - params will be passed to
// the configured e-mail template
var queryStringParameters = new Dictionary<string, string>();
queryStringParameters.Add("orderGuid", purchaseOrder.OrderGuid.ToString());
queryStringParameters.Add("customerId", purchaseOrder.Customer.CustomerId.ToString());
 
// Send e-mail
emailService.Send(localizationContext, 
                    emailProfile, 
                    "OrderConfirmation", 
                    new MailAddress(purchaseOrder.BillingAddress.EmailAddress),
                    queryStringParameters);

Please note that both examples assume that you’ve added a billing address to the basket prior to sending e-mail. Keep in mind that uCommerce uses standard .NET SMTP to send the e-mail so you will have to configure the SMTP server you want to use in web.config.

As of uCommerce 1.1.1.0 you can use a standard pipeline task to send e-mails. Simply edit the relevant pipeline configuration and add SendEmailTask to the flow. When uCommerce 1.1.1.0 is installed OrderConfirmation is added as a default. If you need to send other e-mail types you see how to configure them by taking a look at /umbraco/ucommerce/Checkout.config.

You can tell uCommerce to send a different type of e-mail by specifying an e-mail type name as shown in the screenshot below. Just replace “OrderConfirmation” with the name of your e-mail type; this is the name that you used when you created your e-mail types in a prior step.

uCommerce-configure-send-email-pipeline-task

With that you’ve sent your first e-mail with uCommerce.

Wrap Up

The process of sending e-mail with uCommerce does require a couple of steps to get going, however, in return you get the full power of Umbraco as a content management system to fully style your e-mails thus avoiding to have to learn some arcane templating system.

In addition you can even take advantage of some more advanced macros within uCommerce. Think of the value of sending out your order confirmation e-mail, not only with the details of the order, but with added information about related items to each item bought or special offers tailored to the customer.

This is the value of having Umbraco and uCommerce handle your store e-mails.

posted on Monday, 01 November 2010 17:02:38 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, 18 October 2010

uCommerce comes with built-in support for DIBS payments. This guide will walk you through getting uCommerce to work with DIBS for payment processing.

Authorization is available for all plans with DIBS. If you wish to acquire (capture), refund, or cancel payments DIBS requires you to purchase the “Integration(API)” add-on.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “DIBS”.

clip_image001

Click the newly created node and select “DIBS” in the Service drop down list. Fill out the rest of the required information, like where it’s available from under the “Access” tab, pricing and the language tabs. When you are done click “Save”.

clip_image002

That’s everything in the uCommerce interface.

Settings in DIBS Administration Panel

Changes needed in the DIBS administration panel, so it will work with uCommerce.

Configure MD5 Control Setting

On the Menu on the left side, click “Integration –> MD5 Keys”. Make sure that “Perform MD5 control” is checked. If not, check it and click “Update”.

clip_image004

Configure Return Values

uCommerce performs validation of the payment information when DIBS performs the callback. To verify that the payment wasn’t tampered with you’ll need to configure DIBS to include some additional information as part of the callback.

clip_image001[1]

Editing the DIBS.config File

Now we need to edit the DIBS.config file.

You will find the DIBS.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\DIBS.config”. Usually “rootdir” is c:\inetpub.

clip_image005

Some of the below information are found in the DIBS administration panel, so start by logging in you aren’t already.

Finding testMode

If set to “True”, test mode is enabled and you can that it works. Test credit card information from DIBS can be found here: 5. Your own test.

Finding debug

If set to “True” you will be prompted to click a button before posting the information to “DIBS” otherwise it will do an autosubmit using Javascript. When running in production, you will want this set to “False”.

Finding login

Used if you want to use the remote API to do authorization, capture and cancel. This is the same login used for the DIBS administration panel

Finding password

Only used when doing remote API. This is the password used when logging into the DIBS administration panel

Finding callbackUrl

Leave this at “(auto)” if in doubt.

Finding acceptUrl

Url the user is returned to after successfully authorizing her credit card.

Finding cancelUrl

Url the user is returned to if she cancels a purchase.

Finding merchant

On the Menu on the left, click “Setup –> Edit profile”, here you will find the Merchant ID.

clip_image006

Finding useMd5

True/False indicating weather to use Md5. Its recommended to use Md5 for security reasons.

Finding key1 and key2

The two keys found in the administration panel. On the Menu on the left, click “Integration –> MD5 Keys”, here you will find k1 and k2 which correspond to key1 and key2. Also make sure that “Perform MD5 control” are checked. If not, mark it and click “Update”.

Please note that the configuration files are subject to standard XML limitations. If your MD5 key contains the following characters they must be HTML encoded for .NET to be able to read the value:

For < write &lt;
For & write &amp;
For ' write &#39;
For " write &quot;

Given an MD5 key containing the & symbol you’d replace it to look like this: Before &P]ij|&4jNixCA%zZ è After &amp;P]ij|&4jNixCA%zZ
clip_image007

Excecuting a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, you need to modify the database. If you used the name “DIBS” for the payment method name, you can run this SQL query in the SQL Server Management Studio.

UPDATE uCommerce_PaymentMethod SET Pipeline = 'Checkout' WHERE Name = 'DIBS'

or just edit it manually in SQL Server Management Studio.

clip_image008

Now the default pipeline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

Optional: Enable Acquire, Cancel, and Refund in uCommerce Back Office

To be able to acquire, cancel, and refund payments you need to enable two pipeline tasks in the ToCompletedOrder pipeline and ToCancelled pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

ToCancelled.config

clip_image010

ToCompletedOrder.config

clip_image012

FAQ

· Test mode – Make sure test mode if turned off when going live.

posted on Monday, 18 October 2010 12:40:59 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback

uCommerce comes with built-in support for ePay payments. This guide will walk you through getting uCommerce to work with ePay for payment processing.

Authorization is available for all plans with ePay, i.e. Light, Pro, and Business. If you wish to acquire (capture), refund, or cancel payments ePay requires you to buy the Business plan.

Settings in uCommerce

Add a new payment method, under “uCommerce –> Settings –> Orders –> Payment Methods”. You can call it whatever you like, here I have used “ePay”.

clip_image002

Click the newly created node and select “ePay” in the Service drop down list. Fill out the rest of the required information, like where its available from under the “Access” tab, pricing and the language tabs. When you are done click “Save”.

clip_image003

That’s everything in the uCommerce interface.

Settings in ePay Administration Panel

Changes needed in the ePay administration panel, so it will work with uCommerce.

Unikt orderID, MD5 sikkerhedstjek & callback setting

On the Menu on the left, click “Indstillinger–> Betalingssystemet”, then you should get a view like the one below. These are the settings we recommend. Make a random key out of some digits/characters.

clip_image004

On the same page you need to enter the domain that the callbacks is made to. This include all subdomains.

clip_image005

Optional: Webservice setting if you need to Acquire, Cancel, and Refund

1. Now on the menu to the left, go to “API / Webservices –> Adgang”

2. Set a password if you are using a shared hosting environment

3. At the bottom type in the “IP address” of the webhost accessing the webservice. This needs to be the external ip address

4. Click “Opret IP-adresse” to save it

clip_image006

Editing the ePay.config File

Now we need to edit the ePay.config file.

You will find the ePay.config file in the following location, where “rootdir” is the directory on the computer where you installed Umbraco: “rootdir\umbraco\UCommerce\Configuration\ePay.config”. Usually “rootdir” is c:\inetpub.

clip_image007

Some of the below information are found in the ePay administration panel, so start by logging in you aren’t already.

Finding debug

If set to “True” you will be prompted to click a button before posting the information to “ePay” otherwise it will do an autosubmit using Javascript. When running in production, you will want this set to “False”.

Finding callback

Leave this at “(auto)” if in doubt.

Finding acceptUrl

Url the user is returned to after successfully authorizing her credit card.

Finding declineUrl

Url the user is returned to if she cancels a purchase.

Finding merchantNumber

The “Indløsningsnummer” is unique for your account. This can be found in the menu “Indstillinger -> Betalingssystemet”. Also make sure that “Test mode” is not active, like it is on the picture below, if you’re setting up a production environment.

clip_image008

Optional: Finding pwd if you need to Acquire, Cancel, or Refund

Password used for the webservice, if using a shared host. This can be found in the menu “API / Webservices -> Adgang”.

clip_image009

Finding useMd5

True/False indicating weather to use Md5. Its recommended to use Md5 for security reasons.

Finding key

The Md5 key set in the administration panel.

This can be found in the menu “Indstillinger–> Betalingssystemet”.

clip_image010


Executing a Pipeline on Callback

Running a pipeline once payment is authorized can be helpful if you need to complete the order once the customer returns to your site.

To run a “pipeline” once the callback if received and processed, you need to modify the database. If you used the name “ePay” for the payment method name, you can run this SQL query in the SQL Server Management Studio.

UPDATE uCommerce_PaymentMethod SET Pipeline = 'Checkout' WHERE Name = 'ePay'

or just edit it manually in SQL Server Management Studio.

clip_image011

Now the default piplline that comes with uCommerce will be run after each successful callback. This sets the Basket to an Order, gives it an OrderNumber, and other things.

Optional: Enable Acquire, Cancel, and Refund in uCommerce Back Office

To be able to acquire, cancel, and refund payments you need to enable two pipeline tasks in the ToCompletedOrder pipeline and ToCancelled pipeline.

The pipeline configuration is found in /umbraco/ucommerce/pipelines.

ToCancelled.config

clip_image013

ToCompletedOrder.config

clip_image015

FAQ

· Test mode – Make sure test mode if turned off when going live.

posted on Monday, 18 October 2010 11:43:44 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Wednesday, 13 October 2010

The uCommerce Catalog Foundation holds all the catalog information in your installation and as such serves as the most important foundation in uCommerce. This post will give you an idea of one of the most basic building blocks of the Catalog Foundation: Product Definitions… but first some basics.

Products, Product Families, and Variants. Oh My!

Before we get into the nitty gritty of things we need to get the terminology right so we agree on what’s what.

Products are pretty straight forward they represent a single product in the system with no variants associated.

Product Families are pretty much the same as a product but differ in that they’ve got variants associated with them, hence the product family.

Variants represents a single product much like a stand alone product, but they cannot stand by themselves. Variants are always associated with a product family.

uCommerce supports both products and product families and the good news is you don’t have to go with one over the other. You simply decide on a per product basis whether or not to support variants. So you might have some products be stand alone products and others be product families. Whatever works for your scenario.

Product Definitions

Product Definitions 2Before you can start using catalogs you need to perform some setup to determine the data you’ll be working with, i.e. the taxonomy of your site, the various types of products you’ll support in the site, and finally your pricing scheme.

Product definitions are the most fundamental building blocks of the uCommerce Catalog Foundation. If you’re familiar with Umbraco think of them as Document Types for products. Basically a product definition determines what data you’re working with in uCommerce, both via the UIs and the APIs.

Each product definition in uCommerce represents a different type of product available through your store. Say you’re selling Software and Shirts as in the screenshot below. Software requires a completely different set of data to sell from a Shirt. Notice that Software has different properties from the Shirt.

With product definitions you can tailor uCommerce to your client’s needs.

Adding a New Product Definition

uCommerce supports as many product definitions as you need. Simply right click the Product Definitions node and click create to add a new definition. Each of the product definitions must be named uniquely so you can find it later on.

Adding New Properties to Product Definitions

You can add new properties by right clicking the product definition and clicking Create. Just as you would do when creating a new content node in Umbraco. As you can see the product definition needs a name which will be your key for reference the product definition from code as well the identifier for the product type.

The product family check box indicates whether the product definition allows variants or not. A product family is basically a product with a bunch variants associated with it while a non-product family (product) represent just a single product.

uCommerce Product Definition Create New Property

Once created you’ll have the opportunity to change the meta data of the property to suit your needs.

uCommerce Product Definitions Property Details 

Multilingual Properties

If you need to maintain the data of the property in multiple languages you can tick off the multilingual check box. This will give you a field per language configured in Umbraco.

uCommerce Multilingual Property Definition

If you specify a property to be multilingual the property will show up under the multilingual tabs when you go and edit products.

uCommerce Product Editor Multilingual Properties

Display on Website

A true/false value which is set on the property when accessed via the API.

uCommerce Display on Site Property Definition

Variant Properties

Determines whether the property should be a variant property that you maintain under a product family. If one or more exist the product will turn into a product family automatically and enable you to create multiple variants associated with the product family.

uCommerce Variant Property Definition

Setting the property as a variant property will add the Variants tabs to the editor to any product based on the product definition and will enable you to create variations of a product as part of a product family.

uCommerce Variant Editor

Render in Editor

Sometimes you need data that you don’t want the user to edit. Ticking this check box will tell uCommerce not to render this property as part of the editor UI essentially giving you meta data that you can use and maintain from the API without having to worry about the user tampering with it.

uCommerce Render in Editor Property Definition

Data Types

Each of the properties created in the previous paragraphs are based on data types, which you select when you create new ones. uCommerce comes with a number of built-in data types such as ShortText, LongText, Number, Boolean, Enum, and Image.

uCommerce DataType Property Definition 

Data types include string, number, bool, and enum which is a special type which enables you to predefine a list of values allowed for the user to select, e.g. colors, sizes, basically data with a finite number of options to choose from.

uCommerce Data Type Editor

Validation Expressions

Data types can have validation expressions associated with them to validate user input when editing in the product editor. A validation expression is a standard regular expression evaluated whenever a user clicks the save button.

uCommerce Data Type Validation Expression

In Conclusion

The Product Definition is the secret sauce which makes the uCommerce Catalog Foundation extremely powerful enabling you to model the reality you face be it as a developer creating an e-commerce solution for a client or for yourself.

An important aspect about a product definition is that you can change your mind whenever you please. If you start out without variants nothing is holding you back from moving your properties around even after you start creating products based on that product definition. uCommerce will simply reflect the changes you need without you having to create you products from scratch.

posted on Wednesday, 13 October 2010 21:17:46 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, 02 September 2010

When working in the uCommerce Admin tool it can be useful to be able to add your own custom nodes some in the trees, e.g. a new node under Product Catalog, Orders, Analytics, or Settings. This post describes how to achieve this.

The uCommerce tree handlers are using the standard Umbraco extension point for creating new trees. You can learn more about that in the excellent Umbraco.tv episode Adding a Custom tree.

uCommerce-UI-extension-1-New-Node

Finding the Extension Point

uCommerce comes with a bunch of tree handlers for managing all aspects of the uCommerce Foundations. Each tree handler deals with a separate root node in the uCommerce tree so depending on which tree you want to insert your custom node in you’ll need a different tree handler.

The tree handlers are called Load<whatever> where the whatever is the actual tree that it’s dealing with. All handlers are found in the assembly called UCommerce.Umbraco.dll which contains the integration pieces for Umbraco.

Handlers include:

Product Catalog tree – UCommerce.Umbraco.Menu.LoadCatalog
Orders tree– UCommerce.Umbraco.Menu.LoadOrders
Analytics tree– UCommerce.Umbraco.Menu.LoadAnalytics
Settingstree – UCommerce.Umbraco.Menu.LoadSettings

 

uCommerce-UI-extension-2-Tree-Handlers

Overriding the Default uCommerce Tree Handler

When you’ve found the handler you want to extend you need to  derive from the uCommerce class. In my case I’m extending the Product Catalog handler so I will derive from the LoadCatalog class.

To add your own node your need to override the method called Render(XmlTree tree) on the tree handler. This method is responsible for actually rendering the tree and will be triggered by Umbraco once configured to do so later on.

Please note that Umbraco isn’t exactly forthcoming with error messages which crop up during development of a tree handler so you’ll have to whip out the Sherlock Holmes thinking cap to find some of the issues which crop up. Especially Javascript for your Action will cause you grief.

public class MyCustomTreeHandler : LoadCatalog
{
    // Constructor is required by base type
    public MyCustomTreeHandler(string application) : base(application)
    {   
    }
 
    public override void Render(ref umbraco.cms.presentation.Trees.XmlTree tree)
    {
        base.Render(ref tree);
 
        XmlTreeNode node = XmlTreeNode.Create(this);
 
        string nodeId = "MyCustomNode";
        // Unique id of the node, can be used to store information about a data object being displayed on a particular node
        node.NodeID = nodeId;
 
        // Text to display on the node itself
        node.Text = "My Custom Node";
 
        // Action trigged by mouse click
        node.Action = string.Format("javascript:{0}", "parent.right.document.location.href = '~/MyPage.htm';"); 
 
        node.Icon = "folder.png";
        node.OpenIcon = "folder.png";
 
        // The node type refers to a config file with Umbraco
        // which specifies additional config for a particular node
        // like dialogs and available right click actions
        // ~/umbraco/config/create/UI.xml
        node.NodeType = "my_custom_node_type";
 
        // Available right click actions as per UI.xml
        node.Menu = new List<IAction>(new IAction[] { ActionNew.Instance, ContextMenuSeperator.Instance, ActionDelete.Instance, ContextMenuSeperator.Instance, ActionRefresh.Instance });
 
        // Indicates whether the nodes is expandable
        node.HasChildren = false;
 
        // Source is used to perform async calls
        // uCommerce provides an abstraction which works for both Umbraco 4 and 4.5
        // Notice that the nodeId is reused for this call
        node.Source = GetVersionSafeTreeServiceUrl(nodeId);
 
        tree.Add(node);
    }
}

With the following code the node shows up in the tree. Interestingly the custom node turns up as a subnode to every single node in the catalog system, which isn’t what we’re after. We’d like to be able to insert a node anywhere in the tree, but just that one time.

Read on to find out what’s going in.

Determining Where You are in the uCommerce Tree

uCommerce trees are different from Umbraco trees in the sense that a single tree works with many different types of nodes. For example a catalog consists of product catalog groups (the store level), catalogs, and categories. To help you figure out where you are there are two properties you can ask: CurrentId and CatalogNodeType.

When uCommerce builds its tree ids are consistently built up in the format catalogNodeTypeName_ObjectId. This helps uCommerce determine which internal type we’re working with, e.g. a catalog group, a catalog, or a category, and which data object is currently in play.

To insert our node in a specific location we can ask CatalogNodeType what the type of the node currently being rendered is thus enabling us to only insert the custom node in a specific location in the tree.

For my example I’m inserting the node on the same level as the product catalog groups by inserting the following piece of code in the Render method of the tree handler:

public override void Render(ref umbraco.cms.presentation.Trees.XmlTree tree)
{
    base.Render(ref tree);
    
    if (CurrentNodeType != CatalogNodeType.Root) return;
    
    ...
}

Enabling Child Nodes for a Custom Node

Should you need child nodes for your new node that’s absolutely possible as well. Some additional plumbing is needed to determine which nodes to load for a particular super node.

This is where the Node.Source property comes into play. You’ll have seen it configured on our custom node already like so node.Source = GetVersionSafeTreeServiceUrl(nodeId);.

Basically Umbraco loads child nodes on the fly by requesting a back end URL which is called TreeDataService.ashx. Among the parameters passed to this handler is the nodeKey which tells you the sub tree being requested.

uCommerce-UI-extension-5-Tree-Data-Service

To make sure that we only generate child nodes for our MyCustomNode a check to determine which node is being requested is required as a single handler does all the work for the entire tree. For that to work we have to refactor our code a bit to support the sub nodes.

The Render method is still our main entry point from Umbraco so it has to act as an check point which will determine what needs to be rendered.

public override void Render(ref umbraco.cms.presentation.Trees.XmlTree tree)
{
    // Make sure to only render the default nodes at the root
    // and not under our custom node
    if (NodeKey != "MyCustomNode")
        base.Render(ref tree);
 
    XmlTreeNode node = null;
 
    // If the NodeKey passed by Umbraco is our custom id
    // we know that we need to render subnodes for our
    // custom node
    if (NodeKey == "MyCustomNode")
    {
        node = XmlTreeNode.Create(this);
        node.NodeID = "MyCustomSubnode";
        node.Text = "My Custom Subnode";
        node.Action = string.Format("javascript:{0}", "parent.right.document.location.href = '~/MySubPage.htm';");
        node.Icon = "folder.png";
        node.OpenIcon = "folder.png";
        node.NodeType = "my_custom_node_type";
        node.HasChildren = false;
    }
    // If we're at the root of the catalog
    // we render the custom node
    else if (CurrentNodeType == CatalogNodeType.Root)
    {
        node = RenderMyCustomNode();
    }
    else return;
 
    // Add the rendered content to the tree
    tree.Add(node);
}

Final Code

Final code with support for a custom node under Product Catalog and child nodes for that looks like this:

using System;
using System.Collections.Generic;
using UCommerce.Umbraco.Menu;
using umbraco.cms.presentation.Trees;
using umbraco.interfaces;
using umbraco.BusinessLogic.Actions;
 
namespace MyUCommerceApp.Umbraco