Add Stripe patronage checkout integration
This commit is contained in:
parent
ba01b78d68
commit
861dff3ed7
13 changed files with 812 additions and 32 deletions
|
|
@ -24,13 +24,15 @@ public sealed class HeimdallAuthService(
|
|||
private static readonly HashSet<string> AllowedProviders = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"discord",
|
||||
"patreon"
|
||||
"patreon",
|
||||
"twitch"
|
||||
};
|
||||
|
||||
public async Task<HeimdallAuthStartResult> StartAsync(
|
||||
string provider,
|
||||
string callbackBaseUrl,
|
||||
string returnUrl,
|
||||
bool requireMemberAccess,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!AllowedProviders.Contains(provider))
|
||||
|
|
@ -44,9 +46,9 @@ public sealed class HeimdallAuthService(
|
|||
throw new HeimdallAuthException("Heimdall is not configured.");
|
||||
}
|
||||
|
||||
var entitlementPolicy = provider.Equals("discord", StringComparison.OrdinalIgnoreCase)
|
||||
? BuildDiscordPolicy(options)
|
||||
: BuildPatreonPolicy(options);
|
||||
var entitlementPolicy = requireMemberAccess
|
||||
? BuildMemberAccessPolicy(provider, options)
|
||||
: null;
|
||||
var attemptId = Guid.NewGuid().ToString("N");
|
||||
var callbackUrl = new Uri(new Uri(callbackBaseUrl.TrimEnd('/') + "/", UriKind.Absolute), "auth/heimdall/callback");
|
||||
|
||||
|
|
@ -75,6 +77,7 @@ public sealed class HeimdallAuthService(
|
|||
}
|
||||
|
||||
attemptStore.Create(attemptId, returnUrl);
|
||||
attemptStore.SetRequiresMemberAccess(attemptId, requireMemberAccess);
|
||||
return new HeimdallAuthStartResult(new Uri(payload.AuthorizationUrl, UriKind.Absolute), attemptId);
|
||||
}
|
||||
|
||||
|
|
@ -107,12 +110,12 @@ public sealed class HeimdallAuthService(
|
|||
throw new HeimdallAuthException(payload.ErrorDescription ?? payload.Error ?? "Heimdall auth did not succeed.");
|
||||
}
|
||||
|
||||
if (!payload.HasMemberAccess)
|
||||
if (attempt.RequiresMemberAccess && !payload.HasMemberAccess)
|
||||
{
|
||||
throw new HeimdallAuthException("Heimdall did not grant Bifrost member access.");
|
||||
}
|
||||
|
||||
var userAccount = await UpsertUserAccountAsync(payload, cancellationToken);
|
||||
var userAccount = await UpsertUserAccountAsync(payload, attempt.RequiresMemberAccess, cancellationToken);
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, userAccount.GitHubUserId?.ToString() ?? userAccount.HeimdallAccountId),
|
||||
|
|
@ -137,6 +140,7 @@ public sealed class HeimdallAuthService(
|
|||
|
||||
private async Task<UserAccount> UpsertUserAccountAsync(
|
||||
HeimdallBackendCallbackPayload payload,
|
||||
bool grantMemberAccess,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var now = timeProvider.GetUtcNow();
|
||||
|
|
@ -167,10 +171,12 @@ public sealed class HeimdallAuthService(
|
|||
},
|
||||
Membership = new Bifrost.Web.Domain.Membership
|
||||
{
|
||||
Status = MembershipStatus.Active,
|
||||
Status = grantMemberAccess ? MembershipStatus.Active : MembershipStatus.Authenticated,
|
||||
CreatedAtUtc = now,
|
||||
ApprovedAtUtc = now,
|
||||
Notes = "Activated by Heimdall member access claim"
|
||||
ApprovedAtUtc = grantMemberAccess ? now : null,
|
||||
Notes = grantMemberAccess
|
||||
? "Activated by Heimdall member access claim"
|
||||
: $"Identity verified through Heimdall {payload.Provider}"
|
||||
}
|
||||
};
|
||||
dbContext.UserAccounts.Add(userAccount);
|
||||
|
|
@ -191,18 +197,24 @@ public sealed class HeimdallAuthService(
|
|||
UserAccountId = userAccount.Id,
|
||||
CreatedAtUtc = now
|
||||
};
|
||||
userAccount.Membership.Status = MembershipStatus.Active;
|
||||
userAccount.Membership.ApprovedAtUtc ??= now;
|
||||
if (grantMemberAccess)
|
||||
{
|
||||
userAccount.Membership.Status = MembershipStatus.Active;
|
||||
userAccount.Membership.ApprovedAtUtc ??= now;
|
||||
}
|
||||
}
|
||||
|
||||
userAccount.MemberProfile!.Nickname = displayName;
|
||||
userAccount.MemberProfile.UpdatedAtUtc = now;
|
||||
ApplicationBootstrapper.EnsureRole(
|
||||
userAccount.Membership!,
|
||||
MemberRole.StandardMember,
|
||||
null,
|
||||
now,
|
||||
"Heimdall member access");
|
||||
if (grantMemberAccess)
|
||||
{
|
||||
ApplicationBootstrapper.EnsureRole(
|
||||
userAccount.Membership!,
|
||||
MemberRole.StandardMember,
|
||||
null,
|
||||
now,
|
||||
"Heimdall member access");
|
||||
}
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return userAccount;
|
||||
|
|
@ -236,6 +248,21 @@ public sealed class HeimdallAuthService(
|
|||
options.PatreonTierTitle);
|
||||
}
|
||||
|
||||
private static HeimdallEntitlementPolicy BuildMemberAccessPolicy(string provider, HeimdallOptions options)
|
||||
{
|
||||
if (provider.Equals("discord", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return BuildDiscordPolicy(options);
|
||||
}
|
||||
|
||||
if (provider.Equals("patreon", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return BuildPatreonPolicy(options);
|
||||
}
|
||||
|
||||
throw new HeimdallAuthException($"Heimdall provider '{provider}' does not support Bifrost member access.");
|
||||
}
|
||||
|
||||
private static string ToAttemptReturnUrl(string callbackBaseUrl, string attemptId, string returnUrl)
|
||||
{
|
||||
var baseUri = new Uri(callbackBaseUrl.TrimEnd('/') + "/", UriKind.Absolute);
|
||||
|
|
@ -262,6 +289,14 @@ public sealed class HeimdallAuthAttemptStore
|
|||
_attempts[attemptId] = new HeimdallAuthAttempt(returnUrl, null);
|
||||
}
|
||||
|
||||
public void SetRequiresMemberAccess(string attemptId, bool requiresMemberAccess)
|
||||
{
|
||||
_attempts.AddOrUpdate(
|
||||
attemptId,
|
||||
_ => new HeimdallAuthAttempt("/App", null, requiresMemberAccess),
|
||||
(_, existing) => existing with { RequiresMemberAccess = requiresMemberAccess });
|
||||
}
|
||||
|
||||
public void Complete(string attemptId, HeimdallBackendCallbackPayload payload)
|
||||
{
|
||||
_attempts.AddOrUpdate(
|
||||
|
|
@ -276,14 +311,18 @@ public sealed class HeimdallAuthAttemptStore
|
|||
}
|
||||
}
|
||||
|
||||
public sealed record HeimdallAuthAttempt(string ReturnUrl, HeimdallBackendCallbackPayload? Payload);
|
||||
public sealed record HeimdallAuthAttempt(
|
||||
string ReturnUrl,
|
||||
HeimdallBackendCallbackPayload? Payload,
|
||||
bool RequiresMemberAccess = false);
|
||||
|
||||
public sealed record HeimdallStartRequest(
|
||||
[property: JsonPropertyName("appSlug")] string AppSlug,
|
||||
[property: JsonPropertyName("mode")] string Mode,
|
||||
[property: JsonPropertyName("returnTo")] string ReturnTo,
|
||||
[property: JsonPropertyName("handoff")] HeimdallHandoff Handoff,
|
||||
[property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy EntitlementPolicy);
|
||||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy? EntitlementPolicy);
|
||||
|
||||
public sealed record HeimdallHandoff(
|
||||
[property: JsonPropertyName("kind")] string Kind,
|
||||
|
|
|
|||
|
|
@ -30,9 +30,9 @@ public sealed class PatronageService(
|
|||
.Include(x => x.Membership)
|
||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||
|
||||
if (user.Membership is null || user.Membership.Status != MembershipStatus.Active)
|
||||
if (user.Membership is null || user.Membership.Status == MembershipStatus.Suspended)
|
||||
{
|
||||
throw new InvalidOperationException("Patron support can only be recorded for an active member.");
|
||||
throw new InvalidOperationException("Patron support can only be recorded for an unsuspended Bifrost account.");
|
||||
}
|
||||
|
||||
if (amount <= 0 && kind != PatronSupportEventKind.SupportAdjustment)
|
||||
|
|
|
|||
144
src/Bifrost.Web/Features/Patronage/StripeCheckoutService.cs
Normal file
144
src/Bifrost.Web/Features/Patronage/StripeCheckoutService.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Domain;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Features.Patronage;
|
||||
|
||||
public sealed class StripeCheckoutService(
|
||||
HttpClient httpClient,
|
||||
IOptions<StripeOptions> options)
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, StripePatronageTier> VelvetTiers =
|
||||
new Dictionary<string, StripePatronageTier>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["velvet-room"] = new(
|
||||
"velvet-room",
|
||||
"GameCult Patronage - Velvet Room",
|
||||
"General GameCult patronage with Deru supporter access.",
|
||||
1900,
|
||||
"usd"),
|
||||
["mirror-test"] = new(
|
||||
"mirror-test",
|
||||
"GameCult Patronage - Mirror Test",
|
||||
"General GameCult patronage with Deru supporter access.",
|
||||
1200,
|
||||
"usd"),
|
||||
["after-hours-bundle"] = new(
|
||||
"after-hours-bundle",
|
||||
"GameCult Patronage - After Hours Bundle",
|
||||
"General GameCult patronage with Deru supporter access.",
|
||||
3900,
|
||||
"usd")
|
||||
};
|
||||
|
||||
public async Task<StripeCheckoutResult> CreateVelvetCheckoutAsync(
|
||||
string tierSlug,
|
||||
UserAccount patronAccount,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var stripeOptions = options.Value;
|
||||
if (!stripeOptions.IsCheckoutConfigured)
|
||||
{
|
||||
return StripeCheckoutResult.NotConfigured("Stripe checkout is not configured.");
|
||||
}
|
||||
|
||||
if (!VelvetTiers.TryGetValue(tierSlug.Trim(), out var tier))
|
||||
{
|
||||
return StripeCheckoutResult.UnknownTier($"Unknown Velvet patronage tier '{tierSlug}'.");
|
||||
}
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "v1/checkout/sessions");
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", stripeOptions.SecretKey);
|
||||
request.Content = new FormUrlEncodedContent(BuildCheckoutForm(stripeOptions, tier, patronAccount));
|
||||
|
||||
using var response = await httpClient.SendAsync(request, cancellationToken);
|
||||
var body = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
return StripeCheckoutResult.ProviderError(
|
||||
$"Stripe checkout session creation failed with {(int)response.StatusCode}.");
|
||||
}
|
||||
|
||||
using var json = JsonDocument.Parse(body);
|
||||
var url = json.RootElement.TryGetProperty("url", out var urlElement)
|
||||
? urlElement.GetString()
|
||||
: null;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
{
|
||||
return StripeCheckoutResult.ProviderError("Stripe checkout session response did not include a URL.");
|
||||
}
|
||||
|
||||
return StripeCheckoutResult.Created(new Uri(url));
|
||||
}
|
||||
|
||||
private static IEnumerable<KeyValuePair<string, string>> BuildCheckoutForm(
|
||||
StripeOptions options,
|
||||
StripePatronageTier tier,
|
||||
UserAccount patronAccount)
|
||||
{
|
||||
var referenceId = $"velvet:{tier.Slug}:{patronAccount.Id:N}:{Guid.NewGuid():N}";
|
||||
var metadata = new Dictionary<string, string>
|
||||
{
|
||||
["source"] = "velvet.gamecult.org",
|
||||
["umbrella"] = "GameCult",
|
||||
["ledger"] = "bifrost",
|
||||
["purpose"] = "general_patronage",
|
||||
["model"] = "deru",
|
||||
["tier"] = tier.Slug,
|
||||
["bifrost_user_account_id"] = patronAccount.Id.ToString("N"),
|
||||
["bifrost_github_login"] = patronAccount.GitHubLogin
|
||||
};
|
||||
|
||||
yield return new("mode", "payment");
|
||||
yield return new("success_url", options.SuccessUrl);
|
||||
yield return new("cancel_url", options.CancelUrl);
|
||||
yield return new("client_reference_id", referenceId);
|
||||
yield return new("line_items[0][quantity]", "1");
|
||||
yield return new("line_items[0][price_data][currency]", tier.Currency);
|
||||
yield return new("line_items[0][price_data][unit_amount]", tier.AmountInMinorUnits.ToString());
|
||||
yield return new("line_items[0][price_data][product_data][name]", tier.Name);
|
||||
yield return new("line_items[0][price_data][product_data][description]", tier.Description);
|
||||
|
||||
foreach (var (key, value) in metadata)
|
||||
{
|
||||
yield return new($"metadata[{key}]", value);
|
||||
yield return new($"payment_intent_data[metadata][{key}]", value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record StripePatronageTier(
|
||||
string Slug,
|
||||
string Name,
|
||||
string Description,
|
||||
int AmountInMinorUnits,
|
||||
string Currency);
|
||||
|
||||
public sealed record StripeCheckoutResult(
|
||||
StripeCheckoutStatus Status,
|
||||
Uri? CheckoutUrl,
|
||||
string Message)
|
||||
{
|
||||
public static StripeCheckoutResult Created(Uri checkoutUrl) =>
|
||||
new(StripeCheckoutStatus.Created, checkoutUrl, "Stripe checkout session created.");
|
||||
|
||||
public static StripeCheckoutResult NotConfigured(string message) =>
|
||||
new(StripeCheckoutStatus.NotConfigured, null, message);
|
||||
|
||||
public static StripeCheckoutResult UnknownTier(string message) =>
|
||||
new(StripeCheckoutStatus.UnknownTier, null, message);
|
||||
|
||||
public static StripeCheckoutResult ProviderError(string message) =>
|
||||
new(StripeCheckoutStatus.ProviderError, null, message);
|
||||
}
|
||||
|
||||
public enum StripeCheckoutStatus
|
||||
{
|
||||
Created,
|
||||
NotConfigured,
|
||||
UnknownTier,
|
||||
ProviderError
|
||||
}
|
||||
216
src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs
Normal file
216
src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Features.Patronage;
|
||||
|
||||
public sealed class StripeWebhookService(
|
||||
BifrostDbContext dbContext,
|
||||
PatronageService patronageService,
|
||||
IOptions<StripeOptions> options)
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public async Task<StripeWebhookResult> ProcessAsync(
|
||||
string signatureHeader,
|
||||
string payload,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var stripeOptions = options.Value;
|
||||
if (!stripeOptions.IsWebhookConfigured)
|
||||
{
|
||||
return StripeWebhookResult.NotConfigured("Stripe webhook processing is not configured.");
|
||||
}
|
||||
|
||||
if (!HasValidSignature(signatureHeader, payload, stripeOptions.WebhookSecret))
|
||||
{
|
||||
return StripeWebhookResult.Unauthorized("Invalid Stripe webhook signature.");
|
||||
}
|
||||
|
||||
StripeWebhookEvent? stripeEvent;
|
||||
try
|
||||
{
|
||||
stripeEvent = JsonSerializer.Deserialize<StripeWebhookEvent>(payload, JsonOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return StripeWebhookResult.BadRequest("Stripe webhook payload is not valid JSON.");
|
||||
}
|
||||
|
||||
if (stripeEvent is null || string.IsNullOrWhiteSpace(stripeEvent.Id))
|
||||
{
|
||||
return StripeWebhookResult.BadRequest("Stripe webhook payload is missing an event id.");
|
||||
}
|
||||
|
||||
if (!string.Equals(stripeEvent.Type, "checkout.session.completed", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return StripeWebhookResult.Ignored($"Ignored Stripe event type '{stripeEvent.Type}'.");
|
||||
}
|
||||
|
||||
var session = stripeEvent.Data.Object;
|
||||
if (!string.Equals(session.PaymentStatus, "paid", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return StripeWebhookResult.Ignored($"Ignored Stripe checkout session with payment status '{session.PaymentStatus}'.");
|
||||
}
|
||||
|
||||
if (session.AmountTotal is null or <= 0)
|
||||
{
|
||||
return StripeWebhookResult.BadRequest("Stripe checkout session is missing a positive amount_total.");
|
||||
}
|
||||
|
||||
var patronageAccount = await ResolvePatronageAccountAsync(session, stripeOptions, cancellationToken);
|
||||
|
||||
if (patronageAccount?.Membership is null || patronageAccount.Membership.Status == MembershipStatus.Suspended)
|
||||
{
|
||||
return StripeWebhookResult.NotConfigured(
|
||||
"Stripe checkout session is not linked to an unsuspended Bifrost patron account.");
|
||||
}
|
||||
|
||||
var amount = session.AmountTotal.Value / 100m;
|
||||
var currencyCode = string.IsNullOrWhiteSpace(session.Currency)
|
||||
? "USD"
|
||||
: session.Currency.ToUpperInvariant();
|
||||
|
||||
await patronageService.RecordSupportEventAsync(
|
||||
actorUserAccountId: null,
|
||||
patronageAccount.Id,
|
||||
PatronSupportEventKind.OneTimeDonation,
|
||||
amount,
|
||||
currencyCode,
|
||||
session.Id,
|
||||
ExternalPatronProvider.Stripe,
|
||||
stripeEvent.Id,
|
||||
session.Customer,
|
||||
string.Empty,
|
||||
DateTimeOffset.FromUnixTimeSeconds(stripeEvent.Created),
|
||||
isCurrentRecurringSupport: false,
|
||||
BuildNotes(session),
|
||||
cancellationToken);
|
||||
|
||||
return StripeWebhookResult.Processed("Stripe patronage support event recorded.");
|
||||
}
|
||||
|
||||
private async Task<UserAccount?> ResolvePatronageAccountAsync(
|
||||
StripeCheckoutSession session,
|
||||
StripeOptions stripeOptions,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (session.Metadata.TryGetValue("bifrost_user_account_id", out var userAccountIdText) &&
|
||||
Guid.TryParse(userAccountIdText, out var userAccountId))
|
||||
{
|
||||
return await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(stripeOptions.GeneralPatronageGitHubLogin))
|
||||
{
|
||||
var normalizedLogin = stripeOptions.GeneralPatronageGitHubLogin.Trim().ToUpperInvariant();
|
||||
return await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.SingleOrDefaultAsync(x => x.NormalizedGitHubLogin == normalizedLogin, cancellationToken);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string BuildNotes(StripeCheckoutSession session)
|
||||
{
|
||||
session.Metadata.TryGetValue("tier", out var tier);
|
||||
session.Metadata.TryGetValue("source", out var source);
|
||||
return $"Verified Stripe checkout session for {source ?? "unknown source"} tier {tier ?? "unknown tier"}.";
|
||||
}
|
||||
|
||||
private static bool HasValidSignature(string signatureHeader, string payload, string webhookSecret)
|
||||
{
|
||||
var pieces = signatureHeader
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(piece => piece.Split('=', 2))
|
||||
.Where(parts => parts.Length == 2)
|
||||
.GroupBy(parts => parts[0], parts => parts[1])
|
||||
.ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (!pieces.TryGetValue("t", out var timestamps) ||
|
||||
!pieces.TryGetValue("v1", out var signatures) ||
|
||||
timestamps.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var signedPayload = $"{timestamps[0]}.{payload}";
|
||||
using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes(webhookSecret));
|
||||
var expected = Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes(signedPayload))).ToLowerInvariant();
|
||||
return signatures.Any(signature => FixedTimeEquals(signature, expected));
|
||||
}
|
||||
|
||||
private static bool FixedTimeEquals(string actual, string expected)
|
||||
{
|
||||
var actualBytes = Encoding.UTF8.GetBytes(actual);
|
||||
var expectedBytes = Encoding.UTF8.GetBytes(expected);
|
||||
return actualBytes.Length == expectedBytes.Length &&
|
||||
CryptographicOperations.FixedTimeEquals(actualBytes, expectedBytes);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record StripeWebhookResult(
|
||||
StripeWebhookStatus Status,
|
||||
string Message)
|
||||
{
|
||||
public static StripeWebhookResult Processed(string message) => new(StripeWebhookStatus.Processed, message);
|
||||
|
||||
public static StripeWebhookResult Ignored(string message) => new(StripeWebhookStatus.Ignored, message);
|
||||
|
||||
public static StripeWebhookResult BadRequest(string message) => new(StripeWebhookStatus.BadRequest, message);
|
||||
|
||||
public static StripeWebhookResult Unauthorized(string message) => new(StripeWebhookStatus.Unauthorized, message);
|
||||
|
||||
public static StripeWebhookResult NotConfigured(string message) => new(StripeWebhookStatus.NotConfigured, message);
|
||||
}
|
||||
|
||||
public enum StripeWebhookStatus
|
||||
{
|
||||
Processed,
|
||||
Ignored,
|
||||
BadRequest,
|
||||
Unauthorized,
|
||||
NotConfigured
|
||||
}
|
||||
|
||||
public sealed class StripeWebhookEvent
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
public string Type { get; set; } = string.Empty;
|
||||
|
||||
public long Created { get; set; }
|
||||
|
||||
public StripeWebhookData Data { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class StripeWebhookData
|
||||
{
|
||||
public StripeCheckoutSession Object { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class StripeCheckoutSession
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
public string Customer { get; set; } = string.Empty;
|
||||
|
||||
public string Currency { get; set; } = "usd";
|
||||
|
||||
[JsonPropertyName("amount_total")]
|
||||
public long? AmountTotal { get; set; }
|
||||
|
||||
[JsonPropertyName("payment_status")]
|
||||
public string PaymentStatus { get; set; } = string.Empty;
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ public sealed class StartupConfigurationValidator(
|
|||
IOptions<GitHubOAuthOptions> gitHubOAuthOptions,
|
||||
IOptions<GitHubAppOptions> gitHubAppOptions,
|
||||
IOptions<HeimdallOptions> heimdallOptions,
|
||||
IOptions<StripeOptions> stripeOptions,
|
||||
IOptions<BifrostHostOptions> hostOptions)
|
||||
{
|
||||
public void Validate()
|
||||
|
|
@ -41,6 +42,17 @@ public sealed class StartupConfigurationValidator(
|
|||
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
|
||||
}
|
||||
|
||||
if (stripeOptions.Value.EnableCheckout)
|
||||
{
|
||||
if (!stripeOptions.Value.IsCheckoutConfigured)
|
||||
{
|
||||
failures.Add("Stripe:SecretKey, Stripe:SuccessUrl, and Stripe:CancelUrl are required when Stripe checkout is enabled.");
|
||||
}
|
||||
|
||||
// Stripe:GeneralPatronageGitHubLogin is only a legacy fallback for old sessions
|
||||
// that predate account-bound checkout metadata.
|
||||
}
|
||||
|
||||
var allowedHosts = configuration["AllowedHosts"] ?? string.Empty;
|
||||
if (hostOptions.Value.RequireStrictHostValidation &&
|
||||
(string.IsNullOrWhiteSpace(allowedHosts) || allowedHosts.Contains('*')))
|
||||
|
|
|
|||
Loading…
Reference in a new issue