WeChatPayBackService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. using System;
  2. using System.Collections.Generic;
  3. using Library;
  4. using LitJson;
  5. using System.Linq;
  6. using MySystem.Models;
  7. using Org.BouncyCastle.Crypto.Modes;
  8. using Org.BouncyCastle.Crypto.Engines;
  9. using Org.BouncyCastle.Crypto.Parameters;
  10. using System.Text;
  11. using System.Threading;
  12. namespace MySystem
  13. {
  14. public class WeChatPayBackService
  15. {
  16. public readonly static WeChatPayBackService Instance = new WeChatPayBackService();
  17. private WeChatPayBackService()
  18. { }
  19. public void Start()
  20. {
  21. Thread th = new Thread(Listen);
  22. th.IsBackground = true;
  23. th.Start();
  24. }
  25. public void Listen()
  26. {
  27. bool op = true;
  28. while (op)
  29. {
  30. string content = RedisDbconn.Instance.RPop<string>("WeChatPayBack");
  31. if (!string.IsNullOrEmpty(content))
  32. {
  33. try
  34. {
  35. dosomething(content);
  36. }
  37. catch (Exception ex)
  38. {
  39. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "微信支付回调异常");
  40. }
  41. }
  42. else
  43. {
  44. Thread.Sleep(2000);
  45. }
  46. }
  47. }
  48. public void dosomething(string content)
  49. {
  50. JsonData jsonObj = JsonMapper.ToObject(content);
  51. if (jsonObj.Count > 0)
  52. {
  53. if (jsonObj["event_type"].ToString() == "TRANSACTION.SUCCESS")
  54. {
  55. JsonData resource = jsonObj["resource"];
  56. //开始解密
  57. string WxPayResourceDecryptModel = AesGcmDecrypt(resource["associated_data"].ToString(), resource["nonce"].ToString(), resource["ciphertext"].ToString());
  58. // {\"sp_mchid\":\"1611167423\",\"sub_mchid\":\"1622024882\",\"sp_appid\":\"wxe2c051b3e46c0f6f\",\"out_trade_no\":\"2022022621562926396898863\",\"transaction_id\":\"4200001412202202267619496496\",\"trade_type\":\"JSAPI\",\"trade_state\":\"SUCCESS\",\"trade_state_desc\":\"支付成功\",\"bank_type\":\"OTHERS\",\"attach\":\"\",\"success_time\":\"2022-02-26T21:56:42+08:00\",\"payer\":{\"sp_openid\":\"omawy5W6jb0pgPfuKUVs6K3bEhzk\",\"sub_openid\":\"\"},\"amount\":{\"total\":1,\"payer_total\":1,\"currency\":\"CNY\",\"payer_currency\":\"CNY\"}}
  59. JsonData orderObj = JsonMapper.ToObject(WxPayResourceDecryptModel);
  60. string OrderNo = orderObj["out_trade_no"].ToString();
  61. string TradeNo = orderObj["transaction_id"].ToString();
  62. WebCMSEntities db = new WebCMSEntities();
  63. ConsumerOrderForNo forNo = db.ConsumerOrderForNo.FirstOrDefault(m => m.OrderNo == OrderNo);
  64. if (forNo != null)
  65. {
  66. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == forNo.OrderIds && m.Status == 0);
  67. if (order != null)
  68. {
  69. order.Status = 1;
  70. order.UpdateDate = DateTime.Now;
  71. order.PayMoney = order.PayMoney;
  72. order.MaxDivi = order.MaxDivi;
  73. order.SeoTitle = TradeNo;
  74. MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
  75. order.UserId = merchant.UserId;
  76. ConsumerOrders check = db.ConsumerOrders.FirstOrDefault(m => m.Id < order.Id && m.Status > 0 && m.PayMode == order.PayMode && m.MerchantId == order.MerchantId);
  77. if(check != null)
  78. {
  79. order.QueryCount = check.QueryCount + 1;
  80. }
  81. else
  82. {
  83. order.QueryCount = 1;
  84. }
  85. db.SaveChanges();
  86. }
  87. }
  88. db.Dispose();
  89. }
  90. }
  91. }
  92. public string AesGcmDecrypt(string associatedData, string nonce, string ciphertext)
  93. {
  94. GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
  95. AeadParameters aeadParameters = new AeadParameters(
  96. new KeyParameter(Encoding.UTF8.GetBytes(AppConfig.WeChatParam.AesGemKey)),
  97. 128,
  98. Encoding.UTF8.GetBytes(nonce),
  99. Encoding.UTF8.GetBytes(associatedData));
  100. gcmBlockCipher.Init(false, aeadParameters);
  101. byte[] data = Convert.FromBase64String(ciphertext);
  102. byte[] plaintext = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
  103. int length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plaintext, 0);
  104. gcmBlockCipher.DoFinal(plaintext, length);
  105. return Encoding.UTF8.GetString(plaintext);
  106. }
  107. //分账队列
  108. public void StartProfitShare()
  109. {
  110. Thread th = new Thread(StartProfitShareListen);
  111. th.IsBackground = true;
  112. th.Start();
  113. }
  114. public void StartProfitShareListen()
  115. {
  116. bool op = true;
  117. while (op)
  118. {
  119. try
  120. {
  121. WebCMSEntities db = new WebCMSEntities();
  122. DateTime checkDate = DateTime.Now.AddMinutes(-1);
  123. var list = db.ConsumerOrders.Select(m => new { m.Id, m.CreateDate, m.Status, m.IsAct, m.PayMode }).Where(m => m.Status == 1 && m.PayMode == 2 && m.IsAct == 1 && m.CreateDate < checkDate).OrderBy(m => m.Id).Take(10).ToList();
  124. foreach(var sub in list)
  125. {
  126. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == sub.Id);
  127. if(order != null)
  128. {
  129. order.Status = 2;
  130. MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
  131. MerchantParamSet set = db.MerchantParamSet.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantParamSet();
  132. if(order.IsAct == 1 && order.PayMoney >= set.MinPayMoney)
  133. {
  134. MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
  135. //添加分账接收方
  136. if(merchant.Version == 0)
  137. {
  138. WeChatFunction.Instance.AddReceive(merchantAdd.SubMchid, "MERCHANT_ID", WeChatFunction.Instance.MchId, WeChatFunction.Instance.MchName, "PARTNER");
  139. merchant.Version = 1;
  140. db.SaveChanges();
  141. }
  142. //发起分账
  143. decimal fee = order.PayMoney; //单位:分
  144. if(fee >= 1)
  145. {
  146. string TradeNo = order.SeoTitle;
  147. string OrderNo = order.OrderNo;
  148. List<ReceiverList> Receivers = new List<ReceiverList>();
  149. Receivers.Add(new ReceiverList()
  150. {
  151. type = "MERCHANT_ID", //分账接收方类型
  152. account = WeChatFunction.Instance.MchId, //分账接收方账号
  153. amount = int.Parse(fee.ToString("f0")), //分账金额
  154. description = "服务费", //分账描述
  155. });
  156. WeChatFunction.Instance.ProfitShare(merchantAdd.SubMchid, TradeNo, OrderNo, Receivers);
  157. //开始监听分账状态
  158. Dictionary<string, object> req = new Dictionary<string, object>();
  159. req.Add("SubMchid", merchantAdd.SubMchid); //子商户号
  160. req.Add("TradeNo", TradeNo); //微信订单号
  161. req.Add("OrderNo", OrderNo); //商户订单号
  162. RedisDbconn.Instance.AddList("ProfitShareQueue", Newtonsoft.Json.JsonConvert.SerializeObject(req));
  163. }
  164. else
  165. {
  166. RedisDbconn.Instance.AddList("ConsumerOrders:Divi:2:List", order.Id.ToString());
  167. // RedisDbconn.Instance.AddRightList("ConsumerOrders:Divi:2:" + order.MerchantId, order);
  168. }
  169. }
  170. }
  171. }
  172. db.SaveChanges();
  173. db.Dispose();
  174. }
  175. catch (Exception ex)
  176. {
  177. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "微信分账队列异常");
  178. }
  179. Thread.Sleep(2000);
  180. }
  181. }
  182. }
  183. }