+ Memberships
- DDD
- FutureCreator
- UserTransactions
This commit is contained in:
2024-10-20 14:01:58 -04:00
parent 3d10427821
commit 28d74503df
117 changed files with 2149 additions and 1999 deletions

View File

@@ -0,0 +1,71 @@
using Hutopy.Web.Features.Memberships.Data;
using Hutopy.Web.Features.Memberships.Services;
using Microsoft.Extensions.Options;
using Stripe;
namespace Hutopy.Web.Features.Memberships.Handlers;
public static class StripeEvents
{
public const string SubscriptionCreated = "subscription_created";
public const string CustomerSubscriptionDeleted = "customer.subscription_deleted";
public const string InvoicePaymentSucceeded = "invoice.payment_succeeded";
public const string InvoicePaymentFailed = "invoice.payment_failed";
public const string CheckoutSessionCompleted = "checkout.session.completed";
}
public class StripeWebhookEndpoint(
MembershipDbContext dbContext,
StripeService stripeService,
IOptions<StripeOptions> options)
: EndpointWithoutRequest
{
public override void Configure()
{
Post("/api/stripe");
AllowAnonymous();
Options(o => o.WithTags("Memberships"));
}
public override async Task HandleAsync(CancellationToken ct)
{
using var streamReader = new StreamReader(HttpContext.Request.Body);
var json = await streamReader.ReadToEndAsync(ct);
var signatureHeader = HttpContext.Request.Headers["Stripe-Signature"];
var stripeEvent = EventUtility.ConstructEvent(json, signatureHeader, options.Value.WebhookSecret);
switch (stripeEvent.Type)
{
case StripeEvents.InvoicePaymentSucceeded:
await stripeService.HandlePaymentSucceeded(stripeEvent, ct);
break;
case StripeEvents.InvoicePaymentFailed:
await stripeService.HandlePaymentFailed(stripeEvent, ct);
break;
case StripeEvents.CheckoutSessionCompleted:
await stripeService.HandleCheckoutSessionCompleted(stripeEvent, ct);
break;
case StripeEvents.CustomerSubscriptionDeleted:
{
var subscription = stripeEvent.Data.Object as Stripe.Subscription;
var existingSubscription = await dbContext
.Subscriptions
.FirstOrDefaultAsync(x => x.StripeSubscriptionId == subscription!.Id, ct);
if (existingSubscription != null)
{
var today = DateTime.Today;
int lastDay = DateTime.DaysInMonth(today.Year, today.Month);
var lastDayOfMonth = new DateTime(today.Year, today.Month, lastDay);
existingSubscription.EndDate = new DateTimeOffset(lastDayOfMonth);
await dbContext.SaveChangesAsync(ct);
}
break;
}
}
await SendOkAsync(ct);
}
}