TongLianPayV2Processor.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. using Microsoft.Extensions.DependencyInjection;
  2. using Microsoft.Extensions.Logging;
  3. using Gateway.Payment.Shared;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace PaymentGateway.GatewayApp
  11. {
  12. public class TongLianAllInPayV2Processor : IPaymentProcessor
  13. {
  14. private IServiceProvider services;
  15. private ILogger logger;
  16. public TongLianAllInPayV2Processor(IServiceProvider services)
  17. {
  18. this.services = services;
  19. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  20. this.logger = loggerFactory.CreateLogger("DynamicPrivate_Gateway.Payment");
  21. }
  22. public async Task<GenericProcessResponse> Cancel(PaymentOrder order)
  23. {
  24. return new GenericProcessResponse()
  25. {
  26. AllInPayResponse = null
  27. };
  28. }
  29. public async Task<GenericProcessResponse> Process(PaymentOrder order)
  30. {
  31. order.TradeStatus = TradeStatusEnum.PAYERROR;
  32. var response = new TongLianResponseV2();
  33. try
  34. {
  35. if (order.Optional?.ContainsKey("preCreatedBillNumber") ?? false)
  36. {
  37. var config = (TongLianPayConfigV2)order.Config;
  38. response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
  39. }
  40. else
  41. {
  42. response = QrPay(order);
  43. if (IsSuccessful(response))
  44. {
  45. order.TradeStatus = TradeStatusEnum.SUCCESS;
  46. }
  47. if (IsQueryResponse(response))
  48. {
  49. this.logger.LogDebug($"Continuous query trx result is ongoing for order: {order.ToSimpleLogString()}");
  50. // 当结果码为“2000”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议40秒)
  51. var config = (TongLianPayConfigV2)order.Config;
  52. response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
  53. this.logger.LogDebug($" Continuous query trx result has done for order: {order.ToSimpleLogString()} with response: {response}");
  54. if (IsSuccessful(response))
  55. {
  56. order.TradeStatus = TradeStatusEnum.SUCCESS;
  57. }
  58. }
  59. }
  60. }
  61. catch (Exception ex)
  62. {
  63. this.logger.LogError($"Request AllInPayV2 exceptioned: {ex.ToString()}");
  64. }
  65. return new GenericProcessResponse()
  66. {
  67. AllInPayResponseV2 = response
  68. };
  69. }
  70. private async Task<TongLianResponseV2> QueryTrxResult(PaymentOrder order, int interval = 10, int dueTime = 60)
  71. {
  72. this.logger.LogDebug($"AllInPayV2 QueryTrxResult started, query interval = {interval}, dueTime = {dueTime}");
  73. var reponse = new GenericProcessResponse()
  74. {
  75. AllInPayResponseV2 = new TongLianResponseV2()
  76. };
  77. var cts = new CancellationTokenSource();
  78. try
  79. {
  80. await Task.WhenAny(PeriodicTaskV2.Run(Query, QuitQuerying, order, reponse, cts, TimeSpan.FromSeconds(interval)),
  81. Task.Delay(TimeSpan.FromSeconds(dueTime)));
  82. cts.Cancel();
  83. }
  84. catch (Exception ex)
  85. {
  86. this.logger.LogError($"QueryTrxResult exceptioned, msg {ex}");
  87. }
  88. return reponse.AllInPayResponseV2;
  89. }
  90. public async Task<GenericProcessResponse> Query(PaymentOrder order)
  91. {
  92. order.TradeStatus = TradeStatusEnum.PAYERROR;
  93. var response = DoQuery(order);
  94. if (IsSuccessful(response))
  95. {
  96. order.TradeStatus = TradeStatusEnum.SUCCESS;
  97. }
  98. return new GenericProcessResponse()
  99. {
  100. AllInPayResponseV2 = response
  101. };
  102. }
  103. public async Task<GenericProcessResponse> Query(PaymentOrder order, GenericProcessResponse reponse, CancellationTokenSource cts)
  104. {
  105. var response = await Query(order);
  106. if (IsSuccessful(reponse.AllInPayResponseV2))
  107. {
  108. cts.Cancel();
  109. }
  110. return response;
  111. }
  112. public async Task<GenericProcessResponse> Return(PaymentOrder order)
  113. {
  114. order.TradeStatus = TradeStatusEnum.PAYERROR;
  115. var response = DoCancel(order);
  116. if (IsSuccessful(response))
  117. {
  118. order.TradeStatus = TradeStatusEnum.SUCCESS;
  119. }
  120. if (IsQueryResponse(response))
  121. {
  122. this.logger.LogDebug($"Continuous query trx result is ongoing for order: {order.ToSimpleLogString()}");
  123. //当结果码为“2000”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议40秒)
  124. var config = (TongLianPayConfigV2)order.Config;
  125. response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
  126. this.logger.LogDebug($" Continuous query trx result has done for order: {order.ToSimpleLogString()} with response: {response}");
  127. if (IsSuccessful(response))
  128. {
  129. order.TradeStatus = TradeStatusEnum.SUCCESS;
  130. }
  131. }
  132. //LogResponse(response);
  133. return new GenericProcessResponse()
  134. {
  135. AllInPayResponseV2 = response
  136. };
  137. }
  138. public TongLianResponseV2 QrPay(PaymentOrder order)
  139. {
  140. if (string.IsNullOrEmpty(order.AuthCode))
  141. throw new ArgumentException("Must provide AuthCode for TongLianPayV1");
  142. if (string.IsNullOrEmpty(order.BillNumber))
  143. throw new ArgumentException("Must provide BillNumber for TongLianPayV1");
  144. var config = (TongLianPayConfigV2)order.Config;
  145. var paramDic = BuildBasicParam(config);
  146. var amount = Convert.ToInt32(order.NetAmount * 100);
  147. var bizContent = new BizContent
  148. {
  149. sysId = config.sysId,
  150. bizOrderNo = order.BillNumber,
  151. amount = amount,
  152. consumeTypes = new List<ConsumeType>()
  153. {
  154. new ConsumeType {amount = amount, type = "C0001"}
  155. },
  156. oilStation = new OilStation
  157. {
  158. oilStationNo = config.oilStationNo,
  159. },
  160. shiftsTime = DateTime.Now.ToString("yyyyMMdd"),
  161. shiftsMask = config.shiftsMask
  162. };
  163. bizContent.authCode = order.AuthCode;
  164. bizContent.payType = "CODEPAY_VSP";
  165. paramDic.Add("bizContent", bizContent);
  166. paramDic.Add("service", "oil.pay.apply");
  167. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.key, true));
  168. return DoRequest(paramDic, "", config);
  169. }
  170. public TongLianResponseV2 PlaceUnifiedOrder(PaymentOrder order)
  171. {
  172. var config = (TongLianPayConfigV2)order.Config;
  173. var paramDic = BuildBasicParam(config);
  174. var amount = Convert.ToInt32(order.NetAmount * 100);
  175. var bizContent = new BizContent
  176. {
  177. sysId = config.sysId,
  178. bizOrderNo = order.BillNumber,
  179. amount = amount,
  180. consumeTypes = new List<ConsumeType>()
  181. {
  182. new ConsumeType {amount = amount, type = "C0001"}
  183. },
  184. oilStation = new OilStation
  185. {
  186. oilStationNo = config.oilStationNo,
  187. },
  188. shiftsTime = DateTime.Now.ToString("yyyyMMdd"),
  189. shiftsMask = config.shiftsMask
  190. };
  191. bizContent.account = order.Optional["mobilePayId"] as string;
  192. bizContent.subAppId = config.subAppId;
  193. bizContent.amount = amount;
  194. bizContent.payType = "WECHATPAY_MINIPROGRAM";
  195. paramDic.Add("bizContent", bizContent);
  196. paramDic.Add("service", "oil.pay.apply");
  197. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.key, true));
  198. return DoRequest(paramDic, "", config);
  199. }
  200. public TongLianResponseV2 DoCancel(PaymentOrder order)
  201. {
  202. if (string.IsNullOrEmpty(order.BillNumber))
  203. throw new ArgumentException("Must provide BillNumber for cancel a trx from remote payment provider");
  204. var config = (TongLianPayConfigV2)order.Config;
  205. var paramDic = BuildBasicParam(config);
  206. var bizContent = new BizContent
  207. {
  208. sysId = config.sysId,
  209. bizOrderNo = SequenceNumber.Next(),
  210. oldBizOrderNo = order.BillNumber,
  211. amount = Convert.ToInt32(order.NetAmount * 100),
  212. consumeTypes = new List<ConsumeType>()
  213. {
  214. new ConsumeType {amount = Convert.ToInt32(order.NetAmount * 100), type = "C0001"}
  215. },
  216. shiftsTime = DateTime.Now.ToString("yyyyMMdd"),
  217. shiftsMask = config.shiftsMask
  218. };
  219. paramDic.Add("bizContent", bizContent);
  220. paramDic.Add("service", "oil.pay.refund");
  221. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.key, true));
  222. return DoRequest(paramDic, "", config);
  223. }
  224. public TongLianResponseV2 DoQuery(PaymentOrder order)
  225. {
  226. //String reqsn, String trxid
  227. var config = (TongLianPayConfigV2)order.Config;
  228. var paramDic = BuildBasicParam(config);
  229. var bizContent = new BizContent
  230. {
  231. sysId = config.sysId,
  232. bizOrderNo = order.BillNumber
  233. };
  234. paramDic.Add("bizContent", bizContent);
  235. paramDic.Add("service", "oil.pay.query");
  236. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.key, true));
  237. return DoRequest(paramDic, "", config);
  238. }
  239. private Dictionary<string, object> BuildBasicParam(TongLianPayConfigV2 config)
  240. {
  241. var paramDic = new Dictionary<string, object>();
  242. paramDic.Add("appId", config.appId);
  243. paramDic.Add("version", config.version);
  244. paramDic.Add("charset", config.charset);
  245. paramDic.Add("timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
  246. return paramDic;
  247. }
  248. private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
  249. private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
  250. {
  251. return true; //总是接受
  252. }
  253. public String CreatePostHttpResponse(string url, Dictionary<string, object> parameters, Encoding charset)
  254. {
  255. System.Net.HttpWebRequest request = null;
  256. //HTTPSQ请求
  257. System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  258. request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
  259. request.ProtocolVersion = System.Net.HttpVersion.Version10;
  260. request.Method = "POST";
  261. request.ContentType = "application/x-www-form-urlencoded";
  262. request.UserAgent = DefaultUserAgent;
  263. //如果需要POST数据
  264. if (!(parameters == null || parameters.Count == 0))
  265. {
  266. StringBuilder buffer = new StringBuilder();
  267. int i = 0;
  268. foreach (string key in parameters.Keys)
  269. {
  270. if (key == "key")
  271. {
  272. continue;
  273. }
  274. var value = parameters[key];
  275. if (!(value is string))
  276. {
  277. value = System.Text.Json.JsonSerializer.Serialize(value);
  278. }
  279. if (i > 0)
  280. {
  281. buffer.AppendFormat("&{0}={1}", key, value);
  282. }
  283. else
  284. {
  285. buffer.AppendFormat("{0}={1}", key, value);
  286. }
  287. i++;
  288. }
  289. var bufString = buffer.ToString();
  290. this.logger.LogDebug($"AllInPay or AllInPayV2 CreatePostHttpResponse request: {bufString}");
  291. var urlEncodedStr = System.Web.HttpUtility.UrlEncode(bufString);
  292. byte[] data = charset.GetBytes(buffer.ToString());
  293. using (System.IO.Stream stream = request.GetRequestStream())
  294. {
  295. stream.Write(data, 0, data.Length);
  296. }
  297. }
  298. System.IO.Stream outstream = request.GetResponse().GetResponseStream(); //获取响应的字符串流
  299. System.IO.StreamReader sr = new System.IO.StreamReader(outstream); //创建一个stream读取流
  300. return sr.ReadToEnd();
  301. }
  302. private TongLianResponseV2 DoRequest(Dictionary<string, object> param, string url, TongLianPayConfigV2 config)
  303. {
  304. var rawRsp = CreatePostHttpResponse(config.apiUrl + url, param, Encoding.UTF8);
  305. var response = (TongLianResponseV2)System.Text.Json.JsonSerializer.Deserialize(rawRsp, typeof(TongLianResponseV2));
  306. LogResponse(response);
  307. return response;
  308. }
  309. private void LogResponse(TongLianResponseV2 response)
  310. {
  311. this.logger.LogInformation($"请求返回数据:AllInPayV2 recieved response: {response}");
  312. }
  313. private bool IsSuccessful(TongLianResponseV2 response)
  314. {
  315. return response.code == "SUCCESS" && response.bizCode == "0000" && response.payStatus == "0000";
  316. }
  317. private bool IsQueryResponse(TongLianResponseV2 response)
  318. {
  319. // 当结果码为“2000”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议40秒)
  320. return response.bizCode == "2000" || response.payStatus == "2000";
  321. }
  322. private bool PayFailed(TongLianResponseV2 response)
  323. {
  324. return response.code == "SUCCESS" &&
  325. (response.bizCode == "3045" || response.bizCode == "3999" || response.bizCode == "4999" || response.bizCode == "9999"
  326. || response.payStatus == "3045" || response.payStatus == "3999" || response.payStatus == "4999" || response.payStatus == "9999");
  327. }
  328. private bool QuitQuerying(TongLianResponseV2 response)
  329. {
  330. return IsSuccessful(response) || PayFailed(response);
  331. }
  332. public async Task<GenericProcessResponse> UnifiedOrder(PaymentOrder order)
  333. {
  334. order.TradeStatus = TradeStatusEnum.PAYERROR;
  335. var response = new TongLianResponseV2();
  336. try
  337. {
  338. response = PlaceUnifiedOrder(order);
  339. if (IsSuccessful(response))
  340. {
  341. order.TradeStatus = TradeStatusEnum.SUCCESS;
  342. }
  343. if (IsQueryResponse(response) && !string.IsNullOrEmpty(response.payInfo))
  344. {
  345. order.TradeStatus = TradeStatusEnum.SUCCESS;
  346. }
  347. }
  348. catch (Exception ex)
  349. {
  350. this.logger.LogError($"Request AllInPayV2 exceptioned: {ex.ToString()}");
  351. }
  352. return new GenericProcessResponse()
  353. {
  354. AllInPayResponseV2 = response
  355. };
  356. }
  357. public async Task<GenericProcessResponse> Query(PaymentOrder order, int count, int interval)
  358. {
  359. order.TradeStatus = TradeStatusEnum.PAYERROR;
  360. var response = new TongLianResponseV2();
  361. try
  362. {
  363. // 当结果码为“2000”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议40秒)
  364. var config = (TongLianPayConfigV2)order.Config;
  365. response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
  366. if (IsSuccessful(response))
  367. {
  368. order.TradeStatus = TradeStatusEnum.SUCCESS;
  369. }
  370. }
  371. catch (Exception ex)
  372. {
  373. this.logger.LogError($"Request AllInPayV2 exceptioned: {ex.ToString()}");
  374. }
  375. return new GenericProcessResponse()
  376. {
  377. AllInPayResponseV2 = response
  378. };
  379. }
  380. }
  381. public class PeriodicTaskV2
  382. {
  383. public static async Task Run(Func<PaymentOrder, GenericProcessResponse, CancellationTokenSource, Task<GenericProcessResponse>> process,
  384. Func<TongLianResponseV2, bool> predicate, PaymentOrder order,
  385. GenericProcessResponse response, CancellationTokenSource cts, TimeSpan period)
  386. {
  387. while (!cts.Token.IsCancellationRequested)
  388. {
  389. if (!cts.Token.IsCancellationRequested)
  390. {
  391. response = await process(order, response, cts);
  392. if (response != null && predicate(response.AllInPayResponseV2))
  393. return;
  394. }
  395. await Task.Delay(period, cts.Token);
  396. }
  397. }
  398. }
  399. public class TongLianResponseV2
  400. {
  401. public string amount { get; set; }
  402. public string bizCode { get; set; }
  403. public string bizMsg { get; set; }
  404. public string bizOrderNo { get; set; }
  405. public string createTime { get; set; }
  406. public string code { get; set; }
  407. public string finishTime { get; set; }
  408. public string msg { get; set; }
  409. public string oldBizOrderNo { get; set; }
  410. public string orderNo { get; set; }
  411. public string payInfo { get; set; }
  412. public string payStatus { get; set; }
  413. public string payStatusMsg { get; set; }
  414. public string payType { get; set; }
  415. public string remark { get; set; }
  416. public string shiftsMask { get; set; }
  417. public string shiftsTime { get; set; }
  418. public string sign { get; set; }
  419. public string sysId { get; set; }
  420. public string tradeDirection { get; set; }
  421. public string consumeTypes { get; set; }
  422. public override string ToString()
  423. {
  424. var sb = new StringBuilder();
  425. PropertyInfo[] properties = typeof(TongLianResponseV2).GetProperties();
  426. foreach (PropertyInfo property in properties)
  427. {
  428. sb.Append($"{property.Name}: {property.GetValue(this)}\n");
  429. }
  430. return sb.ToString();
  431. }
  432. }
  433. public class BizContent
  434. {
  435. public string account { get; set; }
  436. public long amount { get; set; }
  437. public string authCode { get; set; }
  438. public string bizOrderNo { get; set; }
  439. public List<ConsumeType> consumeTypes { get; set; }
  440. public OilStation oilStation { get; set; }
  441. public string oldBizOrderNo { get; set; }
  442. public string payType { get; set; }
  443. public string shiftsMask { get; set; }
  444. public string shiftsTime { get; set; }
  445. public string subAppId { get; set; }
  446. public string sysId { get; set; }
  447. }
  448. public class ConsumeType
  449. {
  450. public int amount { get; set; }
  451. public string type { get; set; }
  452. }
  453. public class OilStation
  454. {
  455. //public string oilGunNo { get; set; }
  456. public string oilStationNo { get; set; }
  457. //public string oilStationPersonNo { get; set; }
  458. }
  459. }