WeChatPayBackService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. // decimal hdfee = 0.0038M * order.PayMoney * (1 - set.GetPercent - 0.01M);
  168. // hdfee = decimal.Parse(hdfee.ToString("f2"));
  169. // decimal servicefee = 0.01M * order.PayMoney - hdfee;
  170. // servicefee = servicefee * 100;
  171. // int servicefeeNum = int.Parse(servicefee.ToString("f0"));
  172. List<ReceiverList> Receivers = new List<ReceiverList>();
  173. Receivers.Add(new ReceiverList()
  174. {
  175. type = "MERCHANT_ID", //分账接收方类型
  176. account = WeChatFunction.Instance.MchId, //分账接收方账号
  177. amount = int.Parse(fee.ToString("f0")), //分账金额
  178. description = "服务费", //分账描述
  179. });
  180. LogHelper.Instance.WriteLog("TradeNo:" + TradeNo, "微信分账队列监听");
  181. LogHelper.Instance.WriteLog("OrderNo:" + OrderNo, "微信分账队列监听");
  182. LogHelper.Instance.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(Receivers), "微信分账队列监听");
  183. string ProfitShareResult = WeChatFunction.Instance.ProfitShare(merchantAdd.SubMchid, TradeNo, OrderNo, Receivers);
  184. LogHelper.Instance.WriteLog("分账结果:" + ProfitShareResult, "微信分账队列监听");
  185. order.DivideLog = "请求分账日志:" + ProfitShareResult;
  186. order.DivideFlag = 1;
  187. db.SaveChanges();
  188. //开始监听分账状态
  189. Dictionary<string, object> req = new Dictionary<string, object>();
  190. req.Add("SubMchid", merchantAdd.SubMchid); //子商户号
  191. req.Add("TradeNo", TradeNo); //微信订单号
  192. req.Add("OrderNo", OrderNo); //商户订单号
  193. RedisDbconn.Instance.AddList("ProfitShareQueue", Newtonsoft.Json.JsonConvert.SerializeObject(req));
  194. }
  195. else
  196. {
  197. RedisDbconn.Instance.AddList("ConsumerOrders:Divi:2:List", order.Id.ToString());
  198. // RedisDbconn.Instance.AddRightList("ConsumerOrders:Divi:2:" + order.MerchantId, order);
  199. }
  200. }
  201. }
  202. LogHelper.Instance.WriteLog("\n\n", "微信分账队列监听");
  203. }
  204. db.SaveChanges();
  205. db.Dispose();
  206. }
  207. catch (Exception ex)
  208. {
  209. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "微信分账队列异常");
  210. }
  211. Thread.Sleep(2000);
  212. }
  213. }
  214. //触发分账接口
  215. public void StartDivi()
  216. {
  217. Thread th = new Thread(ListenDivi);
  218. th.IsBackground = true;
  219. th.Start();
  220. }
  221. public void ListenDivi()
  222. {
  223. bool op = true;
  224. while (op)
  225. {
  226. string content = RedisDbconn.Instance.RPop<string>("AddWeChatDiviQueue");
  227. if (!string.IsNullOrEmpty(content))
  228. {
  229. try
  230. {
  231. int id = int.Parse(function.CheckInt(content));
  232. WebCMSEntities db = new WebCMSEntities();
  233. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == id);
  234. if (order != null)
  235. {
  236. MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
  237. MerchantParamSet set = db.MerchantParamSet.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantParamSet();
  238. if (order.IsAct == 1 && order.PayMoney >= set.MinPayMoney)
  239. {
  240. //发起分账
  241. decimal fee = order.PayMoney; //单位:分
  242. if (fee >= 1)
  243. {
  244. string TradeNo = order.SeoTitle;
  245. string OrderNo = order.OrderNo;
  246. List<ReceiverList> Receivers = new List<ReceiverList>();
  247. Receivers.Add(new ReceiverList()
  248. {
  249. type = "MERCHANT_ID", //分账接收方类型
  250. account = WeChatFunction.Instance.MchId, //分账接收方账号
  251. amount = int.Parse(fee.ToString("f0")), //分账金额
  252. description = "服务费", //分账描述
  253. });
  254. LogHelper.Instance.WriteLog("TradeNo:" + TradeNo, "微信分账队列监听");
  255. LogHelper.Instance.WriteLog("OrderNo:" + OrderNo, "微信分账队列监听");
  256. LogHelper.Instance.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(Receivers), "微信分账队列监听");
  257. string ProfitShareResult = WeChatFunction.Instance.ProfitShare(merchantAdd.SubMchid, TradeNo, OrderNo, Receivers);
  258. LogHelper.Instance.WriteLog("分账结果:" + ProfitShareResult, "微信分账队列监听");
  259. order.DivideLog = "请求分账日志:" + ProfitShareResult;
  260. order.DivideFlag = 1;
  261. db.SaveChanges();
  262. //开始监听分账状态
  263. Dictionary<string, object> req = new Dictionary<string, object>();
  264. req.Add("SubMchid", merchantAdd.SubMchid); //子商户号
  265. req.Add("TradeNo", TradeNo); //微信订单号
  266. req.Add("OrderNo", OrderNo); //商户订单号
  267. RedisDbconn.Instance.AddList("ProfitShareQueue", Newtonsoft.Json.JsonConvert.SerializeObject(req));
  268. }
  269. }
  270. }
  271. db.Dispose();
  272. }
  273. catch (Exception ex)
  274. {
  275. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "补微信分账异常");
  276. }
  277. }
  278. else
  279. {
  280. Thread.Sleep(2000);
  281. }
  282. }
  283. }
  284. }
  285. }