I want to achieve the following when I cancel my subscription:
nextBillingTime: 2024-05-10T14:59:58.582+00:00
paypalSubscriptionCancelledAt: 2024-05-07T11:59:18.000+00:00
subscriptionPeriodDuration: 3 days, 3 hours, 0 minutes, 40 seconds
I have the following code:
paypalRouter.post("/cancel-subscription/webhook", async (req, res) => {
try {
const webhookEvent = req.body;
if (verifyResponse.data.verification_status === "SUCCESS") {
if (webhookEvent.event_type === "BILLING.SUBSCRIPTION.CANCELLED") {
const userId = webhookEvent.resource.custom_id;
const subscriptionId = webhookEvent.resource.id;
const nextBillingTime = webhookEvent.resource.billing_info.next_billing_time;
const paypalSubscriptionCancelledAt = webhookEvent.resource.status_update_time;
try {
const updatedUserCancelSubscription = await User.findOneAndUpdate(
{ _id: userId, subscriptionId: subscriptionId },
{
$set: {
suscriptionStatusCancelled: true,
subscriptionStatusPending: false,
subscriptionStatusConfirmed: false,
nextBillingTime: nextBillingTime,
isPremium: true,
paypalSubscriptionCancelledAt: paypalSubscriptionCancelledAt,
subscriptionPeriodDuration:
},
},
{ new: true }
);
// ... (other code)
} catch (error) {
// ... (error handling)
}
}
} else {
// ... (other code)
}
} catch (error) {
// ... (error handling)
}
});
I need help calculating the subscriptionPeriodDuration
using the nextBillingTime
and paypalSubscriptionCancelledAt
dates.
2
Answers
Thank you all for the help. After a bit of struggle, I realized that my logic was incorrect. Instead of focusing on
PayPalSubscriptionCancelledAt
andsubscriptionPeriodDuration
, which are static dates, I should create a dynamic date to updatenextBillingTime
according to my logic. In my case, I created a new property in mymongoose.Schema()
getCurrentTimeAfterRefresh
, which is a dynamic date and updates each day thanks tonode-cron
, and I can create the desired logic. Here is the solution to my problem:Implementing
node-cron
moment is not up to par anymore. Look at their docs and they will give you a bunch of reasons not to use it.
I still use dayjs, but the later ones you should look at are luxon or date-fns.
Check out math with dates on luxon’s docs here:
https://moment.github.io/luxon/#/math