protected void GCheckoutButton1_Click(object sender, ImageClickEventArgs e) { CheckoutShoppingCartRequest Req = GCheckoutButton1.CreateRequest(); Req.AddItem("Snickers", "Packed with peanuts.", 0.75m, 2); Req.AddItem("Gallon of Milk", "Milk goes great with candy bars!", 2.99m, 1); Req.AddStateTaxRule("CA", 0.0825, true); Req.AddStateTaxRule("IL", 0.0625, false); ShippingRestrictions Only48Lower = new ShippingRestrictions(); // Only48Lower.AddAllowedCountryArea(GCheckout.AutoGen.USAreas.CONTINENTAL_48); Req.AddFlatRateShippingMethod("UPS Ground", 7.05m, Only48Lower); ShippingRestrictions OnlyCA_NV = new ShippingRestrictions(); OnlyCA_NV.AddAllowedStateCode("CA"); OnlyCA_NV.AddAllowedStateCode("NV"); Req.AddFlatRateShippingMethod("California Express", 6.35m, OnlyCA_NV); Req.AddFlatRateShippingMethod("USPS", 3.08m); Req.AddPickupShippingMethod("Pick up in store", 0); Req.ContinueShoppingUrl = "http://www.example.com/continueshopping"; Req.EditCartUrl = "http://www.example.com/editcart"; GCheckoutResponse Resp = Req.Send(); Response.Redirect(Resp.RedirectUrl, true); }
public void AddShippingMethods(CheckoutShoppingCartRequest request, IEnumerable <ShippingMethod> shippingMethods) { foreach (var shippingMethod in shippingMethods) { // Is there a way for me to test this method call? request.AddFlatRateShippingMethod(shippingMethod.Name, shippingMethod.PriceExTax, shippingMethod.ToShippingRestrictions()); } }
public void CartExpiration() { byte[] Xml; AutoGen.CheckoutShoppingCart Cart; CheckoutShoppingCartRequest Req = new CheckoutShoppingCartRequest ("123", "456", EnvironmentType.Sandbox, "USD", 0); Req.AddItem("Mars bar", "", 0.75m, 2); Req.AddFlatRateShippingMethod("USPS", 4.30m); Req.SetExpirationMinutesFromNow(10); Xml = Req.GetXml(); Cart = (AutoGen.CheckoutShoppingCart)EncodeHelper.Deserialize(Xml); DateTime Exp = Cart.shoppingcart.cartexpiration.gooduntildate; Exp = Exp.ToLocalTime(); TimeSpan T = Exp.Subtract(DateTime.Now); Assert.IsTrue(T.TotalSeconds <= 600); Assert.IsTrue(T.TotalSeconds > 595); }
public void RequestInitialAuthDetails() { byte[] Xml; AutoGen.CheckoutShoppingCart Cart; CheckoutShoppingCartRequest Req = new CheckoutShoppingCartRequest ("123", "456", EnvironmentType.Sandbox, "USD", 0); Req.AddItem("Mars bar", "", 0.75m, 2); Req.AddFlatRateShippingMethod("USPS", 4.30m); // Check the <order-processing-support> tag is not there by default. Xml = Req.GetXml(); Cart = (AutoGen.CheckoutShoppingCart)EncodeHelper.Deserialize(Xml); Assert.IsNull(Cart.orderprocessingsupport); // Set RequestInitialAuthDetails and check that the XML changes. Req.RequestInitialAuthDetails = true; Xml = Req.GetXml(); Cart = (AutoGen.CheckoutShoppingCart)EncodeHelper.Deserialize(Xml); Assert.IsNotNull(Cart.orderprocessingsupport); Assert.IsTrue(Cart.orderprocessingsupport.requestinitialauthdetails); Assert.IsTrue(Cart.orderprocessingsupport.requestinitialauthdetailsSpecified); }
/// <summary> /// Post cart to google /// </summary> /// <param name="req">Pre-generated request</param> /// <param name="cart">Shopping cart</param> /// <returns>Response</returns> public GCheckoutResponse PostCartToGoogle(CheckoutShoppingCartRequest req, NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart cart) { //items foreach (NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCartItem sci in cart) { ProductVariant productVariant = sci.ProductVariant; if (productVariant != null) { string description = ProductAttributeHelper.FormatAttributes(productVariant, sci.AttributesXml, NopContext.Current.User, ", ", false); string fullName = productVariant.FullProductName; decimal unitPrice = TaxManager.GetPrice(sci.ProductVariant, PriceHelper.GetUnitPrice(sci, NopContext.Current.User, true)); req.AddItem(fullName, description, sci.ShoppingCartItemId.ToString(), unitPrice, sci.Quantity); } } //discounts decimal subTotalDiscountBase = decimal.Zero; Discount appliedDiscount = null; //List<AppliedGiftCard> appliedGiftCards = null; decimal subtotalBaseWithoutPromo = decimal.Zero; decimal subtotalBaseWithPromo = decimal.Zero; string SubTotalError = ShoppingCartManager.GetShoppingCartSubTotal(cart, NopContext.Current.User, out subTotalDiscountBase, out appliedDiscount, out subtotalBaseWithoutPromo, out subtotalBaseWithPromo); if (subTotalDiscountBase > decimal.Zero) { req.AddItem("Discount", string.Empty, string.Empty, (decimal)(-1.0) * subTotalDiscountBase, 1); } //foreach (AppliedGiftCard agc in appliedGiftCards) //{ // req.AddItem(string.Format("Gift Card - {0}", agc.GiftCard.GiftCardCouponCode), string.Empty, string.Empty, (decimal)(-1.0) * agc.AmountCanBeUsed, 1); //} bool shoppingCartRequiresShipping = ShippingManager.ShoppingCartRequiresShipping(cart); if (shoppingCartRequiresShipping) { string shippingError = string.Empty; //TODO AddMerchantCalculatedShippingMethod //TODO AddCarrierCalculatedShippingOption ShippingOptionCollection shippingOptions = ShippingManager.GetShippingOptions(cart, NopContext.Current.User, null, ref shippingError); foreach (ShippingOption shippingOption in shippingOptions) { req.AddFlatRateShippingMethod(shippingOption.Name, TaxManager.GetShippingPrice(shippingOption.Rate, NopContext.Current.User)); } } //add only US, GB states //CountryCollection countries = CountryManager.GetAllCountries(); //foreach (Country country in countries) //{ // foreach (StateProvince state in country.StateProvinces) // { // TaxByStateProvinceCollection taxByStateProvinceCollection = TaxByStateProvinceManager.GetAllByStateProvinceID(state.StateProvinceID); // foreach (TaxByStateProvince taxByStateProvince in taxByStateProvinceCollection) // { // if (!String.IsNullOrEmpty(state.Abbreviation)) // { // Req.AddStateTaxRule(state.Abbreviation, (double)taxByStateProvince.Percentage, false); // } // } // } //} XmlDocument customerInfoDoc = new XmlDocument(); XmlElement customerInfo = customerInfoDoc.CreateElement("CustomerInfo"); customerInfo.SetAttribute("CustomerID", NopContext.Current.User.CustomerId.ToString()); customerInfo.SetAttribute("CustomerLanguageID", NopContext.Current.WorkingLanguage.LanguageId.ToString()); customerInfo.SetAttribute("CustomerCurrencyID", NopContext.Current.WorkingCurrency.CurrencyId.ToString()); req.AddMerchantPrivateDataNode(customerInfo); req.ContinueShoppingUrl = CommonHelper.GetStoreLocation(false); req.EditCartUrl = CommonHelper.GetStoreLocation(false) + "ShoppingCart.aspx"; GCheckoutResponse resp = req.Send(); return(resp); }
public void LoadSetting() { GoogleCheckOutWCFService pw = new GoogleCheckOutWCFService(); List <GoogleCheckOutSettingInfo> sf; OrderDetailsCollection orderdata2 = new OrderDetailsCollection(); orderdata2 = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"]; string itemidsWithVar = ""; foreach (var item in orderdata2.LstOrderItemsInfo) { itemidsWithVar += item.ItemID + "&" + item.Quantity + "&" + orderdata2.ObjOrderDetails.OrderID + "&" + item.Variants + ","; } string country = orderdata2.ObjShippingAddressInfo.Country.ToString(); string state = orderdata2.ObjShippingAddressInfo.State.ToString(); string zip = orderdata2.ObjShippingAddressInfo.Zip.ToString(); int addressID = Convert.ToInt32(orderdata2.ObjShippingAddressInfo.AddressID); try { sf = pw.GetAllGoogleCheckOutSetting(int.Parse(Session["GateWay"].ToString()), storeID, portalID); double amountTotal = double.Parse(Session["GrandTotalAll"].ToString()) * rate; decimal grandTotal = decimal.Parse(amountTotal.ToString(CultureInfo.InvariantCulture)); decimal totalTaxableAmount = 0; decimal subtotalAmount = 0; decimal taxSubTotal = 0; decimal shipping = Convert.ToDecimal(Convert.ToDouble(Session["ShippingCostAll"].ToString()) * rate); decimal shippingCost = decimal.Parse(shipping.ToString(CultureInfo.InvariantCulture)); decimal discountAmount = 0; decimal couponDiscountAmount = 0; decimal rewardDiscountAmount = 0; if (sf[0].GoogleEnvironmentType == "Sandbox") { CheckoutShoppingCartRequest gCartRequest = new CheckoutShoppingCartRequest(sf[0].GoogleMerchantID, sf[0].GoogleMerchantKey, GCheckout.EnvironmentType.Sandbox, sf[0].GoogleCurrencyType, 30, false); HttpContext.Current.Session["EnvironmentType"] = "Sandbox"; List <CartInfoforGoogleCheckOut> cd; cd = pw.GetCartDetailsForPG(storeID, portalID, customerID, userName, GetCurrentCultureName, sessionCode, country, state, zip, addressID); int nCount = 1; foreach (CartInfoforGoogleCheckOut oItem in cd) { string itemName = oItem.ItemName.ToString(); string description = oItem.ShortDescription.ToString(); int qty = Convert.ToInt32(oItem.Quantity.ToString()); decimal TaxRateValue = Convert.ToDecimal(Convert.ToDouble(oItem.TaxRateValue.ToString()) * rate) / qty; decimal amount = Convert.ToDecimal(Convert.ToDouble(oItem.Price.ToString()) * rate); decimal subTotal = amount;// +TaxRateValue; gCartRequest.AddItem(itemName, description, subTotal, qty); nCount++; } nCount--; //Send Discount Amount if (orderdata2.ObjOrderDetails.DiscountAmount != 0) { string itemName = "Cart Discount Amount"; string description = "Discount Applied on Cart Items"; int qty = 1; discountAmount = 0; decimal discount = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.DiscountAmount) * rate); discountAmount = decimal.Parse(discount.ToString(CultureInfo.InvariantCulture)); gCartRequest.AddItem(itemName, description, -discountAmount, qty); } //Send Coupon Amount if (orderdata2.ObjOrderDetails.CouponDiscountAmount != 0) { string itemName = "Coupon Discount Amount"; string description = "Coupon Discount Applied on Cart Items"; int qty = 1; couponDiscountAmount = 0; decimal couponDiscount = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.CouponDiscountAmount) * rate); couponDiscountAmount = decimal.Parse(couponDiscount.ToString(CultureInfo.InvariantCulture)); gCartRequest.AddItem(itemName, description, -couponDiscountAmount, qty); } //Send Reward Discount Amount if (orderdata2.ObjOrderDetails.RewardDiscountAmount != 0) { string itemName = "Reward Points Discount Amount"; string description = "Reward Points Discount Applied on Cart Items"; int qty = 1; rewardDiscountAmount = 0; decimal rewardDiscount = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.RewardDiscountAmount) * rate); rewardDiscountAmount = decimal.Parse(rewardDiscount.ToString(CultureInfo.InvariantCulture)); gCartRequest.AddItem(itemName, description, -rewardDiscountAmount, qty); } //tax if (orderdata2.ObjOrderDetails.TaxTotal != 0) { decimal tax = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.TaxTotal) * rate); taxSubTotal = decimal.Parse(tax.ToString(CultureInfo.InvariantCulture)); } subtotalAmount = grandTotal - shippingCost - taxSubTotal + discountAmount + couponDiscountAmount; totalTaxableAmount = subtotalAmount - discountAmount - couponDiscountAmount; double taxp = Convert.ToDouble((taxSubTotal * 100) / totalTaxableAmount); double taxPer = taxp / 100; gCartRequest.AddCountryTaxRule(USAreas.ALL, taxPer, false); //Shipping Cost string shippingMethod; if (HttpContext.Current.Session["ShippingMethodName"] != null) { shippingMethod = HttpContext.Current.Session["ShippingMethodName"].ToString(); } else { shippingMethod = "Default Shipping"; } //shippingMethod = "Default Shipping"; //decimal shippingcost = Convert.ToDecimal(Convert.ToDouble(Session["ShippingCostAll"].ToString()) * rate); gCartRequest.AddFlatRateShippingMethod(shippingMethod, shippingCost); //Create extra data to pass XmlDocument tempDoc = new System.Xml.XmlDocument(); tempDoc.LoadXml("<root />"); XmlNode orderIdNode = tempDoc.CreateElement("OrderID"); orderIdNode.InnerText = Session["OrderID"].ToString(); gCartRequest.AddMerchantPrivateDataNode(orderIdNode); XmlNode userIdNode = tempDoc.CreateElement("userName"); userIdNode.InnerText = userName; gCartRequest.AddMerchantPrivateDataNode(userIdNode); XmlNode amountNode = tempDoc.CreateElement("amount"); amountNode.InnerText = (double.Parse(Session["GrandTotalAll"].ToString()) * rate).ToString(); gCartRequest.AddMerchantPrivateDataNode(amountNode); XmlNode currencyNode = tempDoc.CreateElement("selectedCurrency"); currencyNode.InnerText = SelectedCurrency; gCartRequest.AddMerchantPrivateDataNode(currencyNode); XmlNode portalIDNode = tempDoc.CreateElement("portalID"); portalIDNode.InnerText = portalID.ToString(); gCartRequest.AddMerchantPrivateDataNode(portalIDNode); XmlNode customerIDNode = tempDoc.CreateElement("customerID"); customerIDNode.InnerText = customerID.ToString(); gCartRequest.AddMerchantPrivateDataNode(customerIDNode); XmlNode itemIdsNode = tempDoc.CreateElement("itemIds"); itemIdsNode.InnerText = itemidsWithVar; gCartRequest.AddMerchantPrivateDataNode(itemIdsNode); XmlNode storeIDNode = tempDoc.CreateElement("storeID"); storeIDNode.InnerText = storeID.ToString(); gCartRequest.AddMerchantPrivateDataNode(storeIDNode); XmlNode couponCodeNode = tempDoc.CreateElement("couponCode"); couponCodeNode.InnerText = couponCode; gCartRequest.AddMerchantPrivateDataNode(couponCodeNode); XmlNode sessionCodeNode = tempDoc.CreateElement("sessionCode"); sessionCodeNode.InnerText = sessionCode; gCartRequest.AddMerchantPrivateDataNode(sessionCodeNode); XmlNode pgIDNode = tempDoc.CreateElement("pgID"); pgIDNode.InnerText = Session["GateWay"].ToString(); gCartRequest.AddMerchantPrivateDataNode(pgIDNode); XmlNode MerchantIDNode = tempDoc.CreateElement("MerchantID"); MerchantIDNode.InnerText = sf[0].GoogleMerchantID; gCartRequest.AddMerchantPrivateDataNode(MerchantIDNode); XmlNode MerchantKeyNode = tempDoc.CreateElement("MerchantKey"); MerchantKeyNode.InnerText = sf[0].GoogleMerchantKey; gCartRequest.AddMerchantPrivateDataNode(MerchantKeyNode); //Get response GCheckoutResponse response = gCartRequest.Send(); // Post the request for Google checkout if (response.IsGood) { Response.Redirect(response.RedirectUrl, false); } } if (sf[0].GoogleEnvironmentType == "Production") { CheckoutShoppingCartRequest gCartRequest = new CheckoutShoppingCartRequest(sf[0].GoogleMerchantID, sf[0].GoogleMerchantKey, GCheckout.EnvironmentType.Production, sf[0].GoogleCurrencyType, 30, false); HttpContext.Current.Session["EnvironmentType"] = "Production"; List <CartInfoforGoogleCheckOut> cd; cd = pw.GetCartDetailsForPG(storeID, portalID, customerID, userName, GetCurrentCultureName, sessionCode, country, state, zip, addressID); int nCount = 1; foreach (CartInfoforGoogleCheckOut oItem in cd) { string itemName = oItem.ItemName.ToString(); string description = oItem.ShortDescription.ToString(); int qty = Convert.ToInt32(oItem.Quantity.ToString()); decimal TaxRateValue = Convert.ToDecimal(Convert.ToDouble(oItem.TaxRateValue.ToString()) * rate) / qty; decimal amount = Convert.ToDecimal(Convert.ToDouble(oItem.Price.ToString()) * rate); decimal subTotal = amount + TaxRateValue; gCartRequest.AddItem(itemName, description, subTotal, qty); nCount++; } nCount--; //Send Discount Amount if (orderdata2.ObjOrderDetails.DiscountAmount != 0) { string itemName = "Cart Discount Amount"; string description = "Discount Applied on Cart Items"; int qty = 1; discountAmount = 0; decimal discount = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.DiscountAmount) * rate); discountAmount = decimal.Parse(discount.ToString(CultureInfo.InvariantCulture)); gCartRequest.AddItem(itemName, description, -discountAmount, qty); } //Send Coupon Amount if (orderdata2.ObjOrderDetails.CouponDiscountAmount != 0) { string itemName = "Coupon Discount Amount"; string description = "Coupon Discount Applied on Cart Items"; int qty = 1; couponDiscountAmount = 0; decimal couponDiscount = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.CouponDiscountAmount) * rate); couponDiscountAmount = decimal.Parse(couponDiscount.ToString(CultureInfo.InvariantCulture)); gCartRequest.AddItem(itemName, description, -couponDiscountAmount, qty); } //Send Reward Discount Amount if (orderdata2.ObjOrderDetails.RewardDiscountAmount != 0) { string itemName = "Reward Points Discount Amount"; string description = "Reward Points Discount Applied on Cart Items"; int qty = 1; rewardDiscountAmount = 0; decimal rewardDiscount = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.RewardDiscountAmount) * rate); rewardDiscountAmount = decimal.Parse(rewardDiscount.ToString(CultureInfo.InvariantCulture)); gCartRequest.AddItem(itemName, description, -rewardDiscountAmount, qty); } //tax if (orderdata2.ObjOrderDetails.TaxTotal != 0) { decimal tax = Convert.ToDecimal(Convert.ToDouble(orderdata2.ObjOrderDetails.TaxTotal) * rate); taxSubTotal = decimal.Parse(tax.ToString(CultureInfo.InvariantCulture)); } subtotalAmount = grandTotal - shippingCost - taxSubTotal + discountAmount + couponDiscountAmount; totalTaxableAmount = subtotalAmount - discountAmount - couponDiscountAmount; double taxp = Convert.ToDouble((taxSubTotal * 100) / totalTaxableAmount); double taxPer = taxp / 100; gCartRequest.AddCountryTaxRule(USAreas.ALL, taxPer, false); //Shipping Cost string shippingMethod; if (HttpContext.Current.Session["ShippingMethodName"] != null) { shippingMethod = HttpContext.Current.Session["ShippingMethodName"].ToString(); } else { shippingMethod = "Default Shipping"; } //shippingMethod = "Default Shipping"; //decimal shippingcost = Convert.ToDecimal(Convert.ToDouble(Session["ShippingCostAll"].ToString()) * rate); gCartRequest.AddFlatRateShippingMethod(shippingMethod, shippingCost); //Create extra data to pass XmlDocument tempDoc = new System.Xml.XmlDocument(); tempDoc.LoadXml("<root />"); XmlNode orderIdNode = tempDoc.CreateElement("OrderID"); orderIdNode.InnerText = Session["OrderID"].ToString(); gCartRequest.AddMerchantPrivateDataNode(orderIdNode); XmlNode userIdNode = tempDoc.CreateElement("userName"); userIdNode.InnerText = userName; gCartRequest.AddMerchantPrivateDataNode(userIdNode); XmlNode amountNode = tempDoc.CreateElement("amount"); amountNode.InnerText = (double.Parse(Session["GrandTotalAll"].ToString()) * rate).ToString(); gCartRequest.AddMerchantPrivateDataNode(amountNode); XmlNode currencyNode = tempDoc.CreateElement("selectedCurrency"); currencyNode.InnerText = SelectedCurrency; gCartRequest.AddMerchantPrivateDataNode(currencyNode); XmlNode portalIDNode = tempDoc.CreateElement("portalID"); portalIDNode.InnerText = portalID.ToString(); gCartRequest.AddMerchantPrivateDataNode(portalIDNode); XmlNode customerIDNode = tempDoc.CreateElement("customerID"); customerIDNode.InnerText = customerID.ToString(); gCartRequest.AddMerchantPrivateDataNode(customerIDNode); XmlNode itemIdsNode = tempDoc.CreateElement("itemIds"); itemIdsNode.InnerText = itemidsWithVar; gCartRequest.AddMerchantPrivateDataNode(itemIdsNode); XmlNode storeIDNode = tempDoc.CreateElement("storeID"); storeIDNode.InnerText = storeID.ToString(); gCartRequest.AddMerchantPrivateDataNode(storeIDNode); XmlNode couponCodeNode = tempDoc.CreateElement("couponCode"); couponCodeNode.InnerText = couponCode; gCartRequest.AddMerchantPrivateDataNode(couponCodeNode); XmlNode sessionCodeNode = tempDoc.CreateElement("sessionCode"); sessionCodeNode.InnerText = sessionCode; gCartRequest.AddMerchantPrivateDataNode(sessionCodeNode); XmlNode pgIDNode = tempDoc.CreateElement("pgID"); pgIDNode.InnerText = Session["GateWay"].ToString(); gCartRequest.AddMerchantPrivateDataNode(pgIDNode); XmlNode MerchantIDNode = tempDoc.CreateElement("MerchantID"); MerchantIDNode.InnerText = sf[0].GoogleMerchantID; gCartRequest.AddMerchantPrivateDataNode(MerchantIDNode); XmlNode MerchantKeyNode = tempDoc.CreateElement("MerchantKey"); MerchantKeyNode.InnerText = sf[0].GoogleMerchantKey; gCartRequest.AddMerchantPrivateDataNode(MerchantKeyNode); //Get response GCheckoutResponse response = gCartRequest.Send(); // Post the request for Google checkout if (response.IsGood) { Response.Redirect(response.RedirectUrl, false); } } } catch (Exception ex) { lblnotity.Text = "Something goes wrong, hit refresh or go back to checkout"; clickhere.Visible = false; ProcessException(ex); } }
/// <summary> /// Post cart to google /// </summary> /// <param name="req">Pre-generated request</param> /// <param name="cart">Shopping cart</param> /// <returns>Response</returns> public GCheckoutResponse PostCartToGoogle(CheckoutShoppingCartRequest req, IList <Core.Domain.Orders.ShoppingCartItem> cart) { //there's no need to round prices (Math.Round(,2)) because GCheckout library does it for us //items foreach (Core.Domain.Orders.ShoppingCartItem sci in cart) { var productVariant = sci.ProductVariant; if (productVariant != null) { decimal taxRate = decimal.Zero; string description = _productAttributeFormatter.FormatAttributes(productVariant, sci.AttributesXml, _workContext.CurrentCustomer, ", ", false); string fullName = ""; if (!String.IsNullOrEmpty(sci.ProductVariant.GetLocalized(x => x.Name))) { fullName = string.Format("{0} ({1})", sci.ProductVariant.Product.GetLocalized(x => x.Name), sci.ProductVariant.GetLocalized(x => x.Name)); } else { fullName = sci.ProductVariant.Product.GetLocalized(x => x.Name); } decimal unitPrice = _taxService.GetProductPrice(sci.ProductVariant, _priceCalculationService.GetUnitPrice(sci, true), out taxRate); req.AddItem(fullName, description, sci.Id.ToString(), unitPrice, sci.Quantity); } } if (cart.RequiresShipping()) { //AddMerchantCalculatedShippingMethod //AddCarrierCalculatedShippingOption var shippingOptions = _shippingService.GetShippingOptions(cart, null); foreach (ShippingOption shippingOption in shippingOptions.ShippingOptions) { req.AddFlatRateShippingMethod(shippingOption.Name, _taxService.GetShippingPrice(shippingOption.Rate, _workContext.CurrentCustomer)); } } //add only US, GB states //CountryCollection countries = IoC.Resolve<ICountryService>().GetAllCountries(); //foreach (Country country in countries) //{ // foreach (StateProvince state in country.StateProvinces) // { // TaxByStateProvinceCollection taxByStateProvinceCollection = TaxByIoC.Resolve<IStateProvinceService>().GetAllByStateProvinceID(state.StateProvinceID); // foreach (TaxByStateProvince taxByStateProvince in taxByStateProvinceCollection) // { // if (!String.IsNullOrEmpty(state.Abbreviation)) // { // Req.AddStateTaxRule(state.Abbreviation, (double)taxByStateProvince.Percentage, false); // } // } // } //} //if (subTotalDiscountBase > decimal.Zero) //{ // req.AddItem("Discount", string.Empty, string.Empty, (decimal)(-1.0) * subTotalDiscountBase, 1); //} //foreach (AppliedGiftCard agc in appliedGiftCards) //{ // req.AddItem(string.Format("Gift Card - {0}", agc.GiftCard.GiftCardCouponCode), string.Empty, string.Empty, (decimal)(-1.0) * agc.AmountCanBeUsed, 1); //} var customerInfoDoc = new XmlDocument(); XmlElement customerInfo = customerInfoDoc.CreateElement("CustomerInfo"); customerInfo.SetAttribute("CustomerID", _workContext.CurrentCustomer.Id.ToString()); customerInfo.SetAttribute("CustomerLanguageID", _workContext.WorkingLanguage.Id.ToString()); customerInfo.SetAttribute("CustomerCurrencyID", _workContext.WorkingCurrency.Id.ToString()); req.AddMerchantPrivateDataNode(customerInfo); req.ContinueShoppingUrl = _webHelper.GetStoreLocation(false); req.EditCartUrl = _webHelper.GetStoreLocation(false) + "cart"; GCheckoutResponse resp = req.Send(); return(resp); }
public void TestAlternateTaxTables() { CheckoutShoppingCartRequest request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120); //Ensure the factory works as expected AlternateTaxTable ohio1 = new AlternateTaxTable("ohio"); request.AlternateTaxTables.Add(ohio1); AlternateTaxTable ohio2 = request.AlternateTaxTables["ohio"]; AlternateTaxTable ohio3 = new AlternateTaxTable("ohio", true); //Ensure that two Tax tables with the same name are not the same reference Assert.AreSame(ohio1, ohio2); Assert.IsFalse(object.ReferenceEquals(ohio1, ohio3)); //Assert.AreEqual(ohio1, ohio3); //Now add some rules to the item ohio1.AddStateTaxRule("OH", .02); //Make sure we can add an item to the cart. ShoppingCartItem item = request.AddItem("Item 1", "Cool Candy 1", 2.00M, 1, ohio1); try { request.AddItem("Item 2", "Cool Candy 2", 2.00M, 1, ohio3); Assert.Fail("An exception should have been thrown when we tried to add an item that has a new Tax Reference"); } catch (Exception) { } //Now this should work fine. request.AddItem("Item 3", "Cool Candy 3", string.Empty, 2.00M, 1, ohio2); //you could create this as an IShoppingCartItem or ShoppingCartItem IShoppingCartItem newItem = new ShoppingCartItem("Item 2", "Cool Candy 2", string.Empty, 2.00M, 2, AlternateTaxTable.Empty, "This is a test of a string of private data"); //now decide to change your mind on the quantity and price newItem.Price = 20; newItem.Quantity = 4; request.AddItem(newItem); //Console.WriteLine("private data:" + newItem.MerchantPrivateItemData); Assert.AreEqual("This is a test of a string of private data", newItem.MerchantPrivateItemData); //now change the private data string and compare again. newItem.MerchantPrivateItemData = "This is a new String"; Assert.AreEqual("This is a new String", newItem.MerchantPrivateItemData); //now change the private data string and compare again. newItem.MerchantPrivateItemData = string.Empty; Assert.AreEqual(string.Empty, newItem.MerchantPrivateItemData); Assert.AreEqual(1, ohio1.RuleCount); DigitalItem emailDigitalItem = new DigitalItem(); request.AddItem("Email Digital Item", "Cool DigitalItem", 2.00m, 1, emailDigitalItem); DigitalItem urlDigitalItem = new DigitalItem(new Uri("http://www.google.com/download.aspx?myitem=1"), "Url Description for item"); request.AddItem("Url Digital Item", "Cool Url DigitalItem", 2.00m, 1, urlDigitalItem); DigitalItem keyDigitalItem = new DigitalItem("24-235-sdf-123541-53", "Key Description for item"); request.AddItem("Url Digital Item", "Cool Url DigitalItem", 2.00m, 1, keyDigitalItem); DigitalItem keyUrlItem = new DigitalItem("24-235-sdf-123541-53", "http://www.google.com/download.aspx?myitem=1", "Url/Key Description for item"); request.AddItem("Url Digital Item", "Cool Url DigitalItem", 2.00m, 1, keyUrlItem); //lets make sure we can add 2 different flat rate shipping amounts request.AddFlatRateShippingMethod("UPS Ground", 5); request.AddFlatRateShippingMethod("UPS 2 Day Air", 25); request.AddFlatRateShippingMethod("Test", 12, new ShippingRestrictions()); //You can't mix shipping methods try { request.AddMerchantCalculatedShippingMethod("Test", 12.95m); Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates."); } catch { } //lets try adding a Carrier Calculated Shipping Type //this should fail because the city is empty try { request.AddShippingPackage("failedpackage", string.Empty, "OH", "44114", DeliveryAddressCategory.COMMERCIAL, 2, 3, 4); Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates."); } catch { } //The first thing that needs to be done for carrier calculated shipping is we must set the FOB address. request.AddShippingPackage("main", "Cleveland", "OH", "44114", DeliveryAddressCategory.COMMERCIAL, 2, 3, 4); //this should fail because two packages exist try { request.AddShippingPackage("failedpackage", "Cleveland", "OH", "44114", DeliveryAddressCategory.COMMERCIAL, 2, 3, 4); Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates."); } catch { } try { request.AddShippingPackage("main", "Cleveland", "OH", "44114"); Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates."); } catch { } //The next thing we will do is add a Fedex Home Package. //We will set the default to 3.99, the Pickup to Regular Pickup, the additional fixed charge to 1.29 and the discount to 2.5% CarrierCalculatedShippingOption option = request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Home_Delivery, 3.99m, CarrierPickup.REGULAR_PICKUP, 1.29m, -2.5); option.AdditionalVariableChargePercent = 0; //make sure we can set it back to 0; option.AdditionalFixedCharge = 0; Assert.AreEqual(option.StatedShippingType, ShippingType.Fedex_Home_Delivery); Assert.AreEqual(option.Price, 3.99m); Assert.AreEqual(option.AdditionalVariableChargePercent, 0); Assert.AreEqual(option.AdditionalFixedCharge, 0); try { option.AdditionalFixedCharge = -1; Assert.Fail("Additional charge must be >= 0"); } catch { } option.AdditionalVariableChargePercent = 2; //make sure we can set it back to 0; option.AdditionalFixedCharge = 3; Assert.AreEqual(option.AdditionalVariableChargePercent, 2); Assert.AreEqual(option.AdditionalFixedCharge, 3); //this should fail try { request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Home_Delivery, 3.99m, CarrierPickup.REGULAR_PICKUP, 1.29m, -2.5); Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates."); } catch { } //verify the rounding works CarrierCalculatedShippingOption ccso = request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Ground, 1.993m); Assert.AreEqual(1.99m, ccso.Price); ccso.Price = 1.975m; Assert.AreEqual(1.98m, ccso.Price); request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Second_Day, 9.99m, CarrierPickup.REGULAR_PICKUP, 2.34m, -24.5); //Ensure we are able to create the cart xml byte[] cart = request.GetXml(); //Console.WriteLine(EncodeHelper.Utf8BytesToString(cart)); //test to see if the item can desialize Assert.IsNotNull(GCheckout.Util.EncodeHelper.Deserialize(cart)); }
/// <summary> /// Post cart to google /// </summary> /// <param name="Req">Pre-generated request</param> /// <param name="Cart">Shopping cart</param> /// <returns>Response</returns> public GCheckoutResponse PostCartToGoogle(CheckoutShoppingCartRequest Req, NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart Cart) { foreach (NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCartItem sci in Cart) { ProductVariant productVariant = sci.ProductVariant; if (productVariant != null) { string pvAttributeDescription = ProductAttributeHelper.FormatAttributes(productVariant, sci.AttributesXML, NopContext.Current.User, ", ", false); string fullName = productVariant.FullProductName; string description = pvAttributeDescription; decimal unitPrice = TaxManager.GetPrice(sci.ProductVariant, PriceHelper.GetUnitPrice(sci, NopContext.Current.User, true)); Req.AddItem(fullName, description, sci.ShoppingCartItemID.ToString(), unitPrice, sci.Quantity); } } decimal shoppingCartSubTotalDiscount; decimal shoppingCartSubTotal = ShoppingCartManager.GetShoppingCartSubTotal(Cart, NopContext.Current.User, out shoppingCartSubTotalDiscount); if (shoppingCartSubTotalDiscount > decimal.Zero) { Req.AddItem("Discount", string.Empty, string.Empty, (decimal)(-1.0) * shoppingCartSubTotalDiscount, 1); } bool shoppingCartRequiresShipping = ShippingManager.ShoppingCartRequiresShipping(Cart); if (shoppingCartRequiresShipping) { string shippingError = string.Empty; //TODO AddMerchantCalculatedShippingMethod //TODO AddCarrierCalculatedShippingOption ShippingOptionCollection shippingOptions = ShippingManager.GetShippingOptions(Cart, NopContext.Current.User, null, ref shippingError); foreach (ShippingOption shippingOption in shippingOptions) { Req.AddFlatRateShippingMethod(shippingOption.Name, TaxManager.GetShippingPrice(shippingOption.Rate, NopContext.Current.User)); } } //add only US, GB states //CountryCollection countries = CountryManager.GetAllCountries(); //foreach (Country country in countries) //{ // foreach (StateProvince state in country.StateProvinces) // { // TaxByStateProvinceCollection taxByStateProvinceCollection = TaxByStateProvinceManager.GetAllByStateProvinceID(state.StateProvinceID); // foreach (TaxByStateProvince taxByStateProvince in taxByStateProvinceCollection) // { // if (!String.IsNullOrEmpty(state.Abbreviation)) // { // Req.AddStateTaxRule(state.Abbreviation, (double)taxByStateProvince.Percentage, false); // } // } // } //} XmlDocument customerInfoDoc = new XmlDocument(); XmlElement customerInfo = customerInfoDoc.CreateElement("CustomerInfo"); customerInfo.SetAttribute("CustomerID", NopContext.Current.User.CustomerID.ToString()); customerInfo.SetAttribute("CustomerLanguageID", NopContext.Current.WorkingLanguage.LanguageID.ToString()); customerInfo.SetAttribute("CustomerCurrencyID", NopContext.Current.WorkingCurrency.CurrencyID.ToString()); Req.AddMerchantPrivateDataNode(customerInfo); Req.ContinueShoppingUrl = CommonHelper.GetStoreLocation(false); Req.EditCartUrl = CommonHelper.GetStoreLocation(false) + "ShoppingCart.aspx"; GCheckoutResponse Resp = Req.Send(); return(Resp); }