MCPcopy Index your code
hub / github.com/sqlchat/sqlchat / webhookHandler

Function webhookHandler

src/pages/api/webhook/index.ts:28–127  ·  view source on GitHub ↗
(req: NextApiRequest, res: NextApiResponse)

Source from the content-addressed store, hash-verified

26});
27
28const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
29 if (req.method === "POST") {
30 const buf = await buffer(req);
31 const sig = req.headers["stripe-signature"]!;
32
33 let event: Stripe.Event;
34
35 try {
36 event = stripe.webhooks.constructEvent(buf.toString(), sig, webhookSecret);
37 } catch (err) {
38 const errorMessage = err instanceof Error ? err.message : "Unknown error";
39 // On error, log and return the error message.
40 if (err! instanceof Error) console.log(err);
41 console.log(`❌ Error message: ${errorMessage}`);
42 res.status(400).send(`Webhook Error: ${errorMessage}`);
43 return;
44 }
45
46 // Cast event data to Stripe object.
47 if (event.type === "payment_intent.succeeded") {
48 const paymentIntent = event.data.object as Stripe.PaymentIntent;
49 const charge = await stripe.charges.retrieve(paymentIntent.latest_charge as string);
50
51 let plan;
52 try {
53 plan = getPlanFromPriceId(paymentIntent.metadata.price);
54 } catch (err) {
55 console.log(err);
56 res.status(400).send(`Invalid price id: ${paymentIntent.metadata.price}`);
57 return;
58 }
59
60 const customerId = paymentIntent.customer as string;
61 if (customerId) {
62 // Save the stripe customer id so that we can relate this customer to future payments.
63 await prisma.user.update({
64 where: {
65 email: paymentIntent.metadata.email,
66 },
67 data: {
68 stripeId: customerId,
69 },
70 });
71 }
72
73 const user = await prisma.user.findUniqueOrThrow({
74 where: { email: paymentIntent.metadata.email },
75 });
76
77 const payment: Prisma.PaymentUncheckedCreateInput = {
78 userId: user.id,
79 email: paymentIntent.metadata.email,
80 createdAt: new Date(paymentIntent.created * 1000),
81 paymentId: paymentIntent.id,
82 customerId: customerId || "",
83 description: plan.description,
84 amount: paymentIntent.amount,
85 currency: paymentIntent.currency,

Callers

nothing calls this directly

Calls 2

getPlanFromPriceIdFunction · 0.90
getSubscriptionByEmailFunction · 0.90

Tested by

no test coverage detected