Basket Checkout thru code

For general questions and discussions specific to the AbleCommerce 7.0 Asp.Net product.
Post Reply
derekz
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 38
Joined: Mon Nov 03, 2008 3:13 pm

Basket Checkout thru code

Post by derekz » Thu Apr 09, 2009 2:08 pm

I'm trying to create an Order object in code. I'm doing this by populating a Basket and running the Basket.Checkout() method.

Populating the Basket with BasketItems and performing the Checkout method is working, but I'm having 1 problem. All my Totals (i.e., Item Sub Total, Discount Amounts, etc..) are correct except for Shipping. Shipping is empty and not shipping item is added to the Order.Items collection. I'm using an integrated carrier (UPS), but also a flat rate ship method. When stepping through the code, the Basket.Shipment[x].ShipMethodId is "0" even though I set it to a valid ShipMethodId (1). I'm guessing that is the problem, but not sure why the ShipMethodId is being cleared out.

Here is a copy of the code.

Code: Select all

            

            Order order = null;

            try
            {

                //initialize user
                User user = UserDataSource.CreateUserInstance();
                user.IsAnonymous = true;
                user.Save();

                // create basket
                Basket basket = user.Basket;

                //setup new address
                Address address = new Address();
                address.Address1 = "1111 15th Street";
                address.City = "Austin";
                address.Province = "TX";
                address.PostalCode = "78704";
                address.LastName = "Doe";
                address.FirstName = "John";
                address.Email = "John@Doe.com";
                address.Phone = "(555) 123-1234";
                address.CountryCode = "US";
                address.UserId = user.UserId;
                address.Save();

                // Save anonymous user
                user.PrimaryAddressId = address.AddressId;
                user.Save();

                //Create Basket Items
                ProductCollection productList;
                ProductVariantCollection variantList;

                foreach (CustomItem item in CustomItems)
                {
                    BasketItem bi = null;
                    // Check to see if this item is a product
                    productList = ProductDataSource.LoadForCriteria(string.Format("SKU = '{0}'", item.ProductSKU));
                    if (productList != null && productList.Count > 0)
                    {
                        bi = BasketItemDataSource.CreateForProduct(productList[0].ProductId, (short)item.QtyOrdered);
                    }

                    if (bi == null) // If bi is null, then the item was not found as a product
                    {
                        // Check to see if this item is a product variant
                        variantList = ProductVariantDataSource.LoadForCriteria(string.Format("SKU = '{0}'", item.ProductSKU));
                        if (variantList != null && variantList.Count > 0)
                        {
                            bi = BasketItemDataSource.CreateForProduct(variantList[0].ProductId, (short)item.QtyOrdered, variantList[0].OptionList);
                        }
                    }

                    if (bi == null)
                    {
                        throw new Exception(string.Format("Product not found: {0}",item.Name));
                    }

                    basket.Items.Add(bi);

                }
                basket.Save();

                //add a shipments to the order
                BasketShipment shipment = new BasketShipment();

                // Set Address information
                Address shipAddress = new Address();
                shipAddress.Address1 = "1111 15th Street";
                shipAddress.City = "Austin";
                shipAddress.CountryCode = "US";
                shipAddress.Email = "john@doe.com";
                shipAddress.FirstName = "John";
                shipAddress.LastName = "Doe";
                shipAddress.Phone = "(555) 123-1234";
                shipAddress.PostalCode = "78704";
                shipAddress.Province = "TX";
                shipAddress.Residence = "tue;
                shipAddress.UserId = user.UserId;
                shipAddress.Save();
                shipment.AddressId = shipAddress.AddressId;

                shipment.BasketId = basket.BasketId;

                // Set Ship Method
                shipment.ShipMethodId = 1;

                // Set reminding items
                shipment.ShipMessage = "Fragile (it's French for major award)";
                shipment.WarehouseId = 1;

                shipment.Save();
                basket.Shipments.Add(shipment);
                
                basket.Save();

                // Add Coupons
                foreach (string couponCode in CouponCodes)
                {

                     string validateCouponMessage = ValidateCoupon(couponCode, basket);

                     if (validateCouponMessage != "Success")
                     {
                        throw new Exception(validateCouponMessage);
                     }
                }
                basket.Save();

                //PROCESS THE CHECKOUT
                basket.Package();
                basket.Recalculate();
                Payment payment = new Payment();
                payment.Amount = basket.Items.TotalPrice();
                CheckoutRequest checkoutRequest = new CheckoutRequest(payment);
                CheckoutResponse checkoutResponse = basket.Checkout(checkoutRequest);

                //if successful
                if (checkoutResponse.Success)
                {
                    order = OrderDataSource.Load(checkoutResponse.OrderId);

                    order.OrderDate = System.Convert.ToDateTime(NewOrderDate);

                    order.Save();
                }
            }
            catch (Exception ex) {
                throw ex;
            }

            return order;
Any ideas why ShipMethodId would be coming up empty???

derekz
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 38
Joined: Mon Nov 03, 2008 3:13 pm

Re: Basket Checkout thru code

Post by derekz » Fri Apr 10, 2009 7:14 am

Update....

I've been playing around with this problem and identified a couple of items that might shed some light on the solution.

In my code, if I remove basket.Package() and only call the Recalculate() method, I get an error on the basket.Checkout() method. The error message doesn't say anything except an error occurred and you have not been charge. Maybe I'm missing payment information???

Any ideas?

User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Re: Basket Checkout thru code

Post by heinscott » Fri Apr 10, 2009 7:23 am

Here is the code I use for the shipment part. Seems to work fine for me.

Code: Select all

basket.Shipments.Add(new BasketShipment());
basket.Shipments[0].AddressId = _User.PrimaryAddressId;
basket.Shipments[0].ShipMethodId = 4;
basket.Package();
basket.Recalculate();
The only difference I can really see between how you are processing and the way I am, is the:

Code: Select all

CheckoutRequest checkoutRequest = new CheckoutRequest(payment);
I am using:

Code: Select all

CheckoutRequest checkoutRequest = new CheckoutRequest(null);
Hope that helps.

Scott

derekz
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 38
Joined: Mon Nov 03, 2008 3:13 pm

Re: Basket Checkout thru code

Post by derekz » Fri Apr 10, 2009 10:34 am

Thanks for the tip Scott. I actually used your earlier post as a reference.

I tried your tip, and it works only in certain situations. From the code I posted above, when I create a new anonymous user, I create an address and assign it as the User's Primary Address. If I use your tip with that Primary Address, everything works perfectly.

Code: Select all

basket.Shipments.Add(new BasketShipment());
basket.Shipments[0].AddressId = _User.PrimaryAddressId;
basket.Shipments[0].ShipMethodId = 4;
basket.Package();
basket.Recalculate();
However, my business requirements need me to create a new address and assign it as the address for the basket shipment. This is where it fails. Could this be a bug, or am I using the Address incorrectly.

Also...I change my checkout to...

Code: Select all

CheckoutRequest checkoutRequest = new CheckoutRequest(null);

User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Re: Basket Checkout thru code

Post by heinscott » Fri Apr 10, 2009 10:49 am

I am also creating a new user, and then the address...

Code: Select all

User _User = InitializeUser();
...and the InitializeUser method.

Code: Select all

private User InitializeUser()
{
        User _User;
        _User = UserDataSource.CreateUserInstance();
        _User.Save();
        _User.Basket.Save();
        return _User;
}
I guess try that. Everything seems to work for me.
Good luck

Scott

derekz
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 38
Joined: Mon Nov 03, 2008 3:13 pm

Re: Basket Checkout thru code

Post by derekz » Fri Apr 10, 2009 1:43 pm

Thanks Scott...this is getting me closer.

I've made some changes, the ship methods are working out, and my basket is getting populated correctly. Now the only other problem is during the checkout. Getting the message about something wrong, and I will not be charge. It's a pretty basic error message, so I'm again at a lost.

Here is my code

Code: Select all

            
           Order order = null;

            try
            {

                //initialize user
                User user = InitializeUser();

                // create basket
                Basket basket = user.Basket;

                //setup new address
                Address address = new Address();
                address.Address1 = "1111 15th Street";
                address.City = "Austin";
                address.Province = "TX";
                address.PostalCode = "78704";
                address.LastName = "Doe";
                address.FirstName = "John";
                address.Email = "John@Doe.com";
                address.Phone = "(555) 123-1234";
                address.CountryCode = "US";
                address.UserId = user.UserId;
                address.Save();

                // Save anonymous user
                user.PrimaryAddressId = address.AddressId;
                user.Save();

                //Create Basket Items
                ProductCollection productList;
                ProductVariantCollection variantList;

                foreach (CustomItem item in CustomItems)
                {
                    BasketItem bi = null;
                    // Check to see if this item is a product
                    productList = ProductDataSource.LoadForCriteria(string.Format("SKU = '{0}'", item.ProductSKU));
                    if (productList != null && productList.Count > 0)
                    {
                        bi = BasketItemDataSource.CreateForProduct(productList[0].ProductId, (short)item.QtyOrdered);
                    }

                    if (bi == null) // If bi is null, then the item was not found as a product
                    {
                        // Check to see if this item is a product variant
                        variantList = ProductVariantDataSource.LoadForCriteria(string.Format("SKU = '{0}'", item.ProductSKU));
                        if (variantList != null && variantList.Count > 0)
                        {
                            bi = BasketItemDataSource.CreateForProduct(variantList[0].ProductId, (short)item.QtyOrdered, variantList[0].OptionList);
                        }
                    }

                    if (bi == null)
                    {
                        throw new Exception(string.Format("Product not found: {0}",item.Name));
                    }

                    basket.Items.Add(bi);

                }
                basket.Save();

                // Add Coupons
                foreach (string couponCode in CouponCodes)
                {

                     string validateCouponMessage = ValidateCoupon(couponCode, basket);

                     if (validateCouponMessage != "Success")
                     {
                        throw new Exception(validateCouponMessage);
                     }
                }
                basket.Save();

                // Prepare the basket for shipping
                basket.Package();
                basket.Recalculate();

                basket.Shipments.Add(new BasketShipment());

                // Set Address information
                Address shipAddress = null;

                // First, check to see if shipping to billing address
                if (orderDTO.ShipToBilling.ToUpper() == "TRUE")
                {
                     shipAddress = user.PrimaryAddress;
                 }
                 else
                 {
                     shipAddress = new Address();
                     shipAddress.Address1 = "1111 15th Street";
                     shipAddress.City = "Austin";
                     shipAddress.CountryCode = "US";
                     shipAddress.Email = "john@doe.com";
                     shipAddress.FirstName = "John";
                     shipAddress.LastName = "Doe";
                     shipAddress.Phone = "(555) 123-1234";
                     shipAddress.PostalCode = "78704";
                     shipAddress.Province = "TX";
                     shipAddress.Residence = "tue;
                     shipAddress.UserId = user.UserId;
                           
                     user.Addresses.Add(shipAddress);
                     user.Save();
                 }

                 basket.Shipments[0].AddressId = shipAddress.AddressId;
                 basket.Shipments[0].ShipMethodId = 7;

                 basket.Shipments.Save();
                 basket.Save();

                //PROCESS THE CHECKOUT
                basket.Recalculate();
                Payment payment = new Payment();
                payment.Amount = basket.Items.TotalPrice();
                CheckoutRequest checkoutRequest = new CheckoutRequest(payment);
                CheckoutResponse checkoutResponse = basket.Checkout(checkoutRequest);

                //if successful
                if (checkoutResponse.Success)
                {
                    order = OrderDataSource.Load(checkoutResponse.OrderId);

                    order.OrderDate = System.Convert.ToDateTime(NewOrderDate);

                    order.Save();
                }
            }
            catch (Exception ex) {
                throw ex;
            }

            return order;

Any thoughts on why it is now populating the basket correctly, but not processing the Checkout() method?

D

derekz
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 38
Joined: Mon Nov 03, 2008 3:13 pm

Re: Basket Checkout thru code

Post by derekz » Mon Apr 13, 2009 1:21 pm

More updates...

So it appears that the above code will work only if you add coupons to the basket. Then the checkout will succeed and the order is created. So why doesn't it work if you don't add any coupons...what is the coupons doing?

I'm using the exact same coupon validation code that is in PlaceOrder2.aspx.cs

Code: Select all


        public string ValidateCoupon(string couponCode, Basket basket) {

            Coupon coupon = CouponDataSource.LoadForCouponCode(couponCode);
            String couponValidityMessage = String.Empty;
            string results = "Success";

            if (coupon != null)
            {
                if (!CouponCalculator.IsCouponAlreadyUsed(basket, coupon))
                {
                    if (CouponCalculator.IsCouponValid(basket, coupon, out couponValidityMessage))
                    {
                        BasketCoupon recentCoupon = new BasketCoupon(basket.UserId, coupon.CouponId);
                        basket.BasketCoupons.Add(recentCoupon);
                        // APPLY COUPON COMBINE RULE
                        //THE RULE: 
                        //If most recently applied coupon is marked "do not combine", then all previously
                        //entered coupons must be removed from Basket.

                        //If most recently applied coupon is marked "combine", then remove any applied
                        //coupon that is marked "do not combine".  (Logically, in this instance there
                        //could be at most one other coupon of this type...)
                        string previousCouponsRemoved = "";

                        if (recentCoupon.Coupon.AllowCombine)
                        {
                            //IF ALLOW COMBINE, REMOVE ALL PREVIOUS NOCOMBINE COUPONS
                            for (int i = (basket.BasketCoupons.Count - 1); i >= 0; i--)
                            {
                                if (!basket.BasketCoupons[i].Coupon.AllowCombine)
                                {
                                    if (previousCouponsRemoved.Length > 0)
                                    {
                                        previousCouponsRemoved += "," + basket.BasketCoupons[i].Coupon.Name;
                                    }
                                    else
                                    {
                                        previousCouponsRemoved = basket.BasketCoupons[i].Coupon.Name;
                                    }

                                    basket.BasketCoupons.DeleteAt(i);
                                }
                            }
                        }
                        else
                        {
                            //IF NOT ALLOW COMBINE, REMOVE ALL EXCEPT THIS COUPON
                            for (int i = (basket.BasketCoupons.Count - 1); i >= 0; i--)
                            {
                                if (basket.BasketCoupons[i] != recentCoupon)
                                {
                                    if (previousCouponsRemoved.Length > 0)
                                    {
                                        previousCouponsRemoved += "," + basket.BasketCoupons[i].Coupon.Name;
                                    }
                                    else
                                    {
                                        previousCouponsRemoved = basket.BasketCoupons[i].Coupon.Name;
                                    }
                                    basket.BasketCoupons.DeleteAt(i);
                                }
                            }
                        }

                        basket.Save();
                        basket.Recalculate();
                        if (previousCouponsRemoved.Length > 0)
                        {
                            if (recentCoupon.Coupon.AllowCombine)
                            {
                                results = String.Format(results, recentCoupon.Coupon.Name, previousCouponsRemoved, previousCouponsRemoved);
                            }
                            else
                            {
                                results = String.Format(results, recentCoupon.Coupon.Name, previousCouponsRemoved);
                            }
                        }
                    }
                    else
                    {
                        results = couponValidityMessage;
                    }
                }
                else
                {
                    results = "The coupon code you've entered is already in use.";
                }
            }
            else
            {
               results = "The coupon code you've entered is invalid.";
            }

            return results;
        
        }

Is this a bug in the API, or I'm I missing something?

Post Reply