-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(webhook): Improve invoice creation handler with better error…
… handling Split invoice processing into smaller, focused functions: - Extract finalizeAndPayInvoice into separate function - Add early return for non-canceled subscriptions - Improve code organization with clear responsibility separation This refactor enhances error handling and makes the code more maintainable by following single responsibility principle.
- Loading branch information
Showing
2 changed files
with
33 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters