Merging carts when customer logs in on Commerce 14
In Commerce 13 and below, we had out of the box default behaviour that when a customer logs in, their cart, wishlist and any orders they made during their anonymous state will get merged into their customer contact associated with their principal object. This is done via a httpmodule where an authentication event would be raised and the IProfileMigrator would get called executing the said actions.
Unfortunately in the current version of Commerce 14 (v14.5.0 at the time of this post) does not include the middleware to hook up the IProfileMigrator and do this automatically as it did with its previous versions.
For the example middleware code please go here: https://www.hiddenfoundry.com/thoughts/merging-carts-when-logging-in-from-an-anonymous-state-in-commerce-14/
Hi, thank you for the blog post, it helped a lot. The code snippet isn't fully working though regarding the service locator and getting the anonymous ID as a feature. Not sure if that's due to the updated in Commerce (running v14.11.0) or because it's incomplete.
For me, the anonymous ID is also removed as soon as the user is authenticated. A workaround I found is to get the ID from the cookie that the anonymous ID middleware sets. This isn't deleted upon logging in.
Here is the middleware that is working for me:
The CustomContext is an implementation that handles session info. When we process a login, we store a value in the user session that flags it as the first load after log-in. This is used elsewhere in the application. Accessing this property removes the session key, which is why I add it back in after running the migration. This prevents multiple requests from triggering the migration simulatenously.
Hope this helps someone.
Thanks for the comment. Sorry the initial attempt didn't work. I've just tried it on the latest version of Commerce 14.12 on a fresh Foundation instance and it was working just fine.
Just make sure you call your middleware after:
app.AnonymousId();
app.UseAuthentication();
app.UseAuthorization();
Hi, yes it seems I had the UseAnonymousId middleware after the two. Moving it to the front makes it work :) Maybe you'll want to add that line to your blog post in the last code snippet.
The syntax to get the Id seems to also have changed slightly from your snippet. This works:
Surjit Bharath,
You deserve 5 star for this post. Thanks for saving our life.