Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

cancel subscription when someone deletes their project

Steven Tey55a97a196ccd
diff --git a/lib/stripe/index.ts b/lib/stripe/index.ts
index 27e692594a..32eaf7508e 100644
--- a/lib/stripe/index.ts
+++ b/lib/stripe/index.ts
@@ -10,3 +10,25 @@ export const stripe = new Stripe(
},
},
);
+
+export async function cancelSubscription(customer?: string) {
+ if (!customer) return;
+
+ try {
+ const subscriptionId = await stripe.subscriptions
+ .list({
+ customer,
+ })
+ .then((res) => res.data[0].id);
+
+ return await stripe.subscriptions.update(subscriptionId, {
+ cancel_at_period_end: true,
+ cancellation_details: {
+ comment: "Customer deleted their Dub project.",
+ },
+ });
+ } catch (error) {
+ console.log("Error cancelling Stripe subscription", error);
+ return;
+ }
+}
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index e276de348b..050eea4278 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -1,6 +1,7 @@
import { withProjectAuth } from "@/lib/auth";
import { deleteDomainAndLinks } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
+import { cancelSubscription } from "@/lib/stripe";
export default withProjectAuth(async (req, res, project) => {
// GET /api/projects/[slug] – get a specific project
@@ -39,10 +40,17 @@ export default withProjectAuth(async (req, res, project) => {
})
).map((domain) => domain.slug);
+ // delete all domains, links, and uploaded images associated with the project
const deleteDomainsResponse = await Promise.allSettled(
domains.map((domain) => deleteDomainAndLinks(domain)),
);
+ // if they have a Stripe subscription, cancel it
+ const cancelSubscriptionResponse = await cancelSubscription(
+ project.stripeId,
+ );
+
+ // delete the project
const deleteProjectResponse = await prisma.project.delete({
where: {
slug: project.slug,
@@ -51,6 +59,7 @@ export default withProjectAuth(async (req, res, project) => {
return res.status(200).json({
deleteProjectResponse,
+ cancelSubscriptionResponse,
deleteDomainsResponse,
});
} else {