AlipayGateway.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #if NETCOREAPP3_1
  2. using Microsoft.Extensions.Options;
  3. #endif
  4. using System.Threading.Tasks;
  5. using PaySharp.Alipay.Request;
  6. using PaySharp.Alipay.Response;
  7. using PaySharp.Core;
  8. using PaySharp.Core.Exceptions;
  9. using PaySharp.Core.Request;
  10. using PaySharp.Core.Utils;
  11. namespace PaySharp.Alipay
  12. {
  13. /// <summary>
  14. /// 支付宝网关
  15. /// </summary>
  16. public sealed class AlipayGateway : BaseGateway
  17. {
  18. #region 私有字段
  19. private readonly Merchant _merchant;
  20. #endregion
  21. #region 构造函数
  22. /// <summary>
  23. /// 初始化支付宝网关
  24. /// </summary>
  25. /// <param name="merchant">商户数据</param>
  26. public AlipayGateway(Merchant merchant)
  27. : base(merchant)
  28. {
  29. _merchant = merchant;
  30. }
  31. #if NETCOREAPP3_1
  32. /// <summary>
  33. /// 初始化支付宝网关
  34. /// </summary>
  35. /// <param name="merchant">商户数据</param>
  36. public AlipayGateway(IOptions<Merchant> merchant)
  37. : this(merchant.Value)
  38. {
  39. }
  40. #endif
  41. #endregion
  42. #region 属性
  43. public override string GatewayUrl { get; set; } = "https://openapi.alipay.com";
  44. public new NotifyResponse NotifyResponse => (NotifyResponse)base.NotifyResponse;
  45. protected override bool IsPaySuccess => NotifyResponse.TradeStatus == "TRADE_SUCCESS" && !IsRefundSuccess;
  46. protected override bool IsRefundSuccess => NotifyResponse.RefundAmount > 0;
  47. protected override bool IsCancelSuccess { get; }
  48. protected override string[] NotifyVerifyParameter => new string[]
  49. {
  50. "app_id","version", "charset","trade_no", "sign","sign_type"
  51. };
  52. #endregion
  53. #region 公共方法
  54. protected override async Task<bool> ValidateNotifyAsync()
  55. {
  56. base.NotifyResponse = await GatewayData.ToObjectAsync<NotifyResponse>(StringCase.Snake);
  57. base.NotifyResponse.Raw = GatewayData.ToUrl(false);
  58. GatewayData.Remove("sign");
  59. GatewayData.Remove("sign_type");
  60. var result = EncryptUtil.Verify(
  61. GatewayData.ToUrl(false),
  62. NotifyResponse.Sign,
  63. _merchant.CertEnvironment == null ? _merchant.AlipayPublicKey : _merchant.CertEnvironment.GetAlipayPublicKey(GatewayData.GetStringValue("alipay_cert_sn"))
  64. );
  65. if (result)
  66. {
  67. return true;
  68. }
  69. throw new GatewayException("签名不一致");
  70. }
  71. public override TResponse Execute<TModel, TResponse>(Request<TModel, TResponse> request)
  72. {
  73. if (request is WapPayRequest || request is WebPayRequest || request is AppPayRequest)
  74. {
  75. return SubmitProcess.SdkExecute(_merchant, request, GatewayUrl);
  76. }
  77. return SubmitProcess.Execute(_merchant, request, GatewayUrl);
  78. }
  79. #endregion
  80. }
  81. }