Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions lib/billing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ export async function applyOrderPaidEntitlement(
}

const order = parsed.data;
const normalizedEmail = order.customer.email.toLowerCase();
const planSlug = order.productId ? planByProductId.get(order.productId) : null;
const planSlug = order.productId
? planByProductId.get(order.productId)
: null;

if (!planSlug) {
console.warn("[Polar] Unmapped product in order.paid", {
Expand All @@ -43,17 +44,29 @@ export async function applyOrderPaidEntitlement(
return;
}

const user = await prisma.user.findUnique({ where: { email: normalizedEmail } })
let user = order.customer.externalId
? await prisma.user.findUnique({ where: { id: order.customer.externalId } })
: null;

if (!user) {
const normalizedEmail = order.customer.email.toLowerCase();
user = await prisma.user.findUnique({ where: { email: normalizedEmail } });
}

if (!user) {
console.error("[Polar] No matching user for paid order", {
orderId: order.id,
email: normalizedEmail,
externalId: order.customer.externalId,
email: order.customer.email.toLowerCase(),
});
return;
}

// Idempotent: skip if this order was already applied
if (user.polarLastOrderId === order.id) {
return;
}

await prisma.user.update({
where: { id: user.id },
data: {
Expand Down
Loading