Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        public static void RecurringChargeRightAway()
        {
            CheckoutShoppingCartRequest cartRequest
                = new CheckoutShoppingCartRequest("123456", "merchantkey", EnvironmentType.Sandbox, "USD", 120);
            //if you are using a web page and it has the Google Checkout button, you would use this syntax.
            //= GCheckoutButton1.CreateRequest()

            Subscription        gSubscription = new Subscription();
            SubscriptionPayment maxCharge     = new SubscriptionPayment();

            DigitalItem urlDigitalItem = new DigitalItem(new Uri("http://www.url.com/login.aspx"),
                                                         "Congratulations, your account has been created!");

            DigitalItem urlDigitalItemSubscription = new DigitalItem(new Uri("http://www.url.com/login.aspx"),
                                                                     "You may now continue to login to your account.");

            ShoppingCartItem gRecurrentItem = new ShoppingCartItem();

            maxCharge.MaximumCharge = 29.99M;

            gRecurrentItem.Name                       = "Entry Level Plan";
            gRecurrentItem.Description                = "Allows for basic stuff. Monthly Subscription:";
            gRecurrentItem.Quantity                   = 1;
            gRecurrentItem.Price                      = 29.99M;
            gRecurrentItem.DigitalContent             = urlDigitalItemSubscription;
            gRecurrentItem.DigitalContent.Disposition = DisplayDisposition.Pessimistic;

            urlDigitalItem.Disposition = DisplayDisposition.Pessimistic;

            gSubscription.Type   = SubscriptionType.google;
            gSubscription.Period = GCheckout.AutoGen.DatePeriod.MONTHLY;
            gSubscription.AddSubscriptionPayment(maxCharge);
            gSubscription.RecurrentItem = gRecurrentItem;

            cartRequest.AddItem("Entry Level Plan", "Allows for basic stuff.", 1, gSubscription);
            cartRequest.AddItem("Entry Level Plan", "First Month:", 29.99M, 1, urlDigitalItem);

            cartRequest.MerchantPrivateData = "UserName:Joe87";

            Debug.WriteLine(EncodeHelper.Utf8BytesToString(cartRequest.GetXml()));

            //Send the request to Google
            //GCheckout.Util.GCheckoutResponse resp = cartRequest.Send();

            //Uncommment this line or perform additional actions
            //if (resp.IsGood) {
            //Response.Redirect(resp.RedirectUrl, True)
            //}
            //else{
            //Response.Write("Resp.ResponseXml = " & Resp.ResponseXml & "<br>");
            //Response.Write("Resp.RedirectUrl = " & Resp.RedirectUrl & "<br>");
            //Response.Write("Resp.IsGood = " & Resp.IsGood & "<br>");
            //Response.Write("Resp.ErrorMessage = " & Resp.ErrorMessage & "<br>");
            //}
        }
Ejemplo n.º 3
0
        // Methods
        public static void InitialCharge()
        {
            //http://code.google.com/apis/checkout/developer/Google_Checkout_Beta_Subscriptions.html
            //using an initial charge with a recurring charge using a different item.

            CheckoutShoppingCartRequest cartRequest
                = new CheckoutShoppingCartRequest("123456", "merchantkey", EnvironmentType.Sandbox, "USD", 120);

            //if you are using a web page and it has the Google Checkout button, you would use this syntax.
            //= GCheckoutButton1.CreateRequest()

            ShoppingCartItem initialItem   = new ShoppingCartItem();
            ShoppingCartItem recurrentItem = new ShoppingCartItem();

            initialItem.Price       = decimal.Zero;
            initialItem.Quantity    = 1;
            initialItem.Name        = "Item that shows in cart";
            initialItem.Description = "This is the item that shows in the cart";

            recurrentItem.Price       = 2M;
            recurrentItem.Quantity    = 1;
            recurrentItem.Name        = "Item that is charged every month";
            recurrentItem.Description = "Description for item that is charged every month";

            Subscription subscription = new Subscription();

            subscription.Period = GCheckout.AutoGen.DatePeriod.MONTHLY;
            subscription.Type   = SubscriptionType.merchant;

            SubscriptionPayment payment = new SubscriptionPayment();

            payment.MaximumCharge = 120M;
            payment.Times         = 12;

            subscription.AddSubscriptionPayment(payment);

            //You must set the item that will be charged for every month.
            subscription.RecurrentItem = recurrentItem;

            //you must set the subscription for the item
            initialItem.Subscription = subscription;

            cartRequest.AddItem(initialItem);

            Debug.WriteLine(EncodeHelper.Utf8BytesToString(cartRequest.GetXml()));

            //Send the request to Google
            //GCheckout.Util.GCheckoutResponse resp = cartRequest.Send();

            //Uncommment this line or perform additional actions
            //if (resp.IsGood) {
            //Response.Redirect(resp.RedirectUrl, True)
            //}
            //else{
            //Response.Write("Resp.ResponseXml = " & Resp.ResponseXml & "<br>");
            //Response.Write("Resp.RedirectUrl = " & Resp.RedirectUrl & "<br>");
            //Response.Write("Resp.IsGood = " & Resp.IsGood & "<br>");
            //Response.Write("Resp.ErrorMessage = " & Resp.ErrorMessage & "<br>");
            //}
        }
Ejemplo n.º 4
0
        public CheckoutShoppingCartRequest CreateRequest(ShoppingCart shoppingCart)
        {
            var request = new CheckoutShoppingCartRequest(_configuration.MerchantId, _configuration.MerchantKey,
                                                          _configuration.EnvironmentType, "GBP", 0);

            foreach (var item in shoppingCart.Items)
            {
                request.AddItem(item.Name, item.Description, item.MerchantItemId, item.UnitPriceExTax, item.Quantity);
            }

            foreach (var discount in shoppingCart.Discounts)
            {
                request.AddItem(discount.Name, discount.Description, -Math.Abs(discount.AmountExTax), discount.Quantity ?? 1);
            }

            // TODO: Support different tax rates
            request.AddWorldAreaTaxRule(.2d, true);

            return(request);
        }
        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);
        }
Ejemplo n.º 7
0
        void btnGoogleCheckout_Click(object sender, ImageClickEventArgs e)
        {
            if (
                (store != null) &&
                (cart != null)
                )
            { //&& (IsValidForCheckout()) ?
                int cartTimeoutInMinutes = 30;

                CheckoutShoppingCartRequest Req = new CheckoutShoppingCartRequest(
                    commerceConfig.GoogleMerchantID,
                    commerceConfig.GoogleMerchantKey,
                    commerceConfig.GoogleEnvironment,
                    siteSettings.GetCurrency().Code,
                    cartTimeoutInMinutes);


                foreach (CartOffer cartOffer in cart.CartOffers)
                {
                    Req.AddItem(
                        cartOffer.Name,
                        string.Empty,
                        cartOffer.OfferPrice,
                        cartOffer.Quantity);
                }

                //Req.AddMerchantCalculatedShippingMethod
                //Req.AnalyticsData
                //Req.ContinueShoppingUrl
                //Req.EditCartUrl

                //Req.RequestInitialAuthDetails
                //Req.AddParameterizedUrl

                // we need to serialize the cart and it items to xml here
                // so when we get it back from google
                // we can validate against the existing cart
                // as its possible items were added to the cart
                // after we passed the user to google

                //Req.MerchantPrivateData = cart.CartGuid.ToString();
                //cart.SerializeCartOffers();
                //Req.MerchantPrivateData = SerializationHelper.SerializeToSoap(cart);

                cart.SerializeCartOffers();
                MerchantData merchantData = new MerchantData();
                merchantData.ProviderName     = "WebStoreGCheckoutNotificationHandlerProvider";
                merchantData.SerializedObject = SerializationHelper.RemoveXmlDeclaration(SerializationHelper.SerializeToString(cart));
                Req.MerchantPrivateData       = SerializationHelper.RemoveXmlDeclaration(SerializationHelper.SerializeToString(merchantData));
                Req.RequestBuyerPhoneNumber   = true;

                // flat rate shipping example
                //Req.AddFlatRateShippingMethod("UPS Ground", 5);

                //Add a rule to tax all items at 7.5% for Ohio
                //Req.AddStateTaxRule("NC", .15, true);
                //TODO: lookup tax

                GCheckoutResponse Resp = Req.Send();

                if (Resp.IsGood)
                {
                    Response.Redirect(Resp.RedirectUrl, true);
                }
                else
                {
                    lblMessage.Text = Resp.ErrorMessage;
                }
            }
        }
        /// <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);
        }
Ejemplo n.º 9
0
    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));
    }
        protected void GCheckoutButton_Click(object sender, ImageClickEventArgs e)
        {
            if (_BasketGrid != null)
            {
                //First Save the updated Basket
                AbleCommerce.Code.BasketHelper.SaveBasket(_BasketGrid);
            }

            GCheckoutButton.Currency = AbleContext.Current.Store.BaseCurrency.ISOCode;
            CheckoutShoppingCartRequest Req = GCheckoutButton.CreateRequest();

            System.Xml.XmlDocument tempDoc = new System.Xml.XmlDocument();

            Basket basket = AbleContext.Current.User.Basket;

            // Add a "BasketId" node.
            System.Xml.XmlNode tempNode2 = tempDoc.CreateElement("BasketId");
            tempNode2.InnerText = basket.Id.ToString();
            Req.AddMerchantPrivateDataNode(tempNode2);

            tempNode2           = tempDoc.CreateElement("BasketContentHash");
            tempNode2.InnerText = GetBasketContentHash(basket);
            Req.AddMerchantPrivateDataNode(tempNode2);

            // We just created this structure on the order level:
            // <merchant-private-data>
            //   <BasketId xmlns="">xxxxxx</BasketId>
            // </merchant-private-data>

            // Now we are going to add the basket items.
            XmlNode[] itemPrivateData;
            foreach (BasketItem item in basket.Items)
            {
                switch (item.OrderItemType)
                {
                case OrderItemType.Product:
                    itemPrivateData = BuildPrivateData(item);
                    bool isDigitalContent = item.Product == null ? false : item.Product.IsDigitalGood;
                    if (isDigitalContent)
                    {
                        Req.AddItem(AcHelper.SanitizeText(item.Name), AcHelper.SanitizeText(item.Product.Description), (Decimal)item.Price, item.Quantity, isDigitalContent, AcHelper.SanitizeText(string.Format("The download will be available from your {0} order receipt once payment is processed.", AbleContext.Current.Store.Name)), itemPrivateData);
                    }
                    else
                    {
                        Req.AddItem(AcHelper.SanitizeText(item.Name), AcHelper.SanitizeText(item.Product.Description), (Decimal)item.Price, item.Quantity, itemPrivateData);
                    }
                    break;

                case OrderItemType.Charge:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Charge", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.Credit:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Credit", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.GiftWrap:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Gift Wrapping", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.Coupon:     //on callback as well
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Your coupon has been applied.", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.Discount:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Discount", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.GiftCertificate:     //on callback
                    break;

                case OrderItemType.Handling:     //on callback
                    break;

                case OrderItemType.Shipping:     //on callback
                    break;

                case OrderItemType.Tax:     //on callback
                    break;
                }
            }

            //setup other settings
            Req.AcceptMerchantCoupons          = GCheckoutButton.GatewayInstance.CouponsEnabled;
            Req.AcceptMerchantGiftCertificates = GCheckoutButton.GatewayInstance.GiftCertificatesEnabled;
            //Req.CartExpiration = expirationDate;
            string storeDomain  = UrlHelper.GetDomainFromUrl(AbleContext.Current.Store.StoreUrl);
            string storeBaseUrl = "http://" + storeDomain;

            Req.ContinueShoppingUrl   = storeBaseUrl + this.ResolveUrl("~/Default.aspx");
            Req.EditCartUrl           = storeBaseUrl + this.ResolveUrl("~/Basket.aspx");
            Req.MerchantCalculatedTax = true;
            //add at least one tax rule
            Req.AddZipTaxRule("99999", 0F, false);
            string storeBaseSecureUrl = AbleContext.Current.Store.Settings.SSLEnabled ? storeBaseUrl.Replace("http://", "https://") : storeBaseUrl;

            Req.MerchantCalculationsUrl = storeBaseSecureUrl + this.ResolveUrl("~/Checkout/Google/MerchantCalc.ashx");
            Req.PlatformID = 769150108975916;
            Req.RequestBuyerPhoneNumber = true;
            Req.SetExpirationMinutesFromNow(GCheckoutButton.GatewayInstance.ExpirationMinutes);

            //add ship methods
            IList <ShipMethod>   shipMethods      = ShipMethodDataSource.LoadAll();
            List <string>        shipMethodsAdded = new List <string>();
            string               shipMethName;
            decimal              basketTotal      = basket.Items.TotalPrice();
            decimal              defaultRate      = GCheckoutButton.GatewayInstance.DefaultShipRate;
            ShippingRestrictions shipRestrictions = new ShippingRestrictions();

            shipRestrictions.AddAllowedWorldArea();

            foreach (ShipMethod shipMethod in shipMethods)
            {
                if (!shipMethod.Name.Equals("Unknown(GoogleCheckout)") &&
                    (shipMethod.MinPurchase <= 0 || shipMethod.MinPurchase <= basketTotal))
                {
                    //add all other shipmethods as merchant calculated irrespective of whether they
                    //are applicable or not. It will be determined on call-back
                    //GoogleCheckout does not allow to mix merchant calculated shipping methods with other methods
                    if (shipMethod.ShipMethodType == ShipMethodType.FlatRate)
                    {
                        defaultRate = GetFlatShipRate(shipMethod);
                    }
                    else
                    {
                        defaultRate = GCheckoutButton.GatewayInstance.DefaultShipRate;
                    }
                    shipMethName = BuildShipMethodName(shipMethod, shipMethodsAdded);
                    Req.AddMerchantCalculatedShippingMethod(shipMethName, defaultRate, shipRestrictions, shipRestrictions);
                    shipMethodsAdded.Add(shipMethName.ToLowerInvariant());
                }
            }

            GCheckoutResponse Resp = Req.Send();

            if (Resp.IsGood)
            {
                Response.Redirect(Resp.RedirectUrl, true);
            }
            else
            {
                DataList msgList;
                if (_WarningMessageList != null)
                {
                    msgList = _WarningMessageList;
                }
                else
                {
                    msgList            = GCWarningMessageList;
                    phWarnings.Visible = true;
                }
                if (msgList != null)
                {
                    List <string> googleMessages = new List <string>();
                    googleMessages.Add("Google Checkout Failed.");
                    googleMessages.Add("Google Checkout Response.IsGood = " + Resp.IsGood);
                    googleMessages.Add("Google Checkout Error Message = " + Resp.ErrorMessage);
                    msgList.DataSource = googleMessages;
                    msgList.DataBind();
                }
            }
        }
Ejemplo n.º 13
0
        /// <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);
        }
        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));
        }
        public void TestSubscriptions_All_Data()
        {
            CheckoutShoppingCartRequest request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);
            //Make sure we can add an item to the cart.
            Subscription sub = new Subscription();

            sub.AddSubscriptionPayment(new SubscriptionPayment(2, 12));
            sub.NoChargeAfter = new DateTime(2010, 1, 1);
            sub.Period        = GCheckout.AutoGen.DatePeriod.DAILY;
            sub.RecurrentItem = new ShoppingCartItem("Sub Item", "Sub Item Description", "Item 1", 0, 3);
            sub.StartDate     = new DateTime(2009, 7, 1);
            sub.Type          = SubscriptionType.merchant;
            ShoppingCartItem item = request.AddItem("Item 1", "Cool Candy 1", 1, sub);

            //Console.WriteLine(EncodeHelper.Utf8BytesToString(request.GetXml()));

            //now deserialize it
            AutoGen.CheckoutShoppingCart cart = EncodeHelper.Deserialize(request.GetXml()) as AutoGen.CheckoutShoppingCart;
            //Console.WriteLine(EncodeHelper.Utf8BytesToString(EncodeHelper.Serialize(cart)));

            foreach (AutoGen.Item ai in cart.shoppingcart.items)
            {
                ShoppingCartItem ci = new ShoppingCartItem(ai);
                Assert.AreEqual(ci.Subscription.NoChargeAfter, sub.NoChargeAfter);
                SubscriptionPayment sp = new SubscriptionPayment(ai.subscription.payments[0]);
                SubscriptionPayment dp = sub.Payments[0];

                Assert.AreEqual(sp.MaximumCharge, dp.MaximumCharge);
                Assert.AreEqual(sp.Times, dp.Times);

                Assert.AreEqual(ci.Subscription.Period, sub.Period);
                Assert.AreEqual(ci.Subscription.StartDate, sub.StartDate);
                Assert.AreEqual(ci.Subscription.Type, sub.Type);
            }

            sub.NoChargeAfter = null;
            sub.Period        = GCheckout.AutoGen.DatePeriod.QUARTERLY;
            sub.StartDate     = null;
            sub.Type          = SubscriptionType.google;

            //reset
            cart = EncodeHelper.Deserialize(request.GetXml()) as AutoGen.CheckoutShoppingCart;
            //Console.WriteLine(EncodeHelper.Utf8BytesToString(EncodeHelper.Serialize(cart)));

            foreach (AutoGen.Item ai in cart.shoppingcart.items)
            {
                ShoppingCartItem ci = new ShoppingCartItem(ai);
                //Console.WriteLine(ci.Subscription.NoChargeAfter);
                Assert.IsFalse(ci.Subscription.NoChargeAfter.HasValue, "NoChargeAfter should be null");
                SubscriptionPayment sp = new SubscriptionPayment(ai.subscription.payments[0]);
                SubscriptionPayment dp = sub.Payments[0];

                Assert.AreEqual(sp.MaximumCharge, dp.MaximumCharge);
                Assert.AreEqual(sp.Times, dp.Times);

                Assert.AreEqual(ci.Subscription.Period, DatePeriod.QUARTERLY);
                //Console.WriteLine(ci.Subscription.StartDate);
                //bug in .net
                //Assert.IsFalse(ci.Subscription.StartDate.HasValue, "StartDate should be null");
                Assert.AreEqual(ci.Subscription.Type, SubscriptionType.google);
            }
        }
        public void TestAddItem()
        {
            //due to the complexity of the add items. we are going to create a known set of data points and add them to the collection.
            ShoppingCartItem si = new ShoppingCartItem();

            si.Description             = "Description";
            si.DigitalContent          = new DigitalItem("Digital Item Key", "Digital Item Description");
            si.MerchantItemID          = "Merchant Item ID";
            si.MerchantPrivateItemData = "Private Data";

            XmlDocument mpdDoc = new XmlDocument();

            mpdDoc.LoadXml("<data />");
            mpdDoc.DocumentElement.AppendChild(mpdDoc.CreateElement("node1"));
            mpdDoc.DocumentElement.AppendChild(mpdDoc.CreateElement("node2"));
            XmlNode[] mpdNodes = new XmlNode[] { mpdDoc.DocumentElement.ChildNodes[0], mpdDoc.DocumentElement.ChildNodes[1] };

            si.MerchantPrivateItemDataNodes = mpdNodes;
            si.Name     = "Name";
            si.Price    = 0.99m;
            si.Quantity = 1;

            AlternateTaxTable taxTable = new AlternateTaxTable("Example");

            taxTable.AddStateTaxRule("OH", .06);

            si.TaxTable = taxTable;
            si.Weight   = 10.5;

            si.TaxTable.AddCountryTaxRule(GCheckout.AutoGen.USAreas.ALL, 5.0);

            CheckoutShoppingCartRequest request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);

            request.ContinueShoppingUrl            = "http://localhost/";
            request.AnalyticsData                  = "Test data";
            request.PlatformID                     = 1234567890;
            request.EditCartUrl                    = "http://localhost/editcart.aspx";
            request.RequestBuyerPhoneNumber        = true;
            request.MerchantCalculationsUrl        = "http://localhost/calculate.aspx";
            request.AcceptMerchantCoupons          = true;
            request.AcceptMerchantGiftCertificates = true;
            request.SetRoundingPolicy(RoundingMode.FLOOR, RoundingRule.TOTAL);
            request.AddShippingPackage("main", "Cleveland", "OH", "44114");

            request.MerchantPrivateData = "Test Cool Stuff";
            request.AddMerchantPrivateDataNode(mpdNodes[0]);

            XmlNode[] mpdn = request.MerchantPrivateDataNodes;

            Assert.AreSame(mpdn[0], mpdNodes[0]);

            try {
                request.AddItem(null);
                Assert.Fail("Null can't be passed to the AddItem methods");
            }
            catch {
            }

            try {
                MethodInfo mi = typeof(CheckoutShoppingCartRequest).GetMethod("AddItem", new Type[] { typeof(IShoppingCartItem) });
                mi.Invoke(request, new object[] { null });
                Assert.Fail("Null can't be passed to the AddItem methods");
            }
            catch {
            }

            request.AddItem(si);
            request.AddItem(si.Clone() as IShoppingCartItem);

            MethodInfo[] methods = typeof(CheckoutShoppingCartRequest).GetMethods();

            foreach (MethodInfo mi in methods)
            {
                bool cancel = false;
                //we are only working with AddItems
                if (mi.Name == "AddItem")
                {
                    Type             sct        = typeof(ShoppingCartItem);
                    ShoppingCartItem si2        = si.Clone() as ShoppingCartItem;
                    ParameterInfo[]  parameters = mi.GetParameters();
                    object[]         setter     = new object[parameters.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        ParameterInfo pi = parameters[i];
                        if (pi.ParameterType == typeof(ShoppingCartItem) || pi.ParameterType == typeof(IShoppingCartItem))
                        {
                            cancel = true;
                            continue;
                        }
                        //get the property from the object
                        PropertyInfo source;
                        if (pi.Name != "digitalItem")
                        {
                            source = sct.GetProperty(pi.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                        }
                        else
                        {
                            source = sct.GetProperty("DigitalContent");
                        }
                        setter[i] = source.GetValue(si2, null);

                        //we want to split and take the first item
                        if (!pi.ParameterType.IsArray && source.PropertyType.IsArray)
                        {
                            object[] vals = setter[i] as object[];
                            setter[i] = vals[0] as object;
                        }
                    }
                    if (!cancel)
                    {
                        //now call the method
                        ShoppingCartItem called = mi.Invoke(request, setter) as ShoppingCartItem;

                        //this is to fix a params array issue.
                        if (parameters[parameters.Length - 1].Name == "MerchantPrivateItemDataNodes")
                        {
                            called.MerchantPrivateItemDataNodes = si2.MerchantPrivateItemDataNodes;
                        }
                    }
                }
            }

            byte[] toXml = request.GetXml();

            //Make sure we can add an item to the cart.
            ShoppingCartItem item = request.AddItem("Item 1", "Cool Candy 1", "Merchant Item ID", 2.00M, 1);

            item.Weight = 2.2;
            item.MerchantPrivateItemData = null; //perform a null check

            //verify we can't set the price to fractions.

            item.Price = 1.975m;
            Assert.AreEqual(1.98m, item.Price);

            item.Price = 1.994m;
            Assert.AreEqual(1.99m, item.Price);

            Assert.AreEqual(2.2, item.Weight);
            Assert.AreEqual("Merchant Item ID", item.MerchantItemID);

            //this is a very specific test to make sure that if only one node exists, return it. it may be for a reason.

            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<data />");
            doc.DocumentElement.SetAttribute("test", "cool");

            string xml = doc.OuterXml;

            item.MerchantPrivateItemDataNodes = new XmlNode[] { doc.DocumentElement };
            string xmlReturn = item.MerchantPrivateItemData;

            Assert.AreEqual(xml, xmlReturn);

            //create a new node
            XmlNode secondNode = doc.DocumentElement.AppendChild(doc.CreateElement("test"));

            item.MerchantPrivateItemDataNodes = new XmlNode[] { doc.DocumentElement, secondNode };

            xmlReturn = item.MerchantPrivateItemData;
            Assert.AreEqual(null, xmlReturn);

            item.MerchantPrivateItemDataNodes = null;
            Assert.AreEqual(new XmlNode[] { }, item.MerchantPrivateItemDataNodes);

            //this should throw an exception
            try {
                item.Weight = -1;
                Assert.Fail("Weight should not be allowed to be negative.");
            }
            catch {
            }

            //create a new instance of the cart item
            ShoppingCartItem testItem = new ShoppingCartItem();
        }
        public void TestExamples()
        {
            CheckoutShoppingCartRequest request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);

            //Make sure we can add an item to the cart.
            request.AddItem("Item 1", "Cool Candy 1", 2.00M, 1);

            request.AddStateTaxRule("CT", .06, true);

            byte[] cart = request.GetXml();

            //Console.WriteLine(EncodeHelper.Utf8BytesToString(cart));

            //test to see if the item can desialize
            Assert.IsNotNull(GCheckout.Util.EncodeHelper.Deserialize(cart));


            //example 2

            request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);

            //Make sure we can add an item to the cart.
            request.AddItem("Item 1", "Cool Candy 1", 2.00M, 1);

            request.AddStateTaxRule("CT", .06, true);
            request.AddStateTaxRule("MD", .05, false);

            cart = request.GetXml();

            //Console.WriteLine(EncodeHelper.Utf8BytesToString(cart));

            //test to see if the item can desialize
            Assert.IsNotNull(GCheckout.Util.EncodeHelper.Deserialize(cart));

            //example 2a

            request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);

            //Make sure we can add an item to the cart.
            request.AddItem("Item 1", "Cool Candy 1", 2.00M, 1);

            cart = request.GetXml();

            //Console.WriteLine(EncodeHelper.Utf8BytesToString(cart));

            //test to see if the item can desialize
            Assert.IsNotNull(GCheckout.Util.EncodeHelper.Deserialize(cart));


            //example 3

            request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);

            //Make sure we can add an item to the cart.
            request.AddItem("Item 1", "Cool Candy 1", 2.00M, 1);

            request.AddZipTaxRule("100*", 0.08375, false);
            request.AddStateTaxRule("NY", 0.0400, true);

            //this should be an invalid format
            try {
                request.AddZipTaxRule("255333", .05, true);
                Assert.Fail("255333 should not be a correct zip code format");
            }
            catch {
            }

            cart = request.GetXml();

            //Console.WriteLine(EncodeHelper.Utf8BytesToString(cart));

            //test to see if the item can desialize
            Assert.IsNotNull(GCheckout.Util.EncodeHelper.Deserialize(cart));

            request.AddMerchantCalculatedShippingMethod("Test 1", 12.11m);
            request.AddMerchantCalculatedShippingMethod("Test 2", 4.95m, new ShippingRestrictions());
            request.AddMerchantCalculatedShippingMethod("Test 3", 5.95m, new ShippingRestrictions());
            request.AddMerchantCalculatedShippingMethod("MerchantCalc", 12.95m, new ShippingRestrictions(), new ShippingRestrictions());

            //create a pickup shipping method
            request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);
            request.AddPickupShippingMethod("Name", 4.95m);
            request.AddCountryTaxRule(GCheckout.AutoGen.USAreas.ALL, .05, true);
            request.AddWorldAreaTaxRule(.02, true);
            //Tax Canada at 5%
            request.AddPostalAreaTaxRule("CA", .05, true);

            //Tax all cities that start with L4L at 7%
            request.AddPostalAreaTaxRule("CA", "L4L*", .07, true);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<data />");
            request.AddMerchantPrivateDataNode(doc.DocumentElement);

            //we must pass in a valid node
            try {
                request.AddMerchantPrivateDataNode(null);
                Assert.Fail("Null can't be sent to AddMerchantPrivateDataNode.");
            }
            catch {
            }
        }