#yen6305
1 messages · Page 1 of 1 (latest)
My code:
import Stripe from 'stripe';
// import { buffer } from "node:stream/consumers";
import { json } from 'micro';
// const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
export default async function handler(req, res) {
// let event = req.body;
// const rawBody = await buffer(req);
let event = req.body;
if(webhookSecret) {
// Get signature send by Stripe
// const signature = req.headers.get('stripe-signature');
const signature = req.headers['stripe-signature'];
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
webhookSecret
);
} catch (err) {
console.log(`Webhook signature verification failed.`, err.message);
}
}
// Handle the event
switch (event.type) {
case 'charge.succeed':
const charge = event.data.object;
console.log(`Charge succeeded for ${charge.amount}`);
break;
// Add more cases to handle other event types as needed
default:
// Unexpected event type
console.log(`Unhandled event type ${event.type}.`);
}
// Return a 200 response to acknowledge receipt of the event
res.send();
}
So the two causes of this error are:
- The webhook secret being unset or set incorrectly
- Your framework changing the raw request body before it gets to your call to the constructEvent method
So to knock out #1, can you double check that your webhookSecret is being properly set to the specific secret for the endpoint that you are sending these event to?
When logging the webhook secret I get to see this: whsec_rC0tLa.....
So I believe that's correct, because that's the secret I've stored in my .env file
Got the secret from: https://dashboard.stripe.com/test/webhooks
Sign in to the Stripe Dashboard to manage business payments and operations in your account. Manage payments and refunds, respond to disputes and more.
Sounds like it is properly set. So it sounds like your framework may be changing the request body before you get it in your handler function. This is often useful but in this specific context even changing the whitespace in the response body will throw off our signature calculations
Looking around I found this article about turning off your body parser and it specifically mentions Stirpe https://www.codedaily.io/tutorials/Stripe-Webhook-Verification-with-NextJS