-
-
Notifications
You must be signed in to change notification settings - Fork 617
Expand file tree
/
Copy pathroute.ts
More file actions
60 lines (51 loc) · 1.81 KB
/
route.ts
File metadata and controls
60 lines (51 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { TRPCError } from "@trpc/server";
import { getHTTPStatusCodeFromError } from "@trpc/server/http";
import type { NextRequest } from "next/server";
import { createTRPCContext } from "@openstatus/api";
import { lambdaRouter, stripe } from "@openstatus/api/src/lambda";
import { env } from "@/env";
export async function POST(req: NextRequest) {
const payload = await req.text();
const signature = req.headers.get("Stripe-Signature");
if (!signature) return new Response("No signature", { status: 400 });
try {
const event = stripe.webhooks.constructEvent(
payload,
signature,
env.STRIPE_WEBHOOK_SECRET_KEY,
);
/**
* Forward to tRPC API to handle the webhook event
*/
const ctx = await createTRPCContext({ req });
const caller = lambdaRouter.createCaller(ctx);
switch (event.type) {
case "checkout.session.completed":
await caller.stripeRouter.webhooks.sessionCompleted({ event });
break;
case "customer.subscription.updated":
await caller.stripeRouter.webhooks.customerSubscriptionUpdated({
event,
});
break;
case "customer.subscription.deleted":
await caller.stripeRouter.webhooks.customerSubscriptionDeleted({
event,
});
break;
default:
throw new Error(`Unhandled event type ${event.type}`);
}
} catch (error) {
if (error instanceof TRPCError) {
const errorCode = getHTTPStatusCodeFromError(error);
console.error("Error in tRPC webhook handler", error);
return new Response(error.message, { status: errorCode });
}
const message = error instanceof Error ? error.message : "Unknown error";
return new Response(`Webhook Error: ${message}`, {
status: 400,
});
}
return new Response(null, { status: 200 });
}