Wednesday, October 29, 2014

Generate an order number for your cart in EPiServer Commerce

Many payment services, such as PayEx, require that you pass in an order number when processing payments. This makes it very easy to track payments as you instantly know which order the payment belongs to. At the same time, if you don't want to generate an order before the payment has been processed, where does this order number come from? In this blog post, I'll show you how to can generate an order number for your Cart and then later generate a purchase order with the same order number.

The Cart in EPiServer Commerce has a CreateOrderNumber delegate you can use to define how the order number for your PurchaseOrder will be generated. EPiServer has a great overview of how this works in their Changing order number sequence article. As the article states, the method you define for the CreateOrderNumber delegate is run in the SaveAsPurchaseOrder method, but we don't want to run this method until after the payment is already processed. So what do we do?

We'll still use the CreateOrderNumber delegate, but we've added a lambda expression:

public void BeforeProcessingPayment(Cart cart)
   var orderNumber = GenerateOrderNumber(cart.OrderGroupId);
   cart.OrderNumberMethod = c => orderNumber;

   // Save cart and process payment, passing in the required orderNumber

// This is the default order number generator in EPiServer Commerce, 
// you can change this around if you want a different format
private string GenerateOrderNumber(int orderGroupId)
   string str = new Random().Next(1000, 9999).ToString();
   return string.Format("PO{0}{1}", orderGroupId, str);

In the BeforeProcessingPayment method, we're generating an order number and using a lambda expression to set the OrderNumberMethod delegate to this value. This means that you can process the payment and call cart.SaveAsPurchaseOrder() after the payment has successfully been processed. The PurchaseOrder will then receive the same order number as you generated for your Cart.

Now, that wasn't too hard, was it?

No comments:

Post a Comment