AlipayNotifyClient.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using Essensoft.AspNetCore.Payment.Alipay.Parser;
  6. using Essensoft.AspNetCore.Payment.Alipay.Utility;
  7. namespace Essensoft.AspNetCore.Payment.Alipay
  8. {
  9. public class AlipayNotifyClient : IAlipayNotifyClient
  10. {
  11. #region AlipayNotifyClient Constructors
  12. public AlipayNotifyClient()
  13. {
  14. }
  15. #endregion
  16. #region IAlipayNotifyClient Members
  17. public Task<T> ExecuteAsync<T>(IDictionary<string, string> parameters, AlipayOptions options) where T : AlipayNotify
  18. {
  19. if (options == null)
  20. {
  21. throw new ArgumentNullException(nameof(options));
  22. }
  23. if (string.IsNullOrEmpty(options.SignType))
  24. {
  25. throw new ArgumentNullException(nameof(options.SignType));
  26. }
  27. if (string.IsNullOrEmpty(options.AppPrivateKey))
  28. {
  29. throw new ArgumentNullException(nameof(options.AppPrivateKey));
  30. }
  31. var parser = new AlipayDictionaryParser<T>();
  32. var rsp = parser.Parse(parameters);
  33. CheckNotifySign(parameters, options);
  34. return Task.FromResult(rsp);
  35. }
  36. #endregion
  37. #region Common Method
  38. private void CheckNotifySign(IDictionary<string, string> dictionary, AlipayOptions options)
  39. {
  40. if (dictionary == null || dictionary.Count == 0)
  41. {
  42. throw new AlipayException("sign check fail: dictionary is Empty!");
  43. }
  44. if (!dictionary.TryGetValue("sign", out var sign))
  45. {
  46. throw new AlipayException("sign check fail: sign is Empty!");
  47. }
  48. var prestr = GetSignContent(dictionary);
  49. if (!AlipaySignature.RSACheckContent(prestr, sign, options.AlipayPublicKey, options.SignType))
  50. {
  51. throw new AlipayException("sign check fail: check Sign Data Fail!");
  52. }
  53. }
  54. private string GetSignContent(IDictionary<string, string> dictionary)
  55. {
  56. if (dictionary == null || dictionary.Count == 0)
  57. {
  58. throw new ArgumentNullException(nameof(dictionary));
  59. }
  60. var sortPara = new SortedDictionary<string, string>(dictionary);
  61. var sb = new StringBuilder();
  62. foreach (var iter in sortPara)
  63. {
  64. if (!string.IsNullOrEmpty(iter.Value) && iter.Key != "sign" && iter.Key != "sign_type")
  65. {
  66. sb.Append(iter.Key).Append("=").Append(iter.Value).Append("&");
  67. }
  68. }
  69. return sb.Remove(sb.Length - 1, 1).ToString();
  70. }
  71. #endregion
  72. }
  73. }