This commit is contained in:
2024-10-22 16:41:11 -04:00
parent 114a10416a
commit 0c11d0aa5e
25 changed files with 1146 additions and 508 deletions

View File

@@ -1,21 +1,10 @@
using Hutopy.Web.Features.Memberships.Data;
using Hutopy.Web.Features.Memberships.Services;
using Hutopy.Web.Features.Memberships.Infrastructure;
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
@@ -37,33 +26,24 @@ public class StripeWebhookEndpoint(
switch (stripeEvent.Type)
{
case StripeEvents.InvoicePaymentSucceeded:
await stripeService.HandlePaymentSucceeded(stripeEvent, ct);
break;
case StripeEvents.InvoicePaymentFailed:
await stripeService.HandlePaymentFailed(stripeEvent, ct);
break;
case StripeEvents.CheckoutSessionCompleted:
case "checkout.session.completed":
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;
}
case "invoice.payment_succeeded":
await stripeService.HandleInvoicePaymentSucceeded(stripeEvent, ct);
break;
case "invoice.payment_failed":
await stripeService.HandleInvoicePaymentFailed(stripeEvent, ct);
break;
case "customer.subscription.created":
await stripeService.HandleCustomerSubscriptionCreated(stripeEvent, ct);
break;
case "customer.subscription.updated":
await stripeService.HandleCustomerSubscriptionUpdated(stripeEvent, ct);
break;
case "customer.subscription.deleted":
await stripeService.HandleCustomerSubscriptionDeleted(stripeEvent, ct);
break;
}
await SendOkAsync(ct);