Created
January 13, 2023 05:02
-
-
Save dipeshhkc/0903e9468a289fec3ef17d57a72be4cf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const handleCustomerSubscriptionUpdated = async ( | |
data: Stripe.Event.Data.Object | |
) => { | |
const stripeSub = data as Stripe.Subscription; | |
const subscription = await db.subscription.findFirst({ | |
where: { | |
stripe_subscription_id: stripeSub.id, | |
}, | |
}); | |
//subscription cancellation | |
if (stripeSub.cancel_at_period_end) { | |
await db.subscription.update({ | |
where: { id: subscription!.id }, | |
data: { | |
//Possible values are incomplete, incomplete_expired, trialing, active, past_due, canceled, or unpaid. | |
stripe_status: stripeSub.status, | |
ends_at: new Date(stripeSub.current_period_end * 1000), | |
}, | |
}); | |
console.log({ | |
message: `Subscription cancelled ${subscription!.stripe_subscription_id}`, | |
}); | |
} else { | |
const newSubscriptionPlan = stripeSub.items.data[0].price; | |
const newPlanId = newSubscriptionPlan.id; | |
// there may be changes in plan | |
if (subscription!.stripe_plan_id !== newPlanId) { | |
const oldPlanName = subscription!.stripe_plan_name; | |
await db.subscription.update({ | |
where: { id: subscription!.id }, | |
data: { | |
stripe_plan_id: newSubscriptionPlan.id, | |
stripe_plan_name: | |
newSubscriptionPlan.nickname || getTierName(newSubscriptionPlan.id), | |
stripe_status: stripeSub.status, | |
}, | |
}); | |
console.log({ | |
message: `Subscription plan switched from ${oldPlanName} to ${ | |
newSubscriptionPlan.nickname | |
} for ${subscription!.stripe_subscription_id}`, | |
}); | |
} else { | |
// plan may be renewed after cancellation | |
await db.subscription.update({ | |
where: { id: subscription!.id }, | |
data: { | |
ends_at: null, | |
}, | |
}); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment