WeChatPayNotifyClient.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #if NETCOREAPP3_1
  2. using System;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Essensoft.AspNetCore.Payment.Security;
  8. using Essensoft.AspNetCore.Payment.WeChatPay.Notify;
  9. using Essensoft.AspNetCore.Payment.WeChatPay.Parser;
  10. using Essensoft.AspNetCore.Payment.WeChatPay.Utility;
  11. using Microsoft.AspNetCore.Http;
  12. using MD5 = Essensoft.AspNetCore.Payment.Security.MD5;
  13. namespace Essensoft.AspNetCore.Payment.WeChatPay
  14. {
  15. public class WeChatPayNotifyClient : IWeChatPayNotifyClient
  16. {
  17. #region WeChatPayNotifyClient Constructors
  18. public WeChatPayNotifyClient()
  19. {
  20. }
  21. #endregion
  22. #region IWeChatPayNotifyClient Members
  23. public async Task<T> ExecuteAsync<T>(HttpRequest request, WeChatPayOptions options) where T : WeChatPayNotify
  24. {
  25. if (request == null)
  26. {
  27. throw new ArgumentNullException(nameof(request));
  28. }
  29. if (options == null)
  30. {
  31. throw new ArgumentNullException(nameof(options));
  32. }
  33. if (string.IsNullOrEmpty(options.Key))
  34. {
  35. throw new ArgumentNullException(nameof(options.Key));
  36. }
  37. var body = await new StreamReader(request.Body, Encoding.UTF8).ReadToEndAsync();
  38. var parser = new WeChatPayNotifyXmlParser<T>();
  39. var notify = parser.Parse(body);
  40. if (notify is WeChatPayRefundNotify)
  41. {
  42. var key = MD5.Compute(options.Key).ToLowerInvariant();
  43. var data = AES.Decrypt((notify as WeChatPayRefundNotify).ReqInfo, key, CipherMode.ECB, PaddingMode.PKCS7);
  44. notify = parser.Parse(body, data);
  45. }
  46. else
  47. {
  48. CheckNotifySign(notify, options);
  49. }
  50. return notify;
  51. }
  52. #endregion
  53. #region Common Method
  54. private void CheckNotifySign(WeChatPayNotify notify, WeChatPayOptions options)
  55. {
  56. if (string.IsNullOrEmpty(notify.Body))
  57. {
  58. throw new WeChatPayException("sign check fail: Body is Empty!");
  59. }
  60. if (notify.Parameters.Count == 0)
  61. {
  62. throw new WeChatPayException("sign check fail: Parameters is Empty!");
  63. }
  64. if (!notify.Parameters.TryGetValue("sign", out var sign))
  65. {
  66. throw new WeChatPayException("sign check fail: sign is Empty!");
  67. }
  68. var cal_sign = WeChatPaySignature.SignWithKey(notify.Parameters, options.Key, WeChatPaySignType.MD5);
  69. if (cal_sign != sign)
  70. {
  71. throw new WeChatPayException("sign check fail: check Sign and Data Fail!");
  72. }
  73. }
  74. #endregion
  75. }
  76. }
  77. #endif