#if NETCOREAPP3_1
using Microsoft.Extensions.Options;
#endif
using System.Threading.Tasks;
using PaySharp.Alipay.Request;
using PaySharp.Alipay.Response;
using PaySharp.Core;
using PaySharp.Core.Exceptions;
using PaySharp.Core.Request;
using PaySharp.Core.Utils;
namespace PaySharp.Alipay
{
///
/// 支付宝网关
///
public sealed class AlipayGateway : BaseGateway
{
#region 私有字段
private readonly Merchant _merchant;
#endregion
#region 构造函数
///
/// 初始化支付宝网关
///
/// 商户数据
public AlipayGateway(Merchant merchant)
: base(merchant)
{
_merchant = merchant;
}
#if NETCOREAPP3_1
///
/// 初始化支付宝网关
///
/// 商户数据
public AlipayGateway(IOptions merchant)
: this(merchant.Value)
{
}
#endif
#endregion
#region 属性
public override string GatewayUrl { get; set; } = "https://openapi.alipay.com";
public new NotifyResponse NotifyResponse => (NotifyResponse)base.NotifyResponse;
protected override bool IsPaySuccess => NotifyResponse.TradeStatus == "TRADE_SUCCESS" && !IsRefundSuccess;
protected override bool IsRefundSuccess => NotifyResponse.RefundAmount > 0;
protected override bool IsCancelSuccess { get; }
protected override string[] NotifyVerifyParameter => new string[]
{
"app_id","version", "charset","trade_no", "sign","sign_type"
};
#endregion
#region 公共方法
protected override async Task ValidateNotifyAsync()
{
base.NotifyResponse = await GatewayData.ToObjectAsync(StringCase.Snake);
base.NotifyResponse.Raw = GatewayData.ToUrl(false);
GatewayData.Remove("sign");
GatewayData.Remove("sign_type");
var result = EncryptUtil.Verify(
GatewayData.ToUrl(false),
NotifyResponse.Sign,
_merchant.CertEnvironment == null ? _merchant.AlipayPublicKey : _merchant.CertEnvironment.GetAlipayPublicKey(GatewayData.GetStringValue("alipay_cert_sn"))
);
if (result)
{
return true;
}
throw new GatewayException("签名不一致");
}
public override TResponse Execute(Request request)
{
if (request is WapPayRequest || request is WebPayRequest || request is AppPayRequest)
{
return SubmitProcess.SdkExecute(_merchant, request, GatewayUrl);
}
return SubmitProcess.Execute(_merchant, request, GatewayUrl);
}
#endregion
}
}