Skip to content

Commit

Permalink
Send payment sucess event to Posthog
Browse files Browse the repository at this point in the history
  • Loading branch information
elie222 committed Dec 26, 2024
1 parent b8b5682 commit d967ad9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
36 changes: 36 additions & 0 deletions apps/web/app/api/lemon-squeezy/webhook/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ export const POST = withError(async (request: Request) => {
});
}

// payment success
if (payload.meta.event_name === "subscription_payment_success") {
return await subscriptionPaymentSuccess({ payload, premiumId });
}

return NextResponse.json({ ok: true });
});

Expand Down Expand Up @@ -303,6 +308,37 @@ async function subscriptionCancelled({
return NextResponse.json({ ok: true });
}

async function subscriptionPaymentSuccess({
payload,
premiumId,
}: {
payload: Payload;
premiumId: string;
}) {
if (payload.data.attributes.status !== "paid") {
throw new Error(
`Unexpected status for subscription payment success: ${payload.data.attributes.status}`,
);
}

const premium = await prisma.premium.findUnique({
where: { id: premiumId },
select: {
admins: { select: { email: true } },
users: { select: { email: true } },
},
});

const email = premium?.admins?.[0]?.email || premium?.users?.[0]?.email;
if (!email) throw new Error("No email found");
await posthogCaptureEvent(email, "Payment success", {
totalPaidUSD: payload.data.attributes.total_usd,
lemonSqueezyId: payload.data.id,
lemonSqueezyType: payload.data.type,
});
return NextResponse.json({ ok: true });
}

function getEmailFromPremium(premium: {
users: Array<{ email: string | null }>;
}) {
Expand Down
4 changes: 3 additions & 1 deletion apps/web/app/api/lemon-squeezy/webhook/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export interface Attributes {
variant_name: string;
user_name: string;
user_email: string;
status: string; // on_trial, active, cancelled, past_due, and optionally paused.
status: string; // on_trial, active, cancelled, past_due, paused, paid
status_formatted: string;
card_brand: string;
card_last_four: string;
Expand All @@ -58,6 +58,8 @@ export interface Attributes {
test_mode: boolean;
first_subscription_item?: FirstSubscriptionItem;
first_order_item?: FirstOrderItem;
// in payment success
total_usd?: number;
}

export interface FirstSubscriptionItem {
Expand Down

1 comment on commit d967ad9

@vercel
Copy link

@vercel vercel bot commented on d967ad9 Dec 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.