예제 #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            storeContext = new StoreContext(Request);
            storeUrls    = new StoreUrls(storeContext);

            string shippingOption = Request.Params["shippingOption"];

            payPalStandard = new PayPalStandardProvider(storeContext.CurrentStore.GetPaymentProviderConfig(PaymentProviderName.PayPalStandard));

            if (!IsPostBack)
            {
                //CartController cartController = new CartController(storeContext);
                //Cart cart = cartController.GetCart(false);

                //Order pendingOrder = ConvertCartToPendingOrder(cart);

                decimal?shippingCost       = WA.Parser.ToDecimal(Request.Params["s"]);
                string  shippingOptionName = Request.Params["sn"] ?? string.Empty;

                CheckoutOrderInfo checkoutOrderInfo = Session[storeContext.SessionKeys.CheckoutOrderInfo] as CheckoutOrderInfo;
                if (checkoutOrderInfo != null)
                {
                    OrderController orderController = new OrderController(storeContext);
                    Order           pendingOrder    = orderController.CreateOrder(checkoutOrderInfo, OrderStatusName.PendingOffsite);
                    if (shippingCost.HasValue)
                    {
                        pendingOrder.ShippingAmount          = shippingCost.Value;
                        pendingOrder.ShippingServiceOption   = shippingOptionName;
                        pendingOrder.ShippingServiceProvider = ShippingProviderType.CustomShipping.ToString();
                        pendingOrder.Save();
                    }
                    GeneratePayPalForm(pendingOrder);
                }
            }
        }
예제 #2
0
        private Order ConvertCartToPendingOrder(Cart cart)
        {
            CheckoutOrderInfo checkoutOrderInfo = new CheckoutOrderInfo()
            {
                Cart = cart
            };

            OrderController orderController = new OrderController(storeContext);

            return(orderController.CreateOrder(checkoutOrderInfo, OrderStatusName.PendingOffsite));
        }
예제 #3
0
        //public List<Coupon> GetAppliedCoupons()
        //{
        //    List<Coupon> coupons = new List<Coupon>();
        //    foreach(CartCoupon cc in this.CartCouponCollectionByCartId)
        //    {
        //        coupons.Add(cc.UpToCouponByCouponId);
        //    }
        //    return coupons;
        //}

        public decimal GetTotal()
        {
            SessionKeyHelper sessionKeyHelper = new SessionKeyHelper(this.StoreId.GetValueOrDefault(-1));

            CheckoutOrderInfo checkoutOrderInfo = HttpContext.Current.Session[sessionKeyHelper.CheckoutOrderInfo] as CheckoutOrderInfo;

            if (checkoutOrderInfo != null)
            {
                return(checkoutOrderInfo.Total);
            }
            else
            {
                checkoutOrderInfo = new CheckoutOrderInfo()
                {
                    Cart = this
                };
                return(checkoutOrderInfo.Total);
            }
        }
예제 #4
0
        private void ShowReviewOrder()
        {
            CheckoutOrderInfo checkoutOrderInfo = FillCheckoutOrderInfo();

            //--- DataBind the cart items
            List <vCartItem> cartItems = checkoutOrderInfo.Cart.GetCartViewItems();

            rptCheckoutItems.DataSource = cartItems;
            rptCheckoutItems.DataBind();

            //--- Billing/Shipping Summaries
            litBillToSummary.Text = checkoutOrderInfo.BillingAddress.ToHumanFriendlyString("<br />");
            litShipToSummary.Text = checkoutOrderInfo.ShippingAddress.ToHumanFriendlyString("<br />");

            // TODO Payment Summary ??

            // TODO Discount(s) Summary ??

            pnlReviewOrder.Visible = true;
            pnlAjaxPanels.Visible  = false;
        }
예제 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadResourceFileSettings();

            cartController = new CartController(StoreContext);

            checkoutOrderInfo = Session[StoreContext.SessionKeys.CheckoutOrderInfo] as CheckoutOrderInfo ?? new CheckoutOrderInfo()
            {
                Cart = cartController.GetCart(true)
            };
            checkoutOrderInfo.Cart = cartController.GetCart(true);
            checkoutOrderInfo.ReCalculateOrderTotals();

            var payPalStandard = new PayPalStandardProvider(StoreContext.CurrentStore.GetPaymentProviderConfig(PaymentProviderName.PayPalStandard));

            collectPayPalStandardShipping = payPalStandard.ShippingLogic == "Store" && !checkoutOrderInfo.HasOnlyDownloadableProducts;

            if (!IsPostBack)
            {
                int?removeCartItem = WA.Parser.ToInt(Request.QueryString["remove"]);
                if (removeCartItem.HasValue)
                {
                    RemoveCartItemFromCart(removeCartItem.Value);
                    UpdateCheckoutSession();

                    // redirect so that the "mini-cart" updates on the page also...
                    Response.Redirect(StoreUrls.Cart());
                }
                // FEATURE: Add product to the cart via URL/QueryString
                string addProductSlug = Request.QueryString["add"] ?? string.Empty;
                if (!string.IsNullOrEmpty(addProductSlug))
                {
                    var productToAdd = Product.GetBySlug(StoreContext.CurrentStore.Id.Value, addProductSlug);
                    if (productToAdd != null)
                    {
                        //bool IsAvailableForPurchase = productToAdd.IsAvailableForPurchase.GetValueOrDefault(true) && WA.Parser.ToBool(StoreContext.CurrentStore.GetSetting(StoreSettingNames.EnableCheckout)).GetValueOrDefault(true);
                        bool IsAvailableForPurchase = productToAdd.IsPurchaseableByUser;
                        if (IsAvailableForPurchase)
                        {
                            int quantityToAdd = Request.QueryString["q"] != null?Convert.ToInt32(Request.QueryString["q"]) : 1;

                            cartController.AddProductToCart(productToAdd.Id.Value, quantityToAdd, string.Empty);
                        }
                        checkoutOrderInfo.Cart = cartController.GetCart(false);
                        checkoutOrderInfo.ReCalculateOrderTotals();

                        bool redirectBackToReferrer = WA.Parser.ToBool(Request.QueryString["redirect"]).GetValueOrDefault(false);
                        if (redirectBackToReferrer && (Request.UrlReferrer != null))
                        {
                            string redirectUrl = Request.UrlReferrer.ToString();


                            // Remove previous flash message from querystring when redirecting
                            if (redirectUrl.ToLower().Contains("flash"))
                            {
                                int flashIndex = redirectUrl.IndexOf("flash");
                                redirectUrl = redirectUrl.Substring(0, flashIndex - 1);
                            }

                            bool referrerIsOnsite = (Request.UrlReferrer.Host == Request.Url.Host);
                            if (referrerIsOnsite)
                            {
                                // redirect and add a 'flash' message to notify customer that product was added to cart
                                if (IsAvailableForPurchase)
                                {
                                    redirectUrl = redirectUrl.AddUrlParam("flash", HttpUtility.UrlPathEncode(string.Format(@"""{0}"" has been added to your cart", productToAdd.Name)));
                                }
                                else
                                {
                                    redirectUrl = redirectUrl.AddUrlParam("flash", HttpUtility.UrlPathEncode(string.Format(@"""{0}"" is not available for purchase.", productToAdd.Name)));
                                }
                            }
                            //Response.Redirect(redirectUrl, true);
                            Response.Redirect(redirectUrl);
                        }
                        else
                        {
                            if (IsAvailableForPurchase)
                            {
                                flash.InnerHtml = string.Format(@"""{0}"" has been added to your cart", productToAdd.Name);
                            }
                            else
                            {
                                flash.InnerHtml = string.Format(@"""{0}"" is not available for purchase", productToAdd.Name);
                            }
                            flash.Visible = true;
                        }
                    }
                }

                DataBindCartItems();

                var store = StoreContext.CurrentStore;

                //---- checkout buttons
                bool payLaterPaymentEnabled        = StoreContext.CurrentStore.IsPaymentProviderEnabled(PaymentProviderName.PayLater);
                bool cardCaptureOnlyPaymentEnabled = StoreContext.CurrentStore.IsPaymentProviderEnabled(PaymentProviderName.CardCaptureOnly);
                bool authorizeNetAimEnabled        = StoreContext.CurrentStore.IsPaymentProviderEnabled(PaymentProviderName.AuthorizeNetAim);
                bool payPalDirectEnabled           = StoreContext.CurrentStore.IsPaymentProviderEnabled(PaymentProviderName.PayPalDirectPayment);
                bool onsitePaymentProviderEnabled  = payLaterPaymentEnabled || cardCaptureOnlyPaymentEnabled || authorizeNetAimEnabled || payPalDirectEnabled;

                btnCheckoutOnsite.Visible         = onsitePaymentProviderEnabled;
                btnCheckoutPayPalStandard.Visible = StoreContext.CurrentStore.IsPaymentProviderEnabled(PaymentProviderName.PayPalStandard);
                ibtnPayPalExpressCheckout.Visible = StoreContext.CurrentStore.IsPaymentProviderEnabled(PaymentProviderName.PayPalExpressCheckout);
                if (btnCheckoutOnsite.Visible && (btnCheckoutPayPalStandard.Visible || ibtnPayPalExpressCheckout.Visible))
                {
                    spnOr.Visible = true;
                }

                //collectPayPalStandardShipping = payPalStandard.ShippingLogic == "Store";
                //payPalStandard = new PayPalStandardProvider(StoreContext.CurrentStore.GetPaymentProviderConfig(PaymentProviderName.PayPalStandard));)
                if (collectPayPalStandardShipping)
                {
                    string        storeCountry         = store.GetSetting(StoreSettingNames.DefaultCountryCode);
                    var           countries            = DnnHelper.GetCountryListAdoNet();
                    StringBuilder countriesOptionsHtml = new StringBuilder(countries.Count);
                    foreach (var c in countries)
                    {
                        countriesOptionsHtml.AppendFormat(@"<option value=""{0}"" {2}>{1}</option>", c.CountryCode, c.Name, c.CountryCode == storeCountry ? "selected=selected" : string.Empty);
                    }
                    litCountryOptionsHtml.Text = countriesOptionsHtml.ToString();
                }

                //IShippingProvider fedExProvider = ShippingProviderFactory.Get(StoreContext.CurrentStore.Id.Value, ShippingProviderType.FedEx);
                //pnlShippingQuoteForm.Visible = fedExProvider.IsEnabled;
                var shippingServices = StoreContext.CurrentStore.GetEnabledShippingProviders(null, checkoutOrderInfo.Cart.Id);
                if (shippingServices.Count > 0)
                {
                    pnlShippingQuoteForm.Visible = true;
                }

                //----------Show / Hide Coupon Box and Shipping Estimate Boxes

                pnlShippingQuoteForm.Visible = WA.Parser.ToBool(store.GetSetting(StoreSettingNames.ShowShippingEstimate)).GetValueOrDefault(true);
                pnlCouponCodeForm.Visible    = WA.Parser.ToBool(store.GetSetting(StoreSettingNames.ShowCouponBox)).GetValueOrDefault(true);
            }
        }
예제 #6
0
        public void ProcessRequest(HttpContext context)
        {
            response = context.Response;
            request  = context.Request;

            //response.ContentType = "text/plain";
            response.ContentType = "application/json"; // jQuery 1.4.2 requires this now!

            try
            {
                StoreContext storeContext = new StoreContext(request);
                StoreUrls    storeUrls    = new StoreUrls(storeContext);

                string  action    = request.Params["action"];
                int?    productId = WA.Parser.ToInt(request.Params["productId"]);
                Product product   = null;
                if (productId.HasValue)
                {
                    product = Product.GetProduct(productId.Value);
                }

                switch (action)
                {
                case "updateShippingRateTypeName":
                    int?shippingRateTypeId = WA.Parser.ToInt(request.Params["shippingServiceRateTypeId"]);
                    if (shippingRateTypeId.HasValue)
                    {
                        string shippingName = request.Params["name"];
                        DataModel.ShippingServiceRateType shippingMethod = DataModel.ShippingServiceRateType.Get(shippingRateTypeId.Value);
                        if (shippingMethod != null)
                        {
                            shippingMethod.DisplayName = shippingName;
                            shippingMethod.Save();

                            RespondWithSuccess();
                        }
                    }
                    break;

                case "getShippingRatesJson":
                    DataModel.ShippingServiceRateType rateType = DataModel.ShippingServiceRateType.Get(WA.Parser.ToShort(request.Params["shippingServiceRateTypeId"]).GetValueOrDefault(-1));
                    if (rateType != null)
                    {
                        List <ShippingServiceRate>     rates     = rateType.GetRates();
                        List <JsonShippingServiceRate> jsonRates = rates.ConvertAll(
                            r =>
                            new JsonShippingServiceRate()
                        {
                            RateTypeId  = rateType.Id.Value,
                            CountryCode = r.CountryCode,
                            Region      = r.Region,
                            MinWeight   = r.WeightMin,
                            MaxWeight   = r.WeightMax,
                            Cost        = r.Cost
                        }
                            );
                        string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonRates);
                        response.Write(json);
                    }
                    break;
                //case "applyShippingRate":
                //    string shippingRate = request.Params["shippingServiceRateTypeId"];
                //    if (shippingRate != null)
                //    {

                //        var store = storeContext.CurrentStore;

                //        var checkoutOrderInfo = HttpContext.Current.Session[storeContext.SessionKeys.CheckoutOrderInfo] as CheckoutOrderInfo;

                //        string[] rateParts = shippingRate.Split("||");
                //        checkoutOrderInfo.ShippingRate.ServiceType = rateParts[0];
                //        checkoutOrderInfo.ShippingRate.ServiceTypeDescription = rateParts[1];
                //        checkoutOrderInfo.ShippingRate.Rate = Convert.ToDecimal(rateParts.Length == 3 ? rateParts[2] : rateParts[1]);
                //        checkoutOrderInfo.ReCalculateOrderTotals();

                //        Session[StoreContext.SessionKeys.CheckoutOrderInfo] = checkoutOrderInfo;
                //    }
                //    break;
                case "getShippingOptionEstimatesJson":

                    string address1   = request.Params["address1"];
                    string address2   = request.Params["address2"];
                    string city       = request.Params["city"];
                    string country    = request.Params["country"];
                    string region     = request.Params["region"];
                    string postalCode = request.Params["postalCode"];
                    bool   isBusiness = Convert.ToBoolean(request.Params["isBusiness"]);

                    var store = storeContext.CurrentStore;

                    var cartController    = new CartController(storeContext);
                    var checkoutOrderInfo = HttpContext.Current.Session[storeContext.SessionKeys.CheckoutOrderInfo] as CheckoutOrderInfo;
                    if (checkoutOrderInfo == null)
                    {
                        var cart = cartController.GetCart(false);
                        checkoutOrderInfo = new CheckoutOrderInfo()
                        {
                            Cart = cart
                        };
                    }
                    //List<string> errors;
                    //var shippingOptionEstimates = store.GetShippingOptionEstimates(origin, destination, checkoutOrderInfo.Cart.GetCartItemsWithProductInfo(), out errors);
                    //var shippingOptions = shippingOptionEstimates.ConvertAll(x => new
                    //                        {
                    //                            Value = x.Cost.GetValueOrDefault(0).ToString("F2"),
                    //                            Name = x.DisplayName,
                    //                            Text = string.Format(@"{0}  :  {1}", x.DisplayName, store.FormatCurrency(x.Cost))
                    //                        });

                    IPostalAddress origin      = store.Address.ToPostalAddress();
                    IPostalAddress destination = new PostalAddress()
                    {
                        Address1 = address1, Address2 = address2, City = city, CountryCode = country, Region = region.ToUpper(), PostalCode = postalCode.ToUpper(), IsResidential = !isBusiness
                    };

                    ShipmentPackagingStrategy shipmentPackagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(store.GetSetting(StoreSettingNames.ShipmentPackagingStrategy), ShipmentPackagingStrategy.SingleBox);

                    var shipmentPackages = checkoutOrderInfo.Cart.GetCartItemsAsShipmentPackages(shipmentPackagingStrategy);
                    var shippingRates    = new List <IShippingRate>();
                    var shippingServices = store.GetEnabledShippingProviders(null, checkoutOrderInfo.Cart.Id);
                    foreach (var shipper in shippingServices)
                    {
                        shippingRates.AddRange(shipper.GetRates(origin, destination, shipmentPackages));
                    }
                    var shippingOptions = shippingRates.Select(x => new
                    {
                        Value = x.Rate.ToString("F2"),
                        Name  = x.ServiceType,
                        Text  = string.Format(@"{0}  :  {1}", x.ServiceType, store.FormatCurrency(x.Rate))
                    });

                    string shippingOptionsJson = Newtonsoft.Json.JsonConvert.SerializeObject(shippingOptions);
                    response.Write(shippingOptionsJson);
                    break;

                case "getProductPhotosJson":
                    if (productId.HasValue)
                    {
                        List <ProductPhoto> productPhotos     = Product.GetAllPhotosInSortOrder(productId.Value);
                        List <JsonPhoto>    jsonProductPhotos =
                            productPhotos.ConvertAll(
                                p =>
                                new JsonPhoto()
                        {
                            Id           = p.Id.Value,
                            OriginalUrl  = storeUrls.ProductPhoto(p, null, null),
                            ThumbnailUrl = storeUrls.ProductPhoto(p, 120, 90)
                        });
                        string jsonPhotos = Newtonsoft.Json.JsonConvert.SerializeObject(jsonProductPhotos);

                        response.Write(jsonPhotos);
                    }
                    break;

                case "deleteProductPhoto":
                    int?photoId = WA.Parser.ToInt(request.Params["photoId"]);
                    if (ProductPhoto.DeletePhoto(photoId.GetValueOrDefault(-1)))
                    {
                        RespondWithSuccess();
                    }
                    else
                    {
                        RespondWithError("unable to delete photo: " + photoId);
                    }
                    break;

                case "updateProductPhotoSortOrder":
                    if (productId.HasValue && request.Params["photoList[]"] != null)
                    {
                        List <string> sortedPhotoList = new List <string>(request.Params.GetValues("photoList[]"));
                        List <int>    sortedPhotoIds  = sortedPhotoList.ConvertAll(p => Convert.ToInt32(p.Split('-')[1]));

                        ProductPhotoQuery q = new ProductPhotoQuery();
                        q.Where(q.ProductId == productId.Value);
                        ProductPhotoCollection photos = new ProductPhotoCollection();
                        if (photos.Load(q))
                        {
                            foreach (ProductPhoto photo in photos)
                            {
                                photo.SortOrder = (short)sortedPhotoIds.IndexOf(photo.Id.Value);
                            }
                            photos.Save();
                        }
                        RespondWithSuccess();
                    }
                    break;

                case "getProductCustomFieldsJson":
                    if (product != null)
                    {
                        List <ProductField>     productFields     = product.GetProductFieldsInSortOrder();
                        List <JsonProductField> jsonProductFields = productFields.ConvertAll(
                            f => new JsonProductField()
                        {
                            Id               = f.Id.Value,
                            WidgetType       = f.WidgetType,
                            Name             = f.Name,
                            Slug             = f.Slug,
                            IsRequired       = f.IsRequired.GetValueOrDefault(),
                            PriceAdjustment  = f.PriceAdjustment.GetValueOrDefault(0),
                            WeightAdjustment = f.WeightAdjustment.GetValueOrDefault(0),
                            SortOrder        = f.SortOrder.GetValueOrDefault(),
                            Choices          = f.GetChoicesInSortOrder().ToList().ConvertAll(
                                c => new JsonProductFieldChoice()
                            {
                                Id               = c.Id.Value,
                                ProductFieldId   = f.Id.Value,
                                Name             = c.Name,
                                PriceAdjustment  = c.PriceAdjustment.GetValueOrDefault(0),
                                WeightAdjustment = c.WeightAdjustment.GetValueOrDefault(0),
                                SortOrder        = c.SortOrder.GetValueOrDefault()
                            })
                        });
                        string jsonCustomFields = Newtonsoft.Json.JsonConvert.SerializeObject(jsonProductFields);

                        response.Write(jsonCustomFields);
                    }
                    break;

                case "updateCategorySortOrder":
                    string[] sortedCatIdStrings = request.Params.GetValues("sortedCategoryIds");
                    if (sortedCatIdStrings != null)
                    {
                        List <int> sortedCatIds = new List <string>(sortedCatIdStrings).ConvertAll(s => WA.Parser.ToInt(s).GetValueOrDefault(-1));
                        CategoryCollection.SetSortOrderByListPosition(sortedCatIds);
                        CacheHelper.ClearCache();
                        RespondWithSuccess();
                    }
                    else
                    {
                        RespondWithError("no category ids found to update sort order");
                    }
                    break;

                case "updateProductFieldSortOrder":
                    var sortedProductFieldIdStrings = request.Params.GetValues("sortedProductFieldIds[]");
                    if (sortedProductFieldIdStrings != null)
                    {
                        List <int> sortedProductFieldIds = new List <string>(sortedProductFieldIdStrings).ConvertAll(s => WA.Parser.ToInt(s).GetValueOrDefault(-1));
                        ProductFieldCollection.SetSortOrderByListPosition(sortedProductFieldIds);
                        RespondWithSuccess();
                    }
                    else
                    {
                        RespondWithError("no product field ids found to update sort order");
                    }
                    break;

                default:
                    RespondWithError("unknown action");
                    break;
                }

                //response.Write("{ success: true }");
            }
            catch (Exception ex)
            {
                RespondWithError(ex.Message + " Stack Trace:" + ex.StackTrace);
            }

            response.Flush();
        }
예제 #7
0
        private CheckoutOrderInfo FillCheckoutOrderInfo()
        {
            CheckoutOrderInfo checkoutOrderInfo = new CheckoutOrderInfo();

            checkoutOrderInfo.PaymentProvider = PaymentProviderName.UNKNOWN;

            //---- Check for the PayPal Express Checkout return page variables
            Dictionary <string, string> payPalVariables = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(Request.QueryString["token"]) && !string.IsNullOrEmpty(Request.QueryString["PayerID"]))
            {
                payPalVariables["token"]   = Request.QueryString["token"];
                payPalVariables["PayerID"] = Request.QueryString["PayerID"];

                checkoutOrderInfo.PayPalVariables.Merge(payPalVariables);
                checkoutOrderInfo.PaymentProvider = PaymentProviderName.PayPalExpressCheckout;
            }
            else
            {
                // user-selected payment method (credit card or PayPal)
                string userSelectedPaymentMethod = Request.Form["paymentMethod"] ?? "";
                if (userSelectedPaymentMethod == "creditCard")
                {
                    checkoutOrderInfo.PaymentProvider = StoreContext.CurrentStore.GetOnsiteCreditCardPaymentProvider();
                }
            }

            if (checkoutOrderInfo.PaymentProvider == PaymentProviderName.UNKNOWN)
            {
                throw new ApplicationException("Unable to determine PaymentProvider for CheckoutOrderInfo!");
            }

            //---- Cart
            checkoutOrderInfo.Cart = cart;

            //---- Billing/Shipping Address
            // TODO - sometimes we need to grab billing/shipping info from Payment Provider (e.g. PayPal Express Checkout)
            AddressInfo billingAddress = billingAddressForm.GetPostedAddressInfo();

            checkoutOrderInfo.BillingAddress = billingAddress;

            AddressInfo shippingAddress = shippingAddressForm.GetPostedAddressInfo();

            checkoutOrderInfo.ShippingAddress = shippingAddress;

            //---- Credit Card Info
            CreditCardInfo creditCard = new CreditCardInfo()
            {
                CardType     = WA.Enum <CreditCardType> .TryParseOrDefault(ddlCCType.SelectedValue, CreditCardType.UNKNOWN),
                CardNumber   = txtCCNumber.Text,
                ExpireMonth  = WA.Parser.ToShort(ddlCCExpireMonth.SelectedValue),
                ExpireYear   = WA.Parser.ToShort(ddlCCExpireYear.SelectedValue),
                NameOnCard   = txtCCNameOnCard.Text,
                SecurityCode = WA.Parser.ToShort(txtCCSecurityCode.Text)
            };

            checkoutOrderInfo.CreditCard = creditCard;

            // TODO - apply the shipping type the user selected, recalculate discounts too?

            //--- Stick the CheckoutOrderInfo into the session so we can grab it when the user clicks "Place Order"
            Session[SessionKey_CheckoutOrderInfo] = checkoutOrderInfo;

            return(checkoutOrderInfo);
        }
예제 #8
0
        private void PlaceOrder()
        {
            CheckoutOrderInfo checkoutOrderInfo = Session[SessionKey_CheckoutOrderInfo] as CheckoutOrderInfo;

            if (checkoutOrderInfo != null)
            {
                try
                {
                    OrderController orderController = new OrderController(StoreContext);
                    Order           submittedOrder  = null;

                    if (checkoutOrderInfo.PaymentProvider == PaymentProviderName.PayPalExpressCheckout)
                    {
                        //---- PayPal Express Checkout
                        submittedOrder = orderController.CompleteExpressCheckoutPayment(checkoutOrderInfo.PayPalVariables);
                    }
                    else
                    {
                        //---- Non-PayPal Process
                        submittedOrder = orderController.CheckoutWithPayment(checkoutOrderInfo);
                    }

                    if ((submittedOrder != null) && (submittedOrder.OrderStatus == OrderStatusName.Completed))
                    {
                        //---- Send Order Email(s)
                        EmailController             emailController = new EmailController(StoreContext);
                        Dictionary <string, string> emailTokens     = orderController.GetTemplateTokens(submittedOrder);

                        string adminEmailResponse = emailController.SendEmailTemplate(EmailTemplateNames.OrderCompletedAdmin, emailTokens, StoreContext.CurrentStore.GetSetting(StoreSettingNames.OrderCompletedEmailRecipient));
                        string emailResponse      = emailController.SendEmailTemplate(EmailTemplateNames.OrderCompleted, emailTokens, submittedOrder.CustomerEmail);

                        if (!string.IsNullOrEmpty(emailResponse))
                        {
                            msgFlash.Visible   = true;
                            msgFlash.InnerHtml = string.Format(@"Oh no! Something went wrong when we tried to email your order receipt. {0}", emailResponse);

                            try
                            {
                                LogToDnnEventLog(string.Format(@"SEND ORDER EMAIL ERROR. PortalId: {0} StoreId: {1} OrderId : {2}. Email Error: {3}", PortalId, StoreContext.CurrentStore.Id, submittedOrder.Id, emailResponse));
                                LogToDnnEventLog(submittedOrder);
                            }
                            catch (Exception ex)
                            {
                                // eat it
                            }
                        }

                        ShowOrderComplete(submittedOrder);

                        Session.Remove(SessionKey_CheckoutOrderInfo);
                        cartController.EmptyCart();
                    }
                    else
                    {
                        string             paymentError       = "";
                        PaymentTransaction paymentTransaction = submittedOrder.GetMostRecentPaymentTransaction();
                        if (paymentTransaction != null)
                        {
                            paymentError = string.Format("Payment Error: <p>{0}</p> <p>{1}</p>", paymentTransaction.GatewayError, paymentTransaction.GatewayRawResponse);
                        }
                        msgFlash.Visible   = true;
                        msgFlash.InnerHtml = string.Format(@"Oh no! Something went wrong when we tried to process your order. {0}", paymentError);

                        try
                        {
                            LogToDnnEventLog(string.Format(@"CHECKOUT ERROR. PortalId: {0} StoreId: {1} OrderId : {2}. Payment Error: {3}", PortalId, StoreContext.CurrentStore.Id, submittedOrder.Id, paymentError));
                            LogToDnnEventLog(submittedOrder);
                        }
                        catch (Exception ex)
                        {
                            // eat it
                        }
                    }
                }
                catch (Exception ex)
                {
                    Exceptions.LogException(ex);

                    msgFlash.Visible   = true;
                    msgFlash.InnerHtml = string.Format(@"Oops! An unexpected error has occurred while trying to process your order. Error: {0} {1}", ex.Message, ex.StackTrace);
                }
            }
            else
            {
                throw new ModuleLoadException("CheckoutOrderInfo is NULL in the Session!");
            }
        }