I am trying to setup of a webhook using Stripe and NextJS 14.0.3

297 Views Asked by At

This is my stripe webhook (I am using Next.js 14 and trying to implement payment using stripe)

this file is stripe-webhook and I double check the file path don't know the error

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})
}

But I got this error! the file path is ok

> Ready! You are using Stripe API Version [2023-10-16]. Your webhook signing secret is whsec_ae0f6c1ba90b1c434264f36f618f9238a3ecb8e6b8de8a5f6ff278d99f30d0cd (^C to quit)
2023-12-04 18:06:24   --> payment_intent.created [evt_3OJbNsGRtGZJ0dW50BaY3sq1]
2023-12-04 18:06:25  <--  [404] POST http://localhost:3000/pages/api/stripe-webhook [evt_3OJbNsGRtGZJ0dW50BaY3sq1]
2023-12-04 18:06:26   --> payment_intent.created [evt_3OJbNtGRtGZJ0dW50ZnH99Dz]
2023-12-04 18:06:26  <--  [404] POST http://localhost:3000/pages/api/stripe-webhook [evt_3OJbNtGRtGZJ0dW50ZnH99Dz]

please help me to fix this error!

0

There are 0 best solutions below