protected void PostCartToGoogle(object sender, ImageClickEventArgs e)
        {
            if ((NopContext.Current.User == null) || (NopContext.Current.User.IsGuest && !CustomerManager.AnonymousCheckoutAllowed))
            {
                string loginURL = CommonHelper.GetLoginPageURL(true);
                Response.Redirect(loginURL);
            }

            //USD for US dollars, GBP for British pounds, SEK for Swedish krona, EUR for Euro etc
            GCheckoutButton1.Currency = CurrencyManager.PrimaryStoreCurrency.CurrencyCode;
            CheckoutShoppingCartRequest    Req = GCheckoutButton1.CreateRequest();
            GoogleCheckoutPaymentProcessor googleCheckoutPaymentProcessor = new GoogleCheckoutPaymentProcessor();

            NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart Cart = ShoppingCartManager.GetCurrentShoppingCart(ShoppingCartTypeEnum.ShoppingCart);
            GCheckoutResponse Resp = googleCheckoutPaymentProcessor.PostCartToGoogle(Req, Cart);

            if (Resp.IsGood)
            {
                Response.Redirect(Resp.RedirectUrl);
            }
            else
            {
                Response.Clear();
                Response.Write("Resp.RedirectUrl = " + Resp.RedirectUrl + "<br />");
                Response.Write("Resp.IsGood = " + Resp.IsGood + "<br />");
                Response.Write("Resp.ErrorMessage = " + Server.HtmlEncode(Resp.ErrorMessage) + "<br />");
                Response.Write("Resp.ResponseXml = " + Server.HtmlEncode(Resp.ResponseXml) + "<br />");
                Response.End();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            PaymentMethod googleCheckoutPaymentMethod = PaymentMethodManager.GetPaymentMethodBySystemKeyword("GoogleCheckout");

            if (googleCheckoutPaymentMethod == null || !googleCheckoutPaymentMethod.IsActive)
            {
                this.Visible = false;
                return;
            }

            NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart Cart = ShoppingCartManager.GetCurrentShoppingCart(ShoppingCartTypeEnum.ShoppingCart);
            if (Cart.Count == 0)
            {
                this.Visible = false;
                return;
            }
        }
        public void BindData()
        {
            bool displayButton = true;

            var gcPaymentMethod = this.PaymentService.GetPaymentMethodBySystemKeyword("GoogleCheckout");

            if (gcPaymentMethod == null || !gcPaymentMethod.IsActive)
            {
                displayButton = false;
            }

            NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart cart = null;
            if (displayButton)
            {
                cart = this.ShoppingCartService.GetCurrentShoppingCart(ShoppingCartTypeEnum.ShoppingCart);
                if (cart.Count == 0)
                {
                    displayButton = false;
                }
            }

            if (displayButton)
            {
                bool minOrderSubtotalAmountOK = this.OrderService.ValidateMinOrderSubtotalAmount(cart, NopContext.Current.User);
                if (!minOrderSubtotalAmountOK)
                {
                    displayButton = false;
                }
            }

            if (displayButton)
            {
                if (cart.IsRecurring && this.PaymentService.SupportRecurringPayments(gcPaymentMethod.PaymentMethodId) == RecurringPaymentTypeEnum.NotSupported)
                {
                    displayButton = false;
                }
            }
            this.Visible = displayButton;

            GCheckoutButton1.UseHttps = CommonHelper.IsCurrentConnectionSecured();
        }
        private void processNewOrderNotification(string xmlData)
        {
            try
            {
                NewOrderNotification newOrderNotification = (NewOrderNotification)EncodeHelper.Deserialize(xmlData, typeof(NewOrderNotification));
                string googleOrderNumber = newOrderNotification.googleordernumber;

                XmlNode  CustomerInfo       = newOrderNotification.shoppingcart.merchantprivatedata.Any[0];
                int      CustomerID         = Convert.ToInt32(CustomerInfo.Attributes["CustomerID"].Value);
                int      CustomerLanguageID = Convert.ToInt32(CustomerInfo.Attributes["CustomerLanguageID"].Value);
                int      CustomerCurrencyID = Convert.ToInt32(CustomerInfo.Attributes["CustomerCurrencyID"].Value);
                Customer customer           = CustomerManager.GetCustomerById(CustomerID);

                NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart Cart = ShoppingCartManager.GetCustomerShoppingCart(customer.CustomerId, ShoppingCartTypeEnum.ShoppingCart);

                if (customer == null)
                {
                    logMessage("Could not load a customer");
                    return;
                }

                NopContext.Current.User = customer;

                if (Cart.Count == 0)
                {
                    logMessage("Cart is empty");
                    return;
                }

                //validate cart
                foreach (NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCartItem sci in Cart)
                {
                    bool ok = false;
                    foreach (Item item in newOrderNotification.shoppingcart.items)
                    {
                        if (!String.IsNullOrEmpty(item.merchantitemid))
                        {
                            if ((Convert.ToInt32(item.merchantitemid) == sci.ShoppingCartItemId) && (item.quantity == sci.Quantity))
                            {
                                ok = true;
                                break;
                            }
                        }
                    }

                    if (!ok)
                    {
                        logMessage(string.Format("Shopping Cart item has been changed. {0}. {1}", sci.ShoppingCartItemId, sci.Quantity));
                        return;
                    }
                }


                string[] billingFullname  = newOrderNotification.buyerbillingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                string   billingFirstName = billingFullname[0];
                string   billingLastName  = string.Empty;
                if (billingFullname.Length > 1)
                {
                    billingLastName = billingFullname[1];
                }
                string        billingEmail           = newOrderNotification.buyerbillingaddress.email.Trim();
                string        billingAddress1        = newOrderNotification.buyerbillingaddress.address1.Trim();
                string        billingAddress2        = newOrderNotification.buyerbillingaddress.address2.Trim();
                string        billingPhoneNumber     = newOrderNotification.buyerbillingaddress.phone.Trim();
                string        billingCity            = newOrderNotification.buyerbillingaddress.city.Trim();
                int           billingStateProvinceID = 0;
                StateProvince billingStateProvince   = StateProvinceManager.GetStateProvinceByAbbreviation(newOrderNotification.buyerbillingaddress.region.Trim());
                if (billingStateProvince != null)
                {
                    billingStateProvinceID = billingStateProvince.StateProvinceId;
                }
                string  billingZipPostalCode = newOrderNotification.buyerbillingaddress.postalcode.Trim();
                int     billingCountryID     = 0;
                Country billingCountry       = CountryManager.GetCountryByTwoLetterIsoCode(newOrderNotification.buyerbillingaddress.countrycode.Trim());
                if (billingCountry != null)
                {
                    billingCountryID = billingCountry.CountryId;
                }

                NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address BillingAddress = customer.BillingAddresses.FindAddress(
                    billingFirstName, billingLastName, billingPhoneNumber,
                    billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity,
                    billingStateProvinceID, billingZipPostalCode, billingCountryID);

                if (BillingAddress == null)
                {
                    BillingAddress = CustomerManager.InsertAddress(CustomerID, true,
                                                                   billingFirstName, billingLastName, billingPhoneNumber, billingEmail,
                                                                   string.Empty, string.Empty, billingAddress1,
                                                                   billingAddress2, billingCity,
                                                                   billingStateProvinceID, billingZipPostalCode,
                                                                   billingCountryID, DateTime.Now, DateTime.Now);
                }
                customer = CustomerManager.SetDefaultBillingAddress(customer.CustomerId, BillingAddress.AddressId);

                NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address ShippingAddress = null;
                customer.LastShippingOption = null;
                bool shoppingCartRequiresShipping = ShippingManager.ShoppingCartRequiresShipping(Cart);
                if (shoppingCartRequiresShipping)
                {
                    string[] shippingFullname  = newOrderNotification.buyershippingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    string   shippingFirstName = shippingFullname[0];
                    string   shippingLastName  = string.Empty;
                    if (shippingFullname.Length > 1)
                    {
                        shippingLastName = shippingFullname[1];
                    }
                    string        shippingEmail           = newOrderNotification.buyershippingaddress.email.Trim();
                    string        shippingAddress1        = newOrderNotification.buyershippingaddress.address1.Trim();
                    string        shippingAddress2        = newOrderNotification.buyershippingaddress.address2.Trim();
                    string        shippingPhoneNumber     = newOrderNotification.buyershippingaddress.phone.Trim();
                    string        shippingCity            = newOrderNotification.buyershippingaddress.city.Trim();
                    int           shippingStateProvinceID = 0;
                    StateProvince shippingStateProvince   = StateProvinceManager.GetStateProvinceByAbbreviation(newOrderNotification.buyershippingaddress.region.Trim());
                    if (shippingStateProvince != null)
                    {
                        shippingStateProvinceID = shippingStateProvince.StateProvinceId;
                    }
                    int     shippingCountryID     = 0;
                    string  shippingZipPostalCode = newOrderNotification.buyershippingaddress.postalcode.Trim();
                    Country shippingCountry       = CountryManager.GetCountryByTwoLetterIsoCode(newOrderNotification.buyershippingaddress.countrycode.Trim());
                    if (shippingCountry != null)
                    {
                        shippingCountryID = shippingCountry.CountryId;
                    }

                    ShippingAddress = customer.ShippingAddresses.FindAddress(
                        shippingFirstName, shippingLastName, shippingPhoneNumber,
                        shippingEmail, string.Empty, string.Empty,
                        shippingAddress1, shippingAddress2, shippingCity,
                        shippingStateProvinceID, shippingZipPostalCode, shippingCountryID);
                    if (ShippingAddress == null)
                    {
                        ShippingAddress = CustomerManager.InsertAddress(CustomerID, false,
                                                                        shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail,
                                                                        string.Empty, string.Empty, shippingAddress1,
                                                                        shippingAddress2, shippingCity, shippingStateProvinceID,
                                                                        shippingZipPostalCode, shippingCountryID,
                                                                        DateTime.Now, DateTime.Now);
                    }

                    customer = CustomerManager.SetDefaultShippingAddress(customer.CustomerId, ShippingAddress.AddressId);

                    string  shippingMethod = string.Empty;
                    decimal shippingCost   = decimal.Zero;
                    if (newOrderNotification.orderadjustment != null &&
                        newOrderNotification.orderadjustment.shipping != null &&
                        newOrderNotification.orderadjustment.shipping.Item != null)
                    {
                        FlatRateShippingAdjustment ShippingMethod = (FlatRateShippingAdjustment)newOrderNotification.orderadjustment.shipping.Item;
                        shippingMethod = ShippingMethod.shippingname;
                        shippingCost   = ShippingMethod.shippingcost.Value;


                        ShippingOption shippingOption = new ShippingOption();
                        shippingOption.Name         = shippingMethod;
                        shippingOption.Rate         = shippingCost;
                        customer.LastShippingOption = shippingOption;
                    }
                }

                //customer.LastCalculatedTax = decimal.Zero;

                PaymentMethod googleCheckoutPaymentMethod = PaymentMethodManager.GetPaymentMethodBySystemKeyword("GoogleCheckout");

                PaymentInfo paymentInfo = new PaymentInfo();
                paymentInfo.PaymentMethodId   = googleCheckoutPaymentMethod.PaymentMethodId;
                paymentInfo.BillingAddress    = BillingAddress;
                paymentInfo.ShippingAddress   = ShippingAddress;
                paymentInfo.CustomerLanguage  = LanguageManager.GetLanguageById(CustomerLanguageID);
                paymentInfo.CustomerCurrency  = CurrencyManager.GetCurrencyById(CustomerCurrencyID);
                paymentInfo.GoogleOrderNumber = googleOrderNumber;
                int    orderID = 0;
                string result  = OrderManager.PlaceOrder(paymentInfo, customer, out orderID);
                if (!String.IsNullOrEmpty(result))
                {
                    logMessage("new-order-notification received. CreateOrder() error: Order Number " + orderID + ". " + result);
                    return;
                }

                Order order = OrderManager.GetOrderById(orderID);
                logMessage("new-order-notification received and saved: Order Number " + orderID);
            }
            catch (Exception exc)
            {
                logMessage("processNewOrderNotification Exception: " + exc.Message + ": " + exc.StackTrace);
            }
        }
        /// <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);
        }
Example #6
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);
        }