public static void AdjustFlatRateShipping(Basket basket, FlatRateShippingAdjustment frsa)
 {
     if (frsa != null)
     {
         BasketItem basketItem = new BasketItem();
         basketItem.OrderItemType = OrderItemType.Shipping;
         basketItem.Price         = frsa.shippingcost.Value;
         basketItem.Quantity      = 1;
         basketItem.BasketId      = basket.BasketId;
         //basketItem.Name = AcHelper.CleanShipMethodName(frsa.shippingname);
         basketItem.Name = frsa.shippingname;
         basketItem.Sku  = basketItem.Name; //frsa.shippingname + "_Google";
         basket.Items.Add(basketItem);
     }
 }
        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);
            }
        }
        public static void DoOrderAdjustments(OrderAdjustment orderAdj, Basket basket)
        {
            TraceContext trace    = WebTrace.GetTraceContext();
            string       traceKey = "OrderAdjustmentHelper.DoOrderAdjustments";

            if (orderAdj == null)
            {
                throw new ArgumentNullException("orderAdj", "OrderAdjustment can't be null");
            }

            OrderAdjustmentMerchantcodes oamcs = orderAdj.merchantcodes;

            if (oamcs != null && oamcs.Items != null)
            {
                trace.Write(traceKey, "check merchant codes");
                Object[]                  merchantCodes = oamcs.Items;
                CouponAdjustment          coupAdj;
                GiftCertificateAdjustment giftCertAdj;

                //coupon and giftcertificate adjustment
                foreach (Object obj in merchantCodes)
                {
                    if (obj == null)
                    {
                        continue;
                    }
                    if (obj is CouponAdjustment)
                    {
                        coupAdj = (CouponAdjustment)obj;
                        trace.Write(traceKey, "Apply coupon: " + coupAdj.code + ", " + coupAdj.appliedamount);
                        OrderAdjustmentHelper.AdjustCoupon(basket, coupAdj);
                    }
                    else if (obj is GiftCertificateAdjustment)
                    {
                        giftCertAdj = (GiftCertificateAdjustment)obj;
                        trace.Write(traceKey, "Apply gift cert: " + giftCertAdj.code + " for " + giftCertAdj.appliedamount.Value);
                        OrderAdjustmentHelper.AdjustGiftCertificate(basket, giftCertAdj);
                    }
                }
            }

            OrderAdjustmentShipping oas = orderAdj.shipping;

            if (oas != null && oas.Item != null)
            {
                trace.Write(traceKey, "check shipping adjustments");
                Object shipAdj = oas.Item;
                if (shipAdj is MerchantCalculatedShippingAdjustment)
                {
                    MerchantCalculatedShippingAdjustment mcsa = (MerchantCalculatedShippingAdjustment)shipAdj;
                    OrderAdjustmentHelper.AdjustMerchantCalculatedShipping(basket, mcsa);
                }
                else if (shipAdj is FlatRateShippingAdjustment)
                {
                    FlatRateShippingAdjustment frsa = (FlatRateShippingAdjustment)shipAdj;
                    OrderAdjustmentHelper.AdjustFlatRateShipping(basket, frsa);
                }
                else if (shipAdj is PickupShippingAdjustment)
                {
                    PickupShippingAdjustment pusa = (PickupShippingAdjustment)shipAdj;
                    OrderAdjustmentHelper.AdjustPickupShipping(basket, pusa);
                }
            }

            //tax adjustments
            if (orderAdj.totaltax != null && orderAdj.totaltax.Value > 0)
            {
                trace.Write(traceKey, "process tax adjustments");
                OrderAdjustmentHelper.AdjustTax(basket, orderAdj.totaltax.Value);
            }
        }