#devparry_webhooks
1 messages ยท Page 1 of 1 (latest)
๐ Welcome to your new thread!
โฒ๏ธ We'll be here soon! We typically respond in a few minutes, but in some cases we might need a bit more time (e.g., server's busy, you've got a complex question, etc.).
โฑ๏ธ We close idle threads, which makes them read-only. Once a thread is closed it won't be reopened, but you can start a new thread if you have another question.
๐ This thread will always be available, even after it's closed. You can find it again using Discord's search, or you can save this link: https://discord.com/channels/841573134531821608/1251132830499606650
๐ Have more to share? Add details, code, screenshots, videos, etc. below.
Can you share you full webhook handler code please?
sure
Generally in Node this is an issue with Express malforming the request payload โ you need to pass the raw request body to the constructEvent function
I am using Express in the node server. and I have follow documentation: https://docs.stripe.com/webhooks#verify-webhook-signatures-with-official-libraries
my src/server.js
`const express = require("express");
const cors = require('cors');
const app = express();
const path = require("path");
const PORT = process.env.PORT || 8080;
const authRoutes = require('./routes/authRoutes');
const stripeWebhookRoutes = require('./routes/stripeWebhookRoutes');
// const { rateLimiter } = require('./utils/RateLimitMiddleware');
app.use(cors());
app.use(express.json());
app.set('view engine', 'ejs')
app.set("views", path.join(__dirname, "views"));
app.use('/auth', authRoutes);
app.use('/stripe', stripeWebhookRoutes);
app.listen(PORT, () => {
console.log("Server is running on port ${PORT} : API Base URL : ${ process.env.API_BASE_URL }");
}); `
here is my code for the router File :
//routes/stripeWebhookRoutes.js
`const express = require("express");
const { handleWebhook } = require('../controller/stripeWebhookController');
const router = express.Router();
router.post('/webhook', express.raw({ type: 'application/json' }), handleWebhook);
module.exports = router;`
+++++++++++++++++++++++++++++++++++
my Controller file :
++++++++++++++++++++++++++++++++++++++
// controller/stripeWebhookController.js
`const Stripe = require('stripe');
const stripe = Stripe(process.env.STRIPE_SECRET_KEY);
const handleWebhook = async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
// const payloadString = JSON.stringify(req.body);
// console.log('Webhook received body : ', payloadString);
// console.log('STRIPE_WEBHOOK_SECRET :',process.env.STRIPE_WEBHOOK_SECRET);
event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET);
} catch (err) {
console.log("โ ๏ธ Webhook signature verification failed:", err.message);
return res.status(400).json({ success : false, message:'Something went wrong, Try later.' });
}
// Handle the event
switch (event.type) {
case 'checkout.session.completed':
const session = event.data.object;
console.log("๐ Payment Checkout session was successful!", session);
break;
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log("PaymentIntent was successful!");
break;
case 'payment_method.attached':
const paymentMethod = event.data.object;
console.log("PaymentMethod was attached to a Customer!");
break;
// ... handle other event types
default:
console.log(`Unhandled event type ${event.type}`);
}
// Return a response to acknowledge receipt of the event
res.json({ received: true });
};`
I have passed it under route file
/routes/stripeWebhookRoutes.js
Checking the code
To confirm, you're using the CLI to forward events to a local listener yes?
yes
Where are you getting the value for your process.env.STRIPE_WEBHOOK_SECRET var from?
Perfect, thanks
from .env file
I suspect it's this JSON middleware that will be on that route:
Can you remove that and try?
okay let me try
Its working now
but after removing
app.use(express.json());
now my other API not working... ๐ฆ
Great! You need to move that middleware into the other routes directly:
app.use('/auth', express.json(), authRoutes);
Should work
you mean in all individual api i have to set it?
You will need to set it on a per route basis I think yes
checking,,,
Using app.use(express.json(() without a route will apply globally: https://expressjs.com/en/guide/using-middleware.html#middleware.application
due to which webhook signature return me error
I'm not sure I understand the question
I am just saying that we used
app.use(express.json());
due to which it apply on all routes automatically along with webhook one due to which signature not confrimed
Yes, that middleware was malforming the request payload of the event and causing the error. You need to not use that express.json() middleware on your /webhook route. Currently you have it configured as a global middleware so it applied to all routes
You're going to need to use it on a per route basis, and exclude it from the /webhook route
Thanks man