Patrik Rikama-Hinnenberg
Patrik Rikama-Hinnenberg

Reputation: 1600

Stripe webhooks don't fire locally NEXT JS

Having trouble getting the local testing of Stripe Webhooks working. Here is a Next JS routehandler api endpoint that should listen to Stripe webhooks. I have confirmed that the endpoint is running by curling it via the terminal and can get a log in the terminal. If I do ex 'Webhook signature verification failed.' as logged. If I do stripe listen --forward-to http://localhost:3000/api/webhooks it starts to listen to my local endpoint but then for example stripe trigger customer.subscription.created or other triggered events do not give any console logging at all nor event log in the Stripe dashboard.

app/api/webhooks/route.ts
stripe version 1.17.1
next: "13.4.4"

import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@utils/stripe';
import Stripe from 'stripe';

export async function POST(request: NextRequest) {
  try {
    console.log('Endpoint hit');
    const rawBody = await request.text();
    console.log('RAW BODY:', rawBody);
    const sig = request.headers.get('stripe-signature') || '';
    console.log('SIGNATURE', sig);

    let event: Stripe.Event;
    try {
      event = stripe.webhooks.constructEvent(
        rawBody,
        sig,
        'whsec_5e..'
      );
    } catch (err) {
      console.log(
        `Webhook signature verification failed.`
      );
      return NextResponse.json({ received: false }, { status: 400 });
    }

    switch (event.type) {
      case 'customer.subscription.created':
        console.log('case sub created');
        break;
      case 'payment_intent.succeeded':
        console.log('PAYMENT INTENT EVENT');
        break;

      default:
        // Unexpected event type
        console.warn(`Unhandled event type: ${event.type}`);
        break;
    }

    // Return a 200 response to acknowledge receipt of the event
    return NextResponse.json({ received: true }, { status: 200 });
  } catch (e) {
    console.log('Error in POST function:', e);
    return NextResponse.json({ received: false }, { status: 500 });
  }
}

Upvotes: 1

Views: 820

Answers (1)

Patrik Rikama-Hinnenberg
Patrik Rikama-Hinnenberg

Reputation: 1600

opened one more terminal and triggered the stripe trigger customer.subscription.created from there

Upvotes: 0

Related Questions