public ActionResult Purchase(CheckoutViewModel viewModel, IPaymentOption paymentOption)
        {
            if (CartIsNullOrEmpty())
            {
                return(Redirect(Url.ContentUrl(ContentReference.StartPage)));
            }

            // Since the payment property is marked with an exclude binding attribute in the CheckoutViewModel
            // it needs to be manually re-added again.
            viewModel.Payment = paymentOption;

            if (User.Identity.IsAuthenticated)
            {
                _checkoutService.CheckoutAddressHandling.UpdateAuthenticatedUserAddresses(viewModel);

                var validation = _checkoutService.AuthenticatedPurchaseValidation;

                if (!validation.ValidateModel(ModelState, viewModel) ||
                    !validation.ValidateOrderOperation(ModelState, _cartService.ValidateCart(Cart)) ||
                    !validation.ValidateOrderOperation(ModelState, _cartService.RequestInventory(Cart)))
                {
                    return(View(viewModel));
                }
            }
            else
            {
                _checkoutService.CheckoutAddressHandling.UpdateAnonymousUserAddresses(viewModel);

                var validation = _checkoutService.AnonymousPurchaseValidation;

                if (!validation.ValidateModel(ModelState, viewModel) ||
                    !validation.ValidateOrderOperation(ModelState, _cartService.ValidateCart(Cart)) ||
                    !validation.ValidateOrderOperation(ModelState, _cartService.RequestInventory(Cart)))
                {
                    return(View(viewModel));
                }
            }

            if (!paymentOption.ValidateData())
            {
                return(View(viewModel));
            }

            _checkoutService.UpdateShippingAddresses(Cart, viewModel);

            _checkoutService.CreateAndAddPaymentToCart(Cart, viewModel);

            var purchaseOrder = _checkoutService.PlaceOrder(Cart, ModelState, viewModel);

            if (purchaseOrder == null)
            {
                return(View(viewModel));
            }

            var confirmationSentSuccessfully = _checkoutService.SendConfirmation(viewModel, purchaseOrder);

            _recommendationService.SendOrderTracking(HttpContext, purchaseOrder);

            return(Redirect(_checkoutService.BuildRedirectionUrl(viewModel, purchaseOrder, confirmationSentSuccessfully)));
        }
Example #2
0
        public PaymentMethodViewModel(IPaymentOption paymentOption)
        {
            PaymentMethodId = paymentOption.PaymentMethodId;
            SystemKeyword   = paymentOption.SystemKeyword;
            FriendlyName    = paymentOption.Name;
            Description     = paymentOption.Description;

            PaymentOption = paymentOption;
        }
Example #3
0
        /// <summary>
        /// Places the order.
        /// </summary>
        public bool FullfilPayment()
        {
            // find selected payment gateway:
            IPaymentOption selectedPayment = null;

            Mediachase.Commerce.Orders.Dto.PaymentMethodDto.PaymentMethodRow paymentMethodRow = null;
            var payments = PaymentManager.GetPaymentMethods("en");

            for (int i = 0; i < PaymentContent.Controls.Count; i++)
            {
                Control control = PaymentContent.Controls[i];

                var radioButton = control.Controls[0] as GlobalRadioButton;
                if (radioButton.Checked)
                {
                    selectedPayment  = control.Controls[2] as IPaymentOption;
                    paymentMethodRow = payments.PaymentMethod[i];
                    break;
                }
            }

            if (selectedPayment == null)
            {
                ErrorManager.GenerateError("Fatal error, system administrator has been notified.");
                return(false);
            }
            try
            {
                var payment = selectedPayment.PreProcess(_cartHelper.OrderForm);
                if (payment != null)
                {
                    payment.PaymentMethodId   = paymentMethodRow.PaymentMethodId;
                    payment.PaymentMethodName = paymentMethodRow.Name;
                    payment.BillingAddressId  = _cartHelper.OrderForm.BillingAddressId;
                    payment.Amount            = _cartHelper.OrderForm.Total;
                    _cartHelper.Cart.OrderForms[0].Payments.Add(payment);
                    // Save changes

                    _cartHelper.Cart.AcceptChanges();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                ErrorManager.GenerateError(ex.Message);
                return(false);
            }

            ErrorManager.GenerateError("Please choose a payment method.");
            return(false);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CheckoutController"/> class.
 /// </summary>
 /// <param name="storeClient">The store client.</param>
 /// <param name="paymentClient">The payment client.</param>
 /// <param name="userClient">The user client.</param>
 /// <param name="countryClient">The country client.</param>
 /// <param name="orderClient">The order client.</param>
 /// <param name="paymentOptions">The payment options.</param>
 public CheckoutController(StoreClient storeClient,
                           PaymentClient paymentClient,
                           UserClient userClient,
                           CountryClient countryClient,
                           OrderClient orderClient,
                           IPaymentOption[] paymentOptions)
 {
     _storeClient = storeClient;
     _paymentClient = paymentClient;
     _userClient = userClient;
     _countryClient = countryClient;
     _orderClient = orderClient;
     _paymentOptions = paymentOptions;
 }
        public ActionResult Purchase(CheckoutViewModel viewModel, IPaymentOption paymentOption)
        {
            if (CartIsNullOrEmpty())
            {
                return(Redirect(Url.ContentUrl(ContentReference.StartPage)));
            }

            // Since the payment property is marked with an exclude binding attribute in the CheckoutViewModel
            // it needs to be manually re-added again.
            viewModel.Payment = paymentOption;

            viewModel.IsAuthenticated = User.Identity.IsAuthenticated;

            _checkoutService.CheckoutAddressHandling.UpdateUserAddresses(viewModel);
            if (!_checkoutService.ValidateOrder(ModelState, viewModel, _cartService.ValidateCart(Cart)))
            {
                return(View(viewModel));
            }

            if (!paymentOption.ValidateData())
            {
                return(View(viewModel));
            }

            _checkoutService.UpdateShippingAddresses(Cart, viewModel);

            _checkoutService.CreateAndAddPaymentToCart(Cart, viewModel);

            var purchaseOrder = _checkoutService.PlaceOrder(Cart, ModelState, viewModel);

            if (!string.IsNullOrEmpty(viewModel.RedirectUrl))
            {
                return(Redirect(viewModel.RedirectUrl));
            }

            if (purchaseOrder == null)
            {
                return(View(viewModel));
            }

            var confirmationSentSuccessfully = _checkoutService.SendConfirmation(viewModel, purchaseOrder);

            if (Request.IsAjaxRequest())
            {
                return(Json(new { Url = _checkoutService.BuildRedirectionUrl(viewModel, purchaseOrder, confirmationSentSuccessfully) }));
            }
            return(Redirect(_checkoutService.BuildRedirectionUrl(viewModel, purchaseOrder, confirmationSentSuccessfully)));
        }
        /// <summary>
        /// Validates the data.
        /// </summary>
        /// <returns></returns>
        public bool ValidateData()
        {
            bool isValid = false;

            PaymentMethodDto.PaymentMethodRow paymentRow = PaymentMethod;
            if (paymentRow != null)
            {
                IPaymentOption po = FindPaymentControl(paymentRow.SystemKeyword);
                if (po != null)
                {
                    isValid = po.ValidateData();
                }
            }

            return(isValid & RadioButtonsPaymentCustomValidator.IsValid);
        }
        /// <summary>
        /// Finds the payment control.
        /// </summary>
        /// <param name="keyword">The keyword.</param>
        /// <returns></returns>
        private IPaymentOption FindPaymentControl(string keyword)
        {
            string key = String.Empty;

            foreach (DataListItem item in PaymentOptionList.Items)
            {
                PlaceHolder paymentOptionHolder = item.FindControl("PaymentOptionHolder") as PlaceHolder;
                if (paymentOptionHolder != null)
                {
                    IPaymentOption po = paymentOptionHolder.FindControl(PaymentMethod.SystemKeyword) as IPaymentOption;
                    if (po != null)
                    {
                        return(po);
                    }
                }
            }

            return(null);
        }
        public void ProcessPayment(IPaymentOption method)
        {
            var cart = CartHelper.Cart;

            if (!cart.OrderForms.Any())
            {
                cart.OrderForms.AddNew();
            }

            var payment = method.PreProcess(cart.OrderForms[0]);

            if (payment == null)
            {
                throw new PreProcessException();
            }

            cart.OrderForms[0].Payments.Add(payment);
            cart.AcceptChanges();

            method.PostProcess(cart.OrderForms[0]);
        }
Example #9
0
        public void ProcessPayment(IPaymentOption method)
        {
            var cart = _cartHelper(Mediachase.Commerce.Orders.Cart.DefaultName).Cart;

            if (!cart.OrderForms.Any())
            {
                cart.OrderForms.AddNew();
            }

            var payment = method.PreProcess(cart.OrderForms[0]);

            if (payment == null)
            {
                throw new PreProcessException();
            }

            cart.OrderForms[0].Payments.Add(payment);
            cart.AcceptChanges();

            method.PostProcess(cart.OrderForms[0]);
        }
Example #10
0
        public void ProcessPayment(IPaymentOption method)
        {
            var cart = _cartHelper(Mediachase.Commerce.Orders.Cart.DefaultName).Cart;

            if (!cart.OrderForms.Any())
            {
                cart.OrderForms.AddNew();
            }

            var payment = method.PreProcess(cart.OrderForms[0]);

            if (payment == null)
            {
                throw new PreProcessException();
            }

            cart.OrderForms[0].Payments.Add(payment);
            cart.AcceptChanges();

            method.PostProcess(cart.OrderForms[0]);
        }
 private CheckoutViewModel CreateCheckoutViewModel(CheckoutPage currentPage, IPaymentOption paymentOption = null)
 {
     return(_checkoutViewModelFactory.CreateCheckoutViewModel(Cart, currentPage, paymentOption));
 }
        public ActionResult Update(CheckoutPage currentPage, UpdateShippingMethodViewModel shipmentViewModel, IPaymentOption paymentOption)
        {
            ModelState.Clear();

            _checkoutService.UpdateShippingMethods(Cart, shipmentViewModel.Shipments);
            _checkoutService.ApplyDiscounts(Cart);
            _orderRepository.Save(Cart);

            var viewModel = CreateCheckoutViewModel(currentPage, paymentOption);

            return(PartialView("Partial", viewModel));
        }
Example #13
0
        public virtual CheckoutViewModel CreateCheckoutViewModel(ICart cart, CheckoutPage currentPage, IPaymentOption paymentOption = null)
        {
            if (cart == null)
            {
                return(CreateEmptyCheckoutViewModel(currentPage));
            }

            var currentShippingAddressId = cart.GetFirstShipment()?.ShippingAddress?.Id;
            var currentBillingAdressId   = cart.GetFirstForm().Payments.FirstOrDefault()?.BillingAddress?.Id;

            var shipments = _shipmentViewModelFactory.CreateShipmentsViewModel(cart).ToList();
            var useBillingAddressForShipment = shipments.Count == 1 && currentBillingAdressId == currentShippingAddressId && _addressBookService.UseBillingAddressForShipment();

            var viewModel = new CheckoutViewModel
            {
                CurrentPage    = currentPage,
                Shipments      = shipments,
                BillingAddress = CreateBillingAddressModel(),
                UseBillingAddressForShipment = useBillingAddressForShipment,
                StartPage          = _contentLoader.Get <StartPage>(ContentReference.StartPage),
                AppliedCouponCodes = cart.GetFirstForm().CouponCodes.Distinct(),
                AvailableAddresses = new List <AddressModel>(),
                ReferrerUrl        = GetReferrerUrl(),
                Payment            = paymentOption,
            };

            UpdatePayment(viewModel);

            var availableAddresses = GetAvailableAddresses();

            if (availableAddresses.Any())
            {
                viewModel.AvailableAddresses.Add(new AddressModel {
                    Name = _localizationService.GetString("/Checkout/MultiShipment/SelectAddress")
                });

                foreach (var address in availableAddresses)
                {
                    viewModel.AvailableAddresses.Add(address);
                }
            }
            else
            {
                viewModel.AvailableAddresses.Add(new AddressModel {
                    Name = _localizationService.GetString("/Checkout/MultiShipment/NoAddressFound")
                });
            }

            SetDefaultShipmentAddress(viewModel, currentShippingAddressId);

            _addressBookService.LoadAddress(viewModel.BillingAddress);
            PopulateCountryAndRegions(viewModel);

            return(viewModel);
        }
Example #14
0
        //protected Json.JsonObject GatewayDataJson = new Json.JsonObject();

        /// <summary>
        /// 构造支付请求接口
        /// </summary>
        /// <param name="option">支付网关回调URL参数</param>
        protected SendPaymentHandlerBase(IPaymentOption <T> option)
        {
            this.Option = option;
        }
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="_isBackRequest">是否为支付网关异步回调请求</param>
 protected PaymentReturnTemplatedPage(IPaymentOption <T> option, bool _isBackRequest)
 {
     this.Option        = option;
     this.isBackRequest = _isBackRequest;
 }
        public CheckoutViewModelFactoryTests()
        {
            _cart = new FakeCart(new MarketImpl(new MarketId(Currency.USD)), Currency.USD);
            _cart.Forms.Single().Shipments.Single().LineItems.Add(new InMemoryLineItem());
            _cart.Forms.Single().CouponCodes.Add("couponcode");

            var paymentServiceMock = new Mock <IPaymentService>();

            paymentServiceMock.Setup(x => x.GetPaymentMethodsByMarketIdAndLanguageCode(It.IsAny <string>(), "en")).Returns(
                new[]
            {
                new PaymentMethodViewModel()
                {
                    PaymentMethodId = Guid.NewGuid(), Description = "Lorem ipsum", FriendlyName = "payment method 1", SystemKeyword = cashPaymentName
                },
                new PaymentMethodViewModel()
                {
                    PaymentMethodId = Guid.NewGuid(), Description = "Lorem ipsum", FriendlyName = "payment method 2", SystemKeyword = creditPaymentName, IsDefault = true
                }
            });

            var marketMock          = new Mock <IMarket>();
            var currentMarketMock   = new Mock <ICurrentMarket>();
            var languageServiceMock = new Mock <LanguageService>(null, null, null);

            currentMarketMock.Setup(x => x.GetCurrentMarket()).Returns(marketMock.Object);
            languageServiceMock.Setup(x => x.GetCurrentLanguage()).Returns(new CultureInfo("en-US"));

            var cashOnDeliveryPaymentOption = new CashOnDeliveryPaymentOption(null, null, currentMarketMock.Object, languageServiceMock.Object, paymentServiceMock.Object);
            var creaditPaymentOption        = new GenericCreditCardPaymentOption(null, null, currentMarketMock.Object, languageServiceMock.Object, paymentServiceMock.Object);

            var paymentOptions = new List <IPaymentOption>();

            paymentOptions.Add(cashOnDeliveryPaymentOption as IPaymentOption);
            paymentOptions.Add(creaditPaymentOption as IPaymentOption);
            _creditPayment = creaditPaymentOption;

            var paymentMethodViewModelFactory = new PaymentMethodViewModelFactory(currentMarketMock.Object, languageServiceMock.Object, paymentServiceMock.Object, paymentOptions);

            var orderGroupFactoryMock = new Mock <IOrderGroupFactory>();

            orderGroupFactoryMock.Setup(x => x.CreatePayment(It.IsAny <IOrderGroup>())).Returns((IOrderGroup orderGroup) => new FakePayment());
            var serviceLocatorMock = new Mock <IServiceLocator>();

            serviceLocatorMock.Setup(x => x.GetInstance <IOrderGroupFactory>()).Returns(orderGroupFactoryMock.Object);
            ServiceLocator.SetLocator(serviceLocatorMock.Object);

            _addressBookServiceMock = new Mock <IAddressBookService>();
            _addressBookServiceMock.Setup(x => x.List()).Returns(() => new List <AddressModel> {
                new AddressModel {
                    AddressId = "addressid"
                }
            });
            _preferredBillingAddress      = CustomerAddress.CreateInstance();
            _preferredBillingAddress.Name = "preferredBillingAddress";
            _addressBookServiceMock.Setup(x => x.GetPreferredBillingAddress()).Returns(_preferredBillingAddress);
            _addressBookServiceMock.Setup(x => x.UseBillingAddressForShipment()).Returns(true);

            _startPage = new StartPage();
            var contentLoaderMock = new Mock <IContentLoader>();

            contentLoaderMock.Setup(x => x.Get <StartPage>(It.IsAny <PageReference>())).Returns(_startPage);

            var urlResolverMock = new Mock <UrlResolver>();
            var httpcontextMock = new Mock <HttpContextBase>();
            var requestMock     = new Mock <HttpRequestBase>();

            requestMock.Setup(x => x.Url).Returns(new Uri("http://site.com"));
            requestMock.Setup(x => x.UrlReferrer).Returns(new Uri("http://site.com"));
            httpcontextMock.Setup(x => x.Request).Returns(requestMock.Object);

            var shipmentViewModelFactoryMock = new Mock <ShipmentViewModelFactory>(null, null, null, null, null);

            shipmentViewModelFactoryMock.Setup(x => x.CreateShipmentsViewModel(It.IsAny <ICart>())).Returns(() => new[]
            {
                new ShipmentViewModel {
                    CartItems = new[]
                    {
                        new CartItemViewModel {
                            Quantity = 1
                        }
                    }
                }
            });

            _subject = new CheckoutViewModelFactory(
                new MemoryLocalizationService(),
                (() => paymentMethodViewModelFactory),
                _addressBookServiceMock.Object,
                contentLoaderMock.Object,
                urlResolverMock.Object,
                (() => httpcontextMock.Object),
                shipmentViewModelFactoryMock.Object);
        }
Example #17
0
 /// <summary>
 /// 构造支付回调/通知Handler
 /// </summary>
 /// <param name="option">支付网关回调URL参数</param>
 /// <param name="isNotify">是否为支付网关异步回调请求</param>
 protected PaymentReturnHandlerBase(IPaymentOption <T> option, bool isNotify)
 {
     Option         = option;
     this._isNotify = isNotify;
 }