#gan_webhooks
1 messages ¡ Page 1 of 1 (latest)
đ Welcome to your new thread!
â˛ď¸ We'll be here soon! Typically we respond in a few minutes, but sometimes we might take a bit longer if the server is busy or if you have a particularly tricky question.
âąď¸ We close idle threads, which makes them read-only. Once a thread is closed it won't be reopened, but you can always 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/1284069296800137216
đ Have more to share? Add more details, code, screenshots, videos, etc. below.
Below are links to other discussions we've had with you in the past week in case you want to review that information. If your question is related to one of these previous discussions, please provide a comprehensive summary of the current state and what you need help with now. We help many users simultaneously, so a summary allows us to resolve your issue as soon as possible.
- gan_webhooks, 20 hours ago, 25 messages
Hi, thanks, I hope you too.
Could you please share the code of your webhook handler?
sure
const paymentUpdation = async (req, res) => {
try {
const sig = req.headers['stripe-signature'];
let event;
const storeId = req.body.data.object.metadata.storeId;
let stripeKey = "";
const store = await Store.findOne({ _id: storeId, isDeleted: 0 });
if (!store) {
return res
.status(400)
.send({ message: "Store not found", success: false });
}
if (
store.generalSettings &&
store.generalSettings.Integrations &&
store.generalSettings.Integrations.enableStripe === true
) {
stripeKey = store.generalSettings.Integrations.stripeSecretKey;
} else {
return res.status(400).send({
message:
"Stripe secret key not found or Stripe integration not enabled for the store",
success: false,
});
}
const stripe = Stripe(stripeKey);
const endpointSecret = store.generalSettings.Integrations.stripeEndPointKey;
try {
// Verify the signature of the event
event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
} catch (err) {
console.error('Webhook signature verification failed.', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log(`PaymentIntent for ${paymentIntent.amount} was successful!`);
// Process successful payment (e.g., update database)
break;
case 'payment_intent.payment_failed':
const failedIntent = event.data.object;
console.log(`PaymentIntent failed: ${failedIntent.last_payment_error?.message}`);
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const { isAuth, isAdmin } = require('../../config/auth');
const { paymentIntent, createCheckoutSession,paymentUpdation,updateStatus }=require("../../controller/online/paymentController");
router.post("/",isAuth,paymentIntent);
router.post("/checkout",isAuth,createCheckoutSession);
router.post('/webhook',express.raw({ type:'application/json' }), paymentUpdation);
router.post("/update",isAuth,updateStatus);
module.exports = router;
req.body.data.object.metadata.storeId;
You are parsing the body in some middleware, right?
yes
as you can see above?
app.use((req, res, next) => {
if (req.originalUrl === '/payment/webhook') {
// Use raw body parser for Stripe webhooks
express.raw({ type: 'application/json' })(req, res, next);
} else {
// Use JSON body parser for all other routes
express.json({ limit: '4mb' })(req, res, next);
}
});
this is the global middleware
Ok, you shouldn't parse the webhook request body and provide it to the constructEvent raw. This way it will be verified against the signature. Then the method will return an parsed object that you can work with.
express.raw({ type: 'application/json' })
i did it
raw the thing
could you modify my code i am bit struggle to understand it
But you still access the properies on this line, so it probably doesn't work: req.body.data.object.metadata.storeId;
It's easiest to put webhook handler on the top, before your middleware kicks in.
the middleware is the global middleware
thats why i give condition for it
What do you mean by "global middleware" exactly?
If you put your webhook handler over this line, it must solve it: app.use((req, res, next) => {
Otherwise, are you able to check if this path is actually taken? if (req.originalUrl === '/payment/webhook') {
any other possible solution?
this is the path for the webhook i am sure about it
Can you check please, with a log or something. Just so we cover all the basic cases.
Try using express.raw({ type: '*/*' }) maybe.
My colleague will take over soon, you can ask them to keep it open for a bit.
hi os4m37
Hey, taking over here. Let me know if there's any follow-up Qs I can answer!
can you see my code and help me with that?
const paymentUpdation = async (req, res) => {
try {
const sig = req.headers['stripe-signature'];
let event;
const storeId = req.body.data.object.metadata.storeId;
let stripeKey = "";
const store = await Store.findOne({ _id: storeId, isDeleted: 0 });
if (!store) {
return res
.status(400)
.send({ message: "Store not found", success: false });
}
if (
store.generalSettings &&
store.generalSettings.Integrations &&
store.generalSettings.Integrations.enableStripe === true
) {
stripeKey = store.generalSettings.Integrations.stripeSecretKey;
} else {
return res.status(400).send({
message:
"Stripe secret key not found or Stripe integration not enabled for the store",
success: false,
});
}
const stripe = Stripe(stripeKey);
const endpointSecret = store.generalSettings.Integrations.stripeEndPointKey;
try {
// Verify the signature of the event
event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
} catch (err) {
console.error('Webhook signature verification failed.', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log(`PaymentIntent for ${paymentIntent.amount} was successful!`);
// Process successful payment (e.g., update database)
break;
case 'payment_intent.payment_failed':
Usually, what I suggest is to pull the official webhook project first:
https://docs.stripe.com/webhooks/quickstart?lang=node
And run it standalone
firt to check that you are able to verify webhook signature
and then include it into your project
Then if you are facing issues, you can refer to our troubleshooting guide fr web signature:
https://docs.stripe.com/webhooks/signature
yes could you check it for us?