forked from xiongyuxing/tiku-backend.net
feat: add payment sdk and tenant secret foundation
This commit is contained in:
@@ -33,6 +33,8 @@
|
||||
<PackageVersion Include="Senparc.Weixin" Version="6.25.0" />
|
||||
<PackageVersion Include="Senparc.Weixin.MP" Version="16.25.1" />
|
||||
<PackageVersion Include="Senparc.Weixin.WxOpen" Version="3.28.1" />
|
||||
<PackageVersion Include="AlipaySDKNet.Standard" Version="4.9.1234" />
|
||||
<PackageVersion Include="SKIT.FlurlHttpClient.Wechat.TenpayV3" Version="3.16.0" />
|
||||
<PackageVersion Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageVersion Include="Serilog.Enrichers.Environment" Version="3.0.1" />
|
||||
<PackageVersion Include="Serilog.Enrichers.Thread" Version="4.0.0" />
|
||||
|
||||
105
Tiku.Application/Commerce/PaymentProviderContracts.cs
Normal file
105
Tiku.Application/Commerce/PaymentProviderContracts.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Tiku.Application.Commerce;
|
||||
|
||||
public static class PaymentProviders
|
||||
{
|
||||
public const string WechatPay = "wechat_pay";
|
||||
public const string Alipay = "alipay";
|
||||
public const string Manual = "manual";
|
||||
}
|
||||
|
||||
public sealed record PaymentProviderAccount(
|
||||
Guid TenantId,
|
||||
string Provider,
|
||||
string Mode,
|
||||
JsonElement ConfigPublic,
|
||||
JsonElement SecretPayload);
|
||||
|
||||
public sealed record CreatePaymentProviderRequest(
|
||||
Guid TenantId,
|
||||
string OrderNo,
|
||||
string Subject,
|
||||
int AmountCents,
|
||||
string Method,
|
||||
string? OpenId,
|
||||
string? ReturnUrl,
|
||||
string? QuitUrl,
|
||||
string NotifyUrl,
|
||||
JsonElement Metadata);
|
||||
|
||||
public sealed record CreatePaymentProviderResult(
|
||||
string Provider,
|
||||
string Method,
|
||||
string Status,
|
||||
string? ProviderTradeNo,
|
||||
JsonElement ClientPayload,
|
||||
JsonElement RawPayload);
|
||||
|
||||
public sealed record PaymentNotificationRequest(
|
||||
Guid TenantId,
|
||||
string Provider,
|
||||
IReadOnlyDictionary<string, string> Headers,
|
||||
string RawBody,
|
||||
JsonElement Body);
|
||||
|
||||
public sealed record PaymentNotificationResult(
|
||||
string Provider,
|
||||
string EventType,
|
||||
string EventId,
|
||||
string OrderNo,
|
||||
string? ProviderTradeNo,
|
||||
int AmountCents,
|
||||
bool Paid,
|
||||
bool SignatureValid,
|
||||
DateTimeOffset? PaidAt,
|
||||
JsonElement RawPayload);
|
||||
|
||||
public interface IPaymentProvider
|
||||
{
|
||||
string Provider { get; }
|
||||
|
||||
Task<CreatePaymentProviderResult> CreatePaymentAsync(
|
||||
PaymentProviderAccount account,
|
||||
CreatePaymentProviderRequest request,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
|
||||
PaymentProviderAccount account,
|
||||
PaymentNotificationRequest request,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public interface IPaymentProviderGateway
|
||||
{
|
||||
Task<CreatePaymentProviderResult> CreatePaymentAsync(
|
||||
string provider,
|
||||
CreatePaymentProviderRequest request,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
|
||||
string provider,
|
||||
PaymentNotificationRequest request,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public interface IPaymentProviderConfigService
|
||||
{
|
||||
Task<PaymentProviderAccount> GetActiveAccountAsync(
|
||||
Guid tenantId,
|
||||
string provider,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public interface ITenantSecretService
|
||||
{
|
||||
Task<JsonElement> GetActiveSecretPayloadAsync(
|
||||
Guid tenantId,
|
||||
string secretRef,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class PaymentProviderException(string message, string code) : Exception(message)
|
||||
{
|
||||
public string Code { get; } = code;
|
||||
}
|
||||
@@ -11,6 +11,18 @@ public sealed class TenantAuthProvider : AuditableTenantEntity
|
||||
public JsonElement ConfigPublic { get; set; } = JsonDefaults.Object();
|
||||
}
|
||||
|
||||
public sealed class TenantSecret : AuditableTenantEntity
|
||||
{
|
||||
public string Purpose { get; set; } = string.Empty;
|
||||
public string Provider { get; set; } = string.Empty;
|
||||
public string SecretKey { get; set; } = string.Empty;
|
||||
public string SecretRef { get; set; } = string.Empty;
|
||||
public TenantSecretStatus Status { get; set; } = TenantSecretStatus.Active;
|
||||
public JsonElement SecretPayload { get; set; } = JsonDefaults.Object();
|
||||
public DateTimeOffset? RotatedAt { get; set; }
|
||||
public DateTimeOffset? ExpiresAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class SmsVerificationCode : Entity
|
||||
{
|
||||
public Guid TenantId { get; set; }
|
||||
@@ -140,6 +152,7 @@ public sealed class TenantStudentFollowup : AuditableTenantEntity
|
||||
}
|
||||
|
||||
public enum TenantAuthProviderStatus { Active, Disabled, Testing }
|
||||
public enum TenantSecretStatus { Active, Disabled, Rotating }
|
||||
public enum SmsPurpose { Login, BindPhone, ResetPassword }
|
||||
public enum SmsVerificationStatus { Pending, Sent, Verified, Expired, Blocked }
|
||||
public enum AuthLoginResult { Sent, Success, Failed, Blocked }
|
||||
|
||||
66
Tiku.Infrastructure/Commerce/AlipayProvider.cs
Normal file
66
Tiku.Infrastructure/Commerce/AlipayProvider.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using System.Text.Json;
|
||||
using Aop.Api;
|
||||
using Tiku.Application.Commerce;
|
||||
|
||||
namespace Tiku.Infrastructure.Commerce;
|
||||
|
||||
internal sealed class AlipayProvider : IPaymentProvider
|
||||
{
|
||||
public string Provider => PaymentProviders.Alipay;
|
||||
|
||||
public Task<CreatePaymentProviderResult> CreatePaymentAsync(
|
||||
PaymentProviderAccount account,
|
||||
CreatePaymentProviderRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = BuildClient(account);
|
||||
throw new PaymentProviderException(
|
||||
"Alipay SDK is configured; checkout call is enabled in the commerce checkout batch.",
|
||||
"alipay_checkout_not_enabled");
|
||||
}
|
||||
|
||||
public Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
|
||||
PaymentProviderAccount account,
|
||||
PaymentNotificationRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = BuildClient(account);
|
||||
throw new PaymentProviderException(
|
||||
"Alipay SDK is configured; notification parsing is enabled in the notification batch.",
|
||||
"alipay_notification_not_enabled");
|
||||
}
|
||||
|
||||
private static DefaultAopClient BuildClient(PaymentProviderAccount account)
|
||||
{
|
||||
return new DefaultAopClient(
|
||||
Required(account.ConfigPublic, "gatewayUrl", "gateway"),
|
||||
Required(account.ConfigPublic, "appId"),
|
||||
Required(account.SecretPayload, "privateKey", "appPrivateKey"),
|
||||
"json",
|
||||
"1.0",
|
||||
"RSA2",
|
||||
Required(account.ConfigPublic, "alipayPublicKey"),
|
||||
"UTF-8",
|
||||
false);
|
||||
}
|
||||
|
||||
private static string Required(JsonElement element, params string[] keys)
|
||||
{
|
||||
if (element.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var key in keys)
|
||||
{
|
||||
if (element.TryGetProperty(key, out var property) &&
|
||||
property.ValueKind == JsonValueKind.String &&
|
||||
!string.IsNullOrWhiteSpace(property.GetString()))
|
||||
{
|
||||
return property.GetString()!;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new PaymentProviderException(
|
||||
"Alipay provider configuration is incomplete.",
|
||||
"alipay_config_incomplete");
|
||||
}
|
||||
}
|
||||
41
Tiku.Infrastructure/Commerce/ManualPaymentProvider.cs
Normal file
41
Tiku.Infrastructure/Commerce/ManualPaymentProvider.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using System.Text.Json;
|
||||
using Tiku.Application.Commerce;
|
||||
|
||||
namespace Tiku.Infrastructure.Commerce;
|
||||
|
||||
internal sealed class ManualPaymentProvider : IPaymentProvider
|
||||
{
|
||||
public string Provider => PaymentProviders.Manual;
|
||||
|
||||
public Task<CreatePaymentProviderResult> CreatePaymentAsync(
|
||||
PaymentProviderAccount account,
|
||||
CreatePaymentProviderRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var payload = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
request.OrderNo,
|
||||
request.AmountCents,
|
||||
request.Subject,
|
||||
Message = "manual_payment_requires_tenant_admin_confirmation"
|
||||
});
|
||||
|
||||
return Task.FromResult(new CreatePaymentProviderResult(
|
||||
Provider,
|
||||
request.Method,
|
||||
"pending",
|
||||
null,
|
||||
payload,
|
||||
payload));
|
||||
}
|
||||
|
||||
public Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
|
||||
PaymentProviderAccount account,
|
||||
PaymentNotificationRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new PaymentProviderException(
|
||||
"Manual payment does not accept provider notifications.",
|
||||
"manual_payment_notification_not_supported");
|
||||
}
|
||||
}
|
||||
80
Tiku.Infrastructure/Commerce/PaymentProviderConfigService.cs
Normal file
80
Tiku.Infrastructure/Commerce/PaymentProviderConfigService.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Tiku.Application.Commerce;
|
||||
using Tiku.Domain.Commerce;
|
||||
using Tiku.Infrastructure.Persistence;
|
||||
|
||||
namespace Tiku.Infrastructure.Commerce;
|
||||
|
||||
internal sealed class PaymentProviderConfigService(
|
||||
TikuDbContext dbContext,
|
||||
ITenantSecretService tenantSecretService) : IPaymentProviderConfigService
|
||||
{
|
||||
public async Task<PaymentProviderAccount> GetActiveAccountAsync(
|
||||
Guid tenantId,
|
||||
string provider,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalizedProvider = NormalizeProvider(provider);
|
||||
var account = await dbContext.TenantPaymentAccounts
|
||||
.AsNoTracking()
|
||||
.Where(item =>
|
||||
item.TenantId == tenantId &&
|
||||
item.Provider == normalizedProvider &&
|
||||
item.Status == TenantPaymentAccountStatus.Active)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (account is null)
|
||||
{
|
||||
throw new PaymentProviderException(
|
||||
"Payment provider account is not configured.",
|
||||
"payment_provider_not_configured");
|
||||
}
|
||||
|
||||
var secretPayload = normalizedProvider == PaymentProviders.Manual
|
||||
? JsonDocument.Parse("{}").RootElement.Clone()
|
||||
: await tenantSecretService.GetActiveSecretPayloadAsync(
|
||||
tenantId,
|
||||
GetString(account.ConfigPublic, "secretRef", "secret_ref") ?? string.Empty,
|
||||
cancellationToken);
|
||||
|
||||
return new PaymentProviderAccount(
|
||||
account.TenantId,
|
||||
normalizedProvider,
|
||||
account.Mode.ToString(),
|
||||
account.ConfigPublic,
|
||||
secretPayload);
|
||||
}
|
||||
|
||||
private static string NormalizeProvider(string provider)
|
||||
{
|
||||
var normalized = provider.Trim().ToLowerInvariant().Replace("-", "_", StringComparison.Ordinal);
|
||||
|
||||
return normalized switch
|
||||
{
|
||||
"wechat" or "wechatpay" or "wxpay" or "wx_pay" => PaymentProviders.WechatPay,
|
||||
"ali_pay" => PaymentProviders.Alipay,
|
||||
"" => throw new PaymentProviderException("Payment provider is required.", "payment_provider_required"),
|
||||
_ => normalized
|
||||
};
|
||||
}
|
||||
|
||||
private static string? GetString(JsonElement element, params string[] keys)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var key in keys)
|
||||
{
|
||||
if (element.TryGetProperty(key, out var property) &&
|
||||
property.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
return property.GetString();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
45
Tiku.Infrastructure/Commerce/PaymentProviderGateway.cs
Normal file
45
Tiku.Infrastructure/Commerce/PaymentProviderGateway.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using Tiku.Application.Commerce;
|
||||
|
||||
namespace Tiku.Infrastructure.Commerce;
|
||||
|
||||
internal sealed class PaymentProviderGateway(
|
||||
IEnumerable<IPaymentProvider> providers,
|
||||
IPaymentProviderConfigService configService) : IPaymentProviderGateway
|
||||
{
|
||||
public async Task<CreatePaymentProviderResult> CreatePaymentAsync(
|
||||
string provider,
|
||||
CreatePaymentProviderRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var resolvedProvider = ResolveProvider(provider);
|
||||
var account = await configService.GetActiveAccountAsync(
|
||||
request.TenantId,
|
||||
resolvedProvider.Provider,
|
||||
cancellationToken);
|
||||
|
||||
return await resolvedProvider.CreatePaymentAsync(account, request, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
|
||||
string provider,
|
||||
PaymentNotificationRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var resolvedProvider = ResolveProvider(provider);
|
||||
var account = await configService.GetActiveAccountAsync(
|
||||
request.TenantId,
|
||||
resolvedProvider.Provider,
|
||||
cancellationToken);
|
||||
|
||||
return await resolvedProvider.ParsePaymentNotificationAsync(account, request, cancellationToken);
|
||||
}
|
||||
|
||||
private IPaymentProvider ResolveProvider(string provider)
|
||||
{
|
||||
var normalized = provider.Trim().ToLowerInvariant().Replace("-", "_", StringComparison.Ordinal);
|
||||
return providers.FirstOrDefault(item => item.Provider == normalized)
|
||||
?? throw new PaymentProviderException(
|
||||
"Payment provider is not supported.",
|
||||
"payment_provider_not_supported");
|
||||
}
|
||||
}
|
||||
43
Tiku.Infrastructure/Commerce/TenantSecretService.cs
Normal file
43
Tiku.Infrastructure/Commerce/TenantSecretService.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Tiku.Application.Commerce;
|
||||
using Tiku.Domain.Tenancy;
|
||||
using Tiku.Infrastructure.Persistence;
|
||||
|
||||
namespace Tiku.Infrastructure.Commerce;
|
||||
|
||||
internal sealed class TenantSecretService(TikuDbContext dbContext) : ITenantSecretService
|
||||
{
|
||||
public async Task<JsonElement> GetActiveSecretPayloadAsync(
|
||||
Guid tenantId,
|
||||
string secretRef,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(secretRef))
|
||||
{
|
||||
throw new PaymentProviderException(
|
||||
"Payment provider secret is not configured.",
|
||||
"payment_secret_not_configured");
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var secret = await dbContext.TenantSecrets
|
||||
.AsNoTracking()
|
||||
.Where(item =>
|
||||
item.TenantId == tenantId &&
|
||||
item.SecretRef == secretRef &&
|
||||
item.Status == TenantSecretStatus.Active &&
|
||||
(item.ExpiresAt == null || item.ExpiresAt > now))
|
||||
.Select(item => item.SecretPayload)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (secret.ValueKind is JsonValueKind.Undefined or JsonValueKind.Null)
|
||||
{
|
||||
throw new PaymentProviderException(
|
||||
"Payment provider secret is not configured.",
|
||||
"payment_secret_not_configured");
|
||||
}
|
||||
|
||||
return secret;
|
||||
}
|
||||
}
|
||||
68
Tiku.Infrastructure/Commerce/WechatPayProvider.cs
Normal file
68
Tiku.Infrastructure/Commerce/WechatPayProvider.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using System.Text.Json;
|
||||
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
|
||||
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;
|
||||
using Tiku.Application.Commerce;
|
||||
|
||||
namespace Tiku.Infrastructure.Commerce;
|
||||
|
||||
internal sealed class WechatPayProvider : IPaymentProvider
|
||||
{
|
||||
public string Provider => PaymentProviders.WechatPay;
|
||||
|
||||
public Task<CreatePaymentProviderResult> CreatePaymentAsync(
|
||||
PaymentProviderAccount account,
|
||||
CreatePaymentProviderRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = BuildClient(account);
|
||||
throw new PaymentProviderException(
|
||||
"WeChat Pay SDK is configured; checkout call is enabled in the commerce checkout batch.",
|
||||
"wechat_pay_checkout_not_enabled");
|
||||
}
|
||||
|
||||
public Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
|
||||
PaymentProviderAccount account,
|
||||
PaymentNotificationRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = BuildClient(account);
|
||||
throw new PaymentProviderException(
|
||||
"WeChat Pay SDK is configured; notification parsing is enabled in the notification batch.",
|
||||
"wechat_pay_notification_not_enabled");
|
||||
}
|
||||
|
||||
private static WechatTenpayClient BuildClient(PaymentProviderAccount account)
|
||||
{
|
||||
var options = new WechatTenpayClientOptions
|
||||
{
|
||||
MerchantId = Required(account.ConfigPublic, "merchantId", "mchId", "mchid"),
|
||||
MerchantV3Secret = Required(account.SecretPayload, "apiV3Key", "merchantV3Secret"),
|
||||
MerchantCertificateSerialNumber = Required(account.ConfigPublic, "certificateSerialNumber", "serialNo"),
|
||||
MerchantCertificatePrivateKey = Required(account.SecretPayload, "privateKey", "merchantCertificatePrivateKey"),
|
||||
PlatformAuthScheme = PlatformAuthScheme.PublicKey,
|
||||
PlatformPublicKeyManager = new InMemoryPublicKeyManager()
|
||||
};
|
||||
|
||||
return WechatTenpayClientBuilder.Create(options).Build();
|
||||
}
|
||||
|
||||
private static string Required(JsonElement element, params string[] keys)
|
||||
{
|
||||
if (element.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var key in keys)
|
||||
{
|
||||
if (element.TryGetProperty(key, out var property) &&
|
||||
property.ValueKind == JsonValueKind.String &&
|
||||
!string.IsNullOrWhiteSpace(property.GetString()))
|
||||
{
|
||||
return property.GetString()!;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new PaymentProviderException(
|
||||
"WeChat Pay provider configuration is incomplete.",
|
||||
"wechat_pay_config_incomplete");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Npgsql;
|
||||
using Tiku.Application.Assets;
|
||||
using Tiku.Application.Auth;
|
||||
using Tiku.Application.Catalog;
|
||||
using Tiku.Application.Commerce;
|
||||
using Tiku.Application.Content;
|
||||
using Tiku.Application.Learning;
|
||||
using Tiku.Application.QuestionBanks;
|
||||
@@ -15,6 +16,7 @@ using Tiku.Application.TenantAdmin;
|
||||
using Tiku.Infrastructure.Assets;
|
||||
using Tiku.Infrastructure.Auth;
|
||||
using Tiku.Infrastructure.Catalog;
|
||||
using Tiku.Infrastructure.Commerce;
|
||||
using Tiku.Infrastructure.Content;
|
||||
using Tiku.Infrastructure.Learning;
|
||||
using Tiku.Infrastructure.Persistence;
|
||||
@@ -61,6 +63,12 @@ public static class DependencyInjection
|
||||
services.AddScoped<IAssetManagementService, AssetManagementService>();
|
||||
services.AddScoped<ILearningActivityService, LearningActivityService>();
|
||||
services.AddScoped<ITenantAdminDirectService, TenantAdminDirectService>();
|
||||
services.AddScoped<ITenantSecretService, TenantSecretService>();
|
||||
services.AddScoped<IPaymentProviderConfigService, PaymentProviderConfigService>();
|
||||
services.AddScoped<IPaymentProviderGateway, PaymentProviderGateway>();
|
||||
services.AddScoped<IPaymentProvider, ManualPaymentProvider>();
|
||||
services.AddScoped<IPaymentProvider, WechatPayProvider>();
|
||||
services.AddScoped<IPaymentProvider, AlipayProvider>();
|
||||
services.AddOptions<AliyunOssOptions>()
|
||||
.Validate(
|
||||
AliyunOssOptions.BeValid,
|
||||
|
||||
@@ -21,6 +21,24 @@ internal sealed class TenantAuthProviderConfiguration : IEntityTypeConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TenantSecretConfiguration : IEntityTypeConfiguration<TenantSecret>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<TenantSecret> builder)
|
||||
{
|
||||
builder.ConfigureTenantEntity("tenant_secrets");
|
||||
builder.ConfigureTimestamps();
|
||||
builder.Property(entity => entity.Purpose).HasMaxLength(80);
|
||||
builder.Property(entity => entity.Provider).HasMaxLength(50);
|
||||
builder.Property(entity => entity.SecretKey).HasMaxLength(120);
|
||||
builder.Property(entity => entity.SecretRef).HasMaxLength(300);
|
||||
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
|
||||
builder.Property(entity => entity.SecretPayload).IsJson("{}");
|
||||
builder.HasIndex(entity => new { entity.TenantId, entity.SecretRef }).IsUnique();
|
||||
builder.HasIndex(entity => new { entity.TenantId, entity.Purpose, entity.Provider, entity.SecretKey }).IsUnique();
|
||||
builder.HasIndex(entity => new { entity.TenantId, entity.Purpose, entity.Provider, entity.Status });
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class SmsVerificationCodeConfiguration : IEntityTypeConfiguration<SmsVerificationCode>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<SmsVerificationCode> builder)
|
||||
|
||||
15660
Tiku.Infrastructure/Persistence/Migrations/20260726112706_AddPaymentSdkAndTenantSecretFoundation.Designer.cs
generated
Normal file
15660
Tiku.Infrastructure/Persistence/Migrations/20260726112706_AddPaymentSdkAndTenantSecretFoundation.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Tiku.Infrastructure.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddPaymentSdkAndTenantSecretFoundation : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "tenant_secrets",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
|
||||
purpose = table.Column<string>(type: "character varying(80)", maxLength: 80, nullable: false),
|
||||
provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
|
||||
secret_key = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
|
||||
secret_ref = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: false),
|
||||
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
secret_payload = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
|
||||
rotated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
expires_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
|
||||
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_tenant_secrets", x => x.id);
|
||||
table.UniqueConstraint("ak_tenant_secrets_tenant_id_id", x => new { x.tenant_id, x.id });
|
||||
table.ForeignKey(
|
||||
name: "fk_tenant_secrets_tenants_tenant_id",
|
||||
column: x => x.tenant_id,
|
||||
principalTable: "tenants",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_tenant_secrets_tenant_id_purpose_provider_secret_key",
|
||||
table: "tenant_secrets",
|
||||
columns: new[] { "tenant_id", "purpose", "provider", "secret_key" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_tenant_secrets_tenant_id_purpose_provider_status",
|
||||
table: "tenant_secrets",
|
||||
columns: new[] { "tenant_id", "purpose", "provider", "status" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_tenant_secrets_tenant_id_secret_ref",
|
||||
table: "tenant_secrets",
|
||||
columns: new[] { "tenant_id", "secret_ref" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "tenant_secrets");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12326,6 +12326,94 @@ namespace Tiku.Infrastructure.Persistence.Migrations
|
||||
b.ToTable("tenant_role_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tiku.Domain.Tenancy.TenantSecret", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id")
|
||||
.HasDefaultValueSql("gen_random_uuid()");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at")
|
||||
.HasDefaultValueSql("now()");
|
||||
|
||||
b.Property<DateTimeOffset?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<string>("Provider")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)")
|
||||
.HasColumnName("provider");
|
||||
|
||||
b.Property<string>("Purpose")
|
||||
.IsRequired()
|
||||
.HasMaxLength(80)
|
||||
.HasColumnType("character varying(80)")
|
||||
.HasColumnName("purpose");
|
||||
|
||||
b.Property<DateTimeOffset?>("RotatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("rotated_at");
|
||||
|
||||
b.Property<string>("SecretKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(120)
|
||||
.HasColumnType("character varying(120)")
|
||||
.HasColumnName("secret_key");
|
||||
|
||||
b.Property<JsonElement>("SecretPayload")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("secret_payload")
|
||||
.HasDefaultValueSql("'{}'::jsonb");
|
||||
|
||||
b.Property<string>("SecretRef")
|
||||
.IsRequired()
|
||||
.HasMaxLength(300)
|
||||
.HasColumnType("character varying(300)")
|
||||
.HasColumnName("secret_ref");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("status");
|
||||
|
||||
b.Property<Guid>("TenantId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("tenant_id");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at")
|
||||
.HasDefaultValueSql("now()");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_tenant_secrets");
|
||||
|
||||
b.HasAlternateKey("TenantId", "Id")
|
||||
.HasName("ak_tenant_secrets_tenant_id_id");
|
||||
|
||||
b.HasIndex("TenantId", "SecretRef")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_tenant_secrets_tenant_id_secret_ref");
|
||||
|
||||
b.HasIndex("TenantId", "Purpose", "Provider", "SecretKey")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_tenant_secrets_tenant_id_purpose_provider_secret_key");
|
||||
|
||||
b.HasIndex("TenantId", "Purpose", "Provider", "Status")
|
||||
.HasDatabaseName("ix_tenant_secrets_tenant_id_purpose_provider_status");
|
||||
|
||||
b.ToTable("tenant_secrets", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tiku.Domain.Tenancy.TenantSettings", b =>
|
||||
{
|
||||
b.Property<Guid>("TenantId")
|
||||
@@ -15479,6 +15567,16 @@ namespace Tiku.Infrastructure.Persistence.Migrations
|
||||
.HasConstraintName("fk_tenant_role_templates_users_updated_by");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tiku.Domain.Tenancy.TenantSecret", b =>
|
||||
{
|
||||
b.HasOne("Tiku.Domain.Tenancy.Tenant", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("TenantId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_tenant_secrets_tenants_tenant_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tiku.Domain.Tenancy.TenantSettings", b =>
|
||||
{
|
||||
b.HasOne("Tiku.Domain.Tenancy.Tenant", null)
|
||||
|
||||
@@ -24,6 +24,7 @@ public sealed class TikuDbContext(DbContextOptions<TikuDbContext> options) : DbC
|
||||
public DbSet<TenantBranding> TenantBrandings => Set<TenantBranding>();
|
||||
public DbSet<TenantSettings> TenantSettings => Set<TenantSettings>();
|
||||
public DbSet<TenantAuthProvider> TenantAuthProviders => Set<TenantAuthProvider>();
|
||||
public DbSet<TenantSecret> TenantSecrets => Set<TenantSecret>();
|
||||
public DbSet<SmsVerificationCode> SmsVerificationCodes => Set<SmsVerificationCode>();
|
||||
public DbSet<AuthLoginEvent> AuthLoginEvents => Set<AuthLoginEvent>();
|
||||
public DbSet<AuthSession> AuthSessions => Set<AuthSession>();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AlibabaCloud.OSS.V2" />
|
||||
<PackageReference Include="AlipaySDKNet.Standard" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
@@ -17,6 +18,7 @@
|
||||
<PackageReference Include="Senparc.Weixin" />
|
||||
<PackageReference Include="Senparc.Weixin.MP" />
|
||||
<PackageReference Include="Senparc.Weixin.WxOpen" />
|
||||
<PackageReference Include="SKIT.FlurlHttpClient.Wechat.TenpayV3" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ public sealed class PersistenceModelTests
|
||||
.Select(entity => entity.GetTableName())
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
Assert.Equal(126, tableNames.Count);
|
||||
Assert.Equal(127, tableNames.Count);
|
||||
Assert.Contains("tenants", tableNames);
|
||||
Assert.Contains("tenant_settings", tableNames);
|
||||
Assert.Contains("content_entries", tableNames);
|
||||
@@ -66,6 +66,7 @@ public sealed class PersistenceModelTests
|
||||
Assert.Contains("dashboard_daily_stats", tableNames);
|
||||
Assert.Contains("revenue_daily_stats", tableNames);
|
||||
Assert.Contains("tenant_auth_providers", tableNames);
|
||||
Assert.Contains("tenant_secrets", tableNames);
|
||||
Assert.Contains("sms_verification_codes", tableNames);
|
||||
Assert.Contains("auth_login_events", tableNames);
|
||||
Assert.Contains("auth_sessions", tableNames);
|
||||
@@ -506,6 +507,7 @@ public sealed class PersistenceModelTests
|
||||
|
||||
[Theory]
|
||||
[InlineData(typeof(TenantAuthProvider), nameof(TenantAuthProvider.ConfigPublic), "'{}'::jsonb")]
|
||||
[InlineData(typeof(TenantSecret), nameof(TenantSecret.SecretPayload), "'{}'::jsonb")]
|
||||
[InlineData(typeof(SmsVerificationCode), nameof(SmsVerificationCode.Metadata), "'{}'::jsonb")]
|
||||
[InlineData(typeof(AuthLoginEvent), nameof(AuthLoginEvent.Metadata), "'{}'::jsonb")]
|
||||
[InlineData(typeof(AuthSession), nameof(AuthSession.Metadata), "'{}'::jsonb")]
|
||||
@@ -538,6 +540,14 @@ public sealed class PersistenceModelTests
|
||||
AssertHasUniqueIndex<TenantAuthProvider>(
|
||||
nameof(TenantAuthProvider.TenantId),
|
||||
nameof(TenantAuthProvider.Provider));
|
||||
AssertHasUniqueIndex<TenantSecret>(
|
||||
nameof(TenantSecret.TenantId),
|
||||
nameof(TenantSecret.SecretRef));
|
||||
AssertHasUniqueIndex<TenantSecret>(
|
||||
nameof(TenantSecret.TenantId),
|
||||
nameof(TenantSecret.Purpose),
|
||||
nameof(TenantSecret.Provider),
|
||||
nameof(TenantSecret.SecretKey));
|
||||
AssertHasUniqueIndex<TenantClassMember>(
|
||||
nameof(TenantClassMember.TenantId),
|
||||
nameof(TenantClassMember.ClassId),
|
||||
|
||||
Reference in New Issue
Block a user