diff --git a/app/webhooks/stripe/handle-invoice-creation.ts b/app/webhooks/stripe/handle-invoice-creation.ts new file mode 100644 index 00000000..b9d97fa9 --- /dev/null +++ b/app/webhooks/stripe/handle-invoice-creation.ts @@ -0,0 +1,30 @@ +import { stripe } from "@/services/external/stripe"; +import type Stripe from "stripe"; + +export async function handleInvoiceCreation(invoice: Stripe.Invoice) { + if (!invoice.subscription || typeof invoice.subscription !== "string") { + throw new Error( + "Invoice is missing a subscription ID. Please check the invoice data.", + ); + } + + const subscription = await stripe.subscriptions.retrieve( + invoice.subscription, + ); + + if (subscription.status !== "canceled") { + return; + } + + await finalizeAndPayInvoice(invoice.id); +} + +async function finalizeAndPayInvoice(invoiceId: string) { + try { + await stripe.invoices.finalizeInvoice(invoiceId); + await stripe.invoices.pay(invoiceId); + } catch (error) { + console.error(`Error processing invoice ${invoiceId}:`, error); + throw new Error("Failed to process invoice"); + } +} diff --git a/app/webhooks/stripe/route.ts b/app/webhooks/stripe/route.ts index 9da26fbc..02c9998b 100644 --- a/app/webhooks/stripe/route.ts +++ b/app/webhooks/stripe/route.ts @@ -1,6 +1,7 @@ import { stripe } from "@/services/external/stripe"; import { upsertSubscription } from "@/services/external/stripe/actions/upsert-subscription"; import type Stripe from "stripe"; +import { handleInvoiceCreation } from "./handle-invoice-creation"; import { handleSubscriptionCancellation } from "./handle-subscription-cancellation"; import { handleSubscriptionCycleInvoice } from "./handle-subscription-cycle-invoice"; @@ -85,35 +86,9 @@ export async function POST(req: Request) { break; case "invoice.created": { - console.log(`🔔 Invoice created: ${event.data.object.id}`); + console.log(`🔔 Invoice created: ${event.data.object.id}`); - const invoice = event.data.object; - - if (!invoice.subscription || typeof invoice.subscription !== "string") { - throw new Error( - "Invoice is missing a subscription ID. Please check the invoice data.", - ); - } - - const subscription = await stripe.subscriptions.retrieve( - invoice.subscription, - ); - - if (subscription.status === "canceled") { - try { - await stripe.invoices.finalizeInvoice(invoice.id); - } catch (error) { - console.error(`Error finalizing invoice ${invoice.id}:`, error); - throw new Error("Failed to finalize invoice."); - } - - try { - await stripe.invoices.pay(invoice.id); - } catch (error) { - console.error(`Error paying invoice ${invoice.id}:`, error); - throw new Error("Failed to pay invoice."); - } - } + await handleInvoiceCreation(event.data.object); // TODO: This block will be removed in the other issue. if (event.data.object.billing_reason === "subscription_cycle") {