From 6739e98662c16571da7aec0e9b52fab0afd3833b Mon Sep 17 00:00:00 2001
From: sunpengfei <i@angelzzz.com>
Date: 星期五, 13 六月 2025 14:07:28 +0800
Subject: [PATCH] fix:修订支付回调和供应商回调并发问题

---
 LifePayment/LifePayment.HttpApi/LifePay/WxPayNotifyController.cs  |    9 ++--
 LifePayment/LifePayment.HttpApi/LifePay/ACOOLYNotifyController.cs |    3 +
 LifePayment/LifePayment.Worker/LifePaymentServicesWorkModule.cs   |    2 
 LifePayment/LifePayment.Worker/Worker/CheckUnPayOrderWork.cs      |   63 ++++++++++++++++---------------
 LifePayment/LifePayment.Application/LifePay/LifePayService.cs     |   15 +++----
 LifePayment/LifePayment.HttpApi/LifePay/AliPayNotifyController.cs |   12 ++---
 6 files changed, 52 insertions(+), 52 deletions(-)

diff --git a/LifePayment/LifePayment.Application/LifePay/LifePayService.cs b/LifePayment/LifePayment.Application/LifePay/LifePayService.cs
index 637ff94..258cc91 100644
--- a/LifePayment/LifePayment.Application/LifePay/LifePayService.cs
+++ b/LifePayment/LifePayment.Application/LifePay/LifePayService.cs
@@ -1484,7 +1484,6 @@
             order.OutRequestNo = result.RequestNo.IsNullOrEmpty() ? null : result.RequestNo;
             order.ACOOLYOrderNo = result.ACOOLYOrderNo;
             order.ACOOLYStatus = ACOOLYStatusEnum.鍏呭�间腑;
-            await _lifePayOrderRepository.UpdateAsync(order);
             _logger.LogInformation("鐢熸椿缂磋垂璁㈠崟锛�" + order.ToJson());
 
             /// 鍒涘缓鐢熸椿缂磋垂娑堣垂璁板綍
@@ -1499,9 +1498,9 @@
             order.LifePayRefundStatus = LifePayRefundStatusEnum.寰呴��娆�;
             order.ACOOLYStatus = ACOOLYStatusEnum.鍏呭�煎け璐�;
             order.RefundApplyRemark = ex.Message;
-            await _lifePayOrderRepository.UpdateAsync(order);
-            _logger.LogError("鐢熸椿缂磋垂璁㈠崟鐘舵�侊細" + order.LifePayOrderStatus.ToString());
         }
+        _logger.LogError("鐢熸椿缂磋垂璁㈠崟鐘舵�侊細" + order.LifePayOrderStatus.ToString());
+        await _lifePayOrderRepository.UpdateAsync(order);
     }
 
     public async Task LifePayRefundsHandler(string orderNo, LifePayRefundStatusEnum refundStatus)
@@ -1532,12 +1531,12 @@
     /// <returns></returns>
     public async Task ACOOLYOrderNotifyHandler(string orderNo, string acoolyOrderNo, LifePayOrderStatusEnum status, ACOOLYStatusEnum acoolyStatus, decimal payAmount, string refundApplyRemark, decimal? parValue = 0, decimal? actualParValue = 0)
     {
+        await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{orderNo}", TimeSpan.FromSeconds(60));
+        _logger.LogInformation($"閿侊細LockKey:UpdateOrder:{orderNo} - {orderLock != null}");
+
         var order = await _lifePayOrderRepository.Where(x => x.OrderNo == orderNo).FirstOrDefaultAsync();
 
         CheckExtensions.IfTrueThrowUserFriendlyException(order == null, "璁㈠崟涓嶅瓨鍦�");
-
-        await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{orderNo}", TimeSpan.FromSeconds(60));
-        _logger.LogInformation($"閿侊細LockKey:UpdateOrder:{orderNo} - {orderLock != null}");
 
         if (order.ACOOLYStatus.HasValue && (int)order.ACOOLYStatus > (int)acoolyStatus)
         {
@@ -1583,8 +1582,6 @@
             order.RefundPrice = Math.Round((1 - ((order.ActualReceivedAmount ?? 0) / (order.RechargeAmount ?? 0))) * (order.PayAmount ?? 0), 2);
         }
 
-        await _lifePayOrderRepository.UpdateAsync(order);
-
         if (order.LifePayOrderStatus == LifePayOrderStatusEnum.宸插畬鎴�)
         {
             ///缁撶畻娓犻亾浣i噾
@@ -1610,6 +1607,8 @@
         /// 鍒涘缓鐢熸椿缂磋垂娑堣垂璁板綍
         await _lifePayOrderService.CreatLifePayConsumption(acoolyStatus, order.OrderNo, order.ACOOLYOrderNo,
                     order.PlatformDeductionAmount ?? 0, order.ChannelId, order.CreationTime, order.FinishTime, order.ChannleRate, parValue, actualParValue);
+
+        await CurrentUnitOfWork.SaveChangesAsync();
     }
 
     /// <summary>
diff --git a/LifePayment/LifePayment.HttpApi/LifePay/ACOOLYNotifyController.cs b/LifePayment/LifePayment.HttpApi/LifePay/ACOOLYNotifyController.cs
index cae6846..d44e90d 100644
--- a/LifePayment/LifePayment.HttpApi/LifePay/ACOOLYNotifyController.cs
+++ b/LifePayment/LifePayment.HttpApi/LifePay/ACOOLYNotifyController.cs
@@ -7,6 +7,7 @@
 using System;
 using System.IO;
 using System.Text;
+using System.Threading;
 using System.Threading.Tasks;
 using Volo.Abp;
 using Volo.Abp.AspNetCore.Mvc;
@@ -39,11 +40,11 @@
         /// </summary>
         /// <returns></returns>
         [HttpPost]
-        [UnitOfWork]
         [AllowAnonymous]
         public async Task ACOOLYNotify()
         {
             _logger.LogError("ACOOLY鍥炶皟閫氱煡寮�濮嬭繘鍏�");
+            Thread.Sleep(200);
             var body = string.Empty;
             using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
             {
diff --git a/LifePayment/LifePayment.HttpApi/LifePay/AliPayNotifyController.cs b/LifePayment/LifePayment.HttpApi/LifePay/AliPayNotifyController.cs
index be0fd5a..9450126 100644
--- a/LifePayment/LifePayment.HttpApi/LifePay/AliPayNotifyController.cs
+++ b/LifePayment/LifePayment.HttpApi/LifePay/AliPayNotifyController.cs
@@ -49,7 +49,6 @@
         /// </summary>
         /// <returns></returns>
         [HttpPost]
-        [UnitOfWork]
         public async Task<ContentResult> AliRechargeNotify()
         {
             _logger.LogError($"鐢熸椿绠″鏀粯瀹濆厖鍊煎洖璋冮�氱煡锛氳繘鍏ユ敮浠樺疂鍥炶皟");
@@ -61,13 +60,13 @@
             //var serializeRequest = "{\"gmt_create\":\"2025-02-25 13:18:59\",\"charset\":\"UTF-8\",\"seller_email\":\"zfb1@818nb.com\",\"subject\":\"鐢熸椿缂磋垂-璇濊垂\",\"sign\":\"Sp06G1GxrAfDvoHPz9l3DJ20SxhvRzEGFeCGu4LHrSWmEG4OY7MHMx+iJi54ETbdXV0YsyDH9JZD7PWN3HCpEq/wGO4Wh4VSYSe7lqxD6r4f/HFiB0YlrdQoSzjZgYPzLjy6bcdlKRRHOeDkgs2i7TfvIsxWxHs9t0xuS0RlkpdZfb7d7m0EuZ/3v2Cbsj5AHjxb1S2PkO0oQyriYgGQdmkPqILZHwieST+tNEHS4dGFKYu2nkfctAGjWIDv/hKQNY7jEUxsEeG0SnK4TPU8zNplFR9/aKM0Wfwp1pdlaiP2u/d8vOtNh5q+emvaYbKrUkIEFBok8pDLNDta7ZjtVw==\",\"invoice_amount\":\"0.01\",\"buyer_open_id\":\"071xYXDfXBLAI9U11jg_WrH1K6hWq8HYGz0u85xBivf3Sce\",\"notify_id\":\"2025022501222131904087711494539601\",\"fund_bill_list\":\"[{\\\"amount\\\":\\\"0.01\\\",\\\"fundChannel\\\":\\\"ALIPAYACCOUNT\\\"}]\",\"notify_type\":\"trade_status_sync\",\"trade_status\":\"TRADE_SUCCESS\",\"receipt_amount\":\"0.01\",\"buyer_pay_amount\":\"0.01\",\"app_id\":\"2021004171602214\",\"sign_type\":\"RSA2\",\"seller_id\":\"2088050542042301\",\"gmt_payment\":\"2025-02-25 13:19:03\",\"notify_time\":\"2025-02-25 13:44:34\",\"merchant_app_id\":\"2021004171602214\",\"version\":\"1.0\",\"out_trade_no\":\"JF202502251318555214671\",\"total_amount\":\"0.01\",\"trade_no\":\"2025022522001487711401331043\",\"auth_app_id\":\"2021004171602214\",\"buyer_logon_id\":\"130****2238\",\"point_amount\":\"0.00\"}";
             var input = JsonConvert.DeserializeObject<AliRechargeNotifyInput>(serializeRequest);
 
+            await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{input.OutTradeNo}", TimeSpan.FromSeconds(60));
+            _logger.LogInformation($"閿侊細LockKey:UpdateOrder:{input.OutTradeNo} - {orderLock != null}");
+
             if (input.OutTradeNo.Contains("JF"))
             {
                 if (input.TradeStatus == LifePaymentConstant.AliPayStatus.鏀粯鎴愬姛 && input.OutBizNo.IsNullOrEmpty())
                 {
-                    await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{input.OutTradeNo}", TimeSpan.FromSeconds(60));
-                    _logger.LogInformation($"閿侊細LockKey:UpdateOrder:{input.OutTradeNo} - {orderLock != null}");
-
                     await _lifePayService.LifePaySuccessHandler(input.OutTradeNo, input.TradeNo);
                     // 鎻掑叆鏀舵敮娴佹按
                     await _lifePayOrderService.AddLifePayExpensesReceipts(new AddLifePayExpensesReceiptsInput()
@@ -77,14 +76,12 @@
                         LifePayType = LifePayTypeEnum.AliPay,
                         ExpensesReceiptsType = ExpensesReceiptsTypeEnum.Expenses
                     });
+                    await CurrentUnitOfWork.SaveChangesAsync();
                 }
                 else if (((input.TradeStatus == LifePaymentConstant.AliPayStatus.鏀粯鎴愬姛 || input.TradeStatus == LifePaymentConstant.AliPayStatus.瓒呮椂鍏抽棴)
                     && input.OutBizNo.IsNotNullOrEmpty()
                     && (input.RefundFee.HasValue && input.RefundFee > 0)))
                 {
-                    await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{input.OutTradeNo}", TimeSpan.FromSeconds(60));
-                    _logger.LogInformation($"閿侊細LockKey:UpdateOrder:{input.OutTradeNo} - {orderLock != null}");
-
                     await _lifePayService.LifePayRefundsHandler(input.OutTradeNo, LifePayRefundStatusEnum.宸查��娆�);
                     // 鎻掑叆鏀舵敮娴佹按
                     await _lifePayOrderService.AddLifePayExpensesReceipts(new AddLifePayExpensesReceiptsInput()
@@ -95,6 +92,7 @@
                         LifePayType = LifePayTypeEnum.AliPay,
                         ExpensesReceiptsType = ExpensesReceiptsTypeEnum.Receipts
                     });
+                    await CurrentUnitOfWork.SaveChangesAsync();
                 }
             }
             else
diff --git a/LifePayment/LifePayment.HttpApi/LifePay/WxPayNotifyController.cs b/LifePayment/LifePayment.HttpApi/LifePay/WxPayNotifyController.cs
index 74ddb7b..9e30708 100644
--- a/LifePayment/LifePayment.HttpApi/LifePay/WxPayNotifyController.cs
+++ b/LifePayment/LifePayment.HttpApi/LifePay/WxPayNotifyController.cs
@@ -53,7 +53,6 @@
         /// <param name="input"></param>
         /// <returns></returns>
         [HttpPost]
-        [UnitOfWork]
         public async Task<WxRechargeNotifyResult> WxRechargeNotify(WxRechargeNotifyInput input)
         {
             try
@@ -64,12 +63,13 @@
                 _logger.LogInformation($"鐢熸椿绠″寰俊鍏呭�煎洖璋冮�氱煡data锛�" + data);
                 var wxPayNotice = JsonConvert.DeserializeObject<WxPayNotice>(data);
 
+                await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{wxPayNotice.OutTradeNo}", TimeSpan.FromSeconds(60));
+                _logger.LogInformation($"閿侊細LockKey:UpdateOrder:{wxPayNotice.OutTradeNo} - {orderLock != null}");
+
                 if (wxPayNotice.OutTradeNo.Contains("JF"))
                 {
                     if (wxPayNotice.TradeState == LifePaymentConstant.WxPayStatus.鏀粯鎴愬姛)
                     {
-                        await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{wxPayNotice.OutTradeNo}", TimeSpan.FromSeconds(60));
-                        _logger.LogInformation($"閿侊細LockKey:UpdateOrder:{wxPayNotice.OutTradeNo} - {orderLock != null}");
 
                         var key = $"WxRechargeNotify_{wxPayNotice.OutTradeNo}";
                         if (string.IsNullOrWhiteSpace(distributedCache.Get(key)))
@@ -93,6 +93,8 @@
                             {
                                 AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
                             });
+
+                            await CurrentUnitOfWork.SaveChangesAsync();
                         }
                         else
                         {
@@ -111,7 +113,6 @@
             }
             catch (Exception ex)
             {
-                await CurrentUnitOfWork.RollbackAsync();
                 return new WxRechargeNotifyResult
                 {
                     Code = "FAIL",
diff --git a/LifePayment/LifePayment.Worker/LifePaymentServicesWorkModule.cs b/LifePayment/LifePayment.Worker/LifePaymentServicesWorkModule.cs
index 94062ab..c5c9272 100644
--- a/LifePayment/LifePayment.Worker/LifePaymentServicesWorkModule.cs
+++ b/LifePayment/LifePayment.Worker/LifePaymentServicesWorkModule.cs
@@ -52,7 +52,7 @@
         public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context)
         {
             await context.AddBackgroundWorkerAsync<GetStaticsWorker>();
-            await context.AddBackgroundWorkerAsync<CheckUnPayOrderWork>();
+            //await context.AddBackgroundWorkerAsync<CheckUnPayOrderWork>();s
         }
 
         private void ConfigurePays(ServiceConfigurationContext context, IConfiguration configuration)
diff --git a/LifePayment/LifePayment.Worker/Worker/CheckUnPayOrderWork.cs b/LifePayment/LifePayment.Worker/Worker/CheckUnPayOrderWork.cs
index 0de3470..0d8287d 100644
--- a/LifePayment/LifePayment.Worker/Worker/CheckUnPayOrderWork.cs
+++ b/LifePayment/LifePayment.Worker/Worker/CheckUnPayOrderWork.cs
@@ -41,7 +41,7 @@
             IAbpDistributedLock distributedLock,
             IRepository<LifePayOrder, Guid> lifePayOrderRepository) : base(timer, serviceScopeFactory)
         {
-            timer.Period = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
+            timer.Period = (int)TimeSpan.FromMinutes(30).TotalMilliseconds;
             this.logger = logger;
             this.lifePayOrderService = lifePayOrderService;
             this.lifePayService = lifePayService;
@@ -55,39 +55,40 @@
             try
             {
                 Logger.LogInformation($"妫�鏌ユ湭鏀粯璁㈠崟鐘舵�佸紑濮�: {DateTime.Now}");
-                var end = DateTime.Now;
-                var start = end.AddMinutes(-15);
-                var orders = lifePayOrderRepository.Where(it => it.PayStatus == LifePayStatusEnum.鏈敮浠� && it.CreationTime >= start && it.CreationTime <= end).ToList();
-                foreach (var order in orders)
-                {
-                    await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{order.OrderNo}", TimeSpan.FromSeconds(60));
-                    logger.LogInformation($"閿侊細LockKey:UpdateOrder:{order.OrderNo} - {orderLock != null}");
+                //var end = DateTime.Now;
+                //var start = end.AddMinutes(-45);
+                //end = end.AddMinutes(-15);
+                //var orders = lifePayOrderRepository.Where(it => it.PayStatus == LifePayStatusEnum.鏈敮浠� && it.CreationTime >= start && it.CreationTime <= end).ToList();
+                //foreach (var order in orders)
+                //{
+                //    await using var orderLock = await distributedLock.TryAcquireAsync($"LockKey:UpdateOrder:{order.OrderNo}", TimeSpan.FromSeconds(60));
+                //    logger.LogInformation($"閿侊細LockKey:UpdateOrder:{order.OrderNo} - {orderLock != null}");
 
-                    Logger.LogInformation($"璁㈠崟锛歿order.OrderNo}-{order.ToJson()}");
-                    var wxPayNotice = await lifePayService.WxPayTradeQuery(order.OrderNo);
-                    var json = wxPayNotice.ToJson();
-                    Logger.LogInformation($"璁㈠崟锛坽wxPayNotice.OutTradeNo}锛変俊鎭�: {json}");
-                    if (wxPayNotice.OutTradeNo.Contains("JF") && wxPayNotice.TradeState == LifePaymentConstant.WxPayStatus.鏀粯鎴愬姛)
-                    {
-                        await lifePayService.LifePaySuccessHandler(wxPayNotice.OutTradeNo, wxPayNotice.TransactionId);
+                //    Logger.LogInformation($"璁㈠崟锛歿order.OrderNo}-{order.ToJson()}");
+                //    var wxPayNotice = await lifePayService.WxPayTradeQuery(order.OrderNo);
+                //    var json = wxPayNotice.ToJson();
+                //    Logger.LogInformation($"璁㈠崟锛坽wxPayNotice.OutTradeNo}锛変俊鎭�: {json}");
+                //    if (wxPayNotice.OutTradeNo.Contains("JF") && wxPayNotice.TradeState == LifePaymentConstant.WxPayStatus.鏀粯鎴愬姛)
+                //    {
+                //        await lifePayService.LifePaySuccessHandler(wxPayNotice.OutTradeNo, wxPayNotice.TransactionId);
 
-                        // 鎻掑叆鏀舵敮娴佹按
-                        await lifePayOrderService.AddLifePayExpensesReceipts(new AddLifePayExpensesReceiptsInput()
-                        {
-                            OrderNo = wxPayNotice.OutTradeNo,
-                            OutOrderNo = wxPayNotice.TransactionId,
-                            LifePayType = LifePayTypeEnum.WxPay,
-                            ExpensesReceiptsType = ExpensesReceiptsTypeEnum.Expenses,
-                            Amount = wxPayNotice.Amount.Total
-                        });
+                //        // 鎻掑叆鏀舵敮娴佹按
+                //        await lifePayOrderService.AddLifePayExpensesReceipts(new AddLifePayExpensesReceiptsInput()
+                //        {
+                //            OrderNo = wxPayNotice.OutTradeNo,
+                //            OutOrderNo = wxPayNotice.TransactionId,
+                //            LifePayType = LifePayTypeEnum.WxPay,
+                //            ExpensesReceiptsType = ExpensesReceiptsTypeEnum.Expenses,
+                //            Amount = wxPayNotice.Amount.Total
+                //        });
 
-                        Logger.LogInformation("宸叉敼涓烘敮浠樻垚鍔�");
-                    }
-                    else
-                    {
-                        Logger.LogInformation("鏈洿鏂�");
-                    }
-                }
+                //        Logger.LogInformation("宸叉敼涓烘敮浠樻垚鍔�");
+                //    }
+                //    else
+                //    {
+                //        Logger.LogInformation("鏈洿鏂�");
+                //    }
+                //}
             }
             catch (Exception ex)
             {

--
Gitblit v1.9.1