TransactionsService.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. using Fuel.Core.Transactions.Dto;
  2. using Microsoft.AspNetCore.Http;
  3. using Newtonsoft.Json;
  4. using FuelServer.Core.Entity;
  5. using System.Linq.Expressions;
  6. using Fuel.Core.Models;
  7. using System.Net;
  8. using Fuel.Payment.Service.Pay;
  9. using DFS.Core.Abstractions.View;
  10. using Fuel.Core;
  11. using System;
  12. using System.Transactions;
  13. using Fuel.Core.WechatServer;
  14. using Fuel.Core.Nozzle.Dto;
  15. using Fuel.Application.MqttService;
  16. using Org.BouncyCastle.Asn1.X509;
  17. using Jayrock.Json;
  18. using Fuel.Core.Transactions;
  19. using Microsoft.Extensions.DependencyInjection;
  20. using static Fuel.Core.WechatServer.WeChatService;
  21. using System.Linq.Dynamic.Core;
  22. using System.Text.Json;
  23. using Org.BouncyCastle.Asn1.Ocsp;
  24. namespace Fuel.Application.Service
  25. {
  26. public class TransactionsService : ITransactionsService
  27. {
  28. private readonly EntityHelper _entityHelper;
  29. private readonly IHttpContextAccessor _httpContextAccessor;
  30. private readonly IPayService _payService;
  31. public readonly IFreeSql _fsql;
  32. private readonly IMqttClientService _mqttService;
  33. private readonly IServiceScopeFactory _serviceScopeFactory;
  34. static NLog.Logger logger = NLog.LogManager.LoadConfiguration("nlog.xml").GetLogger("Main");
  35. public TransactionsService(EntityHelper entityHelper, IHttpContextAccessor httpContextAccessor, IPayService payService, IFreeSql fsql, IMqttClientService mqttService, IServiceScopeFactory serviceScopeFactory)
  36. {
  37. _entityHelper = entityHelper;
  38. _httpContextAccessor = httpContextAccessor;
  39. _payService = payService;
  40. _fsql = fsql;
  41. _mqttService = mqttService;
  42. _serviceScopeFactory = serviceScopeFactory;
  43. }
  44. /// <summary>
  45. /// 创建订单
  46. /// </summary>
  47. /// <param name="uploadTransactions"></param>
  48. /// <returns></returns>
  49. public async Task<ServiceResponse> CreateTransactions(UploadTransactions uploadTransactions)
  50. {
  51. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  52. var site = _fsql.Select<businessunitinfo>().Where(_ => _.Buid == Buid).First();
  53. if (site == null)
  54. {
  55. return ServiceResponse.Error("站点信息查询为空 buid: " + Buid);
  56. }
  57. string key = string.Empty;
  58. var _product = await _entityHelper.GetEntitiesAsync<product>(_ => _.Buid == Buid && _.ProductName == uploadTransactions.Product);
  59. if (_product.Count() <= 0)
  60. {
  61. return ServiceResponse.Error("油品查询失败,油品名称:" + uploadTransactions.Product);
  62. }
  63. var _nozzle = await _entityHelper.GetEntitiesAsync<nozzle>(_ => _.Buid == Buid && _.ExternalGunNumber == uploadTransactions.ExternalGunNumber);
  64. if (_nozzle.Count() <= 0)
  65. {
  66. return ServiceResponse.Error("油枪查询失败,油枪名称:" + uploadTransactions.ExternalGunNumber);
  67. }
  68. if (site.PaymentMode == 1)//预支付
  69. {
  70. key = uploadTransactions.ExternalGunNumber + ":" +
  71. uploadTransactions.OriginalAmount + ":" +
  72. uploadTransactions.Qty + ":" +
  73. uploadTransactions.MiniProgramID + ":" +
  74. Buid.ToString();
  75. string WachatID = HttpRequestReader.GetWachatID(); //用户
  76. var userSession = WechatUserSessionRepo.GetUserSession(WachatID.ToString());
  77. if (userSession == null)
  78. {
  79. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "未找到用户!");
  80. }
  81. var user = _fsql.Select<miniprogramusers>().Where(_ => _.OpenId == userSession.openid).First();
  82. if (uploadTransactions.OriginalAmount != null)
  83. {
  84. decimal decimalValue = uploadTransactions.OriginalAmount.HasValue ? uploadTransactions.OriginalAmount.Value : 0m;
  85. decimal ProductPrice = _product.First().ProductPrice.HasValue ? _product.First().ProductPrice.Value : 0m;
  86. decimal qty = decimalValue / ProductPrice;
  87. uploadTransactions.Qty = qty;
  88. //订单金额不能小于2元、订单金额不能大于9900元
  89. if (uploadTransactions.OriginalAmount < 2 || uploadTransactions.OriginalAmount > 9900)
  90. {
  91. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "订单金额不能小于2元、订单金额不能大于9900元");
  92. }
  93. }
  94. else if (uploadTransactions.Qty != null)
  95. {
  96. decimal decimalValue = uploadTransactions.Qty.HasValue ? uploadTransactions.Qty.Value : 0m;
  97. decimal ProductPrice = _product.First().ProductPrice.HasValue ? _product.First().ProductPrice.Value : 0m;
  98. decimal OriginalAmount = decimalValue * ProductPrice;
  99. uploadTransactions.OriginalAmount = OriginalAmount;
  100. if (uploadTransactions.Qty < 1 || OriginalAmount > 9900)
  101. {
  102. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "升数不能小于1升,订单升数乘单价不能大于9900元");
  103. }
  104. }
  105. else if (uploadTransactions.OriginalAmount == null && uploadTransactions.Qty == null)
  106. {
  107. return ServiceResponse.Error("金额与升数为空");
  108. }
  109. uploadTransactions.MiniProgramID = user.Id;
  110. }
  111. else//后支付
  112. {
  113. key = uploadTransactions.ExternalGunNumber + ":" +
  114. uploadTransactions.OriginalAmount + ":" +
  115. uploadTransactions.Qty + ":" +
  116. uploadTransactions.MiniProgramID + ":" +
  117. uploadTransactions.FuelItemTransactionEndTime + ":" +
  118. uploadTransactions.TransactionNumber + ":" +
  119. Buid.ToString();
  120. }
  121. transactions output = await GetRedisTransactions(uploadTransactions, key);
  122. if (output != null)
  123. {
  124. return ServiceResponse.Ok(output);
  125. }
  126. var trx = uploadTransactions.ToTransactions(uploadTransactions, Buid, _product.FirstOrDefault(), _nozzle.FirstOrDefault(), site.PaymentMode);
  127. //int affectedRows = _fsql.Insert<transactions>().AppendData(trx).ExecuteAffrows();
  128. // var affectedRows = _fsql.Insert<transactions>().AppendData(trx).ExecuteInserted();
  129. var id = _fsql.Insert(trx).ExecuteIdentity();
  130. if (id > 0)
  131. {
  132. var insertedTransaction = _fsql.Select<transactions>()
  133. .Where(t => t.Id == id)
  134. .First();
  135. string jsonString = JsonConvert.SerializeObject(insertedTransaction);
  136. RedisHelper.SetAsync(key, jsonString, 600);
  137. return ServiceResponse.Ok(insertedTransaction);
  138. }
  139. else
  140. {
  141. return ServiceResponse.Error("订单信息插入失败");
  142. }
  143. }
  144. public async Task<ServiceResponse> GetTransactionsAsync(RequestModel input)
  145. {
  146. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  147. var site = _fsql.Select<businessunitinfo>().Where(_ => _.Buid == Buid).First();
  148. var _nozzle = _fsql.Select<nozzle>().ToList();//根据油枪id查询外部枪号
  149. var user = _fsql.Select<miniprogramusers>().ToList();
  150. var paytype = _fsql.Select<paytype>().ToList();
  151. Expression<Func<transactions, bool>> where = p => p.Buid == Buid;
  152. if (input.filter.NozzleID != "")
  153. {
  154. long.TryParse(input.filter.NozzleID, out long NozzleID);
  155. var nozzle = _nozzle.Where(_ => _.ExternalGunNumber == NozzleID).First();//根据油枪id查询外部枪号
  156. where = CombineExpressions(where, p => p.NozzleId == nozzle.Id);
  157. }
  158. if (input.filter.ProductName != "")
  159. {
  160. where = CombineExpressions(where, p => p.ProductName == input.filter.ProductName);
  161. }
  162. if (input.filter.siteName != "")
  163. {
  164. where = CombineExpressions(where, p => p.Buid == site.Buid);
  165. }
  166. if (input.filter.username != "")
  167. {
  168. var userid = user.Where(_ => _.UserName == input.filter.username).First();
  169. where = CombineExpressions(where, p => p.MiniProgramID == userid.Id);
  170. }
  171. //if (input.TransactionETime != null)
  172. //{
  173. // where = CombineExpressions(where, p => p.TransactionTime == input.TransactionETime);
  174. //}
  175. var result = await _entityHelper.GetEntitiesAsync<transactions>(where);
  176. List<TransactionsList> list = new List<TransactionsList>();
  177. foreach (var item in result)
  178. {
  179. // var nozzle = _nozzle.Where(_ => _.Id == item.NozzleId)?.First();//根据油枪id查询外部枪号
  180. var nozzle = _nozzle.FirstOrDefault(_ => _.Id == item.NozzleId);//根据油枪id查询外部枪号
  181. var pay = paytype.FirstOrDefault(_ => _.Id == item.PaymentMethod)?.Name;
  182. TransactionsList transactions = new TransactionsList();
  183. transactions.TransactionNumber = item.TransactionNumber;
  184. transactions.SiteName = site.Name;
  185. transactions.NozzleProductName = item.NozzleId + " | " + item.ProductName;
  186. transactions.ActualPaymentAmount = item.ActualPaymentAmount.ToString();
  187. transactions.TransactionTime = item.TransactionTime?.ToString("yyyy-MM-dd hh:mm:ss");
  188. transactions.OrderStatus = GetChineseStatus(item.OrderStatus);
  189. transactions.RefundAmount = item.RefundAmount;
  190. if (item.MiniProgramID != null)
  191. {
  192. var userid = user.Where(_ => _.Id == item.MiniProgramID).FirstOrDefault();
  193. transactions.UserName = userid?.UserName;
  194. }
  195. transactions.PriceQty = item.Price + " | " + item.Qty;
  196. transactions.PaymentMethod = pay;
  197. list.Add(transactions);
  198. }
  199. return ServiceResponse.Ok(list);
  200. }
  201. /// <summary>
  202. /// 小程序查询未支付订单
  203. /// </summary>
  204. /// <returns></returns>
  205. public async Task<ServiceResponse> GetMiniProgramTransactionsUnpaidAsync(TransactionsInput input)
  206. {
  207. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  208. Expression<Func<transactions, bool>> where = p => p.Buid == Buid;
  209. string WachatID = HttpRequestReader.GetWachatID(); //用户
  210. var userSession = WechatUserSessionRepo.GetUserSession(WachatID.ToString());
  211. if (userSession == null)
  212. {
  213. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "未找到用户!");
  214. }
  215. DateTime dayBeforeTime = DateTime.Now.AddDays(-1);
  216. var user = _fsql.Select<miniprogramusers>().Where(_ => _.OpenId == userSession.openid).First();
  217. where = CombineExpressions(where, p => p.MiniProgramID == user.Id && p.OrderStatus == transactionsORDERSTATUS.Unpaid && p.TransactionTime >= dayBeforeTime);
  218. var result = await _entityHelper.GetEntitiesAsync<transactions>(where);
  219. result = result.OrderByDescending(x => x.CreateTime).ToList();
  220. return ServiceResponse.Ok(result);
  221. }
  222. /// <summary>
  223. /// 小程序用户根据抢号查询未支付订单
  224. /// </summary>
  225. /// <returns></returns>
  226. public async Task<ServiceResponse> GetMiniProgramTransactionsUnpaidNozzleAsync(long NozzleId)
  227. {
  228. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  229. Expression<Func<transactions, bool>> where = p => p.Buid == Buid;
  230. string WachatID = HttpRequestReader.GetWachatID(); //用户
  231. var userSession = WechatUserSessionRepo.GetUserSession(WachatID.ToString());
  232. if (userSession == null)
  233. {
  234. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "未找到用户!");
  235. }
  236. DateTime dayBeforeTime = DateTime.Now.AddDays(-1);
  237. var _nozzle = _fsql.Select<nozzle>().Where(_ => _.Id == NozzleId).First();//根据油枪id查询外部枪号
  238. where = CombineExpressions(where, p => p.NozzleId == _nozzle.ExternalGunNumber && p.OrderStatus == transactionsORDERSTATUS.Unpaid && p.TransactionTime >= dayBeforeTime);
  239. var result = await _entityHelper.GetEntitiesAsync<transactions>(where);
  240. result = result.OrderByDescending(x => x.CreateTime).ToList();
  241. return ServiceResponse.Ok(result);
  242. }
  243. /// <summary>
  244. /// 小程序查询已支付订单
  245. /// </summary>
  246. /// <returns></returns>
  247. public async Task<ServiceResponse> GetMiniProgramTransactionsPaidAsync(TransactionsInput input)
  248. {
  249. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  250. Expression<Func<transactions, bool>> where = p => p.Buid == Buid;
  251. string WachatID = HttpRequestReader.GetWachatID(); //用户
  252. var userSession = WechatUserSessionRepo.GetUserSession(WachatID.ToString());
  253. if (userSession == null)
  254. {
  255. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "未找到用户!");
  256. }
  257. var user = _fsql.Select<miniprogramusers>().Where(_ => _.OpenId == userSession.openid).First();
  258. where = CombineExpressions(where, p => p.MiniProgramID == user.Id && p.OrderStatus == transactionsORDERSTATUS.Paid);
  259. var result = await _entityHelper.GetEntitiesAsync<transactions>(where);
  260. return ServiceResponse.Ok(result);
  261. }
  262. /// <summary>
  263. /// 小程序查询已支付订单
  264. /// </summary>
  265. /// <returns></returns>
  266. public async Task<ServiceResponse> WXFindOrders(DateTime? dateTime, int pageNum, int lineCount)
  267. {
  268. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  269. Expression<Func<transactions, bool>> where = p => p.Buid == Buid;
  270. string WachatID = HttpRequestReader.GetWachatID(); //用户
  271. var userSession = WechatUserSessionRepo.GetUserSession(WachatID.ToString());
  272. if (userSession == null)
  273. {
  274. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "未找到用户!");
  275. }
  276. var user = _fsql.Select<miniprogramusers>().Where(_ => _.OpenId == userSession.openid).First();
  277. DateTime time = dateTime != null ? (DateTime)dateTime : DateTime.Now;
  278. var select = _fsql.Select<transactions>().Where(_ => _.MiniProgramID == user.Id
  279. && (_.TransactionTime >= DateTime.Now.AddDays(-30) && _.TransactionTime <= time));
  280. var list = await select.Page(pageNum, lineCount).OrderByDescending(_ => _.TransactionTime).ToListAsync();
  281. return ServiceResponse.Ok(list);
  282. }
  283. /// <summary>
  284. /// 提交支付
  285. /// </summary>
  286. /// <param name="input"></param>
  287. /// <returns></returns>
  288. public async Task<ServiceResponse> CommitPayment(int trxId, string AuthCode)
  289. {
  290. bool paymentOK = false;
  291. var trx = _entityHelper.GetEntitiesAsync<transactions>(_ => _.Id == trxId).Result.FirstOrDefault();
  292. if (trx == null)
  293. {
  294. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "未查询到订单!");
  295. }
  296. var paytype = _entityHelper.GetEntitiesAsync<paytype>(_ => _.Id == trx.PaymentMethod).Result.FirstOrDefault();
  297. string billNumber = SequenceNumber.Next();//订单编号
  298. trx.TransactionNumber = billNumber;
  299. decimal payDueAmount = (decimal)trx.OriginalAmount;
  300. string Channel = paytype.Channel;
  301. var serviceResult = await _payService.PerformElectronicProcess(AuthCode, payDueAmount, billNumber);
  302. Payment.Core.Models.ElectronicOrderProcessResultModel payResult = (Payment.Core.Models.ElectronicOrderProcessResultModel)serviceResult.Data;
  303. if (!serviceResult.IsSuccessful() || payResult.ResultCode == "PAY_ERROR")
  304. {
  305. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "支付失败");
  306. }
  307. trx.ActualPaymentAmount = payDueAmount;//实际支付金额
  308. trx.ResultCode = payResult?.ResultCode;//支付成功应该为0
  309. trx.ErrorDetail = payResult?.ErrorDetail;
  310. _entityHelper.UpdateAsync(trx);
  311. return ServiceResponse.Ok(trx);
  312. }
  313. /// <summary>
  314. /// 查询redis订单缓存
  315. /// </summary>
  316. /// <returns></returns>
  317. public async Task<transactions> GetRedisTransactions(UploadTransactions uploadTransactions, string key)
  318. {
  319. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  320. var respond = RedisHelper.GetAsync(key).Result;
  321. if (respond == null)
  322. {
  323. return null;
  324. }
  325. transactions transactions = JsonConvert.DeserializeObject<transactions>(respond);
  326. var trx = _entityHelper.GetEntitiesAsync<transactions>(_ => _.Id == transactions.Id).Result.FirstOrDefault();
  327. if (trx == null || trx.OrderStatus != transactionsORDERSTATUS.Unpaid)
  328. {
  329. return null;
  330. }
  331. return transactions;
  332. }
  333. // 辅助方法:组合两个表达式
  334. private static Expression<Func<T, bool>> CombineExpressions<T>(Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
  335. {
  336. ParameterExpression param = expr1.Parameters[0];
  337. Expression body = Expression.AndAlso(expr1.Body, Expression.Invoke(expr2, param));
  338. return Expression.Lambda<Func<T, bool>>(body, param);
  339. }
  340. /// <summary>
  341. /// 退款
  342. /// </summary>
  343. /// <param name="input"></param>
  344. /// <returns></returns>
  345. public async Task<ServiceResponse> RefundTrx(int trxId,
  346. decimal? OriginalQty = null)
  347. {
  348. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  349. var businessunitinfo = _entityHelper.GetEntitiesAsync<businessunitinfo>(_ => _.Buid == Buid).Result.FirstOrDefault();
  350. if (businessunitinfo == null)
  351. {
  352. logger.Debug($"RefundTrx,退款失败,站点为空,Buid={Buid} ,trxId={trxId}");
  353. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "站点为空");
  354. }
  355. string[] parts = businessunitinfo.GpsCoordinates.Split(',');
  356. // if (parts.Length == 2 &&
  357. //double.TryParse(parts[0], out double latitude2) &&
  358. //double.TryParse(parts[1], out double longitude2))
  359. // {
  360. // }
  361. // else
  362. // {
  363. // return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "站点经纬度获取失败");
  364. // }
  365. // //计算调用方和油站的距离,超过距离判定为恶意请求
  366. // double distance = DistanceCalculator.CalculateDistance(longitude, latitude, longitude2, latitude2);
  367. // if (distance > 5)
  368. // {
  369. // return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "该请求大于油站地址5公里");
  370. // }
  371. var trx = _entityHelper.GetEntitiesAsync<transactions>(_ => _.Id == trxId).Result.FirstOrDefault();
  372. if (trx == null)
  373. {
  374. logger.Debug($"退款失败,未查询到订单,Buid={Buid} ,trxId={trxId}");
  375. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "未查询到订单!");
  376. }
  377. else if (trx.RefundStatus == RefundStatus.FullyRefunded)
  378. {
  379. logger.Debug($"该订单已退款,未查询到订单,Buid={Buid} ,trxId={trxId}");
  380. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "该订单已退款");
  381. }
  382. else if (trx.RefundStatus == RefundStatus.PartiallyRefunded)
  383. {
  384. logger.Debug($"该订单已部分退款,Buid={Buid} ,trxId={trxId}");
  385. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "该订单已部分退款");
  386. }
  387. else if (trx.OrderStatus == transactionsORDERSTATUS.Unpaid)
  388. {
  389. logger.Debug($"该订单已退款,该订单未支付,Buid={Buid} ,trxId={trxId}");
  390. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "该订单未支付");
  391. }
  392. //获取单价
  393. decimal? ProductPrice = _entityHelper.GetEntitiesAsync<product>(_ => _.Id == trx.ProductId).Result.FirstOrDefault().ProductPrice;
  394. if (ProductPrice == null)
  395. {
  396. logger.Debug($"该订单已退款,单价获取失败,Buid={Buid} ,trxId={trxId}");
  397. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "单价获取失败");
  398. }
  399. //计算退款金额
  400. //decimal RefundAmount = (decimal)trx.ActualPaymentAmount;
  401. decimal RefundAmount = 0.0M;
  402. if (businessunitinfo.PaymentMode == 0)//后支付
  403. {
  404. logger.Debug($"后支付模式无法退款!,Buid={Buid} ,trxId={trxId}");
  405. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "后支付模式无法退款!");
  406. // RefundAmount = (decimal)((trx.Qty - trx.OriginalQty) * ProductPrice.Value);
  407. }
  408. else if (businessunitinfo.PaymentMode == 1)//预支付
  409. {
  410. decimal volume = OriginalQty ?? 0m;
  411. RefundAmount = (decimal)((trx.Qty - volume) * trx.Price);
  412. //RefundAmount = (decimal)((trx.Qty - OriginalQty) * ProductPrice.Value);
  413. }
  414. if (RefundAmount <= 0.0M)
  415. {
  416. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "该笔单无需退款");
  417. }
  418. //退款
  419. var serviceResult = await _payService.ReturnProcess(RefundAmount, (decimal)trx.ActualPaymentAmount, "WX_SCAN", trx.BillNumber);
  420. Payment.Core.Models.ElectronicOrderProcessResultModel payResult = (Payment.Core.Models.ElectronicOrderProcessResultModel)serviceResult.Data;
  421. if (!serviceResult.IsSuccessful() || payResult.ResultCode == "PAY_ERROR")
  422. {
  423. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "退款失败");
  424. }
  425. if (RefundAmount == (decimal)trx.ActualPaymentAmount)
  426. {
  427. trx.RefundStatus = RefundStatus.FullyRefunded;//全额退款
  428. }
  429. else
  430. {
  431. trx.RefundStatus = RefundStatus.PartiallyRefunded;//部分退款
  432. }
  433. trx.OrderStatus = transactionsORDERSTATUS.Cancelled;
  434. trx.RefundAmount = RefundAmount;
  435. int affectedRows = _fsql.Update<transactions>().SetSource(trx).ExecuteAffrows();
  436. var user = _fsql.Select<miniprogramusers>().Where(_ => _.Id == trx.MiniProgramID).First();
  437. string jsonString = JsonConvert.SerializeObject(trx);
  438. await _mqttService.SubscribeAsync("refund/" + Buid);
  439. await Task.Delay(2000);
  440. var sendjson = new { data = jsonString, UserName = user.UserName, UserPhoneNumber = user.UserPhoneNumber };
  441. await _mqttService.PublishAsync("refund/" + Buid, JsonConvert.SerializeObject(sendjson));
  442. return ServiceResponse.Ok(trx);
  443. }
  444. public async Task<ServiceResponse> UnifiedOrder(int trxId)
  445. {
  446. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  447. try
  448. {
  449. logger.Debug("UnifiedOrder start++");
  450. string WachatID = HttpRequestReader.GetWachatID(); //用户
  451. var userSession = WechatUserSessionRepo.GetUserSession(WachatID.ToString());
  452. if (userSession == null)
  453. {
  454. return ServiceResponse.Error(HttpStatusCode.NonAuthoritativeInformation, "未找到用户!");
  455. }
  456. //var userSession = new WechatUserSessionResponse() { buId = "12345678-9abc-def0-1234-56789abcdef0", openid = "o8pFb5cWH1KkBDvGls2X7yMiFkGA" };
  457. var site = _fsql.Select<businessunitinfo>().Where(_ => _.Buid == Buid).First();
  458. var weChatService = new WeChatService(site.Appid, site.Secret);
  459. var user = _fsql.Select<miniprogramusers>().Where(_ => _.OpenId == userSession.openid).First();
  460. var trx = _entityHelper.GetEntitiesAsync<transactions>(_ => _.Id == trxId).Result.FirstOrDefault();
  461. if (trx == null)
  462. {
  463. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId},未查询到订单");
  464. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "未查询到订单!");
  465. }
  466. logger.Debug($"统一下单开始,Buid={Buid} ,trxId={trxId}");
  467. var serviceResult = await _payService.UnifiedOrder(trx.OriginalAmount.Value, "WX_SCAN", userSession.openid);
  468. var dataProperties = serviceResult.Data.GetType().GetProperty("UnifiedOrderResult");
  469. if (!serviceResult.IsSuccessful() || dataProperties == null)
  470. {
  471. logger.Debug($"统一下单失败,Buid={Buid} ,trxId={trxId}" );
  472. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "统一下单失败");
  473. }
  474. //小程序支付完后,云端需要通过订单编号去支付平台查询支付状态,以便更新订单信息
  475. _ = Task.Delay(1500).ContinueWith(async _ =>
  476. {
  477. using (var scope = _serviceScopeFactory.CreateScope())
  478. {
  479. var scopedMqttService = scope.ServiceProvider.GetRequiredService<IMqttClientService>();
  480. var dataProperties = serviceResult.Data.GetType().GetProperty("eOrder");
  481. var orderModel = (Fuel.Payment.Core.Models.ElectronicOrderModel)dataProperties.GetValue(serviceResult.Data);
  482. var genericResponse = await _payService.QueryOrder(orderModel);
  483. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId},genericResponse.Data={genericResponse.Data}");
  484. if (genericResponse.IsSuccessful() && orderModel.TradeStatus == Fuel.Payment.Core.Models.TradeStatus.SUCCESS)
  485. {
  486. trx.OrderStatus = transactionsORDERSTATUS.Paid;//将订单状态更改成已支付
  487. trx.MiniProgramID = user.Id;
  488. trx.BillNumber = orderModel.BillNumber;
  489. trx.BillNumberBase62 = NumericBase62Converter.Encode(orderModel.BillNumber);
  490. trx.ActualPaymentAmount = trx.OriginalAmount;
  491. trx.PaymentMethod = 2;//2 :微信支付
  492. try
  493. {
  494. await scopedMqttService.SubscribeAsync("paid/" + Buid);
  495. string jsonString = JsonConvert.SerializeObject(trx);
  496. await Task.Delay(2000);
  497. var sendjson = new { data = jsonString, UserName = user.UserName, UserPhoneNumber = user.UserPhoneNumber };
  498. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId},订单推送fcc sendjson={System.Text.Json.JsonSerializer.Serialize(sendjson)}");
  499. //支付完成将订单信息推送到fcc
  500. scopedMqttService.PublishAsync("paid/" + Buid, JsonConvert.SerializeObject(sendjson));
  501. }
  502. catch (Exception ex)
  503. {
  504. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId},异常:"+ ex.Message);
  505. }
  506. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId},更新订单信息");
  507. int affectedRows = _fsql.Update<transactions>().SetSource(trx).ExecuteAffrows();
  508. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId},更新状态" + affectedRows);
  509. //SendMessage(trx,Buid);
  510. }
  511. }
  512. });
  513. var unifiedOrderResult = dataProperties.GetValue(serviceResult.Data);
  514. var options = new JsonSerializerOptions
  515. {
  516. IgnoreReadOnlyProperties = true // 忽略只读属性
  517. };
  518. string serializedUnifiedOrderResult = System.Text.Json.JsonSerializer.Serialize(unifiedOrderResult, options);
  519. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId}, 支付信息 " + serializedUnifiedOrderResult);
  520. return ServiceResponse.Ok(unifiedOrderResult);
  521. }
  522. catch (Exception ex)
  523. {
  524. logger.Debug($"统一下单,Buid={Buid} ,trxId={trxId},Exception:" +ex.Message);
  525. return ServiceResponse.Error(ex.Message);
  526. }
  527. }
  528. public async Task<ServiceResponse> Redeem(int trxId, decimal OriginalQty, decimal FuelItemPumpTotalizerVolume)
  529. {
  530. var trx = _entityHelper.GetEntitiesAsync<transactions>(_ => _.Id == trxId).Result.FirstOrDefault();
  531. if (trx == null)
  532. {
  533. return ServiceResponse.Error(HttpStatusCode.NotAcceptable, "未查询到订单!");
  534. }
  535. var refund = await RefundTrx(trxId, OriginalQty);
  536. trx = _entityHelper.GetEntitiesAsync<transactions>(_ => _.Id == trxId).Result.FirstOrDefault();
  537. trx.OriginalQty = OriginalQty;
  538. trx.FuelItemPumpTotalizerVolume = FuelItemPumpTotalizerVolume;
  539. if (refund.IsSuccessful() || refund.StatusCode == HttpStatusCode.NotAcceptable)
  540. {
  541. trx.OrderStatus = transactionsORDERSTATUS.Completed;
  542. }
  543. int affectedRows = _fsql.Update<transactions>().SetSource(trx).ExecuteAffrows();
  544. return ServiceResponse.Ok(trx);
  545. }
  546. /// <summary>
  547. /// 微信发送模板消息
  548. /// </summary>
  549. /// <returns></returns>
  550. public async Task SendMessage(int trxId, string orderType)
  551. {
  552. var data = new Dictionary<string, object>();//动态字段
  553. Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
  554. var trx = _entityHelper.GetEntitiesAsync<transactions>(_ => _.Id == trxId).Result.FirstOrDefault();
  555. var site = _fsql.Select<businessunitinfo>().Where(_ => _.Buid == Buid).First();
  556. var weChatService = new WeChatService(site.Appid, site.Secret);
  557. string WachatID = HttpRequestReader.GetWachatID(); //用户
  558. //var userSession = WechatUserSessionRepo.GetUserSession(WachatID.ToString());
  559. //if (userSession == null)
  560. //{
  561. //}
  562. //var user = _fsql.Select<miniprogramusers>().Where(_ => _.OpenId == userSession.openid).First();
  563. var user = _fsql.Select<miniprogramusers>().Where(_ => _.OpenId == WachatID).First();
  564. var template = _fsql.Select<configuration>().Where(_ => _.Buid == Buid && _.Type == 2 && _.Name == "小程序通知模板").First();
  565. if (template == null)
  566. {
  567. //模板获取失败
  568. return;
  569. }
  570. //将金额小数改成俩位
  571. if (trx.ActualPaymentAmount.HasValue)
  572. {
  573. decimal roundedValue = Math.Round(trx.ActualPaymentAmount.Value, 2, MidpointRounding.AwayFromZero);
  574. trx.ActualPaymentAmount = roundedValue;
  575. }
  576. // var BillNumber = EncodeBillNumber(trx.BillNumber);
  577. var config = JsonConvert.DeserializeObject<TemplateConfig>(template.Value);
  578. var dataDict = new Dictionary<string, object>();
  579. var dynamicData = new Dictionary<string, object>
  580. {
  581. { "orderType", orderType},
  582. { "BillNumber", trx.BillNumberBase62 },//trx.BillNumber
  583. { "ProductName_Qty", trx.ProductName + " & " + trx.Qty + "L"},
  584. { "ActualPaymentAmount",trx.ActualPaymentAmount.ToString() + "元" },
  585. { "TransactionTime", ToFormattedString(trx.TransactionTime) }
  586. };
  587. foreach (var mapping in config.DataMappings)
  588. {
  589. string dataFieldName = mapping.Key;
  590. string targetFieldName = mapping.Value;
  591. if (dynamicData.TryGetValue(dataFieldName, out object value))
  592. {
  593. dataDict.Add(targetFieldName, new { value = value });
  594. }
  595. }
  596. // 准备要发送的模板消息内容
  597. var templateMessage = new WeChatService.TemplateMessage
  598. {
  599. ToUser = user.OpenId,
  600. TemplateId = config.TemplateId,
  601. Page = "pages/historyOrder/historyOrder",
  602. Data = dataDict
  603. };
  604. //var templateMessage = new WeChatService.TemplateMessage
  605. //{
  606. // ToUser = user.OpenId,
  607. // TemplateId = "V0tl-4n-5hwNZc4SrEttvrmawAyM-SB0pQWZNwp54Ks",
  608. // Page = "pages/historyOrder/historyOrder",
  609. // Data = new
  610. // {
  611. // short_thing10 = new { value = orderType },
  612. // character_string11 = new { value = trx.BillNumber },
  613. // thing12 = new { value = trx.ProductName + " | " + trx.Qty + "L"},
  614. // amount13 = new { value = trx.ActualPaymentAmount },
  615. // time14 = new { value = ToFormattedString(trx.TransactionTime) },
  616. // }
  617. //};
  618. weChatService.SendTemplateMessage(templateMessage);
  619. }
  620. public string ToFormattedString(DateTime? dateTime)
  621. {
  622. if (dateTime.HasValue)
  623. {
  624. return dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
  625. }
  626. else
  627. {
  628. return null;
  629. }
  630. }
  631. public static string GetChineseStatus(transactionsORDERSTATUS status)
  632. {
  633. switch (status)
  634. {
  635. case transactionsORDERSTATUS.Unpaid:
  636. return "订单未支付";
  637. case transactionsORDERSTATUS.Paid:
  638. return "订单已支付";
  639. case transactionsORDERSTATUS.Paying:
  640. return "订单正在支付中";
  641. case transactionsORDERSTATUS.CardPayment:
  642. return "订单通过卡支付";
  643. case transactionsORDERSTATUS.Completed:
  644. return "订单已完成";
  645. case transactionsORDERSTATUS.Cancelled:
  646. return "已退款";
  647. default:
  648. throw new ArgumentOutOfRangeException(nameof(status), status, null);
  649. }
  650. }
  651. }
  652. }