Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.81 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Nop.Core;
  5. using Nop.Core.Domain.Customers;
  6. using Nop.Core.Domain.Orders;
  7. using Nop.Services.Customization.Orders.Cpfm.Models;
  8. using Nop.Services.Payments;
  9. using Nop.Core.Http.Extensions;
  10. using Nop.Services.Orders;
  11. using Nop.Web.Models.Checkout;
  12. using System.Threading.Tasks;
  13. using Nop.Core.Customization.Utilities;
  14. using Nop.Services.Customization.Orders.Cpfm.Models.PCG;
  15. using System.Data;
  16. using System.Collections.Generic;
  17. using System.Net;
  18.  
  19. using Nop.Services.Customization.Orders.PCG;
  20. using Nop.Services.Customization.Payment;
  21. using Microsoft.AspNetCore.Http;
  22.  
  23. using Newtonsoft.Json;
  24.  
  25. using Nop.Services.Customization.Payment.Kbank.Model;
  26. using Nop.Web.Framework.Mvc.Filters;
  27.  
  28. namespace Nop.Web.Controllers
  29. {
  30. public partial class CheckoutController
  31. {
  32. private const string SESSION_CALPRICE_OBJ = "PCG_CALPRICEPROMOTION_RESULT";
  33. private const string SESSION_ISTAX = "PCG_ISTAX";
  34.  
  35. public virtual IActionResult OnePageCheckout()
  36. {
  37. //validation
  38. if (_orderSettings.CheckoutDisabled)
  39. return RedirectToRoute("ShoppingCart");
  40.  
  41. var isTax = Request.Query["tax"].Count() > 0 && Request.Query["tax"][0] == "1";
  42. var cart = _workContext.CurrentCustomer.ShoppingCartItems
  43. .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
  44. .LimitPerStore(_storeContext.CurrentStore.Id)
  45. .ToList();
  46.  
  47. HttpContext.Session.Set(SESSION_ISTAX, isTax);
  48. cart = GetCartTaxNonTax(cart, isTax);
  49.  
  50. if (!cart.Any())
  51. return RedirectToRoute("ShoppingCart");
  52.  
  53. if (!_orderSettings.OnePageCheckoutEnabled)
  54. return RedirectToRoute("Checkout");
  55.  
  56. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  57. return Challenge();
  58.  
  59. var model = _checkoutModelFactory.PrepareOnePageCheckoutModel(cart);
  60. return View(model);
  61. }
  62.  
  63. private List<ShoppingCartItem> GetCartTaxNonTax(List<ShoppingCartItem> cart, bool isTax)
  64. {
  65. var productIdList = cart.Select(x => x.ProductId);
  66. var finalProductIdList = _productService.GetAllProducts(x => productIdList.Contains(x.Id) && x.IsTaxExempt == !isTax).Select(x => x.Id);
  67. cart = cart.Where(x => finalProductIdList.Contains(x.ProductId)).ToList();
  68. return cart;
  69. }
  70.  
  71. public IActionResult CreateOrder(int delayDate, FreebieModel[] freebies)
  72. {
  73. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  74. return RedirectToRoute("CheckoutOnePage");
  75.  
  76. try
  77. {
  78. var currentAddressId = HttpContext.Session.GetInt32("CurrentShippingAddressId") ?? _workContext.CurrentCustomer.ShippingAddressId ?? 0;
  79.  
  80. var dsCalPrice = HttpContext.Session.Get<DataSet>(SESSION_CALPRICE_OBJ);
  81. var orderTotal = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.TOTAL_AMOUNT].ToString().ToDecimal();
  82. var promotionDiscount = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.PRODUCT_DISCOUNT].ToString().ToDecimal();
  83. var commercialDiscount = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.TOTAL_DISCOUNT].ToString().ToDecimal();
  84. var totalDiscount = promotionDiscount + commercialDiscount;
  85. var shipping = dsCalPrice.Tables[OrderTableSchema.TABLE_HDR].Rows[0][OrderHDRSchema.FREIGHT].ToString().ToDecimal();
  86.  
  87. var processPaymentRequest = new ProcessPaymentRequest();
  88. processPaymentRequest.CustomValues.Add("DelayDate", delayDate);
  89. processPaymentRequest.CustomValues.Add("PaymentType", PaymentType.CreditTerm);
  90. processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditTerm.GetDescription();
  91. HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
  92. processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
  93. processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
  94. processPaymentRequest.IsTax = HttpContext.Session.Get<bool>(SESSION_ISTAX);
  95. processPaymentRequest.OrderTotal = orderTotal;
  96. //processPaymentRequest.CustomValues.Add("DeliveryTimePeriod", model.DeliveryPeriod);
  97. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT, promotionDiscount);
  98. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT, commercialDiscount);
  99. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT, totalDiscount);
  100. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERSHIPPINGTOTAL, shipping);
  101. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.SELECTSHIPPINGADDRESSID, currentAddressId);
  102.  
  103. // confirm order process
  104. var isTax = HttpContext.Session.Get<bool>(SESSION_ISTAX);
  105. var result = _orderProcessingService.PCGCreateOrder(dsCalPrice, processPaymentRequest, freebies, isTax);
  106.  
  107. if (result.Status != TaskStatus.RanToCompletion)
  108. {
  109. _logger.Error(result.Exception.Message, result.Exception);
  110. throw result.Exception;
  111. }
  112.  
  113. // get the order
  114. var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
  115. customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
  116. .FirstOrDefault();
  117.  
  118. if (order != null)
  119. {
  120. var orderCompleteModel = new CheckoutCompletedModel()
  121. {
  122. OrderId = order.Id,
  123. CustomOrderNumber = order.CustomOrderNumber,
  124. OnePageCheckoutEnabled = true,
  125. OrderDetailsModel = new Models.Order.OrderDetailsModel()
  126. {
  127. CustomOrderNumber = order.CustomOrderNumber
  128. }
  129. };
  130.  
  131. return Json(new { goto_uri = $"checkout/completed?orderid={order.Id}" });
  132. //return Redirect($"completed?orderid={order.Id}");
  133. }
  134.  
  135. return BadRequest("failed to create order!");
  136. }
  137. catch (Exception ex)
  138. {
  139. return RedirectToRoute("Error");
  140. }
  141. }
  142.  
  143. public virtual async Task<IActionResult> GetPrice(int delayDate)
  144. {
  145. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  146. return RedirectToRoute("CheckoutOnePage");
  147.  
  148. try
  149. {
  150. // customer
  151. var customer = _workContext.CurrentCustomer;
  152.  
  153. // get carts
  154. var carts = customer.ShoppingCartItems
  155. .WithOnlyShoppingCart().ToList();
  156.  
  157. var isTax = HttpContext.Session.Get<bool>(SESSION_ISTAX);
  158. carts = GetCartTaxNonTax(carts, isTax);
  159.  
  160. var currentAddressId = HttpContext.Session.GetInt32("CurrentShippingAddressId") ?? _workContext.CurrentCustomer.ShippingAddressId ?? 0;
  161. var selectedAddressNumber = _addressService.GetAddressById(currentAddressId).AddressNumber.HasValue ? _addressService.GetAddressById(currentAddressId).AddressNumber.Value : 1;
  162.  
  163. var gnerator = new PCGAPIModelGenerator();
  164. var dsRequest = gnerator.CreateCalPriceRequestModel(carts.ToArray(), customer, delayDate, isTax, selectedAddressNumber);
  165.  
  166. // calling orderprocessing service
  167. var dsResponse = await _orderProcessingService.PCGGetPrice(dsRequest);
  168. var result = gnerator.CreateCalPriceResponseModel(dsResponse);
  169.  
  170. if (result.HasError())
  171. throw new Exception(string.Join(", ", result.ErrorMessages()));
  172.  
  173. HttpContext.Session.Set(SESSION_CALPRICE_OBJ, dsResponse);
  174.  
  175. // retrive product info for freebies
  176. var freebiesSku = result.Freebies.Select(x => x.ProductCode);
  177. var freebieProduct = _productService.GetAllProducts(x => freebiesSku.Contains(x.Sku));
  178. foreach(var p in freebieProduct)
  179. {
  180. var o = result.Freebies.SingleOrDefault(x => x.ProductCode == p.Sku);
  181. if(o != null)
  182. {
  183. o.Name = p.Name;
  184. var imageUrl = p.ProductPictures?.ToList().Count > 0 ?_pictureService.GetPictureUrl(p.ProductPictures?.ToList()?[0].Picture, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage) : string.Empty;
  185. o.ImagePath = imageUrl;
  186. o.ProductId = p.Id;
  187. o.ShortName = p.ShortDescription;
  188. }
  189. }
  190.  
  191. var freebiesItemGroup = result.Freebies.GroupBy(u => u.PromotionCode).Select(g => g.ToList());
  192.  
  193. // response result
  194. return Json(new
  195. {
  196. header = new {
  197. ProductNet = result.OrderHeader.ProductNet.ToCurrencyFormat(),
  198. TotalAmount = result.OrderHeader.TotalAmount.ToCurrencyFormat(),
  199. ProductDiscount = result.OrderHeader.ProductDiscount.ToNegativeCurrencyFormat(),
  200. TotalDiscount = result.OrderHeader.TotalDiscount.ToNegativeCurrencyFormat(),
  201. GrandTotalDiscount = (result.OrderHeader.TotalDiscount + result.OrderHeader.ProductDiscount).ToNegativeCurrencyFormat(),
  202. TotalNet = result.OrderHeader.TotalNet.ToCurrencyFormat(),
  203. TotalProductVat = result.OrderHeader.TotalProductVat.ToCurrencyFormat(),
  204. TotalVat = result.OrderHeader.TotalVat.ToCurrencyFormat(),
  205. Freight = result.OrderHeader.Freight.ToNegativeCurrencyFormat(),
  206. FreebiesTotal = freebiesItemGroup.Sum(x => x?[0].FreeQuantity)
  207. },
  208. items = result.Orders.Select(x => new
  209. {
  210. PricePerUnit = x.PricePerUnit.ToString().ToCurrencyFormat(),
  211. PromotionDiscount = x.PromotionDiscount,
  212. TotalAmount = x.TotalAmount.ToString().ToCurrencyFormat(),
  213. Net = x.NetPrice.ToString().ToCurrencyFormat(),
  214. Sku = x.Sku,
  215. Qty = x.Qty,
  216. }),
  217. freebies = freebiesItemGroup
  218. });
  219. }
  220. catch (Exception ex)
  221. {
  222. return BadRequest($"failed to get order amount : {ex.Message}!");
  223. }
  224.  
  225. }
  226.  
  227. //protected CheckoutConfirmModel CpfmConfirmOrder()
  228. //{
  229. // var confirmOrderModel = new CheckoutConfirmModel();
  230. // try
  231. // {
  232. // //validation
  233. // if (_orderSettings.CheckoutDisabled)
  234. // throw new Exception(_localizationService.GetResource("Checkout.Disabled"));
  235.  
  236. // var cart = _workContext.CurrentCustomer.ShoppingCartItems
  237. // .WithOnlyShoppingCart()
  238. // .LimitPerStore(_storeContext.CurrentStore.Id)
  239. // .ToList();
  240. // if (!cart.Any())
  241. // throw new Exception("Your cart is empty");
  242.  
  243. // if (!_orderSettings.OnePageCheckoutEnabled)
  244. // throw new Exception("One page checkout is disabled");
  245.  
  246. // if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  247. // throw new Exception("Anonymous checkout is not allowed");
  248.  
  249. // //prevent 2 orders being placed within an X seconds time frame
  250. // if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
  251. // throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
  252.  
  253. // //place order
  254. // var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
  255. // if(processPaymentRequest == null)
  256. // throw new Exception("Payment information is not entered");
  257.  
  258. // processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
  259. // processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
  260.  
  261. // // process order
  262. // var orderResult = _orderProcessingService.PlaceCpfmOrder(processPaymentRequest);
  263.  
  264.  
  265. // // error
  266. // foreach (var error in orderResult.Errors)
  267. // confirmOrderModel.Warnings.Add(error);
  268.  
  269. // }
  270. // catch (Exception exc)
  271. // {
  272. // _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
  273. // confirmOrderModel.Warnings.Add(exc.Message);
  274. // }
  275.  
  276. // return confirmOrderModel;
  277. //}
  278.  
  279.  
  280. public virtual IActionResult CalculatePrice(int delayDate, DeliveryTimePeriod deliveryTimePeriod)
  281. {
  282. return Ok();
  283. }
  284.  
  285. [HttpPost, ActionName("CreateOrder")]
  286. public virtual IActionResult CreateOrderCustom(Models.Checkout.CreateOrderModel model)
  287. {
  288. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  289. return RedirectToRoute("CheckoutOnePage");
  290.  
  291. try
  292. {
  293.  
  294. var processPaymentRequest = CreateProcessRequest(model, PaymentType.CreditTerm);
  295. HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
  296.  
  297. // confirm order process
  298. var result = CpfmConfirmOrder();
  299. if (result.Warnings.Any())
  300. {
  301. return BadRequest(string.Join(", ", result.Warnings));
  302. }
  303.  
  304. // get the order
  305. var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
  306. customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
  307. .FirstOrDefault();
  308.  
  309. if (order != null)
  310. {
  311. var orderCompleteModel = new CheckoutCompletedModel()
  312. {
  313. OrderId = order.Id,
  314. CustomOrderNumber = order.CustomOrderNumber,
  315. OnePageCheckoutEnabled = true,
  316. OrderDetailsModel = new Models.Order.OrderDetailsModel()
  317. {
  318. CustomOrderNumber = order.CustomOrderNumber
  319. }
  320. };
  321.  
  322. return Json(new
  323. {
  324. goto_uri = Url.Action("Completed", "Checkout", new { id = order.Id, orderId = order.Id, customOrderNumber = order.CustomOrderNumber })
  325. });
  326. }
  327.  
  328. return BadRequest("failed to create order!");
  329. }
  330. catch (Exception ex)
  331. {
  332. return RedirectToRoute("Error");
  333. }
  334. }
  335.  
  336. [HttpPost]
  337. public virtual IActionResult CreateOrderWithCreditcard(Models.Checkout.CreateOrderModel model)
  338. {
  339. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  340. return RedirectToRoute("CheckoutOnePage");
  341.  
  342. try
  343. {
  344. var processPaymentRequest = CreateProcessRequest(model, PaymentType.CreditCard);
  345. var delayDate = (int)processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELAYDATE];
  346.  
  347. // customer
  348. var customer = _workContext.CurrentCustomer;
  349.  
  350. // get carts
  351. var carts = customer.ShoppingCartItems
  352. .WithOnlyShoppingCart().ToArray();
  353.  
  354. // calling orderprocessing service
  355. var orderTotal = _orderProcessingService.CalculationCpfmConfrimPrice(carts, customer, delayDate).Result.GetNetPrice();
  356. var paymentResponse = KbankPayment(orderTotal, _workContext.CurrentCustomer.Username);
  357.  
  358. if (paymentResponse.IsPreAuthorizeSuccess)
  359. {
  360. processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.AUTHORIZATIONTRANSACTIONID] = paymentResponse.id;
  361. var orderResult = _orderProcessingService.CreatePendingOrder(processPaymentRequest);
  362.  
  363. if (orderResult.Success)
  364. {
  365. #if DEBUG
  366. #else
  367. return Redirect(paymentResponse.redirect_url);
  368. #endif
  369. }
  370. else
  371. {
  372. _logger.Error($"Kbank create pending order fail : {string.Join(",", orderResult.Errors)}");
  373. TempData["Error"] = "Cannot create order!";
  374. TempData[ProcessPaymentRequestCustomKey.DELAYDATE] = (int)processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELAYDATE];
  375. TempData[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD] = processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
  376. return RedirectToAction("onepagecheckout");
  377. }
  378.  
  379. #if DEBUG
  380. processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.AUTHORIZATIONTRANSACTIONID] = "chrg_test_202515f473de5e80c46628af5db662e02834e";
  381.  
  382. var kbankCallbackJson = "{\"objectid\":\"chrg_test_202515f473de5e80c46628af5db662e02834e\",\"status\":\"true\",\"token\":\"tokn_test_20251f7ae68e5bfbcdc90d71077bc8da9f18b\",\"savecard\":\"false\"}";
  383. var cli = new WebClient();
  384. cli.Headers[HttpRequestHeader.ContentType] = "application/json";
  385. string response = cli.UploadString("http://store1.wecpg-localhost.com/cpfm/checkout/kbankcallback", "POST", kbankCallbackJson);
  386.  
  387. return Json("kbankCallback Done");
  388. #endif
  389. }
  390. else
  391. {
  392. _logger.Error($"Kbank Card charge fail : {paymentResponse.failure_code} , {paymentResponse.failure_message}");
  393. TempData["Error"] = "Invalid or unauthorize credit card!";
  394. TempData[ProcessPaymentRequestCustomKey.DELAYDATE] = (int)processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELAYDATE];
  395. TempData[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD] = processPaymentRequest.CustomValues[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
  396. return RedirectToAction("onepagecheckout");
  397. }
  398.  
  399. }
  400. catch (Exception ex)
  401. {
  402. return RedirectToRoute("Error");
  403. }
  404. }
  405.  
  406. [HttpPost]
  407. [CheckAccessClosedStore(true)]
  408. [CheckAccessPublicStore(true)]
  409. public IActionResult KbankCallback(KbankCallbackRequest req)
  410. {
  411. _logger.InsertLog(Core.Domain.Logging.LogLevel.Debug, $"Calling {nameof(KbankCallback)}");
  412.  
  413. var jsonStr = JsonConvert.SerializeObject(req);
  414.  
  415. try
  416. {
  417. // get the order
  418. var order = _orderService.GetOrderByAuthorizationTransactionIdAndPaymentMethod(req.objectid, PaymentType.CreditCard.GetDescription());
  419. var customValues = XmlHelper.Deserialize<Dictionary<string, object>>(order.CustomValuesXml);
  420. #if DEBUG
  421. _logger.Information($"checkout - KbankPaymentCallbackModel: {JsonConvert.SerializeObject(req)}");
  422.  
  423. if (true)
  424. #else
  425. if (req?.status?.ToLower() == "true" && req?.objectid == order?.AuthorizationTransactionId)
  426. #endif
  427. {
  428. var cart = _workContext.CurrentCustomer.ShoppingCartItems
  429. .WithOnlyShoppingCart()
  430. .LimitPerStore(_storeContext.CurrentStore.Id)
  431. .ToList();
  432.  
  433. //Check whether payment workflow is required
  434. if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
  435. {
  436. throw new Exception("Payment information is not entered");
  437. }
  438.  
  439. var processPaymentRequest = new ProcessPaymentRequest()
  440. {
  441. CustomerId = order.CustomerId,
  442. StoreId = order.StoreId,
  443. CustomValues = customValues
  444. };
  445.  
  446. // process order
  447. var result = _orderProcessingService.ConfirmPendingOrder(order, processPaymentRequest);
  448.  
  449. if (result.Errors.Any())
  450. {
  451. return BadRequest(string.Join(", ", result.Errors));
  452. }
  453. else
  454. {
  455. return RedirectToAction("Completed", "Checkout", new { id = order.Id, orderId = order.Id, customOrderNumber = order.CustomOrderNumber });
  456. }
  457. }
  458. else
  459. {
  460. _logger.Error($"Kbank Card OTP confirm fail with status: {req.status}, objectid: {req.objectid}");
  461. TempData[ProcessPaymentRequestCustomKey.DELAYDATE] = (int)customValues[ProcessPaymentRequestCustomKey.DELAYDATE];
  462. TempData[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD] = customValues[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
  463. TempData["Error"] = "Invalid OTP or user cancel payment!";
  464. return RedirectToAction("onepagecheckout");
  465. }
  466. }
  467. catch (Exception ex)
  468. {
  469. _logger.Error(ex.Message, ex);
  470. }
  471.  
  472. _logger.InsertLog(Core.Domain.Logging.LogLevel.Debug, $"Calling {nameof(KbankCallback)} Done!", jsonStr);
  473.  
  474. return RedirectToAction("Index");
  475. }
  476.  
  477. private ProcessPaymentRequest CreateProcessRequest(Models.Checkout.CreateOrderModel model, PaymentType paymentType)
  478. {
  479. var processPaymentRequest = new ProcessPaymentRequest();
  480.  
  481. try
  482. {
  483. if (paymentType == PaymentType.CreditTerm)
  484. {
  485. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELAYDATE, model.DelayDate);
  486. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD, model.DeliveryPeriod);
  487. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.PAYMENTTYPE, PaymentType.CreditTerm);
  488.  
  489. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT, model.OrderPromotionDiscount);
  490. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT, model.OrderCommercialDiscount);
  491. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOUPONDISCOUNT, model.OrderCouponDiscount);
  492. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT, model.OrderTotalDiscount);
  493. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERSHIPPINGTOTAL, 0);
  494.  
  495. processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditTerm.GetDescription();
  496.  
  497. }
  498. else
  499. {
  500.  
  501. var delayDateStr = Request.Form[ProcessPaymentRequestCustomKey.DELAYDATE];
  502. var deliveryPeriodStr = Request.Form[ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD];
  503. var orderPromotionDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT];
  504. var orderCommercialDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT];
  505. var orderCouponDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERCOUPONDISCOUNT];
  506. var orderTotalDiscountStr = Request.Form[ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT];
  507.  
  508. var delayDate = string.IsNullOrEmpty(delayDateStr) ? 0 : delayDateStr.ToString().ToInt();
  509. var deliveryPeriod = string.IsNullOrEmpty(deliveryPeriodStr) ? 0 : deliveryPeriodStr.ToString().ToInt();
  510. var orderPromotionDiscount = string.IsNullOrEmpty(orderPromotionDiscountStr) ? 0 : orderPromotionDiscountStr.ToString().ToInt();
  511. var orderCommercialDiscount = string.IsNullOrEmpty(orderCommercialDiscountStr) ? 0 : orderCommercialDiscountStr.ToString().ToInt();
  512. var orderCouponDiscount = string.IsNullOrEmpty(orderCouponDiscountStr) ? 0 : orderCouponDiscountStr.ToString().ToInt();
  513. var orderTotalDiscount = string.IsNullOrEmpty(orderTotalDiscountStr) ? 0 : orderTotalDiscountStr.ToString().ToInt();
  514.  
  515. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELAYDATE, delayDate);
  516. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.DELIVERYTIMEPERIOD, deliveryPeriod);
  517. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.PAYMENTTYPE, PaymentType.CreditCard);
  518. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERPROMOTIONDISCOUNT, orderPromotionDiscount);
  519. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOMMERCIALDISCOUNT, orderCommercialDiscount);
  520. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERCOUPONDISCOUNT, orderCouponDiscount);
  521. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERTOTALDISCOUNT, orderTotalDiscount);
  522. processPaymentRequest.CustomValues.Add(ProcessPaymentRequestCustomKey.ORDERSHIPPINGTOTAL, 0);
  523. processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
  524. processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
  525. processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditCard.GetDescription();
  526. }
  527. }
  528. catch (Exception ex)
  529. {
  530. _logger.Error(ex.Message, ex);
  531. }
  532.  
  533. return processPaymentRequest;
  534. }
  535.  
  536. public virtual IActionResult CreateOrder(int delayDate, DeliveryTimePeriod deliveryPeriod)
  537. {
  538. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  539. return RedirectToRoute("CheckoutOnePage");
  540.  
  541. try
  542. {
  543.  
  544. var processPaymentRequest = new ProcessPaymentRequest();
  545. processPaymentRequest.CustomValues.Add("DelayDate", delayDate);
  546. processPaymentRequest.CustomValues.Add("DeliveryTimePeriod", deliveryPeriod);
  547. processPaymentRequest.CustomValues.Add("PaymentType", PaymentType.CreditTerm);
  548. processPaymentRequest.PaymentMethodSystemName = PaymentType.CreditTerm.GetDescription();
  549.  
  550.  
  551. HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
  552.  
  553. // confirm order process
  554. var result = CpfmConfirmOrder();
  555. if (result.Warnings.Any())
  556. {
  557. return BadRequest(string.Join(", ", result.Warnings));
  558. }
  559.  
  560. // get the order
  561. var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
  562. customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
  563. .FirstOrDefault();
  564.  
  565. if (order != null)
  566. {
  567. var orderCompleteModel = new CheckoutCompletedModel()
  568. {
  569. OrderId = order.Id,
  570. CustomOrderNumber = order.CustomOrderNumber,
  571. OnePageCheckoutEnabled = true,
  572. OrderDetailsModel = new Models.Order.OrderDetailsModel()
  573. {
  574. CustomOrderNumber = order.CustomOrderNumber
  575. }
  576. };
  577.  
  578. return Json(new
  579. {
  580. goto_uri = Url.Action("Completed", "Checkout", new { id = order.Id, orderId = order.Id, customOrderNumber = order.CustomOrderNumber })
  581. });
  582. }
  583.  
  584. return BadRequest("failed to create order!");
  585. }
  586. catch(Exception ex)
  587. {
  588. return RedirectToRoute("Error");
  589. }
  590.  
  591. }
  592.  
  593. public virtual async Task<IActionResult> GetCpfmConfirmPrice(int delayDate)
  594. {
  595. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  596. return RedirectToRoute("CheckoutOnePage");
  597.  
  598. try
  599. {
  600. // get the order
  601. var order = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id,
  602. customerId: _workContext.CurrentCustomer.Id, pageSize: 1)
  603. .FirstOrDefault();
  604.  
  605. // customer
  606. var customer = _workContext.CurrentCustomer;
  607.  
  608. // get carts
  609. var carts = customer.ShoppingCartItems
  610. .WithOnlyShoppingCart().ToArray();
  611.  
  612. // calling orderprocessing service
  613. var result = await _orderProcessingService.CalculationCpfmConfrimPrice(carts, customer, delayDate);
  614.  
  615. if (result.HasError())
  616. throw new Exception(string.Join(", " ,result.ErrorMessages()));
  617.  
  618. // response result
  619. return Json(new
  620. {
  621. GrossPrice = result.GetGrossPrice().ToCurrencyFormat(),
  622. TradeDiscount = result.GetTradeDiscount().ToNegativeCurrencyFormat(),
  623. PromotionDiscount = result.GetPromotionDiscount().ToNegativeCurrencyFormat(),
  624. CouponDiscount = result.GetCouponDiscount().ToNegativeCurrencyFormat(),
  625. TotalDiscount = result.GetTotalDiscount().ToNegativeCurrencyFormat(),
  626. ShippingFee = 0,
  627. NetPrice = result.GetNetPrice().ToCurrencyFormat()
  628. });
  629. }
  630. catch (Exception ex)
  631. {
  632. return BadRequest($"failed to get order amount : {ex.Message}!");
  633. }
  634.  
  635. }
  636.  
  637. protected CheckoutConfirmModel CpfmConfirmOrder()
  638. {
  639. var confirmOrderModel = new CheckoutConfirmModel();
  640. try
  641. {
  642. //validation
  643. if (_orderSettings.CheckoutDisabled)
  644. throw new Exception(_localizationService.GetResource("Checkout.Disabled"));
  645.  
  646. var cart = _workContext.CurrentCustomer.ShoppingCartItems
  647. .WithOnlyShoppingCart()
  648. .LimitPerStore(_storeContext.CurrentStore.Id)
  649. .ToList();
  650. if (!cart.Any())
  651. throw new Exception("Your cart is empty");
  652.  
  653. if (!_orderSettings.OnePageCheckoutEnabled)
  654. throw new Exception("One page checkout is disabled");
  655.  
  656. if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
  657. throw new Exception("Anonymous checkout is not allowed");
  658.  
  659. //prevent 2 orders being placed within an X seconds time frame
  660. if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
  661. throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
  662.  
  663. //place order
  664. var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
  665. if(processPaymentRequest == null)
  666. throw new Exception("Payment information is not entered");
  667.  
  668. processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
  669. processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
  670.  
  671. // process order
  672. var orderResult = _orderProcessingService.PlaceCpfmOrder(processPaymentRequest);
  673.  
  674.  
  675. // error
  676. foreach (var error in orderResult.Errors)
  677. confirmOrderModel.Warnings.Add(error);
  678.  
  679. }
  680. catch (Exception exc)
  681. {
  682. _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
  683. confirmOrderModel.Warnings.Add(exc.Message);
  684. }
  685.  
  686. return confirmOrderModel;
  687. }
  688.  
  689. private KbankCardResponse KbankPayment(decimal orderTotal, string cvNo)
  690. {
  691. //model
  692. var cardChargeRequest = CreateKbankPaymentRequest(orderTotal, cvNo);
  693.  
  694. return null;
  695. }
  696.  
  697. private KbankCardRequest CreateKbankPaymentRequest(decimal orderTotal, string cvNo)
  698. {
  699. var req = new KbankCardRequest();
  700.  
  701. // Get the payment token ID submitted by the form:
  702. string token = Request.Form["token"];
  703.  
  704. var orderTime = DateTime.Now.ToString("ddMMyyyy-HHmmss");
  705.  
  706. ///buid request parameter
  707. req.amount = orderTotal;
  708. req.currency = "THB";
  709. req.description = $"CPFM_{cvNo}_{orderTime}";
  710. req.source_type = "card";
  711. req.mode = "token";
  712. req.token = token;
  713. req.reference_order = $"CPFM_{cvNo}_{orderTime}";
  714. req.ref_1 = "CPFM";
  715. req.ref_2 = cvNo;
  716. req.ref_2 = orderTime;
  717.  
  718. return req;
  719. }
  720. }
  721. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement