TongLianPayV1Processor.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. using System.Net;
  11. using System.Net.Security;
  12. using System.IO;
  13. namespace PaymentGateway.GatewayApp
  14. {
  15. public class TongLianAllInPayV1Processor : IPaymentProcessor
  16. {
  17. private IServiceProvider services;
  18. private ILogger logger;
  19. public TongLianAllInPayV1Processor(IServiceProvider services)
  20. {
  21. this.services = services;
  22. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  23. this.logger = loggerFactory.CreateLogger("DynamicPrivate_Gateway.Payment");
  24. }
  25. public async Task<GenericProcessResponse> Cancel(PaymentOrder order)
  26. {
  27. return new GenericProcessResponse()
  28. {
  29. AllInPayResponse = null
  30. };
  31. }
  32. public async Task<GenericProcessResponse> Process(PaymentOrder order)
  33. {
  34. order.TradeStatus = TradeStatusEnum.PAYERROR;
  35. var response = new Dictionary<string, string>();
  36. try
  37. {
  38. response = QrPay(order);
  39. if (IsSuccessful(response))
  40. {
  41. order.TradeStatus = TradeStatusEnum.SUCCESS;
  42. }
  43. if (response != null && response.ContainsKey("trxstatus") && response["trxstatus"] == "2000")
  44. {
  45. this.logger.LogDebug($"Continuous query trx result is ongoing for order: {order.ToSimpleLogString()}");
  46. // 当结果码为“2000”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议40秒)
  47. var config = (TongLianPayConfigV1)order.Config;
  48. response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
  49. this.logger.LogDebug($" Continuous query trx result has done for order: {order.ToSimpleLogString()} with response: {response}");
  50. if (IsSuccessful(response))
  51. {
  52. order.TradeStatus = TradeStatusEnum.SUCCESS;
  53. }
  54. }
  55. LogResponse(response);
  56. }
  57. catch (Exception ex)
  58. {
  59. this.logger.LogError($"Request AllInPay exceptioned: {ex.ToString()}");
  60. }
  61. return new GenericProcessResponse()
  62. {
  63. AllInPayResponse = response
  64. };
  65. }
  66. private async Task<Dictionary<string, string>> QueryTrxResult(PaymentOrder order, int interval = 10, int dueTime = 60)
  67. {
  68. this.logger.LogDebug($"AllInPay QueryTrxResult started, query interval = {interval}, dueTime = {dueTime}");
  69. var reponse = new GenericProcessResponse()
  70. {
  71. AllInPayResponse = new Dictionary<string, string>()
  72. };
  73. var cts = new CancellationTokenSource();
  74. try
  75. {
  76. await Task.WhenAny(PeriodicTaskV1.Run(Query, QuitQuerying, order, reponse, cts, TimeSpan.FromSeconds(interval)),
  77. Task.Delay(TimeSpan.FromSeconds(dueTime)));
  78. cts.Cancel();
  79. }
  80. catch (Exception ex)
  81. {
  82. this.logger.LogError($"QueryTrxResult exceptioned, msg {ex}");
  83. }
  84. return reponse.AllInPayResponse;
  85. }
  86. public async Task<GenericProcessResponse> Query(PaymentOrder order)
  87. {
  88. order.TradeStatus = TradeStatusEnum.PAYERROR;
  89. var response = DoQuery(order);
  90. if (IsSuccessful(response))
  91. {
  92. order.TradeStatus = TradeStatusEnum.SUCCESS;
  93. }
  94. LogResponse(response);
  95. return new GenericProcessResponse()
  96. {
  97. AllInPayResponse = response
  98. };
  99. }
  100. public async Task<GenericProcessResponse> Query(PaymentOrder order, GenericProcessResponse reponse, CancellationTokenSource cts)
  101. {
  102. var response = await Query(order);
  103. if (IsSuccessful(reponse.AllInPayResponse))
  104. {
  105. cts.Cancel();
  106. }
  107. return response;
  108. }
  109. public async Task<GenericProcessResponse> Return(PaymentOrder order)
  110. {
  111. order.TradeStatus = TradeStatusEnum.PAYERROR;
  112. var response = DoCancel(order);
  113. if (IsSuccessful(response))
  114. {
  115. order.TradeStatus = TradeStatusEnum.SUCCESS;
  116. }
  117. if (response != null && response.ContainsKey("trxstatus") && response["trxstatus"] == "2000")
  118. {
  119. //当结果码为“2000”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议40秒)
  120. var config = (TongLianPayConfigV1)order.Config;
  121. this.logger.LogDebug($"Continuous query trx result is ongoing for order: {order.ToSimpleLogString()}");
  122. response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
  123. this.logger.LogDebug($" Continuous query trx result has done for order: {order.ToSimpleLogString()} with response: {response}");
  124. if (IsSuccessful(response))
  125. {
  126. order.TradeStatus = TradeStatusEnum.SUCCESS;
  127. }
  128. }
  129. LogResponse(response);
  130. return new GenericProcessResponse()
  131. {
  132. AllInPayResponse = response
  133. };
  134. }
  135. public Dictionary<string, string> Pay(PaymentOrder order)
  136. {
  137. var config = (TongLianPayConfigV1)order.Config;
  138. var paramDic = BuildBasicParam(config);
  139. paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
  140. paramDic.Add("reqsn", order.BillNumber);
  141. paramDic.Add("paytype", "W01");
  142. paramDic.Add("body", order.Title);
  143. paramDic.Add("remark", "");
  144. paramDic.Add("acct", "");
  145. paramDic.Add("authcode", order.AuthCode);
  146. paramDic.Add("notify_url", config.notifyUrl);
  147. paramDic.Add("limit_pay", "");
  148. paramDic.Add("idno", "");
  149. paramDic.Add("truename", "");
  150. paramDic.Add("asinfo", "");
  151. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.appKey));
  152. return DoRequest(paramDic, "/pay", config);
  153. }
  154. public Dictionary<string, string> QrPay(PaymentOrder order)
  155. {
  156. if (string.IsNullOrEmpty(order.AuthCode))
  157. throw new ArgumentException("Must provide AuthCode for TongLianPayV1");
  158. if (string.IsNullOrEmpty(order.BillNumber))
  159. throw new ArgumentException("Must provide BillNumber for TongLianPayV1");
  160. var config = (TongLianPayConfigV1)order.Config;
  161. var paramDic = BuildBasicParam(config);
  162. paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
  163. paramDic.Add("reqsn", order.BillNumber);
  164. paramDic.Add("paytype", "W01");
  165. paramDic.Add("body", order.Title);
  166. paramDic.Add("remark", "");
  167. paramDic.Add("acct", "");
  168. paramDic.Add("authcode", order.AuthCode);
  169. paramDic.Add("notify_url", config.notifyUrl);
  170. paramDic.Add("limit_pay", "");
  171. paramDic.Add("idno", "");
  172. paramDic.Add("truename", "");
  173. paramDic.Add("asinfo", "");
  174. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.appKey));
  175. return DoRequest(paramDic, "/scanqrpay", config);
  176. }
  177. public Dictionary<string, string> DoCancel(PaymentOrder order)
  178. {
  179. if (string.IsNullOrEmpty(order.BillNumber))
  180. throw new ArgumentException("Must provide BillNumber for cancel a trx from remote payment provider");
  181. var config = (TongLianPayConfigV1)order.Config;
  182. var paramDic = BuildBasicParam(config);
  183. paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
  184. paramDic.Add("reqsn", DateTime.Now.ToFileTime().ToString());
  185. paramDic.Add("oldtrxid", "");
  186. paramDic.Add("oldreqsn", order.BillNumber);
  187. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.appKey));
  188. return DoRequest(paramDic, "/cancel", config);
  189. }
  190. public Dictionary<string, string> Refund(PaymentOrder order)
  191. {
  192. if (string.IsNullOrEmpty(order.BillNumber))
  193. throw new ArgumentException("Must provide BillNumber for TongLianPayV1");
  194. var config = (TongLianPayConfigV1)order.Config;
  195. var paramDic = BuildBasicParam(config);
  196. paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
  197. paramDic.Add("reqsn", DateTime.Now.ToFileTime().ToString());
  198. paramDic.Add("oldtrxid", "");
  199. paramDic.Add("oldreqsn", order.BillNumber);
  200. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.appKey));
  201. return DoRequest(paramDic, "/refund", config);
  202. }
  203. public Dictionary<string, string> DoQuery(PaymentOrder order)
  204. {
  205. //String reqsn, String trxid
  206. var config = (TongLianPayConfigV1)order.Config;
  207. var paramDic = BuildBasicParam(config);
  208. paramDic.Add("reqsn", order.BillNumber);
  209. paramDic.Add("trxid", "");
  210. paramDic.Add("sign", AllInPayAppUtil.signParam(paramDic, config.appKey));
  211. return DoRequest(paramDic, "/query", config);
  212. }
  213. private Dictionary<string, string> BuildBasicParam(TongLianPayConfigV1 config)
  214. {
  215. var paramDic = new Dictionary<string, string>();
  216. paramDic.Add("cusid", config.cusId);
  217. paramDic.Add("appid", config.appId);
  218. paramDic.Add("version", config.apiVersion);
  219. paramDic.Add("randomstr", DateTime.Now.ToFileTime().ToString());
  220. return paramDic;
  221. }
  222. private Dictionary<string, string> DoRequest(Dictionary<string, string> param, string url, TongLianPayConfigV1 config)
  223. {
  224. var rsp = CreatePostHttpResponse(config.apiUrl + url, param, Encoding.UTF8);
  225. var rspDic = (Dictionary<string, string>)System.Text.Json.JsonSerializer.Deserialize(rsp, typeof(Dictionary<string, string>));
  226. if ("SUCCESS".Equals(rspDic["retcode"], StringComparison.OrdinalIgnoreCase))//验签
  227. {
  228. var signRsp = rspDic["sign"];
  229. rspDic.Remove("sign");
  230. var sign = AllInPayAppUtil.signParam(rspDic, config.appKey);
  231. if (signRsp.Equals(sign))
  232. {
  233. return rspDic;
  234. }
  235. else
  236. throw new Exception("验签失败");
  237. }
  238. else if ("FAIL".Equals(rspDic["retcode"], StringComparison.OrdinalIgnoreCase))
  239. {
  240. return rspDic;
  241. }
  242. else
  243. {
  244. this.logger.LogError("Unexpected response from remote payment gateway, will try to logging it below:");
  245. LogResponse(rspDic);
  246. throw new Exception(rspDic["retmsg"]);
  247. }
  248. }
  249. 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)";
  250. private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
  251. {
  252. return true; //总是接受
  253. }
  254. public static String CreatePostHttpResponse(string url, IDictionary<string, string> parameters, Encoding charset)
  255. {
  256. HttpWebRequest request = null;
  257. //HTTPSQ请求
  258. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  259. request = WebRequest.Create(url) as HttpWebRequest;
  260. request.ProtocolVersion = HttpVersion.Version10;
  261. request.Method = "POST";
  262. request.ContentType = "application/x-www-form-urlencoded";
  263. request.UserAgent = DefaultUserAgent;
  264. //如果需要POST数据
  265. if (!(parameters == null || parameters.Count == 0))
  266. {
  267. StringBuilder buffer = new StringBuilder();
  268. int i = 0;
  269. foreach (string key in parameters.Keys)
  270. {
  271. if (i > 0)
  272. {
  273. buffer.AppendFormat("&{0}={1}", key, parameters[key]);
  274. }
  275. else
  276. {
  277. buffer.AppendFormat("{0}={1}", key, parameters[key]);
  278. }
  279. i++;
  280. }
  281. byte[] data = charset.GetBytes(buffer.ToString());
  282. using (Stream stream = request.GetRequestStream())
  283. {
  284. stream.Write(data, 0, data.Length);
  285. }
  286. }
  287. Stream outstream = request.GetResponse().GetResponseStream(); //获取响应的字符串流
  288. StreamReader sr = new StreamReader(outstream); //创建一个stream读取流
  289. return sr.ReadToEnd();
  290. }
  291. private void LogResponse(Dictionary<string, string> rspDic)
  292. {
  293. var rsp = "请求返回数据:\n";
  294. if (rspDic != null)
  295. {
  296. foreach (var item in rspDic)
  297. {
  298. rsp += item.Key + "-----" + item.Value + ";\n";
  299. }
  300. }
  301. this.logger.LogInformation($"AllInPay recieved response: {rsp}");
  302. }
  303. private bool IsSuccessful(Dictionary<string, string> response)
  304. {
  305. if (response != null && response.Count > 0)
  306. {
  307. if (response.ContainsKey("retcode") &&
  308. response["retcode"] == "SUCCESS")
  309. {
  310. if (response.ContainsKey("trxstatus") &&
  311. response["trxstatus"] == "0000")
  312. {
  313. return true;
  314. }
  315. }
  316. }
  317. return false;
  318. }
  319. private bool PayFailed(Dictionary<string, string> response)
  320. {
  321. if (response != null && response.Count > 0)
  322. {
  323. if (response.ContainsKey("retcode") &&
  324. response["retcode"] == "SUCCESS")
  325. {
  326. if (response.ContainsKey("trxstatus") &&
  327. response["trxstatus"] == "3045")
  328. {
  329. return true;
  330. }
  331. }
  332. }
  333. return false;
  334. }
  335. private bool QuitQuerying(Dictionary<string, string> response)
  336. {
  337. return IsSuccessful(response) || PayFailed(response);
  338. }
  339. public Task<GenericProcessResponse> UnifiedOrder(PaymentOrder order)
  340. {
  341. throw new NotImplementedException();
  342. }
  343. public Task<GenericProcessResponse> Query(PaymentOrder order, int count, int interval)
  344. {
  345. throw new NotImplementedException();
  346. }
  347. }
  348. public class PeriodicTaskV1
  349. {
  350. public static async Task Run(Func<PaymentOrder, GenericProcessResponse, CancellationTokenSource, Task<GenericProcessResponse>> process,
  351. Func<Dictionary<string, string>, bool> predicate, PaymentOrder order,
  352. GenericProcessResponse response, CancellationTokenSource cts, TimeSpan period)
  353. {
  354. while (!cts.Token.IsCancellationRequested)
  355. {
  356. if (!cts.Token.IsCancellationRequested)
  357. {
  358. response = await process(order, response, cts);
  359. if (response != null && predicate(response.AllInPayResponse))
  360. return;
  361. }
  362. await Task.Delay(period, cts.Token);
  363. }
  364. }
  365. }
  366. }