#yen6305
1 messages ยท Page 1 of 1 (latest)
Hi ๐
Can you share the webhook handling code where this error is thrown?
Okay there is a lot here. Where is the error being thrown?
Oh whoops forgot to remove comments, one sec please
Code again:
import Stripe from 'stripe';
// import { buffer } from "node:stream/consumers";
import { json } from 'micro';
import { buffer } 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 const config = {
api: {
bodyParser: false,
},
};
export default async function handler(req, res) {
// let event = req.body;
// const rawBody = await buffer(req);
try {
if(!webhookSecret) {
throw new Error('Webhook secret is not configured.');
}
// Read the request body into a buffer
const bodyBuffer = await buffer(req);
// Verify webhook signature
const event = await stripe.webhooks.constructEvent(
bodyBuffer,
req.headers['stripe-signature'],
webhookSecret
);
// Handle the event
switch (event.type) {
case 'charge.succeeded':
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.status(200).send('OK');
} catch(error) {
console.error('Webhook error:', error.message);
res.status(400).send('Webhook Error');
}
Okay so the error message you got seems to say that req.headers['stripe-signature'] is not providing the expected signature value
It is thrown here:
console.error('Webhook error:', error.message);
res.status(400).send('Webhook Error');
}
Can you try assigning that to a variable and logging the value before you call constructEvent
Yes one sec please
Now it looks like this:
try {
if(!webhookSecret) {
throw new Error('Webhook secret is not configured.');
}
// Read the request body into a buffer
const bodyBuffer = await buffer(req);
const signature = req.headers['stripe-signature'];
console.log(signature);
// Verify webhook signature
const event = await stripe.webhooks.constructEvent(
bodyBuffer,
signature,
webhookSecret
);
console.log(signature) logs undefined
Okay so there is the problem.
Saw someone solving it this way:
try { event = stripe.webhooks.constructEvent( rawBody, req.headers.get("stripe-signature") as string, process.env.STRIPE_WEBHOOK_SECRET_KEY as string );
But that is not working for me the req.headers.get
Can you log the req.headers?
Yes, it logs this:
{
'cache-control': '',
'x-forwarded-host': 'localhost:3000',
'x-forwarded-proto': 'http',
'x-forwarded-port': '3000',
'x-forwarded-for': '::1',
cookie: '__stripe_mid=fa59c37d-f86c-492f-abc1-d241faac6bff73ed85; __stripe_sid=ccfbb449-efd3-4f2a-94f4-0171b73f6f5783422a',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
referer: 'http://localhost:3000/checkout',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
origin: 'http://localhost:3000',
accept: '*/*',
'content-type': 'application/json',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"macOS"',
'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
'content-length': '28',
host: 'localhost:3000',
'x-middleware-invoke': '',
'x-invoke-path': '/api/stripe/webhook',
'x-invoke-query': '%7B%7D',
connection: 'close'
}
Yeah you are missing the stripe-signature header which should have a value that looks like this:
t=1691693025,v1=6135bfea8266597f91dc4e9b0a4d5d565596b50aee45811c46c7865121d76c83,v0=f2b65d0f585e4cba694b12792ca0639429dac561549102d3c474620389dfd45c
Ah okay
Do you know why it is missing the stripe-signature header?
I can't find any information about that in the documentation
No I think this is likely Next.js specific
Ah man ๐ฆ
It looks like this came up here: https://github.com/vercel/next.js/issues/49739
Happy to help! ๐
Can i ask another question?
Sure
Now there are no errors anymore, but it is not logging the console.log's in the switch function. So i've tried to log 'test' above the const bodyBuffer and that logs the 'test'. But it doesn''t log the 'test' beneath const bodyBuffer.
export default async function handler(req, res) {
// let event = req.body;
// const rawBody = await buffer(req);
// Read the request body into a buffer
console.log('test')
const bodyBuffer = await buffer(req);
console.log('test')
const signature = req.headers.get("stripe-signature");
let event;
try {
if(!webhookSecret) {
throw new Error('Webhook secret is not configured.');
}
// Verify webhook signature
event = await stripe.webhooks.constructEvent(
bodyBuffer,
signature,
webhookSecret
);
// Handle the event
switch (event.type) {
case 'charge.succeeded':
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.status(200).send('OK');
} catch(error) {
console.error('Webhook error:', error.message);
res.status(400).send('Webhook Error');
}
}
Tried to log event but it is not logging anything
So the first test is logged but not the second?
Yes
Also tried to log signature but its logging nothing
Not even undefined
So every console.log beneath bodyBuffer isnt logging
Okay that's just weird. So it looks like code execution stops at const bodyBuffer = await buffer(req)?
Yeah..
Really weird
All I did was removing this:
// api: {
// bodyParser: false,
// },
// };
And using req.headers.get instead of req.headers['stripe-signature']
Refactored my code after seeing the solution in here: https://github.com/vercel/next.js/issues/49739
Well it's not the req.headers because i changed it back
Happens after removing the config
But if i uncomment the export config it gives me this error again: Webhook error: No stripe-signature header value was provided.
Hmmm..... ๐ค
But there is no issue with the stripe part right?
Maybe i should ask these questions on a Next.js discord server lol
Im sorry
AFAIK the Stripe part is working just fine.