How to add a product to the shopping cart via an external link.

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
10 years ago
This problem has been bothering me for a long time and I finally figured out how to do it.

The way this works is you place a link on an external site or in an email blast like so:

http://mynopstore.com/addproducttocart/url/15/1/1

After the link is navigated to nop adds the item to the cart and redirects to /cart.

This has only been tested with 3.2 but should work for older versions.

Added to RouteProvider.cs in Nop.Web.Infrastructure
            //add product to cart (without any attributes and options). used on any site.
            routes.MapLocalizedRoute("AddProductToCart-Url",
                            "addproducttocart/url/{productId}/{shoppingCartTypeId}/{quantity}",
                            new { controller = "ShoppingCart", action = "AddProductToCart_Url" },
                            new { productId = @"\d+", shoppingCartTypeId = @"\d+", quantity = @"\d+" },
                            new[] { "Nop.Web.Controllers" });


Added to ShoppingCartController.cs in Nop.Web.Controllers
        [HttpGet]
        public void AddProductToCart_Url(int productId, int shoppingCartTypeId, int quantity, bool forceredirection = false)
        {
            var cartType = (ShoppingCartType)shoppingCartTypeId;

            var product = _productService.GetProductById(productId);
            if (product == null)
                Response.Redirect("/cart");


            //we can add only simple products
            if (product.ProductType != ProductType.SimpleProduct)
            {
                Response.Redirect("/cart");
                return;
            }

            if (product.CustomerEntersPrice)
            {
                Response.Redirect("/cart");
                return;
            }

            var allowedQuantities = product.ParseAllowedQuatities();
            if (allowedQuantities.Length > 0)
            {
                Response.Redirect("/cart");
                return;
            }

            //get standard warnings without attribute validations
            //first, try to find existing shopping cart item
            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                .Where(sci => sci.ShoppingCartType == cartType)
                .Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
                .ToList();
            var shoppingCartItem = _shoppingCartService.FindShoppingCartItemInTheCart(cart, cartType, product);
            //if we already have the same product in the cart, then use the total quantity to validate
            var quantityToValidate = shoppingCartItem != null ? shoppingCartItem.Quantity + quantity : quantity;
            var addToCartWarnings = _shoppingCartService
                .GetShoppingCartItemWarnings(_workContext.CurrentCustomer, cartType,
                product, _storeContext.CurrentStore.Id, string.Empty,
                decimal.Zero, quantityToValidate, false, true, false, false, false);
            if (addToCartWarnings.Count > 0)
            {
                Response.Redirect("/cart");
                return;
            }

            //now let's try adding product to the cart (now including product attribute validation, etc)
            addToCartWarnings = _shoppingCartService.AddToCart(_workContext.CurrentCustomer,
                product, cartType, _storeContext.CurrentStore.Id,
                string.Empty, decimal.Zero, quantity, true);
            if (addToCartWarnings.Count > 0)
            {
                Response.Redirect("/cart");
                return;
            }

            //added to the cart/wishlist
            switch (cartType)
            {
                case ShoppingCartType.Wishlist:
                    {
                        //activity log
                        _customerActivityService.InsertActivity("PublicStore.AddToWishlist", _localizationService.GetResource("ActivityLog.PublicStore.AddToWishlist"), product.Name);

                        Response.Redirect("/cart");
                        return;
                    }
                case ShoppingCartType.ShoppingCart:
                default:
                    {
                        //activity log
                        _customerActivityService.InsertActivity("PublicStore.AddToShoppingCart", _localizationService.GetResource("ActivityLog.PublicStore.AddToShoppingCart"), product.Name);

                        if (_shoppingCartSettings.DisplayCartAfterAddingProduct || forceredirection)
                        {
                            Response.Redirect("/cart");
                            return;
                        }
                        else
                        {

                            //display notification message and update appropriate blocks
                            var updatetopcartsectionhtml = string.Format(_localizationService.GetResource("ShoppingCart.HeaderQuantity"),
                                 _workContext.CurrentCustomer.ShoppingCartItems
                                 .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                                 .Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
                                 .ToList()
                                 .GetTotalProducts());
                            var updateflyoutcartsectionhtml = _shoppingCartSettings.MiniShoppingCartEnabled
                                ? this.RenderPartialViewToString("FlyoutShoppingCart", PrepareMiniShoppingCartModel())
                                : "";

                            Response.Redirect("/cart");
                            return;
                        }
                    }
            }
        }
10 years ago
Nice, maybe write a PlugIn for it so you do not have to touch the core ?
10 years ago
Hi

I have created a plugin to achieve this



Features:
  
  Add product to shopping cart or wish list
  Use product ID or product Sku to add product
  Quantity selected in link
  No product found redirection page selectable
  If link points to grouped to product, product detail page will be displayed.


Version 3.10 can be downloaded here
http://www.cartonline.co.uk/addtocart/NCEATC31U-sku/1

Version 3.20 can be downloaded here
http://www.cartonline.co.uk/addtocart/NCEATC32U-sku/1
10 years ago
Can you post the source?
10 years ago
Hi

I have updated the downloads to include the source code.


Any tips or improvements you may have I would be pleased if you could share with us all.


Thanks
Spire
10 years ago
Hi,
I just want to mention to take care of a search engine indexing...did you avoid it will fill carts?
J.
10 years ago
You would do that like this:



<a href="http://www.cartonline.co.uk/addtocart/NCEATC32U-sku/1" rel="nofollow">BUY NOW!</a>

10 years ago
nikropht wrote:
You would do that like this:



<a href="http://www.cartonline.co.uk/addtocart/NCEATC32U-sku/1" rel="nofollow">BUY NOW!</a>



Some search engines are not that smart :-)... I show Nop commerce team member adding IsSearchEngine() to avoid EU cookie law popup. Maybe add this before executing the code?
10 years ago
Then add the "/addtocart" url to robots.txt as a disallow on the destination site.
9 years ago
Spire wrote:
Hi

I have created a plugin to achieve this



Features:
  
  Add product to shopping cart or wish list
  Use product ID or product Sku to add product
  Quantity selected in link
  No product found redirection page selectable
  If link points to grouped to product, product detail page will be displayed.


Version 3.10 can be downloaded here
http://www.cartonline.co.uk/addtocart/NCEATC31U-sku/1

Version 3.20 can be downloaded here
http://www.cartonline.co.uk/addtocart/NCEATC32U-sku/1


I would really love to get this plugin but the links are getting a 404 error. Is there a new link available or is there somewhere else to get this type of plugin?
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.