Displaying the cost of a uCommerce custom IShippingMethodService

I just found this bog post on how to get the shipping cost for a custom shipping method you may have implemented using IShippingMethodService and thought I would share it here.

http://www.davejsaunders.com/2014/10/20/display-the-cost-of-your-ucommerce-custom-shipping-service.html

A common requirement when displaying shipping methods is to show the price against each, and for the built in uCommerce shipping methods there’s a handy GetPriceForCurrency() method on the shipping method object. However if that shipping method is a custom one, it just returns 0.

 

var allShippingMethods = TransactionLibrary.GetShippingMethods(country);
var currency = purchaseOrder.BillingCurrency;

foreach (var shippingMethod in allShippingMethods)
{
	var cost = shippingMethod.GetPriceForCurrency(currency);
}

The correct way to get your shipping price is to manually call your service to get the price to be calculated.

As we don’t know which implementation of IShippingMethodService will be used we first need to call GetShippingMethodService() to get it.

After that we just need to populate a new Shipment object we the details our custom method needs and then call the CalculateShippingPrice method.

var purchaseOrder = TransactionLibrary.GetBasket().PurchaseOrder;
var allShippingMethods = TransactionLibrary.GetShippingMethods(country);

foreach (var shippingMethod in allShippingMethods)
{
  // Get the IShippingMethodService for this ShippingMethod
  var shippingService = shippingMethod.GetShippingMethodService();

  // Construct a fake shipping method to call the service with
  var shipment = new Shipment
  {
	  ShippingMethod = shippingMethod,
          OrderLines = purchaseOrder.OrderLines,
	  PurchaseOrder = purchaseOrder,
	  ShipmentAddress = purchaseOrder.BillingAddress
  };

  var shippingMethodPrice
 	 = shippingService.CalculateShippingPrice(shipment);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s