NotifyProcess.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System.IO;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using PaySharp.Core.Utils;
  5. namespace PaySharp.Core
  6. {
  7. /// <summary>
  8. /// 网关通知的处理类,通过对返回数据的分析识别网关类型
  9. /// </summary>
  10. internal static class NotifyProcess
  11. {
  12. /// <summary>
  13. /// 是否是Xml格式数据
  14. /// </summary>
  15. /// <returns></returns>
  16. private static bool IsXmlData => HttpUtil.ContentType == "text/xml" || HttpUtil.ContentType == "application/xml";
  17. /// <summary>
  18. /// 是否是GET请求
  19. /// </summary>
  20. /// <returns></returns>
  21. private static bool IsGetRequest => HttpUtil.RequestType == "GET";
  22. /// <summary>
  23. /// 获取网关
  24. /// </summary>
  25. /// <param name="gateways">网关列表</param>
  26. /// <returns></returns>
  27. public static async Task<BaseGateway> GetGatewayAsync(IGateways gateways)
  28. {
  29. var gatewayData = await ReadNotifyDataAsync();
  30. BaseGateway gateway = null;
  31. foreach (var item in gateways.GetList())
  32. {
  33. if (ExistParameter(item.NotifyVerifyParameter, gatewayData))
  34. {
  35. if (item.Merchant.AppId == gatewayData
  36. .GetStringValue(item.NotifyVerifyParameter.FirstOrDefault()))
  37. {
  38. gateway = item;
  39. break;
  40. }
  41. }
  42. }
  43. if (gateway is null)
  44. {
  45. gateway = new NullGateway();
  46. }
  47. gateway.GatewayData = gatewayData;
  48. return gateway;
  49. }
  50. /// <summary>
  51. /// 网关参数数据项中是否存在指定的所有参数名
  52. /// </summary>
  53. /// <param name="parmaName">参数名数组</param>
  54. /// <param name="gatewayData">网关数据</param>
  55. public static bool ExistParameter(string[] parmaName, GatewayData gatewayData)
  56. {
  57. var compareCount = 0;
  58. foreach (var item in parmaName)
  59. {
  60. if (gatewayData.Exists(item))
  61. {
  62. compareCount++;
  63. }
  64. }
  65. return compareCount == parmaName.Length;
  66. }
  67. /// <summary>
  68. /// 读取网关发回的数据
  69. /// </summary>
  70. /// <returns></returns>
  71. public static async Task<GatewayData> ReadNotifyDataAsync()
  72. {
  73. var gatewayData = new GatewayData();
  74. if (IsGetRequest)
  75. {
  76. gatewayData.FromUrl(HttpUtil.QueryString);
  77. }
  78. else
  79. {
  80. if (IsXmlData)
  81. {
  82. var reader = new StreamReader(HttpUtil.Body);
  83. var xmlData = await reader.ReadToEndAsync();
  84. gatewayData.FromXml(xmlData);
  85. }
  86. else
  87. {
  88. try
  89. {
  90. #if NETCOREAPP3_1
  91. gatewayData.FromForm(HttpUtil.Form);
  92. #else
  93. gatewayData.FromNameValueCollection(HttpUtil.Form);
  94. #endif
  95. }
  96. catch { }
  97. }
  98. }
  99. return gatewayData;
  100. }
  101. }
  102. }