(req: NextApiRequest, res: NextApiResponse)
| 26 | }); |
| 27 | |
| 28 | const 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, |
nothing calls this directly
no test coverage detected