Skip to content

Commit

Permalink
♻️ Handle failed payments in webhook (#1443)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukevella authored Nov 23, 2024
1 parent b161ea0 commit c2e1c28
Showing 1 changed file with 50 additions and 1 deletion.
51 changes: 50 additions & 1 deletion apps/web/src/app/api/stripe/webhook/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,56 @@ export async function POST(request: NextRequest) {

break;
}
case "customer.subscription.deleted":
case "customer.subscription.deleted": {
const { id } = event.data.object as Stripe.Subscription;
const subscription = await stripe.subscriptions.retrieve(id);

// void any unpaid invoices
const invoices = await stripe.invoices.list({
subscription: subscription.id,
status: "open",
});

for (const invoice of invoices.data) {
await stripe.invoices.voidInvoice(invoice.id);
}

// remove the subscription from the user
await prisma.user.update({
where: {
subscriptionId: subscription.id,
},
data: {
subscriptionId: null,
},
});
// delete the subscription from the database
await prisma.subscription.delete({
where: {
id: subscription.id,
},
});

try {
const { userId } = subscriptionMetadataSchema.parse(
subscription.metadata,
);

posthog?.capture({
distinctId: userId,
event: "subscription cancel",
properties: {
$set: {
tier: "hobby",
},
},
});
} catch (e) {
Sentry.captureException(e);
}

break;
}
case "customer.subscription.updated":
case "customer.subscription.created": {
const { id } = event.data.object as Stripe.Subscription;
Expand Down

0 comments on commit c2e1c28

Please sign in to comment.