Skip to content

Commit

Permalink
fix: update subscription tracking (#2461)
Browse files Browse the repository at this point in the history
  • Loading branch information
rebelchris authored Nov 19, 2024
1 parent 70b1d50 commit 7f77654
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions src/routes/webhooks/paddle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,11 @@ const updateUserSubscription = async ({
data,
state,
}: {
data: SubscriptionCreatedEvent | SubscriptionCanceledEvent | undefined;
data:
| SubscriptionCreatedEvent
| SubscriptionCanceledEvent
| SubscriptionUpdatedEvent
| undefined;
state: boolean;
}) => {
if (!data) {
Expand Down Expand Up @@ -114,6 +118,24 @@ const getUserId = async ({
return user.id;
};

const planChanged = async (data: SubscriptionUpdatedEvent) => {
const customData = data.data?.customData as { user_id: string };
const userId = await getUserId({
userId: customData?.user_id,
subscriptionId: data.data?.id,
});
const con = await createOrGetConnection();
const flags = await con.getRepository(User).findOne({
where: { id: userId },
select: ['subscriptionFlags'],
});

return (
(flags?.subscriptionFlags?.cycle as string) !==
extractSubscriptionType(data.data?.items)
);
};

const logPaddleAnalyticsEvent = async (
data:
| SubscriptionUpdatedEvent
Expand All @@ -132,7 +154,9 @@ const logPaddleAnalyticsEvent = async (
const currency = data.data?.items?.[0]?.price?.unitPrice?.currencyCode;
const userId = await getUserId({
userId: customData?.user_id,
subscriptionId: 'subscriptionId' in data.data && data.data.subscriptionId,
subscriptionId:
('subscriptionId' in data.data && data.data.subscriptionId) ||
data.data.id,
});
if (!userId) {
return;
Expand Down Expand Up @@ -203,10 +227,17 @@ export const paddle = async (fastify: FastifyInstance): Promise<void> => {
);
break;
case EventName.SubscriptionUpdated:
await logPaddleAnalyticsEvent(
eventData,
AnalyticsEventName.ChangeBillingCycle,
);
const didPlanChange = await planChanged(eventData);
if (didPlanChange) {
await updateUserSubscription({
data: eventData,
state: true,
});
await logPaddleAnalyticsEvent(
eventData,
AnalyticsEventName.ChangeBillingCycle,
);
}
break;
case EventName.TransactionCompleted:
await logPaddleAnalyticsEvent(
Expand Down

0 comments on commit 7f77654

Please sign in to comment.