Sibty Shah
Sibty Shah

Reputation: 21

Stripe Webhook issue in Next js 14

When a stripe payment session is completed successfully, the webhook route is supposed to trigger and save the order details in database but the webhook is not working properly, The response from webhook is like -- HTTP status code 307 (Temporary Redirect) Redirecting...

I have already checked the endpoint is correct and also the payment session is completed in stripe dashboard

Image of api end point of stripe dashboard is attached

The route.ts file in /api/webhook:

import { NextResponse } from "next/server";
import Stripe from "stripe";
import prismadb from "@/lib/prismadb";
      
export async function POST(req: Request) {
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!,{
    apiVersion:"2023-10-16"
  });
    
  const body = await req.text();
    
  const stripeSignature = req.headers.get("stripe-signature") as string;
    
  const endPointSecret = process.env.STRIPE_WEBHOOK_SECRET as string;
    
  let stripeEvent;
    
  try {
    stripeEvent = stripe.webhooks.constructEvent(
      body,
      stripeSignature,
      endPointSecret
    );
   } catch (error) {
      return NextResponse.json({ msg: "Webhook error", error });
   }
    
   const eventType = stripeEvent.type;
    
   if (eventType === "checkout.session.completed") {
      const session = stripeEvent.data.object; //!session contains the metadata of the event and the buyer,the price and the stripeId
    
      const metadata = session.metadata; //`At the time of checkout we stored the eventId and the buyerId in the metadata of the session
    
      const orderData = {
          eventId: metadata?.eventId || "",
          buyerId: metadata?.buyerId || "",
          price: (session.amount_total! / 100).toString(),
          stripeId: session.id,
      };
    
      try {
          const newOrder = await prismadb.order.create({
            data: {
              buyerId: orderData.buyerId,
              eventId: orderData.eventId,
              totalAmount: orderData.price,
              stripeId: orderData.stripeId,
            },
          });
          console.log(newOrder)
          return NextResponse.json({ status: 200, newOrder });
      } catch (error) {
          console.log("Error createOrderDB", error);
          return NextResponse.json({ status: 500, error: "Internal Server Error" });
      }
 
      }

      return new Response("", { status: 200 });
    }

I tried changing the endpoint and correcting it , it was correct already I tried running on local network but the response from webhook was same

Upvotes: 2

Views: 973

Answers (3)

Badr B
Badr B

Reputation: 1413

I was facing a similar issue with a 308 permanent redirect. This is because I was hosting on Vercel, which uses a 308 redirect to route traffic from domain.com to www.domain.com. My Stripe webhook was pointing at domain.com, which meant that Vercel responded with a 308. After changing the Stripe webhook's endpoint to www.domain.com, event deliveries started succeeding.

Upvotes: 0

Juan Castro
Juan Castro

Reputation: 1

It would be the middleware config, in your code check the matcher prop and verify the path, in my case I had problems with the '/api/:path*', I had this line of code:

matcher: ["/user/:path*", '/api/:path*'],

then I remove the api path and got 200 response.

matcher: ["/user/:path*"],

Check also that your webhook listener is active and listening on your stripe dashboard.

Upvotes: 0

Sibty Shah
Sibty Shah

Reputation: 21

The redirecting issue was not related to stripe but clerk auth, I overlooked the route settings in clerk middleware - When I changed the folder for stripe webhook route.ts, I forgot to change the API route in the middleware file for ignored Routes, ignoredRoutes: ["/api/edgestore/init","/api/webhook","/api/webhooks"], After adding the route my problem was fixed and I received the status 200 instead of Redirecting.. in the webhook response.

Upvotes: 0

Related Questions