allBlogsList

CH Upstream Integrations part 3: Example Logic App for Syncing an External System with Sitecore Content Hub

Intro

The following post is a collection of hints and code snippets for .NET SDK - based clients for Sitecore OrderCloud

Read other Sergey's blogs at xcentium.com

Intro

OrderCloud is a new(ish) B2B, B2C, B2X eCommerce platform from Sitecore, which I like a lot: very easy to work with and easy to integrate with. I think something like Next.JS could be a very good choice for the "Head" or Front-End portion of the modern eCommerce website, but what about good old ASP.NET? We had such a client, who needed a simple eCommerce back-end upgrade, which would work with a "classic" ASP.NET - based Sitecore 10 website. We chose to use OrderCloud .NET SDK for the back-end integration and it has proven to be relatively easy to use and reliable. The following post is a collection of hints and code snippets for others, who might need to build something similar

Setting Up

First, NuGet Packages, we added to the Sitecore Solution

The readme file for the SDK Client has enough code samples for getting started, so I won't replicate these here. The following collection of code snippets can be useful for working with OrderCloud's catalog data, orders and carts

Working with Categories, Products and Carts

Initialize OrderCloud Client

The below code is leveraging OrderCloud API client, which need to be configured in OrederCloud first and here are the instructions for that.

protected OrderCloudClient GetClient(string userName, string password)
{
    OrderCloudClient client = new OrderCloudClient(new OrderCloudClientConfig
    {
        ApiUrl = Sitecore.Configuration.Settings.GetSetting("ApiUrl"),
        AuthUrl = Sitecore.Configuration.Settings.GetSetting("AuthUrl"),
        ClientId = Sitecore.Configuration.Settings.GetSetting("ClientId"),
        Username = userName,
        Password = password
    });
    
    return client;
}

Get Categories for a Given Catalog ID

public List<CategoryItem> GetCatagories(string catalogId)
{
    try
    {
        return Task.Run(async () => await Client?.Categories.ListAsync(catalogId)).Result;
    }
    catch (Exception e)
    {
        Sitecore.Diagnostics.Log.Error(e.Message, e, this);
        return new List<CategoryItem>();
    }
}

Get Products by Category and Catalog ID

 private List<BuyerProduct> GetProducts(
            out int totalPages,
            out int totalCount,
            string catalogId = null, 
            string categoryId = null, 
            int pageNumber = 1, 
            int pageSize = 20,
            string sortField = "Name",
            bool isAscending=true)
{
	totalPages = 0;
    totalCount = 0;
    List<BuyerProduct> sortedResults=null;
     
    try
    {
    	if (!string.IsNullOrEmpty(catalogId))
        {            
        	decimal price = 0;
            var products = Task.Run(async () => await Client.Me.ListProductsAsync<BuyerProduct>(p =>
            {
            	p.AddFilter("CatalogID", catalogId);
                p.Page(pageNumber);
                p.PageSize(pageSize);
                       
                if (!string.IsNullOrEmpty(categoryId))
                {
                	p.AddFilter("CategoryID", categoryId);
                }
                
                if (!string.IsNullOrEmpty(searchKeyword))
                {
                	p.SearchFor(searchKeyword).SearchOn(ProductSearchFields);
                }
           }, catalogId, categoryId, null, null, null
           )).Result;

           totalPages = categoryProducts2.Meta.TotalPages;
           totalCount = categoryProducts2.Meta.TotalCount;
           sortedResults = products.Items.Select(i => (BuyerProduct)i).ToList();

           return sortedResults;
      }
       catch (Exception e)
       {
           Sitecore.Diagnostics.Log.Error(e.Message, e, this);
           return new List<BuyerProduct>();
       }
 }

Create Cart/Order

public Order CreateCart(OrderCloudClient Client,
			string userId,
			BuyerAddress billingAddress = null,
			BuyerAddress shippingAddress = null,
			string comments = "",
			decimal shippingCost = 0,
			string cartName)
{
    Order order = null;
    string orderId = GenerateOrderID(userId, cartName);

    try
    {
        order = GetCart(Client, userId, orderId);
        if (order == null)
        {
            order = new Order()
            {
                ID = orderId,
                Comments = comments,
                ShippingCost = shippingCost,
                FromUserID = userId,
                FromCompanyID = BuyerOrganizationId,
                BillingAddressID = billingAddress?.ID,
                ShippingAddressID = shippingAddress?.ID,
            };

            order = Task.Run(async () => await Client.Orders.CreateAsync(OrderDirection.Outgoing, order)).Result;
        }

    }
    catch (Exception e)
    {
        Sitecore.Diagnostics.Log.Error($"Error creating an order for user ID {userId}!", e, this);
        order = null;
    }

    return order ?? null;
}

Get Existing Cart (or Order)

Cart and Order are used interchangeably in OrderCloud as a cart is nothing other than Order that hasn't been submitted

public Order GetCart(OrderCloudClient Client, string userId, string orderId)
{
    Order order = null;
    try
    {
        order = Task.Run(async () => await Client.Orders.GetAsync(OrderDirection.Outgoing, orderId)).Result;
    }
    catch (Exception e)
    {
        Sitecore.Diagnostics.Log.Error($"Error retrieving an order/cart with ID {orderId} for a user ID {userId}.", e, new object());
    }

    return order ?? null;
}

Add Item to Cart

public Order AddToCart(OrderCloudClient Client,
                       string userId,
    				 string productId, 
                      int quantity, 
                      Order cart = null)
{
    lock (_lock)
    {
        lineItemCount = 0;
        if (cart == null)
        {
            cart = CreateCart(Client, userId, null, null, null, 0, DefaultCartName);
        }
        if (cart != null)
        {
            LineItem lineItem = CreateLineItem(Client, cart.ID, productId, quantity);
            cart = GetCart(null, cart.ID);

            if (lineItem == null)
            {
                return null;
            }
        }

        return cart;
    }
}

Get Product Details

try
{
    product = Task.Run(async () => await Client?.Me.GetProductAsync(productId)).Result;
}
catch (Flurl.Http.FlurlHttpException e)
{
    Sitecore.Diagnostics.Log.Error($"Product {productId} was not found!", e, this);
    return null;
}
catch (Exception e)
{
    Sitecore.Diagnostics.Log.Error(e.Message, e, this);
    return null;
}