While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message
ReferenceError: prisma is not defined
popped up. How can I resolve this?
import { NextApiRequest, NextApiResponse } from "next"
import { buffer } from "stream/consumers"
import Stripe from "stripe"
export const config = {
api:{
bodyParser: false
}
}
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string,{
apiVersion: '2023-10-16'
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
){
const buf = await buffer(req)
const sig = req.headers['stripe-signature']
if(!sig){
return res.status(400).send("Missing the stripe signature!")
}
let event: Stripe.Event
try{
event = stripe.webhooks.constructEvent(
buf, sig, process.env.STRIPE_WEBHOOK_SECRET!
)
}catch(err){
return res.status(400).send("Webhook error" + err)
}
switch(event.type){
case 'charge.succeeded':
const charge: any = event.data.object as Stripe.Charge;
if(typeof charge.payment_intent === 'string'){
await prisma?.order.update({
where: {paymentIntentId: charge.payment_intent},
data: {status: "complete", address: charge.shipping?.address},
});
}
break;
default:
console.log("Unhandled event type:" + event.type)
}
res.json({received: true})
}
This is my current folder structure.
https://i.stack.imgur.com/BlPwT.png
The following error has been identified:
Unhandled event type:payment_intent.succeeded
⨯ pages\api\stripe-webhook.ts (41:16) @ handler
⨯ ReferenceError: prisma is not defined
at handler (webpack-internal:///(api)/./pages/api/stripe-webhook.ts:38:17)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
page: '/api/stripe-webhook'
}
39 | const charge: any = event.data.object as Stripe.Charge;
40 | if(typeof charge.payment_intent === 'string'){
> 41 | await prisma?.order.update({
| ^
42 | where: {paymentIntentId: charge.payment_intent},
43 | data: {status: "complete", address: charge.shipping?.address},
44 | });
○ Compiling /_error ...
✓ Compiled /_error in 2.7s (736 modules)