SaaS CMS has officially launched! Learn more now.

Francisco Quintanilla
Mar 27, 2023
  1510
(0 votes)

How to Merge Anonymous Carts When a Customer Logs In with Optimizely Commerce 14

In e-commerce, it is common for users to browse a site anonymously, adding items to their cart without creating an account. Later, when the user decides to create an account or log in, they may have items already in their anonymous cart that they would like to keep. In this scenario, it is important to merge the anonymous cart with the authenticated cart to ensure a seamless shopping experience.

In this blog post, I will show you how to merge anonymous carts with authenticated carts in Optimizely Commerce 14.

Overview

The code I will be using is a middleware component that runs on every incoming HTTP request. If the user is authenticated, the middleware retrieves the user's anonymous cart using the IAnonymousIdFeature and merges it with their authenticated cart.

using EPiServer.Commerce.Order;
using EPiServer.ServiceLocation;
using Mediachase.Commerce;
using Mediachase.Commerce.Anonymous;
using Mediachase.Commerce.Customers;
using Mediachase.Commerce.Markets;

namespace Infrastructure.Commerce.Extensions
{
    public class AnonymousCartMergingMiddleware
    {
        private readonly RequestDelegate _next;

        public AnonymousCartMergingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            if (context.User.Identity != null && context.User.Identity.IsAuthenticated)
            {
                var anonymousId = context.Features.Get<IAnonymousIdFeature>().AnonymousId;
                
                if (!string.IsNullOrWhiteSpace(anonymousId))
                {
                    var orderRepository = ServiceLocator.Current.GetInstance<IOrderRepository>();
                    var marketService = ServiceLocator.Current.GetInstance<IMarketService>();
                    
                    var market = marketService.GetMarket(MarketId.Default);
                    var cart = orderRepository.LoadCart<ICart>(new Guid(anonymousId), Constants.CartName.ShoppingCart, market.MarketId);

                    if (cart != null && cart.GetAllLineItems().ToList().Count > 0)
                    {
                        var currentMarket = ServiceLocator.Current.GetInstance<ICurrentMarket>();
                        cart.MarketId = currentMarket.GetCurrentMarket().MarketId;
                        orderRepository.Save(cart);
                        
                        var profileMigrator = ServiceLocator.Current.GetInstance<IProfileMigrator>();
                        profileMigrator.MigrateCarts(new Guid(anonymousId));
                    }
                }
            }

            await _next(context);
        }
    }
}

You can use an extension method to expose the middleware through `IApplicationBuilder`.

namespace Infrastructure.Commerce.Extensions
{
    public static class AnonymousCartMergingMiddlewareExtensions
    {
        public static IApplicationBuilder UseAnonymousCartMerging(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AnonymousCartMergingMiddleware>();
        }
    }
}

The following code calls the middleware from `Startup.cs`

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseAnonymousCartMerging();        
    }
Mar 27, 2023

Comments

Manoj Kumawat
Manoj Kumawat Apr 20, 2023 02:08 PM

I am curious to know if AnonymousId is consistent throughout the user session until you merge the carts. 

in CMS 11 we had a problem of Anonymous ID being lost in a load-balanced environment. Then I had to do this in order to keep anonymousID persistent. 

https://vimvq1987.com/loading-carts-load-balancing-environment/

Not sure if this is still a problem with that. If not, then it is not a problem anymore to worry about. 

Please login to comment.
Latest blogs
Optimizely SaaS CMS Concepts and Terminologies

Whether you're a new user of Optimizely CMS or a veteran who have been through the evolution of it, the SaaS CMS is bringing some new concepts and...

Patrick Lam | Jul 15, 2024

How to have a link plugin with extra link id attribute in TinyMce

Introduce Optimizely CMS Editing is using TinyMce for editing rich-text content. We need to use this control a lot in CMS site for kind of WYSWYG...

Binh Nguyen Thi | Jul 13, 2024

Create your first demo site with Optimizely SaaS/Visual Builder

Hello everyone, We are very excited about the launch of our SaaS CMS and the new Visual Builder that comes with it. Since it is the first time you'...

Patrick Lam | Jul 11, 2024

Integrate a CMP workflow step with CMS

As you might know Optimizely has an integration where you can create and edit pages in the CMS directly from the CMP. One of the benefits of this i...

Marcus Hoffmann | Jul 10, 2024

GetNextSegment with empty Remaining causing fuzzes

Optimizely CMS offers you to create partial routers. This concept allows you display content differently depending on the routed content in the URL...

David Drouin-Prince | Jul 8, 2024 | Syndicated blog

Product Listing Page - using Graph

Optimizely Graph makes it possible to query your data in an advanced way, by using GraphQL. Querying data, using facets and search phrases, is very...

Jonas Bergqvist | Jul 5, 2024