OrdersPayService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Linq;
  5. using System.Data;
  6. using MySystem;
  7. using Library;
  8. using LitJson;
  9. using Aop.Api;
  10. using Aop.Api.Request;
  11. using Newtonsoft.Json;
  12. using Aop.Api.Response;
  13. using System.Net;
  14. using System.Security.Cryptography;
  15. using System.IO;
  16. using MySystem.MainModels;
  17. using Microsoft.AspNetCore.Http;
  18. using Microsoft.Extensions.Logging;
  19. using MySystem.Areas.Api.Controllers;
  20. using Microsoft.Extensions.Options;
  21. /// <summary>
  22. /// 来客吧支付
  23. /// </summary>
  24. public class OrdersPayService
  25. {
  26. public readonly static OrdersPayService Instance = new OrdersPayService();
  27. private OrdersPayService()
  28. {
  29. }
  30. public void StartEverTime()
  31. {
  32. Thread th = new Thread(StartEverTimeDo);
  33. th.IsBackground = true;
  34. th.Start();
  35. }
  36. #region 来客吧支付队列
  37. private void StartEverTimeDo()
  38. {
  39. while (true)
  40. {
  41. try
  42. {
  43. string data = RedisDbconn.Instance.RPop<string>("OrdersPayQueue");
  44. if (!string.IsNullOrEmpty(data))
  45. {
  46. function.WriteLog("data:" + data, "来客吧支付回调日志");
  47. JsonData jsonData = JsonMapper.ToObject(data);
  48. string SnNo = jsonData["Sn"].ToString(); //码牌SN
  49. int PayMode = int.Parse(function.CheckInt(jsonData["PayMode"].ToString())); //支付方式
  50. decimal PayMoney = decimal.Parse(function.CheckNum(jsonData["PayMoney"].ToString())); //支付金额
  51. string Code = jsonData["Code"].ToString(); // 订单唯一标识
  52. string OnlyFlag = jsonData["OnlyFlag"].ToString();
  53. string Value = jsonData["Value"].ToString();
  54. Dictionary<string, object> Obj = new Dictionary<string, object>();
  55. MySystem.AppResultJson returnObj = new MySystem.AppResultJson();
  56. MerchantQrCode qrcode = MerchantQrCodeDbconn.Instance.Get(SnNo) ?? new MerchantQrCode();
  57. PosMachinesTwo pos = PosMachinesTwoDbconn.Instance.Get(SnNo) ?? new PosMachinesTwo();
  58. PosMachines machine = PosMachinesDbconn.Instance.Get(SnNo) ?? new PosMachines();
  59. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "-5", "支付时间监控");
  60. int MerchantId = pos.BindMerchantId;
  61. if (machine.DeviceKind == "1")
  62. {
  63. MerchantId = machine.BindMerchantId;
  64. }
  65. if (pos.OpId == 1 || machine.DeviceKind == "1")
  66. {
  67. WebCMSEntities maindb = new WebCMSEntities();
  68. MerchantInfo merchant = MerchantInfoDbconn.Instance.Get(MerchantId) ?? new MerchantInfo();
  69. MerchantAddInfo merchantAdd = MerchantAddInfoDbconn.Instance.Get(MerchantId) ?? new MerchantAddInfo();
  70. MerchantParamSet merchantset = MerchantParamSetDbconn.Instance.Get(MerchantId) ?? new MerchantParamSet();
  71. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "-6", "支付时间监控");
  72. //通过Code获取OpenId
  73. string openid = GetOpenIdByCodeAndPayMode(Code, PayMode);
  74. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "-7", "支付时间监控");
  75. //通过OpenId获取ConsumerId
  76. int ConsumerId = GetConsumerIdByOpenId(openid);
  77. string OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
  78. bool ActFlag = merchantset.IsAll == 1 ? false : true;
  79. if (PayMoney < merchantset.MinPayMoney) //支付金额小于活动最小金额,则不分账
  80. {
  81. ActFlag = false;
  82. }
  83. ConsumerOrders order = maindb.ConsumerOrders.Add(new ConsumerOrders()
  84. {
  85. // Id = PublicFunction.MakeConsumerOrderId(),
  86. CreateDate = DateTime.Now, //创建时间
  87. MerchantId = MerchantId, //商户
  88. ConsumerId = ConsumerId, //消费者
  89. UserId = merchant.UserId, //创客
  90. PayMode = PayMode, //支付方式
  91. PayMoney = PayMoney, //支付金额
  92. SnNo = SnNo, //SN号
  93. OrderNo = OrderNo,
  94. MaxDivi = ActFlag ? PayMoney * merchantset.DiviPercent / 100 : 0,
  95. IsAct = ActFlag ? 1u : 0u,
  96. MerchantActualAmount = ActFlag ? PayMoney * merchantset.GetPercent / 100 : PayMoney,
  97. SeoDescription = Newtonsoft.Json.JsonConvert.SerializeObject(merchantset),
  98. }).Entity;
  99. maindb.SaveChanges();
  100. maindb.ConsumerOrderForNo.Add(new ConsumerOrderForNo()
  101. {
  102. OrderNo = OrderNo,
  103. OrderIds = order.Id,
  104. });
  105. maindb.SaveChanges();
  106. if (PayMode == 1)
  107. {
  108. string backString = new AlipayFunction().CreateTrade(OrderNo, merchant.Name, PayMoney, openid, merchantAdd.AlipayAuthToken, ConfigurationManager.AppSettings["SpHost"].ToString() + "/api/alipay/notice");
  109. JsonData obj = JsonMapper.ToObject(backString);
  110. if (obj["alipay_trade_create_response"]["code"].ToString() == "10000")
  111. {
  112. string tradeNo = obj["alipay_trade_create_response"]["trade_no"].ToString();
  113. Obj.Add("respCode", obj["alipay_trade_create_response"]["code"].ToString());
  114. Obj.Add("tradeNo", tradeNo);
  115. }
  116. else
  117. {
  118. Obj.Add("respCode", obj["alipay_trade_create_response"]["code"].ToString());
  119. Obj.Add("tradeNo", "");
  120. returnObj = new MySystem.AppResultJson() { Status = "-1", Info = obj["alipay_trade_create_response"]["sub_msg"].ToString(), Data = Obj };
  121. }
  122. }
  123. else if (PayMode == 2)
  124. {
  125. string SubMchId = merchantAdd.SubMchid;
  126. string Description = merchant.Name;
  127. string OpenId = openid;
  128. string Key = AppConfig.WeChatParam.AesGemKey;
  129. string NotifyUrl = ConfigurationManager.AppSettings["SpHost"].ToString() + "/api/wechat/notice";
  130. Dictionary<string, string> dic = new WeChatFunction().Pay(SubMchId, PayMoney, OrderNo, Description, OpenId, Key, NotifyUrl, ActFlag);
  131. Obj.Add("appId", dic["appId"]); //微信小程序appid
  132. Obj.Add("timeStamp", dic["timeStamp"]); //时间戳
  133. Obj.Add("nonceStr", dic["nonceStr"]); //随机字符串
  134. Obj.Add("package", dic["package"]); //统一支付接口返回的prepayid参数值
  135. Obj.Add("paySign", dic["paySign"]); //支付签名
  136. Obj.Add("ConsumerId", ConsumerId);
  137. }
  138. RedisDbconn.Instance.AddList("OrdersPayBack:" + OnlyFlag, Newtonsoft.Json.JsonConvert.SerializeObject(returnObj));
  139. }
  140. else
  141. {
  142. string result = function.PostWebRequest(AppConfig.Base.Host2 + "api/v1/consumerorders/pay", "value=" + Value);
  143. // return Newtonsoft.Json.JsonConvert.DeserializeObject<AppResultJson>(result);
  144. RedisDbconn.Instance.AddList("OrdersPayBack:" + OnlyFlag, result);
  145. }
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧支付回调线程异常");
  151. }
  152. }
  153. }
  154. #endregion
  155. #region 通过Code和支付方式获取OpenId
  156. /// <summary>
  157. /// 通过Code获取OpenId
  158. /// </summary>
  159. /// <param name="Code">消费者编码</param>
  160. /// <param name="PayMode">支付方式(1 支付宝 2 微信)</param>
  161. /// <returns></returns>
  162. public string GetOpenIdByCodeAndPayMode(string Code, int PayMode)
  163. {
  164. var OpenId = "";
  165. if (PayMode == 1)
  166. {
  167. OpenId = new AlipayFunction().GetAlipayUserId(Code);
  168. if (OpenId.Contains("|"))
  169. {
  170. OpenId = OpenId.Split('|')[0];
  171. }
  172. }
  173. else
  174. {
  175. string result = function.GetWebRequest("https://api.weixin.qq.com/sns/jscode2session?appid=" + new WeChatFunction().AppId + "&secret=" + new WeChatFunction().AppSecret + "&js_code=" + Code + "&grant_type=authorization_code");
  176. function.WriteLog(DateTime.Now.ToString() + "\n" + result, "微信小程序获取openid");
  177. JsonData jsonObj = JsonMapper.ToObject(result);
  178. OpenId = jsonObj["openid"].ToString();
  179. }
  180. return OpenId;
  181. }
  182. #endregion
  183. #region 通过OpenId获取ConsumerId
  184. /// <summary>
  185. /// 通过OpenId获取ConsumerId
  186. /// </summary>
  187. /// <param name="OpenId">消费者唯一标识</param>
  188. /// <returns></returns>
  189. public int GetConsumerIdByOpenId(string OpenId)
  190. {
  191. WebCMSEntities maindb = new WebCMSEntities();
  192. var ConsumerId = 0;
  193. Consumers check = maindb.Consumers.FirstOrDefault(m => m.WechatOpenId == OpenId);
  194. if (check == null)
  195. {
  196. // ConsumerId = PublicFunction.MakeConsumerId();
  197. Consumers consumer = maindb.Consumers.Add(new Consumers()
  198. {
  199. Id = ConsumerId,
  200. CreateDate = DateTime.Now,
  201. WechatOpenId = OpenId,
  202. }).Entity;
  203. maindb.SaveChanges();
  204. ConsumerId = consumer.Id;
  205. }
  206. else
  207. {
  208. ConsumerId = check.Id;
  209. }
  210. maindb.SaveChanges();
  211. return ConsumerId;
  212. }
  213. #endregion
  214. }