WeChatPayBackService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. var machines = db.PosMachines.Select(m => new { m.DeviceKind, m.BrandId, m.Detail, m.BindMerchantId }).Where(m => m.DeviceKind == "1" && m.BindMerchantId == order.MerchantId);
  88. foreach(var machine in machines)
  89. {
  90. if(machine.BrandId == 2)
  91. {
  92. TianYuVoiceHelper.Instance.doSomething(DateTime.Now.ToString("yyyyMMddHHmmssfff"), machine.Detail, order.PayMoney.ToString("f2"));
  93. }
  94. else if(machine.BrandId == 3)
  95. {
  96. MqLinksHelper.Instance.doSomething(machine.Detail, order.PayMoney.ToString("f2"));
  97. }
  98. }
  99. }
  100. }
  101. db.Dispose();
  102. }
  103. }
  104. }
  105. public string AesGcmDecrypt(string associatedData, string nonce, string ciphertext)
  106. {
  107. GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
  108. AeadParameters aeadParameters = new AeadParameters(
  109. new KeyParameter(Encoding.UTF8.GetBytes(AppConfig.WeChatParam.AesGemKey)),
  110. 128,
  111. Encoding.UTF8.GetBytes(nonce),
  112. Encoding.UTF8.GetBytes(associatedData));
  113. gcmBlockCipher.Init(false, aeadParameters);
  114. byte[] data = Convert.FromBase64String(ciphertext);
  115. byte[] plaintext = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
  116. int length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plaintext, 0);
  117. gcmBlockCipher.DoFinal(plaintext, length);
  118. return Encoding.UTF8.GetString(plaintext);
  119. }
  120. //分账队列
  121. public void StartProfitShare()
  122. {
  123. Thread th = new Thread(StartProfitShareListen);
  124. th.IsBackground = true;
  125. th.Start();
  126. }
  127. public void StartProfitShareListen()
  128. {
  129. bool op = true;
  130. while (op)
  131. {
  132. try
  133. {
  134. WebCMSEntities db = new WebCMSEntities();
  135. DateTime checkDate = DateTime.Now.AddMinutes(-1);
  136. 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();
  137. foreach(var sub in list)
  138. {
  139. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "微信分账队列异常");
  140. LogHelper.Instance.WriteLog("Id:" + sub.Id, "微信分账队列异常");
  141. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == sub.Id);
  142. if(order != null)
  143. {
  144. order.Status = 2;
  145. MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
  146. MerchantParamSet set = db.MerchantParamSet.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantParamSet();
  147. LogHelper.Instance.WriteLog("IsAct:" + order.IsAct, "微信分账队列监听");
  148. LogHelper.Instance.WriteLog("PayMoney:" + order.PayMoney, "微信分账队列监听");
  149. LogHelper.Instance.WriteLog("MinPayMoney:" + set.MinPayMoney, "微信分账队列监听");
  150. if(order.IsAct == 1 && order.PayMoney >= set.MinPayMoney)
  151. {
  152. MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
  153. //添加分账接收方
  154. if(merchant.Version == 0)
  155. {
  156. WeChatFunction.Instance.AddReceive(merchantAdd.SubMchid, "MERCHANT_ID", WeChatFunction.Instance.MchId, WeChatFunction.Instance.MchName, "PARTNER");
  157. merchant.Version = 1;
  158. db.SaveChanges();
  159. }
  160. LogHelper.Instance.WriteLog("准备分账", "微信分账队列监听");
  161. //发起分账
  162. decimal fee = order.PayMoney; //单位:分
  163. if(fee >= 1)
  164. {
  165. string TradeNo = order.SeoTitle;
  166. string OrderNo = order.OrderNo;
  167. List<ReceiverList> Receivers = new List<ReceiverList>();
  168. Receivers.Add(new ReceiverList()
  169. {
  170. type = "MERCHANT_ID", //分账接收方类型
  171. account = WeChatFunction.Instance.MchId, //分账接收方账号
  172. amount = int.Parse(fee.ToString("f0")), //分账金额
  173. description = "服务费", //分账描述
  174. });
  175. LogHelper.Instance.WriteLog("TradeNo:" + TradeNo, "微信分账队列监听");
  176. LogHelper.Instance.WriteLog("OrderNo:" + OrderNo, "微信分账队列监听");
  177. LogHelper.Instance.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(Receivers), "微信分账队列监听");
  178. string ProfitShareResult = WeChatFunction.Instance.ProfitShare(merchantAdd.SubMchid, TradeNo, OrderNo, Receivers);
  179. LogHelper.Instance.WriteLog("分账结果:" + ProfitShareResult, "微信分账队列监听");
  180. //开始监听分账状态
  181. Dictionary<string, object> req = new Dictionary<string, object>();
  182. req.Add("SubMchid", merchantAdd.SubMchid); //子商户号
  183. req.Add("TradeNo", TradeNo); //微信订单号
  184. req.Add("OrderNo", OrderNo); //商户订单号
  185. RedisDbconn.Instance.AddList("ProfitShareQueue", Newtonsoft.Json.JsonConvert.SerializeObject(req));
  186. }
  187. else
  188. {
  189. RedisDbconn.Instance.AddList("ConsumerOrders:Divi:2:List", order.Id.ToString());
  190. // RedisDbconn.Instance.AddRightList("ConsumerOrders:Divi:2:" + order.MerchantId, order);
  191. }
  192. }
  193. }
  194. LogHelper.Instance.WriteLog("\n\n", "微信分账队列监听");
  195. }
  196. db.SaveChanges();
  197. db.Dispose();
  198. }
  199. catch (Exception ex)
  200. {
  201. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "微信分账队列异常");
  202. }
  203. Thread.Sleep(2000);
  204. }
  205. }
  206. }
  207. }