public ActionResult ConfirmOrder(FormCollection form) { var storeId = 0; var customer = _workContext.CurrentCustomer; var cart = _workContext.CurrentCustomer.GetCartItems(); if (!cart.IsAny()) { return(RedirectToAction("Index", "Home")); } var processPaymentRequest = new ProcessPaymentRequest { StoreId = storeId, CustomerId = customer.Id, PaymentMethodSystemName = customer.GetAttribute("Customer", Contains.SelectedPaymentMethod, _genericAttributeService) }; var placeOrderExtraData = new Dictionary <string, string>(); _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData); return(RedirectToAction("Complete")); }
public CheckoutPlaceOrderModel PlaceOrder() { var model = new CheckoutPlaceOrderModel(); try { var processPaymentRequest = _session["OrderPaymentInfo"] as ProcessPaymentRequest; if (processPaymentRequest == null) { model.RedirectToCart = true; return(model); } //prevent 2 orders being placed within an X seconds time frame if (!_stripeCheckoutService.IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer)) { throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval")); } //place order processPaymentRequest.StoreId = _storeContext.CurrentStore.Id; processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id; processPaymentRequest.PaymentMethodSystemName = "Payments.Stripe"; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); if (placeOrderResult.Success) { _session["OrderPaymentInfo"] = null; var postProcessPaymentRequest = new PostProcessPaymentRequest { Order = placeOrderResult.PlacedOrder }; _paymentService.PostProcessPayment(postProcessPaymentRequest); if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone) { //redirection or POST has been done in PostProcessPayment model.IsRedirected = true; return(model); } else { model.CompletedId = placeOrderResult.PlacedOrder.Id; return(model); } } else { foreach (var error in placeOrderResult.Errors) { model.Warnings.Add(error); } } } catch (Exception exc) { _logger.Warning(exc.Message, exc); model.Warnings.Add(exc.Message); } return(model); }
private PlaceOrderResult PlaceOrder(Order newOrder, Customer customer) { int cardExpirationMonth = 0; int cardExpirationYear = 0; int.TryParse(newOrder.CardExpirationMonth, out cardExpirationMonth); int.TryParse(newOrder.CardExpirationYear, out cardExpirationYear); var processPaymentRequest = new ProcessPaymentRequest { StoreId = newOrder.StoreId, CustomerId = customer.Id, PaymentMethodSystemName = newOrder.PaymentMethodSystemName, CreditCardName = newOrder.CardName, CreditCardNumber = newOrder.CardNumber, CreditCardType = newOrder.CardType, CreditCardExpireMonth = cardExpirationMonth, CreditCardExpireYear = cardExpirationYear, CreditCardCvv2 = newOrder.CardCvv2, }; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); return placeOrderResult; }
/// <summary> /// Places an order /// </summary> /// <param name="processPaymentRequest">Process payment request</param> /// <returns>Place order result</returns> public HttpResponseMessage PlaceOrder(PlaceOrderRequest request) { try { var result = _orderProcessingService.PlaceOrder(request.processPaymentRequest, request.processPaymentResult, request.details); return(Request.CreateResponse(HttpStatusCode.OK, result)); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
private PlaceOrderResult PlaceOrder(Order newOrder, Customer customer) { var processPaymentRequest = new ProcessPaymentRequest(); processPaymentRequest.StoreId = newOrder.StoreId; processPaymentRequest.CustomerId = customer.Id; processPaymentRequest.PaymentMethodSystemName = newOrder.PaymentMethodSystemName; PlaceOrderResult placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); return(placeOrderResult); }
private PlaceOrderResult PlaceOrder(Order newOrder, Customer customer) { var processPaymentRequest = new ProcessPaymentRequest { StoreId = newOrder.StoreId, CustomerId = customer.Id, PaymentMethodSystemName = newOrder.PaymentMethodSystemName }; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); return placeOrderResult; }
private PlaceOrderResult PlaceOrder(Guid instantCheckoutOrderId, Order newOrder, Customer customer) { var processPaymentRequest = new ProcessPaymentRequest { OrderGuid = instantCheckoutOrderId, StoreId = newOrder.StoreId, CustomerId = customer.Id, PaymentMethodSystemName = newOrder.PaymentMethodSystemName }; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); return(placeOrderResult); }
private PlaceOrderResult PlaceOrder(Order newOrder, Customer customer) { var processPaymentRequest = new ProcessPaymentRequest { StoreId = newOrder.StoreId, CustomerId = customer.Id, PaymentMethodSystemName = newOrder.PaymentMethodSystemName, OrderGuid = newOrder.OrderGuid, CustomValues = new Dictionary <string, object>() }; // MAJAKO CHANGES processPaymentRequest.CustomValues.Add("textalk", newOrder.CustomOrderNumber); var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); return(placeOrderResult); }
//Reques A Credit Order Study public virtual IActionResult RequestCredit(int orderId) { var order = _orderService.GetOrderById(orderId); if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId) { return(Challenge()); } order.OrderNotes.Add(new OrderNote() { Order = order, Note = "Solicitud de Credito" }); var processPaymentRequest = new ProcessPaymentRequest(); GenerateOrderGuid(processPaymentRequest); processPaymentRequest.OrderGuid = order.OrderGuid; processPaymentRequest.StoreId = _storeContext.CurrentStore.Id; processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id; processPaymentRequest.PaymentMethodSystemName = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id); var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); if (placeOrderResult.Success) { HttpContext.Session.Set("OrderPaymentInfo", null); var postProcessPaymentRequest = new PostProcessPaymentRequest { Order = placeOrderResult.PlacedOrder }; _paymentService.PostProcessPayment(postProcessPaymentRequest); RedirectToRoute("CheckoutCompleted", new { orderId = placeOrderResult.PlacedOrder.Id }); } return(RedirectToRoute("Home")); }
public ActionResult ConfirmOrder(FormCollection form) { //validation var storeId = _storeContext.CurrentStore.Id; var customer = _workContext.CurrentCustomer; var cart = customer.GetCartItems(ShoppingCartType.ShoppingCart, storeId); if (cart.Count == 0) { return(RedirectToRoute("ShoppingCart")); } if ((customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) { return(new HttpUnauthorizedResult()); } var model = new CheckoutConfirmModel(); PlaceOrderResult placeOrderResult = null; PostProcessPaymentRequest postProcessPaymentRequest = null; try { var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest; if (processPaymentRequest == null) { //Check whether payment workflow is required if (IsPaymentWorkflowRequired(cart)) { return(RedirectToAction("PaymentMethod")); } processPaymentRequest = new ProcessPaymentRequest(); } //prevent 2 orders being placed within an X seconds time frame if (!IsMinimumOrderPlacementIntervalValid(customer)) { throw new Exception(T("Checkout.MinOrderPlacementInterval")); } //place order processPaymentRequest.StoreId = storeId; processPaymentRequest.CustomerId = customer.Id; processPaymentRequest.PaymentMethodSystemName = customer.GetAttribute <string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, storeId); var placeOrderExtraData = new Dictionary <string, string>(); placeOrderExtraData["CustomerComment"] = form["customercommenthidden"]; placeOrderExtraData["SubscribeToNewsLetter"] = form["SubscribeToNewsLetterHidden"]; placeOrderExtraData["AcceptThirdPartyEmailHandOver"] = form["AcceptThirdPartyEmailHandOverHidden"]; placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData); if (!placeOrderResult.Success) { model.Warnings.AddRange(placeOrderResult.Errors.Select(x => HtmlUtils.ConvertPlainTextToHtml(x))); } } catch (Exception exception) { Logger.Warn(exception, exception.Message); if (!model.Warnings.Any(x => x == exception.Message)) { model.Warnings.Add(exception.Message); } } if (placeOrderResult == null || !placeOrderResult.Success || model.Warnings.Any()) { return(View(model)); } try { postProcessPaymentRequest = new PostProcessPaymentRequest { Order = placeOrderResult.PlacedOrder }; _paymentService.PostProcessPayment(postProcessPaymentRequest); } catch (Exception exception) { NotifyError(exception); } finally { _httpContext.Session["OrderPaymentInfo"] = null; _httpContext.RemoveCheckoutState(); } if (postProcessPaymentRequest != null && postProcessPaymentRequest.RedirectUrl.HasValue()) { return(Redirect(postProcessPaymentRequest.RedirectUrl)); } return(RedirectToAction("Completed")); }
private Order CreateOrderAndSyncWithKlarna(KlarnaCheckoutEntity klarnaRequest, Customer customer, KlarnaCheckoutOrder klarnaCheckoutOrder, Uri resourceUri) { SyncCartWithKlarnaOrder(customer, klarnaCheckoutOrder); var processPaymentRequest = new ProcessPaymentRequest { OrderGuid = klarnaRequest.OrderGuid, CustomerId = customer.Id, StoreId = _storeContext.CurrentStore.Id, PaymentMethodSystemName = KlarnaCheckoutProcessor.PaymentMethodSystemName }; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); // If you tamper with the cart after the klarna widget is rendered nop fails to create the order. if (!placeOrderResult.Success) { var errors = string.Join("; ", placeOrderResult.Errors); _logger.Error(string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Klarna has been processed but order could not be created in Nop! Klarna ID={0}, ResourceURI={1}. Errors: {2}", klarnaCheckoutOrder.Id, klarnaRequest.KlarnaResourceUri, errors), customer: customer); _klarnaCheckoutPaymentService.CancelPayment(klarnaCheckoutOrder.Reservation, customer); throw new KlarnaCheckoutException("Error creating order: " + errors); } // Order was successfully created. var orderId = placeOrderResult.PlacedOrder.Id; var nopOrder = _orderService.GetOrderById(orderId); var klarnaPayment = _paymentService.LoadPaymentMethodBySystemName(KlarnaCheckoutProcessor.PaymentMethodSystemName); klarnaPayment.PostProcessPayment(new PostProcessPaymentRequest { Order = nopOrder }); var orderTotalInCurrentCurrency = _currencyService.ConvertFromPrimaryStoreCurrency(nopOrder.OrderTotal, _workContext.WorkingCurrency); // Due to rounding when using prices contains more than 2 decimals (e.g. currency conversion), we allow // a slight diff in paid price and nop's reported price. // For example nop rounds the prices after _all_ cart item prices have been summed but when sending // items to Klarna, each price needs to be rounded separately (Klarna uses 2 decimals). // Assume a cart with two items. // 1.114 + 2.114 = 3.228 which nop rounds to 3.23. // 1.11 + 2.11 is sent to Klarna, which totals 3.22. var allowedPriceDiff = orderTotalInCurrentCurrency * 0.01m; var diff = Math.Abs(orderTotalInCurrentCurrency - (klarnaCheckoutOrder.Cart.TotalPriceIncludingTax.Value / 100m)); if (diff >= allowedPriceDiff) { var orderTotalInCents = _klarnaCheckoutHelper.ConvertToCents(orderTotalInCurrentCurrency); nopOrder.OrderNotes.Add(new OrderNote { Note = string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Order total differs from Klarna order. OrderTotal: {0}, OrderTotalInCents: {1}, KlarnaTotal: {2}, AllowedDiff: {3}, Diff: {4}, Uri: {5}", orderTotalInCurrentCurrency, orderTotalInCents, klarnaCheckoutOrder.Cart.TotalPriceIncludingTax, allowedPriceDiff, diff, resourceUri), DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); } nopOrder.OrderNotes.Add(new OrderNote { Note = "KlarnaCheckout: Order acknowledged. Uri: " + resourceUri, DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(nopOrder); if (_orderProcessingService.CanMarkOrderAsAuthorized(nopOrder)) { _orderProcessingService.MarkAsAuthorized(nopOrder); // Sometimes shipping isn't required, e.g. if only ordering virtual gift cards. // In those cases, make sure the Klarna order is activated. if (nopOrder.OrderStatus == OrderStatus.Complete || nopOrder.ShippingStatus == ShippingStatus.ShippingNotRequired) { nopOrder.OrderNotes.Add(new OrderNote { Note = "KlarnaCheckout: Order complete after payment, will try to capture payment.", CreatedOnUtc = DateTime.UtcNow, DisplayToCustomer = false }); _orderService.UpdateOrder(nopOrder); if (_orderProcessingService.CanCapture(nopOrder)) { _orderProcessingService.Capture(nopOrder); } } } return(nopOrder); }
public ActionResult ConfirmOrder(FormCollection form) { //validation var cart = _workContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id); if (cart.Count == 0) return RedirectToRoute("ShoppingCart"); if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) return new HttpUnauthorizedResult(); //model var model = new CheckoutConfirmModel(); try { bool isPaymentPaymentWorkflowRequired = IsPaymentWorkflowRequired(cart); var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest; if (processPaymentRequest == null) { //Check whether payment workflow is required if (isPaymentPaymentWorkflowRequired) return RedirectToAction("PaymentMethod"); processPaymentRequest = new ProcessPaymentRequest(); } //prevent 2 orders being placed within an X seconds time frame if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer)) throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval")); //place order processPaymentRequest.StoreId = _storeContext.CurrentStore.Id; processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id; processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>( SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id); var placeOrderExtraData = new Dictionary<string, string>(); placeOrderExtraData["CustomerComment"] = form["customercommenthidden"]; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData); if (placeOrderResult.Success) { if (isPaymentPaymentWorkflowRequired) { var postProcessPaymentRequest = new PostProcessPaymentRequest() { Order = placeOrderResult.PlacedOrder }; _paymentService.PostProcessPayment(postProcessPaymentRequest); } _httpContext.Session["PaymentData"] = null; _httpContext.Session["OrderPaymentInfo"] = null; _httpContext.RemoveCheckoutState(); if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone) { //redirection or POST has been done in PostProcessPayment return Content("Redirected"); } else { //if no redirection has been done (to a third-party payment page) //theoretically it's not possible return RedirectToAction("Completed"); } } else { foreach (var error in placeOrderResult.Errors) model.Warnings.Add(error); } } catch (Exception exc) { Logger.Warning(exc.Message, exc); model.Warnings.Add(exc.Message); } //If we got this far, something failed, redisplay form //if (model.Warnings.Count > 0) // TempData["ConfirmOrderWarnings"] = model.Warnings; //return RedirectToRoute("CheckoutConfirm"); return View(model); }
private void ProcessNewOrderNotification(string xmlData) { try { var newOrderNotification = (NewOrderNotification)EncodeHelper.Deserialize(xmlData, typeof(NewOrderNotification)); string googleOrderNumber = newOrderNotification.googleordernumber; XmlNode customerInfo = newOrderNotification.shoppingcart.merchantprivatedata.Any[0]; int customerId = Convert.ToInt32(customerInfo.Attributes["CustomerID"].Value); int customerLanguageId = Convert.ToInt32(customerInfo.Attributes["CustomerLanguageID"].Value); int customerCurrencyId = Convert.ToInt32(customerInfo.Attributes["CustomerCurrencyID"].Value); var customer = _customerService.GetCustomerById(customerId); if (customer == null) { LogMessage("Could not load a customer"); return; } var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); _workContext.CurrentCustomer = customer; if (cart.Count == 0) { LogMessage("Cart is empty"); return; } //validate cart foreach (var sci in cart) { bool ok = false; foreach (Item item in newOrderNotification.shoppingcart.items) { if (!String.IsNullOrEmpty(item.merchantitemid)) { if ((Convert.ToInt32(item.merchantitemid) == sci.Id) && (item.quantity == sci.Quantity)) { ok = true; break; } } } if (!ok) { LogMessage(string.Format("Shopping Cart item has been changed. {0}. {1}", sci.Id, sci.Quantity)); return; } } string[] billingFullname = newOrderNotification.buyerbillingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string billingFirstName = billingFullname[0]; string billingLastName = string.Empty; if (billingFullname.Length > 1) { billingLastName = billingFullname[1]; } string billingEmail = newOrderNotification.buyerbillingaddress.email.Trim(); string billingAddress1 = newOrderNotification.buyerbillingaddress.address1.Trim(); string billingAddress2 = newOrderNotification.buyerbillingaddress.address2.Trim(); string billingPhoneNumber = newOrderNotification.buyerbillingaddress.phone.Trim(); string billingCity = newOrderNotification.buyerbillingaddress.city.Trim(); int? billingStateProvinceId = null; var billingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(newOrderNotification.buyerbillingaddress.region.Trim()); if (billingStateProvince != null) { billingStateProvinceId = billingStateProvince.Id; } string billingZipPostalCode = newOrderNotification.buyerbillingaddress.postalcode.Trim(); int? billingCountryId = null; var billingCountry = _countryService.GetCountryByTwoLetterIsoCode(newOrderNotification.buyerbillingaddress.countrycode.Trim()); if (billingCountry != null) { billingCountryId = billingCountry.Id; } var billingAddress = customer.Addresses.ToList().FindAddress( billingFirstName, billingLastName, billingPhoneNumber, billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity, billingStateProvinceId, billingZipPostalCode, billingCountryId); if (billingAddress == null) { billingAddress = new Core.Domain.Common.Address() { FirstName = billingFirstName, LastName = billingLastName, PhoneNumber = billingPhoneNumber, Email = billingEmail, Address1 = billingAddress1, Address2 = billingAddress2, City = billingCity, StateProvinceId = billingStateProvinceId, ZipPostalCode = billingZipPostalCode, CountryId = billingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(billingAddress); } //set default billing address customer.SetBillingAddress(billingAddress); _customerService.UpdateCustomer(customer); _customerService.SaveCustomerAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.LastShippingOption, null); bool shoppingCartRequiresShipping = cart.RequiresShipping(); if (shoppingCartRequiresShipping) { string[] shippingFullname = newOrderNotification.buyershippingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string shippingFirstName = shippingFullname[0]; string shippingLastName = string.Empty; if (shippingFullname.Length > 1) { shippingLastName = shippingFullname[1]; } string shippingEmail = newOrderNotification.buyershippingaddress.email.Trim(); string shippingAddress1 = newOrderNotification.buyershippingaddress.address1.Trim(); string shippingAddress2 = newOrderNotification.buyershippingaddress.address2.Trim(); string shippingPhoneNumber = newOrderNotification.buyershippingaddress.phone.Trim(); string shippingCity = newOrderNotification.buyershippingaddress.city.Trim(); int? shippingStateProvinceId = null; var shippingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(newOrderNotification.buyershippingaddress.region.Trim()); if (shippingStateProvince != null) { shippingStateProvinceId = shippingStateProvince.Id; } int? shippingCountryId = null; string shippingZipPostalCode = newOrderNotification.buyershippingaddress.postalcode.Trim(); var shippingCountry = _countryService.GetCountryByTwoLetterIsoCode(newOrderNotification.buyershippingaddress.countrycode.Trim()); if (shippingCountry != null) { shippingCountryId = shippingCountry.Id; } var shippingAddress = customer.Addresses.ToList().FindAddress( shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail, string.Empty, string.Empty, shippingAddress1, shippingAddress2, shippingCity, shippingStateProvinceId, shippingZipPostalCode, shippingCountryId); if (shippingAddress == null) { shippingAddress = new Core.Domain.Common.Address() { FirstName = shippingFirstName, LastName = shippingLastName, PhoneNumber = shippingPhoneNumber, Email = shippingEmail, Address1 = shippingAddress1, Address2 = shippingAddress2, City = shippingCity, StateProvinceId = shippingStateProvinceId, ZipPostalCode = shippingZipPostalCode, CountryId = shippingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(shippingAddress); } //set default shipping address customer.SetShippingAddress(shippingAddress); _customerService.UpdateCustomer(customer); if (newOrderNotification.orderadjustment != null && newOrderNotification.orderadjustment.shipping != null && newOrderNotification.orderadjustment.shipping.Item != null) { var shippingMethod = (FlatRateShippingAdjustment)newOrderNotification.orderadjustment.shipping.Item; var shippingOption = new ShippingOption(); shippingOption.Name = shippingMethod.shippingname; shippingOption.Rate = shippingMethod.shippingcost.Value; _customerService.SaveCustomerAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.LastShippingOption, shippingOption); } } //customer.LastCalculatedTax = decimal.Zero; var paymentInfo = new ProcessPaymentRequest() { PaymentMethodSystemName = "Payments.GoogleCheckout", Customer = customer, GoogleOrderNumber = googleOrderNumber }; //TODO set customer language and currency //paymentInfo.CustomerLanguage = IoC.Resolve<ILanguageService>().GetLanguageById(CustomerLanguageID); //paymentInfo.CustomerCurrency = IoC.Resolve<ICurrencyService>().GetCurrencyById(CustomerCurrencyID); var result = _orderProcessingService.PlaceOrder(paymentInfo); if (!result.Success) { LogMessage("new-order-notification received. CreateOrder() error: Order Number " + googleOrderNumber + ". " + result); return; } var order = result.PlacedOrder; if (order != null) { LogMessage("new-order-notification received and saved: Order Number " + order.Id); } } catch (Exception exc) { LogMessage("processNewOrderNotification Exception: " + exc.Message + ": " + exc.StackTrace); } }
public ActionResult CreateTransaction(int productId, string nonce, string device) { var resp = new DataSourceResult(); string authorization = _httpContext.Request.Headers["Authorization"]; var customer = GetCustomerFromToken(authorization, device); if (customer != null) { var payPalStandardPaymentSettings = _settingService.LoadSetting <PayPalStandardPaymentSettings>(_storeContext.CurrentStore.Id); string environment = payPalStandardPaymentSettings.UseSandbox ? "sandbox" : "product"; string merchantId = payPalStandardPaymentSettings.MerchantId; string publicKey = payPalStandardPaymentSettings.PublicKey; string privateKey = payPalStandardPaymentSettings.PrivateKey; var braintreeGateway = new BraintreeGateway(environment, merchantId, publicKey, privateKey); //清空购物车中的数据 if (customer.ShoppingCartItems.Count > 0) { var itemList = customer.ShoppingCartItems.ToList(); foreach (var item in itemList) { _shoppingCartService.DeleteShoppingCartItem(item); } } //添加当前优惠卷到购物车 var product = _productService.GetProductById(productId); var warnings = _shoppingCartService.AddToCart(customer, product, ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id); if (warnings.Count > 0) { return(Json(resp)); } var processPaymentRequest = new ProcessPaymentRequest(); processPaymentRequest.StoreId = _storeContext.CurrentStore.Id; processPaymentRequest.CustomerId = customer.Id; processPaymentRequest.PaymentMethodSystemName = "Payments.PayPalStandard"; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); if (placeOrderResult.Success) { var request = new TransactionRequest { Amount = placeOrderResult.PlacedOrder.OrderTotal, PaymentMethodNonce = nonce, Options = new TransactionOptionsRequest { SubmitForSettlement = true } }; Result <Transaction> result = braintreeGateway.Transaction.Sale(request); if (result.IsSuccess()) { Transaction transaction = result.Target; resp.ExtraData = transaction.Id; if (_orderProcessingService.CanMarkOrderAsPaid(placeOrderResult.PlacedOrder)) { placeOrderResult.PlacedOrder.AuthorizationTransactionId = transaction.Id; //_orderService.UpdateOrder(placeOrderResult.PlacedOrder); _orderProcessingService.MarkOrderAsPaid(placeOrderResult.PlacedOrder); IList dataList = new ArrayList(); foreach (var item in placeOrderResult.PlacedOrder.OrderItems) { var coupon = new { orderId = item.OrderId, cid = item.CustomOrderItemNumber, productId = item.Product.Id, userName = customer.Username, orderTotal = placeOrderResult.PlacedOrder.OrderTotal, paymentStatus = placeOrderResult.PlacedOrder.PaymentStatusId, startTime = placeOrderResult.PlacedOrder.PaidDateUtc.HasValue ? placeOrderResult.PlacedOrder.PaidDateUtc.Value.ToString("yyyy-MM-dd HH:mm:ss") : product.CreatedOnUtc.ToString("yyyy-MM-dd HH:mm:ss"), endTime = product.AvailableEndDateTimeUtc.HasValue ? product.AvailableEndDateTimeUtc.Value.ToString("yyyy-MM-dd HH:mm:ss") : "", deleted = placeOrderResult.PlacedOrder.Deleted }; dataList.Add(coupon); } resp.Data = dataList; } } else if (result.Transaction != null) { resp.ExtraData = result.Transaction.Id; } else { string errorMessages = ""; foreach (ValidationError error in result.Errors.DeepAll()) { errorMessages += "Error: " + (int)error.Code + " - " + error.Message + "\n"; } resp.Errors = errorMessages; } } else { resp.Errors = "E_3000"; } } else { resp.Errors = "E_1002"; } return(Json(resp)); }
/// <summary> /// Places an order /// </summary> /// <param name="processPaymentRequest">Process payment request</param> /// <returns>Place order result</returns> public PlaceOrderResult PlaceOrder(ProcessPaymentRequest processPaymentRequest) { return(_orderProcessingService.PlaceOrder(processPaymentRequest)); }
public ActionResult SubmitButton() { ActionResult result; try { if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed) { result = RedirectToRoute("Login"); } else { IEnumerable <ShoppingCartItem> shoppingCartItems = _workContext.CurrentCustomer.ShoppingCartItems; List <ShoppingCartItem> list = shoppingCartItems.Where(item => item.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); if (list.Count == 0) { result = RedirectToRoute("ShoppingCart"); } else { string currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode; var curencies = _p24PaymentSettings.Currencies.Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries); if (!curencies.Contains(currencyCode)) { throw new ApplicationException("Privat24. currency is not supported. (only UAH, USD, EUR)"); } if (string.IsNullOrEmpty(_p24PaymentSettings.MerchantId)) { throw new ApplicationException("Privat24. merchant_id is not set"); } if (string.IsNullOrEmpty(_p24PaymentSettings.MerchantSignature)) { throw new ApplicationException("Privat24. merchant_sig is not set"); } var privat24PaymentProcessor = _paymentService.LoadPaymentMethodBySystemName("Nop.Payments.Privat24") as Privat24PaymentProcessor; if (privat24PaymentProcessor == null || !privat24PaymentProcessor.IsPaymentMethodActive(_paymentSettings) || !privat24PaymentProcessor.PluginDescriptor.Installed) { throw new NopException("Privat24 module cannot be loaded"); } var processPaymentRequest = new ProcessPaymentRequest { PaymentMethodSystemName = "Nop.Payments.Privat24", CustomerId = _workContext.CurrentCustomer.Id }; ProcessPaymentRequest processPaymentRequest2 = processPaymentRequest; PlaceOrderResult placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest2); if (!placeOrderResult.Success) { privat24PaymentProcessor.LogMessage(string.Format("CreateOrder() error: {0}", placeOrderResult)); result = RedirectToRoute("ShoppingCart"); } else { Order placedOrder = placeOrderResult.PlacedOrder; if (placedOrder == null) { privat24PaymentProcessor.LogMessage("order==null"); result = RedirectToRoute("ShoppingCart"); } else { privat24PaymentProcessor.LogMessage("create new order: Order Number " + placedOrder.Id); string text = privat24PaymentProcessor.CreateFormPrivat24(placedOrder.Id, placedOrder.OrderTotal); result = new RedirectResult(text); } } } } } catch (Exception arg) { result = Content("Error: " + arg); } return(result); }
public CheckoutPlaceOrderModel PlaceOrder() { var model = new CheckoutPlaceOrderModel(); try { var processPaymentRequest = _session.Get <ProcessPaymentRequest>(Defaults.ProcessPaymentRequestKey); if (processPaymentRequest == null) { model.RedirectToCart = true; return(model); } //prevent 2 orders being placed within an X seconds time frame if (!_payPalExpressCheckoutService.IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer)) { throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval")); } //place order processPaymentRequest.StoreId = _storeContext.CurrentStore.Id; processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id; processPaymentRequest.PaymentMethodSystemName = "Payments.PayPalExpressCheckout"; var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); if (placeOrderResult.Success) { var doExpressCheckoutPaymentResponseType = _session.Get <DoExpressCheckoutPaymentResponseType>(Defaults.CheckoutPaymentResponseTypeKey); doExpressCheckoutPaymentResponseType?.LogOrderNotes(placeOrderResult.PlacedOrder.OrderGuid); _session.Remove(Defaults.ProcessPaymentRequestKey); var postProcessPaymentRequest = new PostProcessPaymentRequest { Order = placeOrderResult.PlacedOrder }; _paymentService.PostProcessPayment(postProcessPaymentRequest); if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone) { //redirection or POST has been done in PostProcessPayment model.IsRedirected = true; return(model); } model.CompletedId = placeOrderResult.PlacedOrder.Id; return(model); } foreach (var error in placeOrderResult.Errors) { model.Warnings.Add(error); } } catch (Exception exc) { _logger.Warning(exc.Message, exc); model.Warnings.Add(exc.Message); } return(model); }
public IActionResult ConfirmParatikaPayment(string merchantPaymentId, string responseCode, string responseMsg) { var model = new PaymentInfoModel(); var processPaymentRequest = new ProcessPaymentRequest(); processPaymentRequest.OrderGuid = Guid.Parse(merchantPaymentId); HttpContext.Session.Set <ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest); if (_orderSettings.CheckoutDisabled) { return(RedirectToRoute("ShoppingCart")); } var cart = _workContext.CurrentCustomer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); if (!cart.Any()) { return(RedirectToRoute("ShoppingCart")); } if (_orderSettings.OnePageCheckoutEnabled) { return(RedirectToRoute("CheckoutOnePage")); } if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed) { return(Challenge()); } //Check whether payment workflow is required var isPaymentWorkflowRequired = _orderProcessingService.IsPaymentWorkflowRequired(cart); if (!isPaymentWorkflowRequired) { return(RedirectToRoute("CheckoutConfirm")); } //load payment method var paymentMethodSystemName = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id); var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) { return(RedirectToRoute("CheckoutPaymentMethod")); } var orderGuid = _session.Get <string>("MERCHANTPAYMENTID_" + _workContext.CurrentCustomer.Id); if (responseCode == "00") { try { processPaymentRequest.StoreId = _storeContext.CurrentStore.Id; processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id; processPaymentRequest.PaymentMethodSystemName = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id); processPaymentRequest.OrderGuid = Guid.Parse(merchantPaymentId); HttpContext.Session.Set <ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest); var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest); if (placeOrderResult.Success) { HttpContext.Session.Set <ProcessPaymentRequest>("OrderPaymentInfo", null); var postProcessPaymentRequest = new PostProcessPaymentRequest { Order = placeOrderResult.PlacedOrder, }; _paymentService.PostProcessPayment(postProcessPaymentRequest); if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone) { //redirection or POST has been done in PostProcessPayment return(Content("Redirected")); } return(RedirectToRoute("CheckoutCompleted", new { orderId = placeOrderResult.PlacedOrder.Id })); } foreach (var error in placeOrderResult.Errors) { model.Error += error; } } catch (Exception exc) { _logger.Warning(exc.Message, exc); model.Error += exc.Message; } } else { model.Error += _localizationService.GetResource("Plugins.Payments.Paratika.Fields.Error"); } model.Error += responseMsg; return(RedirectToRoute("CheckoutPaymentMethod")); }