Kieran Harvey | 17/09/2012
If you would like to use a custom shipping service in uCommerce it is quite easy. You will have to make use of the IShippingMethodService provided by uCommerce. By implementing this class and adding it to the pipeline tasks you can create custom shipping values for each order line of your basket. Bellow we can see the implementation of the IShippingMethodService.
public class InternationalShippingMethodService : IShippingMethodService
{
public virtual string Name { get; set; }
Money IShippingMethodService.CalculateShippingPrice(Shipment shipment) {
}
bool IShippingMethodService.ValidateForShipping(Shipment shipment) {
}
}
The code for the shipping method. This code uses a custom property “Weight” to get the weight of the entire basket and multiply it by a rate per kg and add a base shipping price to determine the final shipping value.
Money IShippingMethodService.CalculateShippingPrice(Shipment shipment) {
//calculate the total weight for the basket
var weight = shipment.OrderLines.Sum(
orderline =>
Convert.ToDecimal(
Product.SingleOrDefault(
product =>
product.Sku == orderline.Sku
&& product.VariantSku == orderline.VariantSku
).ProductProperties.FirstOrDefault(prop=>prop.Product
DefinitionField.Name=="Weight").Value
)
* orderline.Quantity );
var method = shipment.ShippingMethod;
var baseRate = 3m; //apply your rates
var ratePerKg = 0.5m; //apply your rates
//reset the shipping total
shipment.ShipmentTotal = 0;
decimal shippingCost = baseRate + ( ratePerKg * decimal.Ceiling( weight ) );
return new Money( shippingCost, shipment.PurchaseOrder.BillingCurrency );
}
Here we fill out the validation for shipping. This was taken from
bool IShippingMethodService.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 true;
}
The final steps is to register the shipping method in your appropriate web config file.
<configuration>
<commerce>
<ordersConfiguration>
<shippingMethodServices>
<add name="InternationalShippingMethodService" type="DLL_NAME.NAMESPACE.InternationalShippingMethodService, DLL_NAME " />
shippingMethodServices>
ordersConfiguration>
commerce>
configuration>
tags:
Umbraco
,
e-commerce
Interested in learning more?
Wiliam is a leading supplier of web solutions and can provide expert advice to assist your business or organisation online.