Skip to content

Commit b70f38f

Browse files
Merge pull request #46 from harishdeivanayagam/feature/ee-cloud-billing
fix: billing webhook
2 parents 1e6fd1f + 6a170ec commit b70f38f

File tree

1 file changed

+32
-17
lines changed

1 file changed

+32
-17
lines changed

src/app/api/ee/billing/webhooks/route.ts

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,17 +26,12 @@ export async function POST(request: NextRequest) {
2626
)
2727
}
2828

29-
const paddle = new Paddle(process.env.PADDLE_API_KEY || "", {
29+
const paddle = new Paddle(process.env.PADDLE_CLIENT_SECRET || "", {
3030
environment: process.env.PADDLE_MODE === "production" ? Environment.production : Environment.sandbox
3131
})
3232

3333
const event = await paddle.webhooks.unmarshal(rawBody, secret, signature)
3434

35-
const planData = {
36-
[process.env.PADDLE_PRICE_PRO || "PRO"]: "PRO",
37-
[process.env.PADDLE_PRICE_ENT || "ENTERPRISE"]: "ENTERPRISE"
38-
}
39-
4035
if (!event) {
4136
return NextResponse.json(
4237
{ error: "Invalid event" },
@@ -46,7 +41,7 @@ export async function POST(request: NextRequest) {
4641

4742
if (event && (event.eventType === EventName.TransactionCompleted)) {
4843
const customerId = event.data.customerId || ""
49-
const planId = event.data.items[0].price?.id || ""
44+
const priceId = event.data.items[0].price?.id || ""
5045

5146
const billing = await prisma.billing.findFirstOrThrow({
5247
where: {
@@ -58,16 +53,36 @@ export async function POST(request: NextRequest) {
5853
await paddle.subscriptions.cancel(billing.subscriptionId, { effectiveFrom: "immediately" })
5954
}
6055

61-
await prisma.billing.update({
62-
where: {
63-
organizationId: billing.organizationId
64-
},
65-
data: {
66-
plan: planData[planId || ""] as Plan,
67-
subscriptionId: event.data.subscriptionId,
68-
expiresAt: new Date(event.data.billingPeriod?.endsAt || "")
69-
}
70-
})
56+
// Handle Pro Plan
57+
if (priceId === process.env.PRO_PLAN_PRICE_ID_MONTHLY || priceId === process.env.PRO_PLAN_PRICE_ID_YEARLY) {
58+
await prisma.billing.update({
59+
where: {
60+
organizationId: billing.organizationId
61+
},
62+
data: {
63+
plan: "PRO",
64+
credits: {
65+
increment: parseInt(process.env.PRO_PLAN_CREDITS || "0")
66+
},
67+
subscriptionId: event.data.subscriptionId,
68+
expiresAt: new Date(event.data.billingPeriod?.endsAt || "")
69+
}
70+
})
71+
}
72+
73+
// Handle Additional Credits
74+
if (priceId === process.env.ADDITIONAL_CREDITS_PRICE_ID) {
75+
await prisma.billing.update({
76+
where: {
77+
organizationId: billing.organizationId
78+
},
79+
data: {
80+
credits: {
81+
increment: parseInt(process.env.ADDITIONAL_CREDITS_QTY || "0")
82+
}
83+
}
84+
})
85+
}
7186
}
7287

7388
if (event && (event.eventType === EventName.SubscriptionCanceled || event.eventType === EventName.SubscriptionPastDue)) {

0 commit comments

Comments
 (0)