Programatically add product to cart

Posted by Community Admin on 04-Aug-2018 21:49

Programatically add product to cart

All Replies

Posted by Community Admin on 01-Dec-2011 00:00
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!
Posted by Community Admin on 05-Dec-2011 00:00
Bumping this up, hoping someone might have a response...
Posted by Community Admin on 05-Dec-2011 00:00
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
Posted by Community Admin on 05-Dec-2011 00:00
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.
Posted by Community Admin on 06-Dec-2011 00:00
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). 
Posted by Community Admin on 06-Dec-2011 00:00
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
Posted by Community Admin on 08-Dec-2011 00:00
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
Posted by Community Admin on 13-Dec-2011 00:00
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
Posted by Community Admin on 22-Aug-2016 00:00

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,

Posted by Community Admin on 04-Dec-2017 00:00
Nuwan, did you ever manage to get this working? 
This thread is closed