feat(tenpayv2): 基于 ErroredResult 改造验签相关扩展方法

This commit is contained in:
Fu Diwei 2024-02-05 13:40:44 +08:00 committed by RHQYZ
parent 082199dc26
commit 7d565811a1

View File

@ -4,6 +4,8 @@ using System.Xml;
namespace SKIT.FlurlHttpClient.Wechat.TenpayV2
{
using SKIT.FlurlHttpClient.Primitives;
/// <summary>
/// 为 <see cref="WechatTenpayClient"/> 提供回调通知事件签名验证的扩展方法。
/// </summary>
@ -15,24 +17,12 @@ namespace SKIT.FlurlHttpClient.Wechat.TenpayV2
/// <param name="client"></param>
/// <param name="webhookBody">微信回调通知中请求正文。</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static bool VerifyEventSignature(this WechatTenpayClient client, string webhookBody)
{
return VerifyEventSignature(client, webhookBody, out _);
}
/// <summary>
/// <para>验证回调通知事件签名。</para>
/// </summary>
/// <param name="client"></param>
/// <param name="webhookBody">微信回调通知中请求正文。</param>
/// <param name="error"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static bool VerifyEventSignature(this WechatTenpayClient client, string webhookBody, out Exception? error)
public static ErroredResult VerifyEventSignature(this WechatTenpayClient client, string webhookBody)
{
if (client is null) throw new ArgumentNullException(nameof(client));
ErroredResult result;
try
{
@ -49,14 +39,18 @@ namespace SKIT.FlurlHttpClient.Wechat.TenpayV2
string signData = Utilities.JsonHelper.ParseToSortedQueryString(json);
string actualSign = Utilities.RequestSigner.SignFromSortedQueryString(signData, client.Credentials.MerchantSecret, signType);
error = null;
return string.Equals(expectedSign, actualSign, StringComparison.OrdinalIgnoreCase);
bool valid = string.Equals(expectedSign, actualSign, StringComparison.OrdinalIgnoreCase);
if (valid)
result = ErroredResult.Ok();
else
result = ErroredResult.Fail(new Exception($"Signature does not match. Maybe \"{actualSign}\" is an illegal signature."));
}
catch (Exception ex)
{
error = new WechatTenpayException("Failed to verify event. Please see the inner exception for more details.", ex);
return false;
result = ErroredResult.Fail(ex);
}
return result;
}
}
}