The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Fix trial subscription payment_behavior (#4006)
Steven Tey5a11cb799ba9
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.tsindex b08203b6bf..722ea7b201 100644--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts@@ -173,7 +173,7 @@ async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {workspaceOwners.map(({ user }) => ({variant: "notifications",to: user.email!,- subject: `Your ${pluralize("domain", domains.length)} have been renewed`,+ subject: `Your ${pluralize("domain", domains.length)} ${domains.length === 1 ? "has" : "have"} been renewed`,react: DomainRenewed({email: user.email!,workspace: {diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-created.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-created.tsnew file mode 100644index 0000000000..0b1b227c37--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-created.ts@@ -0,0 +1,22 @@+import { stripe } from "@/lib/stripe";+import Stripe from "stripe";++// workaround to make sure trial subscriptions are created with payment_behavior="default_incomplete"+export async function customerSubscriptionCreated(+ event: Stripe.CustomerSubscriptionCreatedEvent,+) {+ const createdSubscription = event.data.object;++ if (createdSubscription.status !== "trialing") {+ return `Subscription ${createdSubscription.id} is not in trialing status, skipping...`;+ }++ const updatedSubscription = await stripe.subscriptions.update(+ createdSubscription.id,+ {+ payment_behavior: "default_incomplete",+ },+ );++ return `Updated trial subscription ${updatedSubscription.id} with payment_behavior="default_incomplete"`;+}diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.tsindex 3319901253..cff4b65fdf 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts@@ -21,9 +21,9 @@ import { updateWorkspacePlan } from "./utils/update-workspace-plan";export async function customerSubscriptionDeleted(event: Stripe.CustomerSubscriptionDeletedEvent,) {- const subscriptionDeleted = event.data.object;+ const deletedSubscription = event.data.object;- const stripeId = subscriptionDeleted.customer.toString();+ const stripeId = deletedSubscription.customer.toString();// If a workspace deletes their subscription, reset their usage limit in the database to 1000.// Also remove the root domain link for all their domains from MySQL, Redis, and Tinybirddiff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.tsindex 97adb6b7bc..f50534443f 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts@@ -1,5 +1,6 @@import { prisma } from "@dub/prisma";-import { getPlanAndTierFromPriceId } from "@dub/utils";+import { getPlanAndTierFromPriceId, TRIAL_LIMITS } from "@dub/utils";+import { differenceInHours } from "date-fns";import Stripe from "stripe";import { sendCancellationFeedback } from "./utils/send-cancellation-feedback";import { updateWorkspacePlan } from "./utils/update-workspace-plan";@@ -16,7 +17,13 @@ export async function customerSubscriptionUpdated(return `Invalid price ID in customer.subscription.updated event: ${priceId}`;}- if (!["active", "trialing"].includes(updatedSubscription.status)) {+ if (+ ![+ "active",+ "trialing",+ "past_due", // special case for handling past_due subscriptions (after a free trial)+ ].includes(updatedSubscription.status)+ ) {return `Invalid updated subscription status "${updatedSubscription.status}" for subscription ${updatedSubscription.id}, skipping...`;}@@ -52,7 +59,41 @@ export async function customerSubscriptionUpdated(});if (!workspace) {- return `Workspace with Stripe ID ${stripeId} not found in customer.subscription.updated callback.`;+ return `Workspace with Stripe ID ${stripeId} not found, skipping...`;+ }++ if (updatedSubscription.status === "past_due") {+ const trialEndsAt = updatedSubscription.trial_end+ ? new Date(updatedSubscription.trial_end * 1000)+ : null;++ // if the subscription became past_due and the workspace's trial ended less than 2 hours ago+ // it means that their payment failed and we need to revert to their trial limits+ if (trialEndsAt && differenceInHours(new Date(), trialEndsAt) < 2) {+ await prisma.project.update({+ where: {+ stripeId,+ },+ data: {+ trialEndsAt,+ // revert to trial limits+ usageLimit: TRIAL_LIMITS.clicks,+ linksLimit: TRIAL_LIMITS.links,+ payoutsLimit: TRIAL_LIMITS.payouts,+ domainsLimit: TRIAL_LIMITS.domains,+ aiLimit: TRIAL_LIMITS.ai,+ tagsLimit: TRIAL_LIMITS.tags,+ partnerTagsLimit: TRIAL_LIMITS.partnerTags,+ foldersLimit: TRIAL_LIMITS.folders,+ groupsLimit: TRIAL_LIMITS.groups,+ networkInvitesLimit: TRIAL_LIMITS.networkInvites,+ partnersLimit: TRIAL_LIMITS.partners,+ usersLimit: TRIAL_LIMITS.users,+ },+ });+ return `Reverted workspace ${workspace.slug} to trial limits due to past_due subscription.`;+ }+ return `Unrelated past_due subscription event for workspace ${workspace.slug}, skipping...`;}await updateWorkspacePlan({diff --git a/apps/web/app/(ee)/api/stripe/webhook/route.ts b/apps/web/app/(ee)/api/stripe/webhook/route.tsindex dcd744ecbf..17c5e8d69d 100644--- a/apps/web/app/(ee)/api/stripe/webhook/route.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/route.ts@@ -6,6 +6,7 @@ import { chargeFailed } from "./charge-failed";import { chargeRefunded } from "./charge-refunded";import { chargeSucceeded } from "./charge-succeeded";import { checkoutSessionCompleted } from "./checkout-session-completed";+import { customerSubscriptionCreated } from "./customer-subscription-created";import { customerSubscriptionDeleted } from "./customer-subscription-deleted";import { customerSubscriptionUpdated } from "./customer-subscription-updated";import { invoicePaymentFailed } from "./invoice-payment-failed";@@ -17,6 +18,7 @@ const relevantEvents = new Set(["charge.failed","charge.refunded","checkout.session.completed",+ "customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","invoice.payment_failed",@@ -62,6 +64,9 @@ export const POST = async (req: Request) => {case "checkout.session.completed":response = await checkoutSessionCompleted(event);break;+ case "customer.subscription.created":+ response = await customerSubscriptionCreated(event);+ break;case "customer.subscription.updated":response = await customerSubscriptionUpdated(event);break;