+1-888-365-2779
Try Now
More in this section

Forums / Developing with Sitefinity / Programatically add product to cart

Programatically add product to cart

9 posts, 0 answered
  1. Amanda Shafer
    Amanda Shafer avatar
    198 posts
    Registered:
    12 Oct 2012
    01 Dec 2011
    Link to this post
    Hi,
    I was wondering if anyone had any example code for programatically adding a product to a visitors shopping cart. 

    Here's the scenario. I have a complicated registration form which pulls data from another system. I would like at the end of the process to add a product (event registration) to their shopping cart and then direct them to the payment processing.

    I'm a beginning programmer, but I have created another form that imports events from the other system into Sitefinity. (see http://www.sitefinity.com/devnet/forums/sitefinity-4-x/general-discussions/import-events-from-different-database.aspx
    )  I was hoping there was something similar I can do for adding the product.

    Thanks!
  2. Amanda Shafer
    Amanda Shafer avatar
    198 posts
    Registered:
    12 Oct 2012
    05 Dec 2011
    Link to this post
    Bumping this up, hoping someone might have a response...
  3. SteveV
    SteveV avatar
    178 posts
    Registered:
    06 Nov 2011
    05 Dec 2011
    Link to this post
    I started a similar thread around the same time as you and I'm waiting for an anwser as well.  Seems like this should be easy to do but the lact of response from Telerik has me a bit concerned.  My thread is located here: Using ecommerce for donations and adding items to cart programatically

    --Steve
  4. Amanda Shafer
    Amanda Shafer avatar
    198 posts
    Registered:
    12 Oct 2012
    05 Dec 2011
    Link to this post
    I've found that there is an add to cart method for the orders manager, but I can't figure out how to get the cart order to input it.
    Here is what I have so far:
    CatalogManager catalog = new CatalogManager();
                Product product = catalog.GetProduct("AEATT12/A3ME");
     
                OrdersManager orderm = new OrdersManager();
                CartOrder cartItem = orderm.CreateCartOrder();
                 orderm.AddToCart(cartItem, product, 1);
         orderm.SaveChanges();


    But I keep getting an error message that it cannot be inputed because of a null price value.
  5. Amanda Shafer
    Amanda Shafer avatar
    198 posts
    Registered:
    12 Oct 2012
    06 Dec 2011
    Link to this post
    Correction: It was a currency value that was needed. I modified the code and got this to work (almost).

    CatalogManager catalog = new CatalogManager();
    Product product = catalog.GetProduct("AEATT12/A3ME");
     
    OrdersManager orderm = new OrdersManager();
    CartOrder cartItem = orderm.CreateCartOrder();
    cartItem.Currency = "USD";
     
    orderm.AddToCart(cartItem, product, 1);
     
    orderm.SaveChanges();

    It seems to put the order in the shopping cart in the database, however it does't set the cookie that's needed for the user to actually checkout ( I think that's what is necessary). 
  6. Venkata Koppaka
    Venkata Koppaka avatar
    67 posts
    Registered:
    24 Sep 2012
    06 Dec 2011
    Link to this post
    Hi Amanda Shafer,

    You can use the snippet below -
    public void AddToCart()
    {
        var ordersManager = OrdersManager.GetManager();
        var catManager = CatalogManager.GetManager();
        Guid productId = Guid.NewGuid(); //Get the Guid of the product you want to add to cart
     
        var product = catManager.GetProduct(productId);
         
         
        int quantity = 1 //Set the quantity that is supposed to be added to the cart;
         
        try
        {
            CartOrder shoppingCart = GetShoppingCartForUser(ordersManager);
            CartDetail cartDetail = shoppingCart.Details.Where(d => d.ProductId == product.Id).SingleOrDefault();
     
            if (cartDetail != null)
            {
                ordersManager.IncreaseQuantity(cartDetail.Id, quantity);
            }
            else
            {
                shoppingCart.Currency = Config.Get<EcommerceConfig>().DefaultCurrency;
                ordersManager.AddToCart(shoppingCart, product, quantity);
            }
     
            ordersManager.SaveChanges();
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException(Res.Get<OrdersResources>("NotAddedToCart"));
        }
    }
     
    public Guid GetShoopingCartId()
    {
        HttpCookie shoppingCartCookie = HttpContext.Current.Request.Cookies[EcommerceConstants.OrdersConstants.ShoppingCartIdCookieName];
     
        if (shoppingCartCookie == null || string.IsNullOrWhiteSpace(shoppingCartCookie.Value))
            return Guid.Empty;
     
        if (!shoppingCartCookie.Value.IsGuid())
            throw new InvalidOperationException("cartOrderId string cannot be parsed as a GUID; please provide a valid cartOrderId value.");
     
        return new Guid(shoppingCartCookie.Value);
    }
     
    public CartOrder GetShoppingCartForUser(OrdersManager ordersManager)
    {
        Guid shoppingCartId = GetShoopingCartId();
        CartOrder shoppingCart = ordersManager.TryGetCartOrder(shoppingCartId);
     
        if (shoppingCart == null)
        {
            shoppingCartId = Guid.NewGuid();
            shoppingCart = ordersManager.CreateCartOrder(shoppingCartId, null);
        }
     
        return shoppingCart;
    }



    Best wishes,
    Venkata Koppaka
    the Telerik team
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  7. Amanda Shafer
    Amanda Shafer avatar
    198 posts
    Registered:
    12 Oct 2012
    08 Dec 2011
    Link to this post
    Hi Venkata,

    I tried using the code you provided. However, it appears as if it does not set the cookie at all. So when the user navigates to the car, nothing appears in there.

    Through trial and error, I came up with this code. Don't know if it's the best way to go about it, but it does what I want.


    CatalogManager catalog = new CatalogManager();
    Product product = catalog.GetProduct("AEATT12/A3ME");
     
    HttpCookie cookie = Request.Cookies.Get("shoppingCartId");
    OrdersManager orderm = new OrdersManager();
     
    // Check if shopping cart cookie exists in the current request.
    if (cookie == null) //if it does not exist...
    {
        CartOrder cartItem = orderm.CreateCartOrder(); //create a new cart order
        var shoppingcartid = cartItem.Id;  // that id is equal to the cookie value
        HttpCookie Cookie = new HttpCookie("shoppingCartId");  //create a new shopping cart cookie
        DateTime now = DateTime.Now; // Set the cookie value.
        Cookie.Value = shoppingcartid.ToString(); // Set the cookie expiration date.
        Cookie.Expires = now.AddYears(1);// Add the cookie.
        Response.Cookies.Add(Cookie);  //give cart item currency of USD because it cannot be null
        cartItem.Currency = "USD"; //add the product to the cart
        orderm.AddToCart(cartItem, product, 1); //save all changes
        orderm.SaveChanges();
    }
    else //if the cookie does exist
    {
        Guid guid = new Guid(cookie.Value.ToString()); //get the cookie value as the guid
        CartOrder cartItem = orderm.GetCartOrder(guid); //get the cart based on the cookie value
        orderm.AddToCart(cartItem, product, 1); // add the item to the cart
        orderm.SaveChanges(); //save changes
    }
  8. Venkata Koppaka
    Venkata Koppaka avatar
    67 posts
    Registered:
    24 Sep 2012
    13 Dec 2011
    Link to this post
    Hello Amanda Shafer,

    Yes, your sample should work, I can also give you utility methods to remove and set the cookie in case you need it.
    Below are the snippets -
    public void SetShoppingCartId(Guid shoppingCartId)
    {
        const string shoppingCartCookieName = EcommerceConstants.OrdersConstants.ShoppingCartIdCookieName;
        HttpContext.Current.Response.Cookies[shoppingCartCookieName].Value = shoppingCartId.ToString();
        HttpContext.Current.Response.Cookies[shoppingCartCookieName].Expires = DateTime.Now.AddMonths(6);
    }
     
    public void RemoveShoppingCartCookie(this IOrdersControl ordersControl)
    {
        HttpCookie shoppingCartCookie = new HttpCookie(EcommerceConstants.OrdersConstants.ShoppingCartIdCookieName,"");
        shoppingCartCookie.Expires = DateTime.Now.AddDays(-1);
        HttpContext.Current.Response.Cookies.Add(shoppingCartCookie);
    }

    Thanks
    Venkata Koppaka
  9. Nuwan
    Nuwan avatar
    1 posts
    Registered:
    16 Mar 2016
    22 Aug in reply to Venkata Koppaka
    Link to this post

    Hi,

    I'm having the same issue. I can see the cart order in "sf_ec_cart_order" and "sf_ec_cart_detail" tables. However I can't see the order in my shopping cart. I tried everything in this thread, but no success. Can anyone provide me little help please.

    Thank you,

9 posts, 0 answered