Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using Microsoft.AspNetCore.Mvc;
- using Nop.Core;
- using Nop.Core.Domain.Customers;
- using Nop.Core.Domain.Orders;
- using Nop.Services.Customization.Orders.Cpfm.Models;
- using Nop.Services.Payments;
- using Nop.Core.Http.Extensions;
- using Nop.Services.Orders;
- using Nop.Web.Models.Checkout;
- using System.Threading.Tasks;
- using Nop.Core.Customization.Utilities;
- using Nop.Services.Customization.Orders.Cpfm.Models.PCG;
- using System.Data;
- using System.Collections.Generic;
- using System.Net;
- using Nop.Services.Customization.Orders.PCG;
- using Nop.Services.Customization.Payment;
- using Microsoft.AspNetCore.Http;
- using Newtonsoft.Json;
- using Nop.Services.Customization.Payment.Kbank.Model;
- using Nop.Web.Framework.Mvc.Filters;
- namespace Nop.Web.Controllers
- {
- public partial class CheckoutController
- {
- private const string SESSION_CALPRICE_OBJ = "PCG_CALPRICEPROMOTION_RESULT";
- private const string SESSION_ISTAX = "PCG_ISTAX";
- public virtual IActionResult OnePageCheckout()
- {
- //validation
- if (_orderSettings.CheckoutDisabled)
- return RedirectToRoute("ShoppingCart");
- var isTax = Request.Query["tax"].Count() > 0 && Request.Query["tax"][0] == "1";
- var cart = _workContext.CurrentCustomer.ShoppingCartItems
- .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
- .LimitPerStore(_storeContext.CurrentStore.Id)
- .ToList();
- HttpContext.Session.Set(SESSION_ISTAX, isTax);
- cart = GetCartTaxNonTax(cart, isTax);
- if (!cart.Any())
- return RedirectToRoute("ShoppingCart");
- if (!_orderSettings.OnePageCheckoutEnabled)
- return RedirectToRoute("Checkout");
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- return Challenge();
- var model = _checkoutModelFactory.PrepareOnePageCheckoutModel(cart);
- return View(model);
- }
- private List<ShoppingCartItem> GetCartTaxNonTax(List<ShoppingCartItem> cart, bool isTax)
- {
- var productIdList = cart.Select(x => x.ProductId);
- var finalProductIdList = _productService.GetAllProducts(x => productIdList.Contains(x.Id) && x.IsTaxExempt == !isTax).Select(x => x.Id);
- cart = cart.Where(x => finalProductIdList.Contains(x.ProductId)).ToList();
- return cart;
- }
- public IActionResult CreateOrder(int delayDate, FreebieModel[] freebies)
- {
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- return RedirectToRoute("CheckoutOnePage");
- try
- {
- var currentAddressId = HttpContext.Session.GetInt32("CurrentShippingAddressId") ?? _workContext.CurrentCustomer.ShippingAddressId ?? 0;
- var dsCalPrice = HttpContext.Session.Get<DataSet>(SESSION_CALPRICE_OBJ);
- var orderTotal = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.TOTAL_AMOUNT].ToString().ToDecimal();
- var promotionDiscount = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.PRODUCT_DISCOUNT].ToString().ToDecimal();
- var commercialDiscount = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.TOTAL_DISCOUNT].ToString().ToDecimal();
- var totalDiscount = promotionDiscount + commercialDiscount;
- var shipping = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.FREIGHT].ToString().ToDecimal();
- var processPaymentRequest = new ProcessPaymentRequest();
- processPaymentRequest.CustomValues.Add("DelayDate", delayDate);
- processPaymentRequest.CustomValues.Add("PaymentType", PaymentType.CreditTerm);
- processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditTerm.GetDescription();
- HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
- processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
- processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
- processPaymentRequest.IsTax = HttpContext.Session.Get<bool>(SESSION_ISTAX);
- processPaymentRequest.OrderTotal = orderTotal;
- //processPaymentRequest.CustomValues.Add("DeliveryTimePeriod", model.DeliveryPeriod);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT, promotionDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT, commercialDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT, totalDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERSHIPPINGTOTAL, shipping);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.SELECTSHIPPINGADDRESSID, currentAddressId);
- // confirm order process
- var isTax = HttpContext.Session.Get<bool>(SESSION_ISTAX);
- var result = _orderProcessingService.PCGCreateOrder(dsCalPrice, processPaymentRequest, freebies, isTax);
- if (result.Status != TaskStatus.RanToCompletion)
- {
- _logger.Error(result.Exception.Message, result.Exception);
- throw result.Exception;
- }
- // get the order
- var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
- customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
- .FirstOrDefault();
- if (order != null)
- {
- var orderCompleteModel = new CheckoutCompletedModel()
- {
- OrderId = order.Id,
- CustomOrderNumber = order.CustomOrderNumber,
- OnePageCheckoutEnabled = true,
- OrderDetailsModel = new Models.Order.OrderDetailsModel()
- {
- CustomOrderNumber = order.CustomOrderNumber
- }
- };
- return Json(new { goto_uri = $"checkout/completed?orderid={order.Id}" });
- //return Redirect($"completed?orderid={order.Id}");
- }
- return BadRequest("failed to create order!");
- }
- catch (Exception ex)
- {
- return RedirectToRoute("Error");
- }
- }
- public virtual async Task<IActionResult> GetPrice(int delayDate)
- {
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- return RedirectToRoute("CheckoutOnePage");
- try
- {
- // customer
- var customer = _workContext.CurrentCustomer;
- // get carts
- var carts = customer.ShoppingCartItems
- .WithOnlyShoppingCart().ToList();
- var isTax = HttpContext.Session.Get<bool>(SESSION_ISTAX);
- carts = GetCartTaxNonTax(carts, isTax);
- var currentAddressId = HttpContext.Session.GetInt32("CurrentShippingAddressId") ?? _workContext.CurrentCustomer.ShippingAddressId ?? 0;
- var selectedAddressNumber = _addressService.GetAddressById(currentAddressId).AddressNumber.HasValue ? _addressService.GetAddressById(currentAddressId).AddressNumber.Value : 1;
- var gnerator = new PCGAPIModelGenerator();
- var dsRequest = gnerator.CreateCalPriceRequestModel(carts.ToArray(), customer, delayDate, isTax, selectedAddressNumber);
- // calling orderprocessing service
- var dsResponse = await _orderProcessingService.PCGGetPrice(dsRequest);
- var result = gnerator.CreateCalPriceResponseModel(dsResponse);
- if (result.HasError())
- throw new Exception(string.Join(", ", result.ErrorMessages()));
- HttpContext.Session.Set(SESSION_CALPRICE_OBJ, dsResponse);
- // retrive product info for freebies
- var freebiesSku = result.Freebies.Select(x => x.ProductCode);
- var freebieProduct = _productService.GetAllProducts(x => freebiesSku.Contains(x.Sku));
- foreach(var p in freebieProduct)
- {
- var o = result.Freebies.SingleOrDefault(x => x.ProductCode == p.Sku);
- if(o != null)
- {
- o.Name = p.Name;
- var imageUrl = p.ProductPictures?.ToList().Count > 0 ?_pictureService.GetPictureUrl(p.ProductPictures?.ToList()?[0].Picture, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage) : string.Empty;
- o.ImagePath = imageUrl;
- o.ProductId = p.Id;
- o.ShortName = p.ShortDescription;
- }
- }
- var freebiesItemGroup = result.Freebies.GroupBy(u => u.PromotionCode).Select(g => g.ToList());
- // response result
- return Json(new
- {
- header = new {
- ProductNet = result.OrderHeader.ProductNet.ToCurrencyFormat(),
- TotalAmount = result.OrderHeader.TotalAmount.ToCurrencyFormat(),
- ProductDiscount = result.OrderHeader.ProductDiscount.ToNegativeCurrencyFormat(),
- TotalDiscount = result.OrderHeader.TotalDiscount.ToNegativeCurrencyFormat(),
- GrandTotalDiscount = (result.OrderHeader.TotalDiscount + result.OrderHeader.ProductDiscount).ToNegativeCurrencyFormat(),
- TotalNet = result.OrderHeader.TotalNet.ToCurrencyFormat(),
- TotalProductVat = result.OrderHeader.TotalProductVat.ToCurrencyFormat(),
- TotalVat = result.OrderHeader.TotalVat.ToCurrencyFormat(),
- Freight = result.OrderHeader.Freight.ToNegativeCurrencyFormat(),
- FreebiesTotal = freebiesItemGroup.Sum(x => x?[0].FreeQuantity)
- },
- items = result.Orders.Select(x => new
- {
- PricePerUnit = x.PricePerUnit.ToString().ToCurrencyFormat(),
- PromotionDiscount = x.PromotionDiscount,
- TotalAmount = x.TotalAmount.ToString().ToCurrencyFormat(),
- Net = x.NetPrice.ToString().ToCurrencyFormat(),
- Sku = x.Sku,
- Qty = x.Qty,
- }),
- freebies = freebiesItemGroup
- });
- }
- catch (Exception ex)
- {
- return BadRequest($"failed to get order amount : {ex.Message}!");
- }
- }
- //protected CheckoutConfirmModel CpfmConfirmOrder()
- //{
- // var confirmOrderModel = new CheckoutConfirmModel();
- // try
- // {
- // //validation
- // if (_orderSettings.CheckoutDisabled)
- // throw new Exception(_localizationService.GetResource("Checkout.Disabled"));
- // var cart = _workContext.CurrentCustomer.ShoppingCartItems
- // .WithOnlyShoppingCart()
- // .LimitPerStore(_storeContext.CurrentStore.Id)
- // .ToList();
- // if (!cart.Any())
- // throw new Exception("Your cart is empty");
- // if (!_orderSettings.OnePageCheckoutEnabled)
- // throw new Exception("One page checkout is disabled");
- // if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- // throw new Exception("Anonymous checkout is not allowed");
- // //prevent 2 orders being placed within an X seconds time frame
- // if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
- // throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
- // //place order
- // var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
- // if(processPaymentRequest == null)
- // throw new Exception("Payment information is not entered");
- // processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
- // processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
- // // process order
- // var orderResult = _orderProcessingService.PlaceCpfmOrder(processPaymentRequest);
- // // error
- // foreach (var error in orderResult.Errors)
- // confirmOrderModel.Warnings.Add(error);
- // }
- // catch (Exception exc)
- // {
- // _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
- // confirmOrderModel.Warnings.Add(exc.Message);
- // }
- // return confirmOrderModel;
- //}
- public virtual IActionResult CalculatePrice(int delayDate, DeliveryTimePeriod deliveryTimePeriod)
- {
- return Ok();
- }
- [HttpPost, ActionName("CreateOrder")]
- public virtual IActionResult CreateOrderCustom(Models.Checkout.CreateOrderModel model)
- {
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- return RedirectToRoute("CheckoutOnePage");
- try
- {
- var processPaymentRequest = CreateProcessRequest(model, PaymentType.CreditTerm);
- HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
- // confirm order process
- var result = CpfmConfirmOrder();
- if (result.Warnings.Any())
- {
- return BadRequest(string.Join(", ", result.Warnings));
- }
- // get the order
- var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
- customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
- .FirstOrDefault();
- if (order != null)
- {
- var orderCompleteModel = new CheckoutCompletedModel()
- {
- OrderId = order.Id,
- CustomOrderNumber = order.CustomOrderNumber,
- OnePageCheckoutEnabled = true,
- OrderDetailsModel = new Models.Order.OrderDetailsModel()
- {
- CustomOrderNumber = order.CustomOrderNumber
- }
- };
- return Json(new
- {
- goto_uri = Url.Action("Completed", "Checkout", new { id = order.Id, orderId = order.Id, customOrderNumber = order.CustomOrderNumber })
- });
- }
- return BadRequest("failed to create order!");
- }
- catch (Exception ex)
- {
- return RedirectToRoute("Error");
- }
- }
- [HttpPost]
- public virtual IActionResult CreateOrderWithCreditcard(Models.Checkout.CreateOrderModel model)
- {
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- return RedirectToRoute("CheckoutOnePage");
- try
- {
- var processPaymentRequest = CreateProcessRequest(model, PaymentType.CreditCard);
- var delayDate = (int)processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELAYDATE];
- // customer
- var customer = _workContext.CurrentCustomer;
- // get carts
- var carts = customer.ShoppingCartItems
- .WithOnlyShoppingCart().ToArray();
- // calling orderprocessing service
- var orderTotal = _orderProcessingService.CalculationCpfmConfrimPrice(carts, customer, delayDate).Result.GetNetPrice();
- var paymentResponse = KbankPayment(orderTotal, _workContext.CurrentCustomer.Username);
- if (paymentResponse.IsPreAuthorizeSuccess)
- {
- processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.AUTHORIZATIONTRANSACTIONID] = paymentResponse.id;
- var orderResult = _orderProcessingService.CreatePendingOrder(processPaymentRequest);
- if (orderResult.Success)
- {
- #if DEBUG
- #else
- return Redirect(paymentResponse.redirect_url);
- #endif
- }
- else
- {
- _logger.Error($"Kbank create pending order fail : {string.Join(",", orderResult.Errors)}");
- TempData["Error"] = "Cannot create order!";
- TempData[ProcessPaymentRequestCustomKey.DELAYDATE] = (int)processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELAYDATE];
- TempData[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD] = processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
- return RedirectToAction("onepagecheckout");
- }
- #if DEBUG
- processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.AUTHORIZATIONTRANSACTIONID] = "chrg_test_202515f473de5e80c46628af5db662e02834e";
- var kbankCallbackJson = "{\"objectid\":\"chrg_test_202515f473de5e80c46628af5db662e02834e\",\"status\":\"true\",\"token\":\"tokn_test_20251f7ae68e5bfbcdc90d71077bc8da9f18b\",\"savecard\":\"false\"}";
- var cli = new WebClient();
- cli.Headers[HttpRequestHeader.ContentType] = "application/json";
- string response = cli.UploadString("http://store1.wecpg-localhost.com/cpfm/checkout/kbankcallback", "POST", kbankCallbackJson);
- return Json("kbankCallback Done");
- #endif
- }
- else
- {
- _logger.Error($"Kbank Card charge fail : {paymentResponse.failure_code} , {paymentResponse.failure_message}");
- TempData["Error"] = "Invalid or unauthorize credit card!";
- TempData[ProcessPaymentRequestCustomKey.DELAYDATE] = (int)processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELAYDATE];
- TempData[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD] = processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
- return RedirectToAction("onepagecheckout");
- }
- }
- catch (Exception ex)
- {
- return RedirectToRoute("Error");
- }
- }
- [HttpPost]
- [CheckAccessClosedStore(true)]
- [CheckAccessPublicStore(true)]
- public IActionResult KbankCallback(KbankCallbackRequest req)
- {
- _logger.InsertLog(Core.Domain.Logging.LogLevel.Debug, $"Calling {nameof(KbankCallback)}");
- var jsonStr = JsonConvert.SerializeObject(req);
- try
- {
- // get the order
- var order = _orderService.GetOrderByAuthorizationTransactionIdAndPaymentMethod(req.objectid, PaymentType.CreditCard.GetDescription());
- var customValues = XmlHelper.Deserialize<Dictionary<string, object>>(order.CustomValuesXml);
- #if DEBUG
- _logger.Information($"checkout - KbankPaymentCallbackModel: {JsonConvert.SerializeObject(req)}");
- if (true)
- #else
- if (req?.status?.ToLower() == "true" && req?.objectid == order?.AuthorizationTransactionId)
- #endif
- {
- var cart = _workContext.CurrentCustomer.ShoppingCartItems
- .WithOnlyShoppingCart()
- .LimitPerStore(_storeContext.CurrentStore.Id)
- .ToList();
- //Check whether payment workflow is required
- if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
- {
- throw new Exception("Payment information is not entered");
- }
- var processPaymentRequest = new ProcessPaymentRequest()
- {
- CustomerId = order.CustomerId,
- StoreId = order.StoreId,
- CustomValues = customValues
- };
- // process order
- var result = _orderProcessingService.ConfirmPendingOrder(order, processPaymentRequest);
- if (result.Errors.Any())
- {
- return BadRequest(string.Join(", ", result.Errors));
- }
- else
- {
- return RedirectToAction("Completed", "Checkout", new { id = order.Id, orderId = order.Id, customOrderNumber = order.CustomOrderNumber });
- }
- }
- else
- {
- _logger.Error($"Kbank Card OTP confirm fail with status: {req.status}, objectid: {req.objectid}");
- TempData[ProcessPaymentRequestCustomKey.DELAYDATE] = (int)customValues[ProcessPaymentRequestCustomKey.DELAYDATE];
- TempData[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD] = customValues[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
- TempData["Error"] = "Invalid OTP or user cancel payment!";
- return RedirectToAction("onepagecheckout");
- }
- }
- catch (Exception ex)
- {
- _logger.Error(ex.Message, ex);
- }
- _logger.InsertLog(Core.Domain.Logging.LogLevel.Debug, $"Calling {nameof(KbankCallback)} Done!", jsonStr);
- return RedirectToAction("Index");
- }
- private ProcessPaymentRequest CreateProcessRequest(Models.Checkout.CreateOrderModel model, PaymentType paymentType)
- {
- var processPaymentRequest = new ProcessPaymentRequest();
- try
- {
- if (paymentType == PaymentType.CreditTerm)
- {
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELAYDATE, model.DelayDate);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD, model.DeliveryPeriod);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.PAYMENTTYPE, PaymentType.CreditTerm);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT, model.OrderPromotionDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT, model.OrderCommercialDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOUPONDISCOUNT, model.OrderCouponDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT, model.OrderTotalDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERSHIPPINGTOTAL, 0);
- processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditTerm.GetDescription();
- }
- else
- {
- var delayDateStr = Request.Form[ProcessPaymentRequestCustomKey.DELAYDATE];
- var deliveryPeriodStr = Request.Form[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
- var orderPromotionDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT];
- var orderCommercialDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT];
- var orderCouponDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERCOUPONDISCOUNT];
- var orderTotalDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT];
- var delayDate = string.IsNullOrEmpty(delayDateStr) ? 0 : delayDateStr.ToString().ToInt();
- var deliveryPeriod = string.IsNullOrEmpty(deliveryPeriodStr) ? 0 : deliveryPeriodStr.ToString().ToInt();
- var orderPromotionDiscount = string.IsNullOrEmpty(orderPromotionDiscountStr) ? 0 : orderPromotionDiscountStr.ToString().ToInt();
- var orderCommercialDiscount = string.IsNullOrEmpty(orderCommercialDiscountStr) ? 0 : orderCommercialDiscountStr.ToString().ToInt();
- var orderCouponDiscount = string.IsNullOrEmpty(orderCouponDiscountStr) ? 0 : orderCouponDiscountStr.ToString().ToInt();
- var orderTotalDiscount = string.IsNullOrEmpty(orderTotalDiscountStr) ? 0 : orderTotalDiscountStr.ToString().ToInt();
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELAYDATE, delayDate);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD, deliveryPeriod);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.PAYMENTTYPE, PaymentType.CreditCard);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT, orderPromotionDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT, orderCommercialDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOUPONDISCOUNT, orderCouponDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT, orderTotalDiscount);
- processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERSHIPPINGTOTAL, 0);
- processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
- processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
- processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditCard.GetDescription();
- }
- }
- catch (Exception ex)
- {
- _logger.Error(ex.Message, ex);
- }
- return processPaymentRequest;
- }
- public virtual IActionResult CreateOrder(int delayDate, DeliveryTimePeriod deliveryPeriod)
- {
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- return RedirectToRoute("CheckoutOnePage");
- try
- {
- var processPaymentRequest = new ProcessPaymentRequest();
- processPaymentRequest.CustomValues.Add("DelayDate", delayDate);
- processPaymentRequest.CustomValues.Add("DeliveryTimePeriod", deliveryPeriod);
- processPaymentRequest.CustomValues.Add("PaymentType", PaymentType.CreditTerm);
- processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditTerm.GetDescription();
- HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
- // confirm order process
- var result = CpfmConfirmOrder();
- if (result.Warnings.Any())
- {
- return BadRequest(string.Join(", ", result.Warnings));
- }
- // get the order
- var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
- customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
- .FirstOrDefault();
- if (order != null)
- {
- var orderCompleteModel = new CheckoutCompletedModel()
- {
- OrderId = order.Id,
- CustomOrderNumber = order.CustomOrderNumber,
- OnePageCheckoutEnabled = true,
- OrderDetailsModel = new Models.Order.OrderDetailsModel()
- {
- CustomOrderNumber = order.CustomOrderNumber
- }
- };
- return Json(new
- {
- goto_uri = Url.Action("Completed", "Checkout", new { id = order.Id, orderId = order.Id, customOrderNumber = order.CustomOrderNumber })
- });
- }
- return BadRequest("failed to create order!");
- }
- catch(Exception ex)
- {
- return RedirectToRoute("Error");
- }
- }
- public virtual async Task<IActionResult> GetCpfmConfirmPrice(int delayDate)
- {
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- return RedirectToRoute("CheckoutOnePage");
- try
- {
- // get the order
- var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
- customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
- .FirstOrDefault();
- // customer
- var customer = _workContext.CurrentCustomer;
- // get carts
- var carts = customer.ShoppingCartItems
- .WithOnlyShoppingCart().ToArray();
- // calling orderprocessing service
- var result = await _orderProcessingService.CalculationCpfmConfrimPrice(carts, customer, delayDate);
- if (result.HasError())
- throw new Exception(string.Join(", " ,result.ErrorMessages()));
- // response result
- return Json(new
- {
- GrossPrice = result.GetGrossPrice().ToCurrencyFormat(),
- TradeDiscount = result.GetTradeDiscount().ToNegativeCurrencyFormat(),
- PromotionDiscount = result.GetPromotionDiscount().ToNegativeCurrencyFormat(),
- CouponDiscount = result.GetCouponDiscount().ToNegativeCurrencyFormat(),
- TotalDiscount = result.GetTotalDiscount().ToNegativeCurrencyFormat(),
- ShippingFee = 0,
- NetPrice = result.GetNetPrice().ToCurrencyFormat()
- });
- }
- catch (Exception ex)
- {
- return BadRequest($"failed to get order amount : {ex.Message}!");
- }
- }
- protected CheckoutConfirmModel CpfmConfirmOrder()
- {
- var confirmOrderModel = new CheckoutConfirmModel();
- try
- {
- //validation
- if (_orderSettings.CheckoutDisabled)
- throw new Exception(_localizationService.GetResource("Checkout.Disabled"));
- var cart = _workContext.CurrentCustomer.ShoppingCartItems
- .WithOnlyShoppingCart()
- .LimitPerStore(_storeContext.CurrentStore.Id)
- .ToList();
- if (!cart.Any())
- throw new Exception("Your cart is empty");
- if (!_orderSettings.OnePageCheckoutEnabled)
- throw new Exception("One page checkout is disabled");
- if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
- throw new Exception("Anonymous checkout is not allowed");
- //prevent 2 orders being placed within an X seconds time frame
- if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
- throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
- //place order
- var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
- if(processPaymentRequest == null)
- throw new Exception("Payment information is not entered");
- processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
- processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
- // process order
- var orderResult = _orderProcessingService.PlaceCpfmOrder(processPaymentRequest);
- // error
- foreach (var error in orderResult.Errors)
- confirmOrderModel.Warnings.Add(error);
- }
- catch (Exception exc)
- {
- _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
- confirmOrderModel.Warnings.Add(exc.Message);
- }
- return confirmOrderModel;
- }
- private KbankCardResponse KbankPayment(decimal orderTotal, string cvNo)
- {
- //model
- var cardChargeRequest = CreateKbankPaymentRequest(orderTotal, cvNo);
- return null;
- }
- private KbankCardRequest CreateKbankPaymentRequest(decimal orderTotal, string cvNo)
- {
- var req = new KbankCardRequest();
- // Get the payment token ID submitted by the form:
- string token = Request.Form["token"];
- var orderTime = DateTime.Now.ToString("ddMMyyyy-HHmmss");
- ///buid request parameter
- req.amount = orderTotal;
- req.currency = "THB";
- req.description = $"CPFM_{cvNo}_{orderTime}";
- req.source_type = "card";
- req.mode = "token";
- req.token = token;
- req.reference_order = $"CPFM_{cvNo}_{orderTime}";
- req.ref_1 = "CPFM";
- req.ref_2 = cvNo;
- req.ref_2 = orderTime;
- return req;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement