admin/src/Oms.Application/Services/Payment/WeChatPayClientFactory.cs
zzh b0fd3a30e1
All checks were successful
Build and Deploy / deploy (push) Successful in 1m29s
feat: 微信在线支付入账加固(CAS 防重、禁人工审未付单、下单失败清理)
回调/查单/补偿走事务内原子占单再入账;关单同步驳回充值;创建先落单失败即 Failed;列表标记在线支付态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 12:25:45 +08:00

129 lines
4.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Fake.DependencyInjection;
using Microsoft.Extensions.Logging;
using Oms.Domain.SystemAggregate.Consts;
using Oms.Domain.SystemAggregate.Repositories;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;
namespace Oms.Application.Services.Payment;
/// <summary>
/// 按系统配置构建微信支付客户端(带平台证书缓存刷新)。
/// </summary>
public class WeChatPayClientFactory : IScopedDependency
{
private static readonly SemaphoreSlim RefreshLock = new(1, 1);
private static DateTime _certsRefreshedAt = DateTime.MinValue;
private static readonly InMemoryCertificateManager SharedCertManager = new();
private readonly ISystemOtherConfigRepository _otherConfigRepository;
private readonly ILogger<WeChatPayClientFactory> _logger;
public WeChatPayClientFactory(
ISystemOtherConfigRepository otherConfigRepository,
ILogger<WeChatPayClientFactory> logger)
{
_otherConfigRepository = otherConfigRepository;
_logger = logger;
}
public async Task<WeChatPayMerchantSettings> GetSettingsAsync(CancellationToken cancellationToken = default)
{
var pay = await _otherConfigRepository.GetByConfigCodeAsync(
SystemOtherConfigCodes.WeChatPayMerchant,
cancellationToken);
var mp = await _otherConfigRepository.GetByConfigCodeAsync(
SystemOtherConfigCodes.WeChatMp,
cancellationToken);
return new WeChatPayMerchantSettings
{
Enabled = pay?.Enabled == true,
MchId = pay?.AppKey?.Trim() ?? string.Empty,
MchSerialNo = pay?.Remark?.Trim() ?? string.Empty,
ApiV3Key = pay?.AppSecret?.Trim() ?? string.Empty,
PrivateKeyPem = pay?.AccessToken?.Trim() ?? string.Empty,
NotifyUrl = pay?.BaseUrl?.Trim() ?? string.Empty,
AppId = mp?.AppKey?.Trim() ?? string.Empty
};
}
public async Task<(WechatTenpayClient Client, WeChatPayMerchantSettings Settings)> CreateAsync(
CancellationToken cancellationToken = default)
{
var settings = await GetSettingsAsync(cancellationToken);
if (!settings.IsReady)
{
throw new InvalidOperationException("微信支付商户未配置完整或未启用(需 MchId / 证书序列号 / APIv3Key / 私钥 / NotifyUrl,且公众号 AppId 已配置)");
}
var options = new WechatTenpayClientOptions
{
MerchantId = settings.MchId,
MerchantV3Secret = settings.ApiV3Key,
MerchantCertificateSerialNumber = settings.MchSerialNo,
MerchantCertificatePrivateKey = settings.PrivateKeyPem,
PlatformCertificateManager = SharedCertManager,
AutoEncryptRequestSensitiveProperty = false,
AutoDecryptResponseSensitiveProperty = true
};
var client = new WechatTenpayClient(options);
await EnsurePlatformCertificatesAsync(client, cancellationToken);
return (client, settings);
}
private async Task EnsurePlatformCertificatesAsync(
WechatTenpayClient client,
CancellationToken cancellationToken)
{
if (DateTime.UtcNow - _certsRefreshedAt < TimeSpan.FromHours(6)
&& SharedCertManager.AllEntries().Any())
{
return;
}
await RefreshLock.WaitAsync(cancellationToken);
try
{
if (DateTime.UtcNow - _certsRefreshedAt < TimeSpan.FromHours(6)
&& SharedCertManager.AllEntries().Any())
{
return;
}
var response = await client.ExecuteQueryCertificatesAsync(new QueryCertificatesRequest(), cancellationToken);
if (!response.IsSuccessful())
{
_logger.LogWarning(
"刷新微信平台证书失败 Code={Code} Msg={Msg}",
response.ErrorCode,
response.ErrorMessage);
if (!SharedCertManager.AllEntries().Any())
{
throw new InvalidOperationException($"刷新微信平台证书失败:{response.ErrorCode} {response.ErrorMessage}");
}
return;
}
client.DecryptResponseSensitiveProperty(response);
foreach (var cert in response.CertificateList ?? [])
{
if (cert == null)
{
continue;
}
SharedCertManager.AddEntry(CertificateEntry.Parse(cert));
}
_certsRefreshedAt = DateTime.UtcNow;
}
finally
{
RefreshLock.Release();
}
}
}