public ActionResult Checkout(CheckoutViewModel creditCardValues) { var yearExpiration = Convert.ToInt16(creditCardValues.ExpirationYear); var monthExpiration = Convert.ToByte(creditCardValues.ExpirationMonth); var order = new Order(_randomOrderId, 4700.00m, DateTime.Now, "Goku e GokuSSJ"); var paymentMethod = new PaymentMethod(CreditCard.MasterCard, PurchaseType.Credit); var options = new CreateTransactionOptions(AuthorizationType.AuthorizeSkippingAuthentication, true); var creditCardData = new CreditCardData(creditCardValues.CreditCardNumber, new CreditCardExpiration(yearExpiration, monthExpiration), SecurityCodeIndicator.Sent, creditCardValues.SecurityCode); var createTransactionRequest = new CreateTransactionRequest(order, paymentMethod, options, creditCardData, _configuration); try { var response = _cieloService.CreateTransaction(createTransactionRequest); Session["tid"] = response.Tid; return Redirect("CheckStatus"); } catch (ResponseException ex) { ViewBag.MessageError = ex.Message; return View(creditCardValues); } }
public void CancelPayment(CheckoutViewModel checkoutViewModel) { var completeCheckoutStatementsArray = _state.Get<List<CheckoutStatementBase>>(STATE_KEY); var eventId = completeCheckoutStatementsArray.OfType<TransactionStatement>().First().Event; var @event = ParseObject.CreateWithoutData<Event>(eventId); @event.EventStatus = EventStatus.EventCanceledByUser; Task.Run(() => @event.SaveAsync()).Wait(); var purchaseUpdateStatements = completeCheckoutStatementsArray.Where(x => x.RecordType == RecordTypes.PurchaseUpdate).OfType<UpdatePurchaseTransactionStatement>().Select(x => x).ToArray(); var purchasesToUpdate = purchaseUpdateStatements.Select(x => new Purchase { ObjectId = x.ObjectId, Event = @event }); _repository.BulkSave(purchasesToUpdate); }
public string ExecuteCompleteCheckout( ParseUser loggedInUser, CheckoutViewModel checkoutViewModel, string worldId, Purchase[] userHistoricalPurchases, out string paymentUrl) { paymentUrl = string.Empty; var completeCheckoutLetterDto = new CompleteCheckoutLetterDto(); var completeCheckoutStatementsArray = new List<CheckoutStatementBase>(); var checkoutItemLetterDtoArray = new List<CheckoutItemLetterDto>(); var accountStatementsBuilder = new AccountStatementBuilder(_repository, _currencyRetriver); var checkoutManager = new CheckoutManager(_repository, loggedInUser, checkoutViewModel); try { CreatePaymentRecords(checkoutViewModel, worldId, userHistoricalPurchases, checkoutManager,completeCheckoutLetterDto, checkoutItemLetterDtoArray, completeCheckoutStatementsArray); SetLetters(loggedInUser,checkoutViewModel,completeCheckoutStatementsArray,checkoutItemLetterDtoArray,completeCheckoutLetterDto,loggedInUser); if (checkoutViewModel.PaymentTransactionForCalc == 0) { checkoutManager.SavePaymentRecords(completeCheckoutStatementsArray, accountStatementsBuilder, checkoutViewModel); InitPuchaseView(loggedInUser, checkoutViewModel); } else { _state.Set(STATE_KEY,completeCheckoutStatementsArray); paymentUrl = GetPaymentUrl(checkoutManager,checkoutViewModel); } } catch(Exception ex) { BL.DomainServices.Log.LoggerFactory.GetLogger().LogError(ex); Mailer.SendCheckoutError(loggedInUser, checkoutManager.EventId, "Check out error"); throw; } return checkoutManager.EventId; }
public IActionResult CheckOut(CheckoutViewModel checkoutViewModel) { _checkOutService.ProcessCheckout(checkoutViewModel); return(RedirectToAction("Receipt")); }
private void LoadBillingAddressFromAddressBook(CheckoutViewModel checkoutViewModel) { _addressBookService.LoadAddress(checkoutViewModel.BillingAddress); }
public async Task <IActionResult> Index(CheckoutViewModel model) { await GetCurrentCart(model); if (ModelState.IsValid) { if (!string.IsNullOrEmpty(model.SavedAddressId) || (!string.IsNullOrEmpty(model.ShippingAddressLine1) && !string.IsNullOrEmpty(model.ShippingLocale) && !string.IsNullOrEmpty(model.ShippingRegion) && !string.IsNullOrEmpty(model.ShippingPostalCode) && !string.IsNullOrEmpty(model.ShippingCountry))) { Order newOrder = new Order { TrackingNumber = Guid.NewGuid().ToString(), OrderDate = DateTime.Now, OrderItems = model.Cart.CartItems.Select(x => new OrderItem { ProductID = x.Product.ID, ProductName = x.Product.Name, ProductPrice = (x.Product.Price ?? 0), Quantity = x.Quantity }).ToArray(), AddressLine1 = model.ShippingAddressLine1, AddressLine2 = model.ShippingAddressLine2, Country = model.ShippingCountry, Email = model.ContactEmail, PhoneNumber = model.ContactPhoneNumber, Locale = model.ShippingLocale, PostalCode = model.ShippingPostalCode, Region = model.ShippingRegion }; Braintree.Customer customer = null; Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Is(model.ContactEmail); var searchResult = await _brainTreeGateway.Customer.SearchAsync(search); if (searchResult.Ids.Count == 0) { //Create a new Braintree Customer Braintree.Result <Customer> creationResult = await _brainTreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest { Email = model.ContactEmail, Phone = model.ContactPhoneNumber }); customer = creationResult.Target; } else { customer = searchResult.FirstItem; } CreditCard creditCard = null; if (model.SaveBillingCard) { var newCardRequest = new CreditCardRequest { CardholderName = model.BillingNameOnCard, CustomerId = customer.Id, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString(), Number = model.BillingCardNumber, CVV = model.BillingCardVerificationValue }; var newCardResult = await _brainTreeGateway.CreditCard.CreateAsync(newCardRequest); if (newCardResult.IsSuccess()) { creditCard = newCardResult.Target; } } Address savedAddress = null; if (model.SaveShippingAddress) { var newAddressRequest = new AddressRequest { StreetAddress = model.ShippingAddressLine1, ExtendedAddress = model.ShippingAddressLine2, CountryName = model.ShippingCountry, PostalCode = model.ShippingPostalCode, Locality = model.ShippingLocale, Region = model.ShippingRegion }; var newAddressResult = await _brainTreeGateway.Address.CreateAsync(customer.Id, newAddressRequest); if (newAddressResult.IsSuccess()) { savedAddress = newAddressResult.Target; } } //More on card testing: https://developers.braintreepayments.com/reference/general/testing/dotnet TransactionRequest transaction = new TransactionRequest { //Amount = 1, Amount = model.Cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)), CustomerId = customer.Id, LineItems = model.Cart.CartItems.Select(x => new TransactionLineItemRequest { Name = x.Product.Name, Description = x.Product.Description, ProductCode = x.Product.ID.ToString(), Quantity = x.Quantity, LineItemKind = TransactionLineItemKind.DEBIT, UnitAmount = x.Product.Price * x.Quantity, TotalAmount = x.Product.Price * x.Quantity }).ToArray() }; if (creditCard == null) { transaction.CreditCard = new TransactionCreditCardRequest { Number = model.BillingCardNumber, CardholderName = model.BillingNameOnCard, CVV = model.BillingCardVerificationValue, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString() }; } else { transaction.PaymentMethodToken = creditCard.Token; } if (savedAddress != null) { transaction.ShippingAddressId = savedAddress.Id; } var transactionResult = await _brainTreeGateway.Transaction.SaleAsync(transaction); if (transactionResult.IsSuccess()) { _countryClubDbContext.Orders.Add(newOrder); _countryClubDbContext.CartItems.RemoveRange(model.Cart.CartItems); _countryClubDbContext.Carts.Remove(model.Cart); await _countryClubDbContext.SaveChangesAsync(); //Send email after purchase button is hit. Sends email first before moving onto the reciept page view //Try to checkout Response.Cookies.Delete("cartId"); return(RedirectToAction("Index", "Receipt", new { id = newOrder.TrackingNumber })); } for (int i = 0; i < transactionResult.Errors.Count; i++) { ModelState.AddModelError("BillingCardNumber" + i, transactionResult.Errors.All()[i].Message); } } } return(View(model)); }
public async Task <ActionResult> PlaceOrder(CheckoutPage currentPage, CheckoutViewModel checkoutViewModel) { // shipping information UpdateShipmentAddress(checkoutViewModel); // subscription AddSubscription(checkoutViewModel); // billing address UpdatePaymentAddress(checkoutViewModel); _orderRepository.Save(CartWithValidationIssues.Cart); try { var purchaseOrder = _checkoutService.PlaceOrder(CartWithValidationIssues.Cart, ModelState, checkoutViewModel); if (purchaseOrder == null) { TempData["ErrorMessages"] = "There is no payment was processed"; return(RedirectToAction("Index")); } if (checkoutViewModel.BillingAddressType == 0) { _addressBookService.Save(checkoutViewModel.BillingAddress); } foreach (var shipment in checkoutViewModel.Shipments) { if (shipment.ShippingAddressType == 0 && shipment.ShippingMethodId != _cartService.InStorePickupInfoModel.MethodId) { _addressBookService.Save(shipment.Address); } } if (Request.IsAuthenticated) { var contact = _customerContext.GetCurrentContact().Contact; var organization = contact.ContactOrganization; if (organization != null) { purchaseOrder.Properties[Constant.Customer.CustomerFullName] = contact.FullName; purchaseOrder.Properties[Constant.Customer.CustomerEmailAddress] = contact.Email; purchaseOrder.Properties[Constant.Customer.CurrentCustomerOrganization] = organization.Name; _orderRepository.Save(purchaseOrder); } } checkoutViewModel.CurrentContent = currentPage; var confirmationSentSuccessfully = await _checkoutService.SendConfirmation(checkoutViewModel, purchaseOrder); //await _checkoutService.CreateOrUpdateBoughtProductsProfileStore(CartWithValidationIssues.Cart); //await _checkoutService.CreateBoughtProductsSegments(CartWithValidationIssues.Cart); await _recommendationService.TrackOrder(HttpContext, purchaseOrder); return(Redirect(_checkoutService.BuildRedirectionUrl(checkoutViewModel, purchaseOrder, confirmationSentSuccessfully))); } catch (Exception e) { TempData["ErrorMessages"] = e.Message; return(RedirectToAction("Index")); } }
private ViewResult View(CheckoutViewModel checkoutViewModel) => View(checkoutViewModel.ViewName, CreateCheckoutViewModel(checkoutViewModel.CurrentContent, checkoutViewModel.Payments.FirstOrDefault()));
private void SetBundleClips(Purchase[] userPurchases, CheckoutViewModel model, IMyMentorRepository repository) { var bundleIds = userPurchases.Where(x => x.BundleKey != null).Select(x => x.BundleKey.ObjectId).ToArray(); model.LessonsForBundles = repository.FindClipsForBundle(bundleIds); }
// GET: Checkout public ActionResult OnePageCheckout(string basketId) { var response = _checkoutApi.Checkout(Sanitizer.GetSafeHtmlFragment(basketId)); var checkout = response.Result; if (checkout.BasketId == null || checkout.Basket == null || checkout.Basket.LineItems.Count < 1) { return(RedirectToAction("BasketNotFound", "Common")); } foreach (var pay in checkout.PaymentOptions) { pay.CardInfo.Amount = checkout.BalanceAmount.Raw.WithTax; } var result = _configApi.GetConfig(); var data = result.Result; //checkout.Basket.shippingMethods = 0 is simpl check this implementation later data.ShippingCountries = data.ShippingCountries.Where(x => checkout.Basket.shippingMethods.Any(y => y.CountryCode == x.TwoLetterIsoCode) || checkout.Basket.shippingMethods.Count() == 0).Distinct().ToList(); var model = new CheckoutViewModel { Checkout = checkout, Register = new RegistrationModel(), Login = new LoginViewModel(), BillingCountries = data.BillingCountries, ShippingCountries = data.ShippingCountries, CurrentDate = DateTime.Today.Date.AddDays(1) }; if (_sessionContext.CurrentUser == null) { model.RegistrationPrompt = Convert.ToBoolean(_sessionContext.CurrentSiteConfig.BasketSettings.RegistrationPrompt); } string returnUrl = string.Empty; //So that the user can be referred back to where they were when they click logon if (Request.UrlReferrer != null) { returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery); } //if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl)) if (!string.IsNullOrEmpty(returnUrl)) { TempData["ReturnURL"] = returnUrl; } if (_sessionContext.CurrentUser == null) { if (Guid.Parse(checkout.CustomerId) != Guid.Empty) { var customerresult = _customerRepository.GetUserdetailsById <CustomerDetailModel>(checkout.CustomerId); if (customerresult != null) { checkout.Email = customerresult.Result.Email; checkout.CompanyId = customerresult.Result.CompanyId; } } else { _checkoutApi.UpdateUserToBasket(checkout.BasketId, Guid.Empty.ToString()); checkout.Stage = BasketStage.Anonymous.GetHashCode(); } SetDataLayerVariables(response.Result?.Basket, WebhookEventTypes.CheckoutStarted); return(View(CustomViews.ONE_PAGE_CHECKOUT, model)); } model.Checkout.CustomerId = _sessionContext.CurrentUser.UserId.ToString(); model.Checkout.Email = _sessionContext.CurrentUser.Email; var WishlistResponse = _customerRepository.GetWishlist(model.Checkout.CustomerId, true); model.Checkout.WishlistProducts = WishlistResponse.Result; SetDataLayerVariables(response.Result?.Basket, WebhookEventTypes.CheckoutStarted); return(View(CustomViews.ONE_PAGE_CHECKOUT, model)); }
public ActionResult AddSubscription(CheckoutViewModel checkoutViewModel) { _checkoutService.UpdatePaymentPlan(CartWithValidationIssues.Cart, checkoutViewModel); _orderRepository.Save(CartWithValidationIssues.Cart); return(RedirectToAction("PlaceOrder", "Checkout")); }
public IActionResult Checkout(CheckoutViewModel model) { model.Cart = HttpContext.Session.Get <Cart>("Cart") !; var customer = GetCustomerOrAddError(); if (customer == null) { return(View(model)); } var creditCard = GetCreditCardForUser(); try { creditCard.GetCardForUser(); } catch (WebGoatCreditCardNotFoundException) { } //Get form of payment //If form specified card number, try to use it instead one stored for user if (model.CreditCard != null && model.CreditCard.Length >= 13) { creditCard.Number = model.CreditCard; creditCard.Expiry = new DateTime(model.ExpirationYear, model.ExpirationMonth, 1); } else { ModelState.AddModelError(string.Empty, "The card number specified is too short."); _model = model; return(View(_model)); } //Authorize payment through our bank or Authorize.net or someone. if (!creditCard.IsValid()) { ModelState.AddModelError(string.Empty, "That card is not valid. Please enter a valid card."); _model = model; return(View(_model)); } if (model.RememberCreditCard) { creditCard.SaveCardForUser(); } var order = new Order { ShipVia = model.ShippingMethod, ShipName = model.ShipTarget, ShipAddress = model.Address, ShipCity = model.City, ShipRegion = model.Region, ShipPostalCode = model.PostalCode, ShipCountry = model.Country, OrderDetails = model.Cart.OrderDetails.Values.ToList(), CustomerId = customer.CustomerId, OrderDate = DateTime.Now, RequiredDate = DateTime.Now.AddDays(7), Freight = Math.Round(_shipperRepository.GetShipperByShipperId(model.ShippingMethod).GetShippingCost(model.Cart.SubTotal), 2), EmployeeId = 1, }; var approvalCode = creditCard.ChargeCard(order.Total); order.Shipment = new Shipment() { ShipmentDate = DateTime.Today.AddDays(1), ShipperId = order.ShipVia, TrackingNumber = _shipperRepository.GetNextTrackingNumber(_shipperRepository.GetShipperByShipperId(order.ShipVia)), }; //Create the order itself. var orderId = _orderRepository.CreateOrder(order); //Create the payment record. _orderRepository.CreateOrderPayment(orderId, order.Total, creditCard.Number, creditCard.Expiry, approvalCode); HttpContext.Session.SetInt32("OrderId", orderId); HttpContext.Session.Remove("Cart"); return(RedirectToAction("Receipt")); }
public virtual void UpdateAnonymousUserAddresses(CheckoutViewModel viewModel) => SetDefaultBillingAddressName(viewModel);
public ActionResult UpdatePaymentAddress(CheckoutPage currentPage, CheckoutViewModel viewModel) { var orderSummary = _orderSummaryViewModelFactory.CreateOrderSummaryViewModel(CartWithValidationIssues.Cart); var isMissingPayment = !CartWithValidationIssues.Cart.Forms.SelectMany(x => x.Payments).Any(); if (isMissingPayment || orderSummary.PaymentTotal != 0) { var model = CreateCheckoutViewModel(currentPage); model.OrderSummary = orderSummary; model.AddressType = viewModel.AddressType; model.BillingAddress = viewModel.BillingAddress; if (viewModel.AddressType == 1) { if (string.IsNullOrEmpty(viewModel.BillingAddress.AddressId)) { ModelState.AddModelError("BillingAddress.AddressId", "Address is required."); model.AddressType = 1; } } if (isMissingPayment) { ModelState.AddModelError("SelectedPayment", _localizationService.GetString("/Shared/PaymentRequired")); } if (orderSummary.PaymentTotal != 0) { ModelState.AddModelError("PaymentTotal", "PaymentTotal is invalid."); } return(View("BillingInformation", model)); } if (viewModel.AddressType == 1) { if (string.IsNullOrEmpty(viewModel.BillingAddress.AddressId)) { ModelState.AddModelError("BillingAddress.AddressId", "Address is required."); var model = CreateCheckoutViewModel(currentPage); model.OrderSummary = orderSummary; model.AddressType = 1; return(View("BillingInformation", model)); } _addressBookService.LoadAddress(viewModel.BillingAddress); } else { viewModel.BillingAddress.AddressId = null; viewModel.BillingAddress.Name = DateTime.Now.ToString(); _addressBookService.Save(viewModel.BillingAddress); } foreach (var payment in CartWithValidationIssues.Cart.GetFirstForm().Payments) { payment.BillingAddress = _addressBookService.ConvertToAddress(viewModel.BillingAddress, CartWithValidationIssues.Cart); } _orderRepository.Save(CartWithValidationIssues.Cart); return(RedirectToAction("CreateSubscription", "Checkout")); }
public virtual void UpdateAuthenticatedUserAddresses(CheckoutViewModel viewModel) { LoadBillingAddressFromAddressBook(viewModel); LoadShippingAddressesFromAddressBook(viewModel); }
public virtual IPurchaseOrder PlaceOrder(ICart cart, ModelStateDictionary modelState, CheckoutViewModel checkoutViewModel) { try { var paymentProcessingResults = cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator); if (paymentProcessingResults.Any(r => !r.IsSuccessful)) { modelState.AddModelError("", _localizationService.GetString("/Checkout/Payment/Errors/ProcessingPaymentFailure") + string.Join(", ", paymentProcessingResults.Select(p => p.Message))); return(null); } var redirectPayment = paymentProcessingResults.FirstOrDefault(r => !string.IsNullOrEmpty(r.RedirectUrl)); if (redirectPayment != null) { checkoutViewModel.RedirectUrl = redirectPayment.RedirectUrl; return(null); } var processedPayments = cart.GetFirstForm().Payments.Where(x => x.Status.Equals(PaymentStatus.Processed.ToString())); if (!processedPayments.Any()) { // Return null in case there is no payment was processed. return(null); } var totalProcessedAmount = processedPayments.Sum(x => x.Amount); if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount) { throw new InvalidOperationException("Wrong amount"); } PurchaseValidation validation = null; if (checkoutViewModel.IsAuthenticated) { validation = AuthenticatedPurchaseValidation; } else { validation = AnonymousPurchaseValidation; } if (!validation.ValidateOrderOperation(modelState, _cartService.RequestInventory(cart))) { return(null); } var orderReference = _orderRepository.SaveAsPurchaseOrder(cart); var purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId); _orderRepository.Delete(cart.OrderLink); return(purchaseOrder); } catch (PaymentException ex) { modelState.AddModelError("", _localizationService.GetString("/Checkout/Payment/Errors/ProcessingPaymentFailure") + ex.Message); } return(null); }
public async Task <ActionResult> Checkout(CheckoutViewModel model) { var userId = User.Identity.GetUserId(); if (userId == null) { return(RedirectToAction("Index", "Home")); } if (string.IsNullOrEmpty(model.PaymentMethodId)) { ModelState.AddModelError("PaymentMethodId", "A payment method could not be retrieved."); return(View(model)); } try { string orderId = Guid.NewGuid().ToString(); model.GamesInCart = GetGamesFromCart(userId); // add new order record var newOrder = new Order { Id = orderId, UserId = userId, PurchaseDate = DateTime.Now, CreditCardUsed = model.PaymentMethodId }; db.Orders.Add(newOrder); // add new orderItem records foreach (var game in model.GamesInCart) { db.OrderItems.Add(new OrderItem { OrderId = orderId, GameId = game.Id }); } // if any of the games bought were in the user's wish list, remove them from there var userWishList = db.WishLists.Where(i => i.userId == userId); foreach (var game in model.GamesInCart) { var gameInWishList = userWishList.FirstOrDefault(i => i.gameId == game.Id); if (gameInWishList != null) { db.WishLists.Remove(gameInWishList); } } // remove all items from user's cart var cartItem = db.UserCartItems.Where(c => c.UserId == userId).ToList(); db.UserCartItems.RemoveRange(cartItem); List <string> gameIds = new List <string>(); foreach (Game g in model.GamesInCart) { gameIds.Add(g.Id); } // remove the games from wishlist var wishes = db.WishLists.Where(c => c.userId == userId && gameIds.Contains(c.gameId)); db.WishLists.RemoveRange(wishes); await db.SaveChangesAsync(); Session["cart"] = "0"; } catch (Exception ex) { ModelState.AddModelError("", "An unexpected error occured while attempting to place your order."); return(View(model)); } return(RedirectToAction("OrderComplete", "Cart")); }
public ActionResult CheckoutComplete() { CheckoutViewModel checkoutViewModel = new CheckoutViewModel(); string ErrorMessage = ""; Session["userCheckoutCompleted"]="true"; if ((string)Session["userCheckoutCompleted"] != "true") { Session["userCheckoutCompleted"] = string.Empty; ErrorMessage = "Unvalidated%20Checkout"; RedirectToAction("CheckoutError", ErrorMessage); } NVPAPICaller payPalCaller = new NVPAPICaller(); string retMsg = ""; string token = ""; string finalPaymentAmount = ""; string PayerID = ""; NVPCodec decoder = new NVPCodec(); string PaymentConfirmation = ""; token = Session["token"].ToString(); PayerID = Session["payerId"].ToString(); finalPaymentAmount = Session["payment_amt"].ToString(); bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg); // bool ret = true; if (ret) { // Retrieve PayPal confirmation value. PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString(); // PaymentConfirmation ="34rt56789"; checkoutViewModel.PayementConfirmationNo = PaymentConfirmation; // Get the current order id. int currentOrderId = -1; if (Session["currentOrderId"].ToString() !=string.Empty) { currentOrderId = Convert.ToInt32(Session["currentOrderID"]); } string CartID=""; if (currentOrderId >= 0) { OrderApplicationService orderApplicationService = new OrderApplicationService(); var Cart = ShoppingCartActions.GetCart(); CartID = Cart.ShoppingCartId; // Get the order based on order id. // Update the order to reflect payment has been completed.Clear shopping cart. orderApplicationService.UpdateOrderEmptyCart(currentOrderId, PaymentConfirmation, CartID); } // Clear order id. Session["currentOrderId"] = string.Empty; } else { RedirectToAction("CheckoutError", retMsg); } return View("CheckoutComplete", checkoutViewModel); }
private bool GetExpressCheckoutDetails(PayPalAPI ppAPI, ref GetExpressCheckoutDetailsResponseType ppResponse, CheckoutViewModel model) { ppResponse = ppAPI.GetExpressCheckoutDetails(Request.QueryString["token"]); if (ppResponse.Ack == AckCodeType.Success || ppResponse.Ack == AckCodeType.SuccessWithWarning) { model.CurrentOrder.UserEmail = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer; model.CurrentOrder.ShippingAddress.FirstName = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName ?? string.Empty; if (ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.MiddleName.Length > 0) { model.CurrentOrder.ShippingAddress.MiddleInitial = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.MiddleName.Substring(0, 1); } else { model.CurrentOrder.ShippingAddress.MiddleInitial = string.Empty; } model.CurrentOrder.ShippingAddress.LastName = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName ?? string.Empty; model.CurrentOrder.ShippingAddress.Company = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerBusiness ?? string.Empty; model.CurrentOrder.ShippingAddress.Line1 = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1 ?? string.Empty; model.CurrentOrder.ShippingAddress.Line2 = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2 ?? string.Empty; model.CurrentOrder.ShippingAddress.CountryData.Name = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName ?? string.Empty; model.CurrentOrder.ShippingAddress.CountryData.Bvin = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString(); model.CurrentOrder.ShippingAddress.City = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName ?? string.Empty; model.CurrentOrder.ShippingAddress.RegionData.Name = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince ?? string.Empty; model.CurrentOrder.ShippingAddress.RegionData.Abbreviation = model.CurrentOrder.ShippingAddress.RegionData.Name ?? string.Empty; model.CurrentOrder.ShippingAddress.PostalCode = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode ?? string.Empty; model.CurrentOrder.ShippingAddress.Phone = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.ContactPhone ?? string.Empty; if (ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.AddressStatus == AddressStatusCodeType.Confirmed) { ViewBag.AddressStatus = "Confirmed"; } else { ViewBag.AddressStatus = "Unconfirmed"; } return(true); } else { return(false); } }
public ActionResult CompleteCheckout(CheckoutViewModel model) { ActionResult actionResult; if (EnsureLoggedOnUser(out actionResult)) return actionResult; var checkoutViewModel = new CheckoutViewModel(); var loggedInUser = Session.GetLoggedInUser(); try { using (var repository = RepositoryFactory.GetInstance(Session)) { var userPurchases = FindPurchasesForUser(repository).ToArray(); var userHistoricalPurchases = repository.FindHistoricalUserPurchases(Session.GetLoggedInUser().ObjectId).ToArray(); var worldId = new WorldContentTypeRetriver(HttpContext, repository).GetWorldContentTypeId(); string paymentUrl; checkoutViewModel = GetCheckoutViewModel(userPurchases, repository); checkoutViewModel.PurchaseFor = model.PurchaseFor; SetBundleClips(userPurchases, checkoutViewModel, repository); var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository); var sessionState = new SessionState(); var indexUrl = HttpContext.Request.Url.ToString().ToLower().Replace("completecheckout", "index") + string.Format("/?purchaseFor={0}", model.PurchaseFor); var expressCheckoutManager = new ExpressCheckoutManager(indexUrl); var logic = new CheckoutLogic(repository, currencyRetriver, sessionState, expressCheckoutManager); logic.ExecuteCompleteCheckout(loggedInUser, checkoutViewModel, worldId, userHistoricalPurchases, out paymentUrl); if (!string.IsNullOrEmpty(paymentUrl)) { return Redirect(paymentUrl); } } } catch { checkoutViewModel.ErrorMessage = Strings.GetLocalizedString(Strings.ShoppingCartPaymentFailure); } return View("Index", checkoutViewModel); }
public ActionResult Order() { checkoutViewModel = new CheckoutViewModel(); checkoutViewModel.ShoppingCart = (List <ProductLine>)Session["shoppingCart"]; return(View(checkoutViewModel)); }
private void SetCoupons(Coupon[] userCoupons, Purchase[] userPurchases, CurrencyDto currencyDto, IMyMentorRepository repository, CheckoutViewModel model) { var coupnIdToContentId = userCoupons.ToDictionary(x => x.ObjectId, x => x.Bundle != null ? x.Bundle.ObjectId : x.Clip.ObjectId); var unUsedCouponids = coupnIdToContentId .Where(x => !userPurchases.Any(p => p.BundleKey != null ? p.BundleKey.ObjectId == x.Value : p.ClipKey.ObjectId == x.Value)) .Select(x => x.Key); var unUsedCoupons = userCoupons.Where(x => unUsedCouponids.Contains(x.ObjectId)).Union(userCoupons.Where(x => x.State == CouponStates.UnUsed.ToString())); var couponNameTemplate = MyMentorResources.checkoutCouponTitleTemplate; foreach (var coupon in unUsedCoupons) { var lessonOrBundle = coupon.Bundle != null ? MyMentorResources.checkoutBundle : MyMentorResources.checkoutLesson; var itemName = coupon.Bundle != null ? coupon.Bundle.GetLocalizedField("bundleName") : coupon.Clip.GetLocalizedField("name"); var originalPrice = CurrencyConverter.ConvertFromNis(coupon.OriginalPriceNIS, currencyDto, repository).ToCurrency(currencyDto); var yourPrice = CurrencyConverter.ConvertFromNis(coupon.SiteCouponFeeNIS + coupon.TeacherCouponFeeNIS, currencyDto, repository).ToCurrency(currencyDto); var expiration = coupon.IssueDate.AddDays(10).ToString("dd/MM/yyyy"); model.CouponsForUser.Add(coupon.ObjectId, string.Format(couponNameTemplate, lessonOrBundle, itemName, originalPrice, yourPrice, expiration)); } }
public async Task <IActionResult> CheckOut(CheckoutViewModel model) { ISession session = HttpContext.Session; Customer customer = await userManager.GetUserAsync(User); Tube tubeTemp; int adressId = 0; //update shipping, billing address in customer try { adressId = await UpdateCustomerAndAddresses(model); } catch (Exception ex) { logger.LogInformation(ex.Message); logger.LogInformation($"Failed updating customer and adresses"); } if (adressId == 0) { logger.LogInformation($"Failed updating customer and adresses"); return(RedirectToAction(nameof(ReturnCart))); } //new invoice Invoice invoice = new Invoice() { OrderDate = DateTime.Now, CustomerId = customer.Id, ShippingAddressId = adressId, }; //get coupon string couponName = session.GetString("Coupon"); Coupon coupon = await coupons.FindAsync(x => x.CouponName.Equals(couponName)) ?? new Coupon(); if (coupon.CouponId != 0) { invoice.CouponId = coupon.CouponId; } //get shoppingcart items ShoppingCart shoppingCart = new ShoppingCart(); shoppingCart.ShoppingCartId = session.GetString("ShoppingCartId"); List <ShoppingCartItem> sessionList = JsonConvert.DeserializeObject <List <ShoppingCartItem> >( session.GetString("ShoppingCartItems")); if (sessionList.Count() == 0) { logger.LogInformation($"List in cart is empty???"); return(RedirectToAction(nameof(ReturnCart))); } //get cartitems => to invoiceinfo in new invoice try { foreach (var item in sessionList) { tubeTemp = await tubes.GetAsync(item.TubeId); invoice.InvoicesInfo.Add(new InvoiceInfo() { TubeId = item.TubeId, Price = tubeTemp.Price, Quantity = item.Quantity, Discount = tubeTemp.Discount }); } } catch (Exception ex) { logger.LogInformation($"Adding tubes to order failed"); logger.LogInformation(ex.Message); modalNotification.AddNotificationSweet("Fail", NotificationType.error, "Please try later!"); } //total cost for invoice foreach (var item in invoice.InvoicesInfo) { invoice.Total += item.Quantity * item.Price * (1 - item.Discount); } invoice.Total *= (1 - coupon.CouponValue); //saving invoice try { var invoiceResult = await invoices.AddAsync(invoice); } catch (Exception ex) { logger.LogInformation($"Inovice saving failed"); logger.LogInformation(ex.Message); modalNotification.AddNotificationSweet("Fail", NotificationType.error, "Please try later!"); } //decrease number of tubes in stock try { foreach (var item in invoice.InvoicesInfo) { tubeTemp = await tubes.GetAsync(item.TubeId); tubeTemp.Quantity -= item.Quantity; var tubeResult = await tubes.UpdateAsync(tubeTemp); } } catch (Exception ex) { logger.LogInformation($"Tube minus quantity failed"); logger.LogInformation(ex.Message); modalNotification.AddNotificationSweet("Fail", NotificationType.error, "Please try later!"); } //clear shoppingcart HttpContext.Session.Remove("ShoppingCartId"); HttpContext.Session.Remove("ShoppingCartItems"); modalNotification.AddNotificationSweet("Invoice", NotificationType.success, "Invoice created. Now you can pay it"); return(RedirectToAction(nameof(InvoiceController.Index), "Invoice")); }
public async Task <ActionResult> Purchase(CheckoutViewModel viewModel, IPaymentMethod 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.Payments = paymentOption; if (User.Identity.IsAuthenticated) { _checkoutService.CheckoutAddressHandling.UpdateAuthenticatedUserAddresses(viewModel); var validation = _checkoutService.AuthenticatedPurchaseValidation; if (!validation.ValidateModel(ModelState, viewModel) || !validation.ValidateOrderOperation(ModelState, _cartService.ValidateCart(CartWithValidationIssues.Cart)) || !validation.ValidateOrderOperation(ModelState, _cartService.RequestInventory(CartWithValidationIssues.Cart))) { return(View(viewModel)); } } else { _checkoutService.CheckoutAddressHandling.UpdateAnonymousUserAddresses(viewModel); var validation = _checkoutService.AnonymousPurchaseValidation; if (!validation.ValidateModel(ModelState, viewModel) || !validation.ValidateOrderOperation(ModelState, _cartService.ValidateCart(CartWithValidationIssues.Cart)) || !validation.ValidateOrderOperation(ModelState, _cartService.RequestInventory(CartWithValidationIssues.Cart))) { return(View(viewModel)); } } if (!paymentOption.ValidateData()) { return(View(viewModel)); } _checkoutService.UpdateShippingAddresses(CartWithValidationIssues.Cart, viewModel); _checkoutService.CreateAndAddPaymentToCart(CartWithValidationIssues.Cart, viewModel); var purchaseOrder = _checkoutService.PlaceOrder(CartWithValidationIssues.Cart, ModelState, viewModel); if (purchaseOrder == null) { return(View(viewModel)); } if (Request.IsAuthenticated) { var contact = _customerContext.GetCurrentContact().Contact; var organization = contact.ContactOrganization; if (organization != null) { purchaseOrder.Properties[Constant.Customer.CustomerFullName] = contact.FullName; purchaseOrder.Properties[Constant.Customer.CustomerEmailAddress] = contact.Email; purchaseOrder.Properties[Constant.Customer.CurrentCustomerOrganization] = organization.Name; _orderRepository.Save(purchaseOrder); } } var confirmationSentSuccessfully = await _checkoutService.SendConfirmation(viewModel, purchaseOrder); //await _checkoutService.CreateOrUpdateBoughtProductsProfileStore(CartWithValidationIssues.Cart); //await _checkoutService.CreateBoughtProductsSegments(CartWithValidationIssues.Cart); await _recommendationService.TrackOrder(HttpContext, purchaseOrder); return(Redirect(_checkoutService.BuildRedirectionUrl(viewModel, purchaseOrder, confirmationSentSuccessfully))); }
public CheckoutView(CheckoutViewModel viewModel) { InitializeComponent(); this.viewModel = viewModel; DataContext = this.viewModel; }
public void AddSubscription(CheckoutViewModel checkoutViewModel) { _checkoutService.UpdatePaymentPlan(CartWithValidationIssues.Cart, checkoutViewModel); }
private static void CreatePaymentRecords( CheckoutViewModel checkoutViewModel, string worldId, Purchase[] userHistoricalPurchases, CheckoutManager checkoutManager, CompleteCheckoutLetterDto completeCheckoutLetterDto, List<CheckoutItemLetterDto> checkoutItemLetterDtoArray, List<CheckoutStatementBase> completeCheckoutStatementsArray) { checkoutManager.StartPaymentEvent(completeCheckoutLetterDto); checkoutManager.SetPayerCreditForPayment(completeCheckoutStatementsArray, completeCheckoutLetterDto, worldId); checkoutManager.SetPayerDebitForContent(completeCheckoutStatementsArray, completeCheckoutLetterDto); checkoutManager.SetSiteAndVatAccountRecords(completeCheckoutStatementsArray, completeCheckoutLetterDto); foreach (var purchaseViewModel in checkoutViewModel.PurchasesForUser) { var checkoutItemLetterDto = new CheckoutItemLetterDto(); checkoutItemLetterDto.IsLesson = purchaseViewModel.IsLesson; checkoutManager.SetTeacherCommission(checkoutItemLetterDto, purchaseViewModel); checkoutManager.SetTeacherData(checkoutItemLetterDto, purchaseViewModel); checkoutManager.SetAgentCommission(checkoutItemLetterDto, purchaseViewModel); checkoutManager.SetTeacherSiteAgentCommissionsCalculations(checkoutItemLetterDto, purchaseViewModel); checkoutManager.SetMaam(checkoutItemLetterDto); checkoutManager.SetConvertsionCommissions(checkoutItemLetterDto); // כתיבת תנועות כספיות checkoutManager.TeacherSaleCommissionCredit(completeCheckoutStatementsArray, checkoutItemLetterDto,purchaseViewModel); checkoutManager.TeacherSaleCommissionDebit(completeCheckoutStatementsArray, checkoutItemLetterDto,purchaseViewModel); checkoutManager.TeacherConversionDebit(completeCheckoutStatementsArray, checkoutItemLetterDto, purchaseViewModel); checkoutManager.SiteConversionCredit(completeCheckoutStatementsArray, checkoutItemLetterDto, purchaseViewModel); checkoutManager.AgentToAgentConversionCredit(completeCheckoutStatementsArray, checkoutItemLetterDto,purchaseViewModel); checkoutManager.AgentToSiteConversionCredit(completeCheckoutStatementsArray, checkoutItemLetterDto,purchaseViewModel); checkoutManager.AgentConversionDebit(completeCheckoutStatementsArray, checkoutItemLetterDto, purchaseViewModel); checkoutManager.SiteAgentConversionCredit(completeCheckoutStatementsArray, checkoutItemLetterDto,purchaseViewModel); // כתיבת רשומות checkoutManager.UpdateCoupon(completeCheckoutStatementsArray, purchaseViewModel); checkoutManager.UpdatePurchase(completeCheckoutStatementsArray, completeCheckoutLetterDto, purchaseViewModel); // טיפול בחבילה checkoutManager.HandlePackage(completeCheckoutStatementsArray, purchaseViewModel, checkoutViewModel, userHistoricalPurchases, worldId, completeCheckoutLetterDto.StudentKeyLetter,completeCheckoutLetterDto.StudentCurrencyLetter); checkoutItemLetterDtoArray.Add(checkoutItemLetterDto); } // add basketitemnames checkoutManager.GetBasketItemNames(completeCheckoutStatementsArray, checkoutItemLetterDtoArray, checkoutViewModel); }
public async Task <ActionResult> Buy(CheckoutViewModel model) { Offer offer = await offerService.GetOfferAsync(model.OfferId, o => o.UserProfile, o => o.UserProfile.User, o => o.Order, o => o.Order.StatusLogs, o => o.Order.CurrentStatus); if (offer != null && offer.Order == null && offer.State == OfferState.active && offer.UserProfileId != User.Identity.GetUserId <int>()) { var currentUserId = User.Identity.GetUserId <int>(); var user = userProfileService.GetUserProfile(u => u.Id == currentUserId, i => i.User); var mainCup = userProfileService.GetUserProfileByName("playerup"); if (user != null && mainCup != null && user.Balance >= model.OrderSum) { //var amount = Decimal.Parse(Request.Form["ik_am"]); offer.Order = new Order { BuyerId = currentUserId, SellerId = offer.UserProfileId, CreatedDate = DateTime.Now }; offer.State = OfferState.closed; if (mainCup != null) { var seller = offer.UserProfile; var buyer = user; if (offer.SellerPaysMiddleman) { offer.Order.Sum = offer.Price; offer.Order.AmmountSellerGet = offer.Price - offer.MiddlemanPrice.Value; if (buyer.Balance >= offer.Order.Sum) { transactionService.CreateTransaction(new Transaction { Amount = offer.Order.Sum, Order = offer.Order, Receiver = mainCup, Sender = buyer, CreatedDate = DateTime.Now }); buyer.Balance -= offer.Order.Sum; mainCup.Balance += offer.Order.Sum; } else { return(View("NotEnoughMoney")); } } else { offer.Order.Sum = offer.Price + offer.MiddlemanPrice.Value; offer.Order.AmmountSellerGet = offer.Price; if (buyer.Balance >= offer.Order.Sum) { transactionService.CreateTransaction(new Transaction { Amount = offer.Order.Sum, Order = offer.Order, Receiver = mainCup, Sender = buyer, CreatedDate = DateTime.Now }); buyer.Balance -= offer.Order.Sum; mainCup.Balance += offer.Order.Sum; } else { return(View("NotEnoughMoney")); } } offer.Order.StatusLogs.AddLast(new StatusLog() { OldStatus = orderStatusService.GetOrderStatusByValue(OrderStatuses.OrderCreating), NewStatus = orderStatusService.GetOrderStatusByValue(OrderStatuses.BuyerPaying), TimeStamp = DateTime.Now }); offer.Order.StatusLogs.AddLast(new StatusLog() { OldStatus = orderStatusService.GetOrderStatusByValue(OrderStatuses.BuyerPaying), NewStatus = orderStatusService.GetOrderStatusByValue(OrderStatuses.MiddlemanFinding), TimeStamp = DateTime.Now }); offer.Order.CurrentStatus = orderStatusService.GetOrderStatusByValue(OrderStatuses.MiddlemanFinding); offer.Order.BuyerChecked = false; offer.Order.SellerChecked = false; if (offer.Order.JobId != null) { BackgroundJob.Delete(offer.Order.JobId); offer.Order.JobId = null; } if (offer.JobId != null) { BackgroundJob.Delete(offer.JobId); offer.JobId = null; } orderService.SaveOrder(); MarketplaceMVCHangfire.SetSendEmailChangeStatus(offer.Order.Id, seller.User.Email, offer.Order.CurrentStatus.DuringName, Url.Action("SellDetails", "Order", new { id = offer.Order.Id }, protocol: Request.Url.Scheme)); MarketplaceMVCHangfire.SetSendEmailChangeStatus(offer.Order.Id, buyer.User.Email, offer.Order.CurrentStatus.DuringName, Url.Action("BuyDetails", "Order", new { id = offer.Order.Id }, protocol: Request.Url.Scheme)); offer.Order.JobId = MarketplaceMVCHangfire.SetOrderCloseJob(offer.Order.Id, TimeSpan.FromDays(1)); //_orderService.UpdateOrder(order); orderService.SaveOrder(); TempData["orderBuyStatus"] = "Оплата прошла успешно"; return(RedirectToAction("BuyDetails", "Order", new { id = offer.Order.Id })); } } } return(HttpNotFound()); }
private string GetPaymentUrl(CheckoutManager checkoutManager, CheckoutViewModel checkoutViewModel) { var checkoutItems = new List<CheckoutItem>(); foreach (var purchaseViewModel in checkoutViewModel.PurchasesForUser) { string name = Language.CurrentLanguageCode == Cultures.HE_IL ? purchaseViewModel.ContentName_he_il : purchaseViewModel.ContentName_en_us; double price = purchaseViewModel.HasCoupon ? purchaseViewModel.PriceWithCoupon: purchaseViewModel.RegularPrice; name = string.Format("{0}{1}", purchaseViewModel.IsLesson ? MyMentorResources.checkoutLesson : MyMentorResources.checkoutBundle, name); checkoutItems.Add(new CheckoutItem { Name = name, Price = price }); } if (checkoutViewModel.BalanceForCalc > 0) { checkoutItems.Add(new CheckoutItem { Name = MyMentorResources.checkoutBalance, Price = (checkoutViewModel.BalanceForCalc * -1) }); } if (checkoutViewModel.BalanceForCalc < 0) { checkoutItems.Add(new CheckoutItem { Name = MyMentorResources.checkoutBalanceCover, Price = (checkoutViewModel.BalanceForCalc * -1) }); } var response = _payPalExpressCheckoutManager.ValidatePayment( checkoutItems, checkoutViewModel.UserCurrency.PaypalCode, checkoutViewModel.PaymentTransactionForCalc); return response.ValidationUrl; }
public RedirectToRouteResult CompleteCart(CheckoutViewModel model) { DateTime orderTime = DateTime.Now; Order order = null; int addressId = -1; Order verifyInsertion = null; string name = this.HttpContext.User.Identity.Name; var currentUser = this.userRepo.GetAll().Where(u => u.UserName == name).First(); //Check if user entered new address or used old one if (model.Address == null || model.Address == string.Empty) { if (model.NewAddress != null && model.NewAddress != string.Empty) { Address addressToAdd = new Address() { Address1 = model.NewAddress }; //Add new address to address repo addressRepo.Insert(addressToAdd); addressRepo.Save(); currentUser.Addresses.Add(addressToAdd); userRepo.Save(); addressId = addressToAdd.AddressId; } } else { try { int.TryParse(model.Address, out addressId); } catch (Exception) { throw; } } if (addressId >= 1) { order = new Order() { ClientId = currentUser.Id, OrderTime = orderTime, DeliveryAddressId = addressId, OrderDeliverd = false, OrderPrice = ((Cart)Session["Cart"]).TotalPrice(), OrderPrepared = false, IsActive = true, ExtraSpecifications = model.ExtraSpecifications, }; //We add the order to the database. orderRepo.Insert(order); orderRepo.Save(); //We add the order reference to each of the dishes. foreach (CartLine line in ((Cart)Session["Cart"]).Lines) { //We add the order reference to the dishes in the //cart session to ensure the many to many relationship. var currentDish = dishRepo.GetById(line.Dish.DishId); currentDish.Orders.Add(order); orderRepo.Save(); } orderRepo.Save(); dishRepo.Save(); verifyInsertion = orderRepo.GetById(order.OrderId); Debug.WriteLine($"{order.Dishes.Count()}"); } else { return(RedirectToAction("CompleteCart")); } //check if order got registered. if (verifyInsertion != null) { return(RedirectToAction("Completed", new { orderId = order.OrderId })); } else { return(RedirectToAction("CompleteCart")); } }
public override bool ValidateModel(ModelStateDictionary modelState, CheckoutViewModel viewModel) { return (ValidateBillingAddress(modelState, viewModel) && ValidateShippingMethods(modelState, viewModel)); }
public void ExecutePayment(string payerId, string paymentId, CheckoutViewModel checkoutViewModel, ParseUser loggedInUser) { var completeCheckoutStatementsArray = _state.Get<List<CheckoutStatementBase>>(STATE_KEY); var eventId = completeCheckoutStatementsArray.OfType<TransactionStatement>().First().Event; var executePayment = _payPalExpressCheckoutManager.ExecutePayment(payerId, paymentId); if (executePayment == null) { Mailer.SendCheckoutError(loggedInUser, eventId,"payment failed, database not upadated"); return; } try { var accountStatementsBuilder = new AccountStatementBuilder(_repository, _currencyRetriver); var checkoutManager = new CheckoutManager(_repository, loggedInUser, checkoutViewModel); checkoutManager.EventId = eventId; checkoutManager.SavePaymentRecords(completeCheckoutStatementsArray, accountStatementsBuilder, checkoutViewModel, executePayment.ConvertToJson()); InitPuchaseView(loggedInUser, checkoutViewModel); } catch (Exception ex) { Mailer.SendCheckoutError(loggedInUser, eventId, "Payment succeeded, Data Base update failed"); BL.DomainServices.Log.LoggerFactory.GetLogger().LogError(ex); throw; } }
/// <summary> /// 初始化 /// </summary> public void Init(object obj) { CheckoutViewModel viewModel = this.DataContext as CheckoutViewModel; viewModel.Init(obj); }
private static void InitPuchaseView(ParseUser loggedInUser, CheckoutViewModel checkoutViewModel) { var adminData = loggedInUser.GetPointerObject<UserAdminData>("adminData"); adminData.PurchaseCount = 0; Task.Run(() => adminData.SaveAsync()); checkoutViewModel.PaymentSuccess = true; checkoutViewModel.PurchasesForUser = new CheckoutPurchaseViewModel[0]; }
private void WrapPanel_MouseDown(object sender, MouseButtonEventArgs e) { CheckoutViewModel viewModel = this.DataContext as CheckoutViewModel; viewModel.FinishPaidPrice(); }
private void SetLetters(ParseUser loggedInUser, CheckoutViewModel checkoutViewModel, List<CheckoutStatementBase> completeCheckoutStatementsArray, List<CheckoutItemLetterDto> checkoutItemLetterDtos, CompleteCheckoutLetterDto completeCheckoutLetterDto, ParseUser inUser) { var checkoutManager = new CheckoutManager(_repository, loggedInUser, checkoutViewModel); //כתיבת רשומת מכתב לפריט למורה checkoutManager.GetItemLetterForTeacher(completeCheckoutStatementsArray,checkoutItemLetterDtos); //כתיבת רשומת מכתב לפריט לסוכן checkoutManager.GetItemLetterForAgent(completeCheckoutStatementsArray,checkoutItemLetterDtos); //כתיבת רשומת מכתב לפריט למנהל checkoutManager.GetItemLetterForAdmin(completeCheckoutStatementsArray,checkoutItemLetterDtos,completeCheckoutLetterDto); // כתיבת רשומת מכתב סיכום לרוכש checkoutManager.GetSummaryLetterForStudent(completeCheckoutStatementsArray,completeCheckoutLetterDto,checkoutViewModel); //כתיבת רשומת מכתב סיכום למנהל checkoutManager.GetSummaryLetterForAdmin(completeCheckoutStatementsArray,completeCheckoutLetterDto,checkoutViewModel); if (checkoutViewModel.PurchaseFor != loggedInUser.Username) { //מכתב לתלמיד checkoutManager.GetStudentLetter(completeCheckoutStatementsArray, completeCheckoutLetterDto, checkoutViewModel); } }
public virtual IPurchaseOrder PlaceOrder(ICart cart, ModelStateDictionary modelState, CheckoutViewModel checkoutViewModel) { try { if (cart.Properties[Constant.Quote.ParentOrderGroupId] != null) { var orderLink = int.Parse(cart.Properties[Constant.Quote.ParentOrderGroupId].ToString()); if (orderLink != 0) { var quoteOrder = _orderRepository.Load <IPurchaseOrder>(orderLink); if (quoteOrder.Properties[Constant.Quote.QuoteStatus] != null) { checkoutViewModel.QuoteStatus = quoteOrder.Properties[Constant.Quote.QuoteStatus].ToString(); if (quoteOrder.Properties[Constant.Quote.QuoteStatus].ToString().Equals(Constant.Quote.RequestQuotationFinished)) { _ = DateTime.TryParse(quoteOrder.Properties[Constant.Quote.QuoteExpireDate].ToString(), out var quoteExpireDate); if (DateTime.Compare(DateTime.Now, quoteExpireDate) > 0) { _orderRepository.Delete(cart.OrderLink); _orderRepository.Delete(quoteOrder.OrderLink); throw new InvalidOperationException("Quote Expired"); } } } } } var processPayments = cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator); var unsuccessPayments = processPayments.Where(x => !x.IsSuccessful); if (unsuccessPayments != null && unsuccessPayments.Any()) { throw new InvalidOperationException(string.Join("\n", unsuccessPayments.Select(x => x.Message))); } var processedPayments = cart.GetFirstForm().Payments.Where(x => x.Status.Equals(PaymentStatus.Processed.ToString())); if (!processedPayments.Any()) { // Return null in case there is no payment was processed. return(null); } var totalProcessedAmount = processedPayments.Sum(x => x.Amount); if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount) { throw new InvalidOperationException("Wrong amount"); } var orderReference = cart.Properties["IsUsePaymentPlan"] != null && cart.Properties["IsUsePaymentPlan"].Equals(true) ? SaveAsPaymentPlan(cart) : _orderRepository.SaveAsPurchaseOrder(cart); var purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId); _orderRepository.Delete(cart.OrderLink); cart.AdjustInventoryOrRemoveLineItems((item, validationIssue) => { }); //Loyalty Program: Add Points and Number of orders _loyaltyService.AddNumberOfOrders(); return(purchaseOrder); } catch (PaymentException ex) { modelState.AddModelError("", _localizationService.GetString("/Checkout/Payment/Errors/ProcessingPaymentFailure") + ex.Message); } catch (Exception ex) { modelState.AddModelError("", ex.Message); } return(null); }
private bool ValidatePaymentErrorOrder(CheckoutViewModel model) { model.Violations.AddRange(ValidateAddress(model.CurrentOrder.BillingAddress, "Billing")); model.Violations.AddRange(ValidatePayment(model)); return(model.Violations.Count <= 0); }
public async Task <IActionResult> Index(CheckoutViewModel model) { await GetCurrentCart(model); if (ModelState.IsValid) { if (!string.IsNullOrEmpty(model.SavedAddressId) || (!string.IsNullOrEmpty(model.ShippingAddressLine1) && !string.IsNullOrEmpty(model.ShippingLocale) && !string.IsNullOrEmpty(model.ShippingRegion) && !string.IsNullOrEmpty(model.ShippingPostalCode) && !string.IsNullOrEmpty(model.ShippingCountry))) { Order newOrder = new Order { TrackingNumber = Guid.NewGuid().ToString(), OrderDate = DateTime.Now, OrderItems = model.Cart.CartItems.Select(x => new OrderItem { ProductID = x.Product.ID, ProductName = x.Product.Name, ProductPrice = (x.Product.Price ?? 0), Quantity = x.Quantity }).ToArray(), AddressLine1 = model.ShippingAddressLine1, AddressLine2 = model.ShippingAddressLine2, Country = model.ShippingCountry, Email = model.ContactEmail, PhoneNumber = model.ContactPhoneNumber, Locale = model.ShippingLocale, PostalCode = model.ShippingPostalCode, Region = model.ShippingRegion }; Braintree.Customer customer = null; Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Is(model.ContactEmail); var searchResult = await _brainTreeGateway.Customer.SearchAsync(search); if (searchResult.Ids.Count == 0) { //Create a new Braintree Customer Braintree.Result <Customer> creationResult = await _brainTreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest { Email = model.ContactEmail, Phone = model.ContactPhoneNumber }); customer = creationResult.Target; } else { customer = searchResult.FirstItem; } CreditCard creditCard = null; if (model.SaveBillingCard) { var newCardRequest = new CreditCardRequest { CardholderName = model.BillingNameOnCard, CustomerId = customer.Id, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString(), Number = model.BillingCardNumber, CVV = model.BillingCardVerificationValue }; var newCardResult = await _brainTreeGateway.CreditCard.CreateAsync(newCardRequest); if (newCardResult.IsSuccess()) { creditCard = newCardResult.Target; } } Address savedAddress = null; if (model.SaveShippingAddress) { var newAddressRequest = new AddressRequest { StreetAddress = model.ShippingAddressLine1, ExtendedAddress = model.ShippingAddressLine2, CountryName = model.ShippingCountry, PostalCode = model.ShippingPostalCode, Locality = model.ShippingLocale, Region = model.ShippingRegion }; var newAddressResult = await _brainTreeGateway.Address.CreateAsync(customer.Id, newAddressRequest); if (newAddressResult.IsSuccess()) { savedAddress = newAddressResult.Target; } } else { } TransactionRequest transaction = new TransactionRequest { Amount = model.Cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)), CustomerId = customer.Id, LineItems = model.Cart.CartItems.Select(x => new TransactionLineItemRequest { Name = x.Product.Name, Description = x.Product.Description, ProductCode = x.Product.ID.ToString(), Quantity = x.Quantity, LineItemKind = TransactionLineItemKind.DEBIT, UnitAmount = x.Product.Price * x.Quantity, TotalAmount = x.Product.Price * x.Quantity }).ToArray() }; if (creditCard == null) { transaction.CreditCard = new TransactionCreditCardRequest { Number = model.BillingCardNumber, CardholderName = model.BillingNameOnCard, CVV = model.BillingCardVerificationValue, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString() }; } else { transaction.PaymentMethodToken = creditCard.Token; } if (savedAddress != null) { transaction.ShippingAddressId = savedAddress.Id; } var transactionResult = await _brainTreeGateway.Transaction.SaleAsync(transaction); if (transactionResult.IsSuccess()) { _thisSiteDbContext.Orders.Add(newOrder); _thisSiteDbContext.CartItems.RemoveRange(model.Cart.CartItems); _thisSiteDbContext.Carts.Remove(model.Cart); await _thisSiteDbContext.SaveChangesAsync(); //Try to checkout //Confirmation Email //TODO: var serOrder serializes user order. I want to parse this JSON and send to SendGrid template for custom receipt /*var serOrder = JsonConvert.SerializeObject(newOrder, Formatting.Indented, * new JsonSerializerSettings * { * ReferenceLoopHandling = ReferenceLoopHandling.Ignore * }); */ var user = model.ContactEmail; var orderCompleteSubject = "Order #" + newOrder.TrackingNumber + " Completed"; var htmlContent = "Thanks for placing your order with us! Please reference your order number above."; var plainTextContent = "Thanks for placing your order with us! Please reference your order number above."; var emailResult = await _emailService.SendEmailAsync(user, orderCompleteSubject, htmlContent, plainTextContent); //await _emailService.SendEmailAsync(user, orderCompleteSubject, htmlContent, plainTextContent); if (!emailResult.Success) { throw new Exception(string.Join(',', emailResult.Errors.Select(x => x.Message))); } Response.Cookies.Delete("cartId"); return(RedirectToAction("Index", "Receipt", new { id = newOrder.TrackingNumber })); } for (int i = 0; i < transactionResult.Errors.Count; i++) { ModelState.AddModelError("BillingCardNumber" + i, transactionResult.Errors.All()[i].Message); } } } return(View(model)); }
public ActionResult CheckoutError(string errorMessage) { CheckoutViewModel checkoutViewModel = new CheckoutViewModel(); checkoutViewModel.ErrorMessage = errorMessage; return View("CheckoutError", checkoutViewModel); }
public async Task <IActionResult> Checkout(CheckoutViewModel viewModel) { if (ModelState.IsValid) { //Add income to the database ShopIncome income = new ShopIncome(); income.MoneyIn = viewModel.FullPrice; income.Date = DateTime.Now; _incomeRepository.AddIncome(income); //Add all items to the database and update stock List <ShoppingCartItemModel> Items = _shoppingCartItemRepository.GetItemsByCartId(viewModel.CartId); for (int i = 0; i < Items.Count; i++) { //Add ordered item Items[i].Product = _productRepository.GetProduct(Items[i].ItemId); UserOrderItemModel user_item = new UserOrderItemModel(); user_item.Ammount = Items[i].Ammount; user_item.ProductName = Items[i].Product.Name; user_item.ProductOrderId = Items[i].Product.Id; user_item.OrderId = Items[i].ShoppingCartId; _userOrderItemRepository.AddOrderItem(user_item); //Update stock ProductModel product = _productRepository.GetProduct(Items[i].ItemId); product.Quantity -= user_item.Ammount; _productRepository.Update(product); } //Get user var user = await _userManager.GetUserAsync(HttpContext.User); //Create order object UserOrderModel user_order = new UserOrderModel(); user_order.DateOfOrder = DateTime.Now; user_order.OrderId = viewModel.CartId; user_order.AdditionalInformation = viewModel.AdditionalInformation; user_order.FullPrice = viewModel.FullPrice; //Add user information user_order.UserId = user.Id; user_order.UserCity = user.City; user_order.UserEmail = user.Email; user_order.UserName = $"{user.FirstName} {user.LastName}"; user_order.UserPhoneNumber = user.PhoneNumber; user_order.UserPostCode = user.PostCode; user_order.UserStreetAdress = $"{user.StreetName} {user.StreetNumber}"; user_order.UserCity = user.City; _userOrderRepository.AddOrder(user_order); //Update statistics _statisticsRepository.UpdateUserOrderMean(viewModel.FullPrice); _statisticsRepository.UpdateTotalSalesMoney(viewModel.FullPrice); _statisticsRepository.UpdateTotalNumberOfOrders(); //Update ordering user iformations user.OrdersAmmount++; user.MoneySpent += viewModel.FullAmmount; await _userManager.UpdateAsync(user); //Clear cart return(RedirectToAction("ClearCartPayment", "Cart")); } return(View(viewModel)); }
private CheckoutViewModel GetCheckoutViewModel(Purchase[] userPurchases, IMyMentorRepository repository) { var loggedInUser = Session.GetLoggedInUser(); var model = new CheckoutViewModel(); CurrencyDto currencyDto = Task.Run(() => loggedInUser.GetPointerObject<BL.Models.Currency>("currency")).Result.ConvertToCurrencyDto(); model.UserCurrency = currencyDto; var worldRetriver = new WorldContentTypeRetriver(HttpContext, repository); var world = worldRetriver.GetWorldContentTypeId(); string issuedFor = loggedInUser.ObjectId; var userCoupons = repository.FindCoupon(issuedFor, world).ToArray(); UpdateDuplicateRecords(ref userCoupons, ref userPurchases); SetPurchases(model, userPurchases, userCoupons, repository, currencyDto); SetCoupons(userCoupons, userPurchases, currencyDto, repository, model); SetTotals(model, repository, currencyDto); model.PurchaseFor = loggedInUser.Username; return model; }
private ViewResult View(CheckoutViewModel checkoutViewModel) { return(View(checkoutViewModel.ViewName, CreateCheckoutViewModel(checkoutViewModel.CurrentPage, checkoutViewModel.Payment))); }
private void SetTotals(CheckoutViewModel model, IMyMentorRepository repository, CurrencyDto currencyDto) { var loggedInUser = Session.GetLoggedInUser(); var userAdminData = Task.Run(() => loggedInUser.GetPointerObject<UserAdminData>("adminData")).Result; var currentBalance = userAdminData.Balance; var minimumTransaction = repository.FindGlobalTeacherCommission().MinimumTransaction; var basketPrice = model.PurchasesForUser.Sum(x => x.RegularPrice); var basketPriceWithCoupon = model.PurchasesForUser.Sum(x => { if (x.HasCoupon) return x.PriceWithCoupon; return x.RegularPrice; }); var paymentTransactionWithCoupon = currentBalance < 0 ? basketPriceWithCoupon - currentBalance : basketPriceWithCoupon >= currentBalance ? basketPriceWithCoupon - currentBalance : 0; var paymentTransactionNis = CurrencyConverter.ConvertToNis(paymentTransactionWithCoupon,currencyDto,repository); paymentTransactionWithCoupon = paymentTransactionNis < minimumTransaction ? 0 : paymentTransactionWithCoupon; var reduceFromBalance = basketPriceWithCoupon == 0 || paymentTransactionWithCoupon > basketPriceWithCoupon || currentBalance <= 0 ? 0 : basketPriceWithCoupon - paymentTransactionWithCoupon; model.BasketPrice = basketPrice.ToCurrency(currencyDto); model.BasketPriceWithCouopn = basketPriceWithCoupon.Equals(basketPrice) ? string.Empty : basketPriceWithCoupon.ToCurrency(currencyDto); model.BasketPriceWithCouopnForCalc = basketPriceWithCoupon; model.Balance = currentBalance.ToCurrency(currencyDto); model.BalanceForCalc = currentBalance; model.ReduceFromBalance = reduceFromBalance.ToCurrency(currencyDto); model.PaymentTransaction = paymentTransactionWithCoupon.ToCurrency(currencyDto); model.PaymentTransactionForCalc = paymentTransactionWithCoupon; model.RequiresPayment = paymentTransactionWithCoupon > 0; }
public IActionResult Checkout(CheckoutViewModel model) { return(View(model)); }
private void SetPurchases(CheckoutViewModel model, Purchase[] userPurchases, Coupon[] userCoupons, IMyMentorRepository repository, CurrencyDto currencyDto) { model.PurchasesForUser = userPurchases.Select(purchase => new CheckoutPurchaseViewModel { Id = purchase.ObjectId, ContentTitlePart1 = GetTitle1(purchase), ContentTitlePart2 = GetTitle2(purchase), ContentName_he_il = GetName_he_il(purchase), ContentName_en_us = GetName_en_us(purchase), HasUnUsedCouopn = CheckUnUsedCouponsForPurchase(purchase, userCoupons), IncludingSupport = purchase.IncludingSupport, RegularPrice = GetPrice(purchase, repository, currencyDto), RegularPriceString = GetPrice(purchase, repository, currencyDto).ToCurrency(model.UserCurrency), PriceWithCoupon = GetPriceWithCoupon(purchase, userCoupons, repository, currencyDto), PriceWithCouponString = GetPriceWithCoupon(purchase, userCoupons, repository, currencyDto).ToCurrency(model.UserCurrency), IsLesson = purchase.ClipKey != null, ContentId = purchase.ClipKey != null ? purchase.ClipKey.ObjectId : purchase.BundleKey.ObjectId, CurrencyId = purchase.UserCurrency.ObjectId, Coupon = CheckCouponForPurchase(purchase, userCoupons), TeacherInfo = new TeacherInfo { Teacher = GetTeacher(purchase), Agent = GetAgent(purchase).ConvertToParseUserDto(), TeacherAdminData = GetTeacherAdminData(purchase), AgentAdminData = GetAgetAdminData(purchase) }, }).ToArray(); }
public async Task <IActionResult> Index(CheckoutViewModel model, string braintreeNonce) { ViewData["clientToken"] = await _braintreeGateway.ClientToken.GenerateAsync(); if (string.IsNullOrEmpty(braintreeNonce)) { this.ModelState.AddModelError("nonce", "We're unable to validate this credit card"); } if (this.ModelState.IsValid) { HatUser hatUser = null; if (User.Identity.IsAuthenticated) { hatUser = _userManager.FindByNameAsync(User.Identity.Name).Result; } Cart cart = CartService.GetCart(_context, Request, Response, hatUser); if (cart.CartItems.Count > 0) { var orderId = Guid.NewGuid().ToString().Substring(0, 8); Braintree.TransactionRequest transactionRequest = new Braintree.TransactionRequest(); transactionRequest.PaymentMethodNonce = braintreeNonce; transactionRequest.PurchaseOrderNumber = orderId; transactionRequest.Amount = cart.CartItems.Sum(x => x.Quantity * x.Product.Price); transactionRequest.ShippingAddress = new Braintree.AddressRequest { StreetAddress = model.ShippingStreet1, ExtendedAddress = model.ShippingStreet2, PostalCode = model.ShippingPostalCode, //CountryName = model.ShippingCountry, //This thing is picky about casing FirstName = model.ContactName.Split(' ').First(), LastName = model.ContactName.Contains(' ') ? string.Join(' ', model.ContactName.Split(' ').Skip(1)) : "", Locality = model.ShippingCity, Region = model.ShippingRegion }; transactionRequest.Customer = new Braintree.CustomerRequest { Email = hatUser != null ? hatUser.Email : model.ContactEmail, }; transactionRequest.LineItems = cart.CartItems.Select(x => new Braintree.TransactionLineItemRequest { Name = x.Product.Name, Description = x.Product.Description, ProductCode = x.ProductID.ToString(), Quantity = x.Quantity, UnitAmount = x.Product.Price, TotalAmount = x.Product.Price * x.Quantity, LineItemKind = Braintree.TransactionLineItemKind.DEBIT }).ToArray(); Braintree.Result <Braintree.Transaction> transactionResult = _braintreeGateway.Transaction.Sale(transactionRequest); if (transactionResult.IsSuccess()) { //TODO: Get a lot more info here, validate credit card + address, save it to a database Order order = new Order(); order.ID = orderId; order.OrderDate = DateTime.Now.ToString(); order.ContactEmail = model.ContactEmail; order.ContactName = model.ContactName; order.ContactPhoneNumber = model.ContactPhoneNumber; order.ShippingCity = model.ShippingCity; order.ShippingCountry = model.ShippingCountry; order.ShippingPostalCode = model.ShippingPostalCode; order.ShippingRegion = model.ShippingRegion; order.ShippingStreet1 = model.ShippingStreet1; order.ShippingStreet2 = model.ShippingStreet2; order.OrderItems = cart.CartItems.Select(ci => new OrderItem { ProductID = ci.ProductID, Color = ci.ProductColor != null ? ci.ProductColor.Color : null, Description = ci.Product.Description, Name = ci.Product.Name, Price = ci.Product.Price, Quantity = ci.Quantity, Size = ci.ProductSize != null ? ci.ProductSize.Size : null }).ToArray(); _context.CartItems.RemoveRange(cart.CartItems); _context.Carts.Remove(cart); Response.Cookies.Delete("HatShopCartInfo"); _context.Orders.Add(order); if (hatUser != null) { order.HatUser = hatUser; } _context.SaveChanges(); await _emailSender.SendEmailAsync(model.ContactEmail, "Receipt for order #" + order.ID, "Thanks for your order!"); return(RedirectToAction("index", "receipt", new { id = order.ID })); } } ModelState.AddModelError("cart", "There was a problem processing your cart"); } return(View(model)); }