#gan_webhooks

1 messages ¡ Page 1 of 1 (latest)

plush jettyBOT
#

👋 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.

jolly sundial
#

hi vanya

#

hope you having a good day

south arrow
#

Hi, thanks, I hope you too.

#

Could you please share the code of your webhook handler?

jolly sundial
#

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;

south arrow
#

req.body.data.object.metadata.storeId;
You are parsing the body in some middleware, right?

jolly sundial
#

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

south arrow
#

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.

jolly sundial
#

express.raw({ type: 'application/json' })
i did it

#

raw the thing

#

could you modify my code i am bit struggle to understand it

south arrow
#

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.

jolly sundial
#

thats why i give condition for it

south arrow
#

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') {

jolly sundial
#

any other possible solution?

jolly sundial
south arrow
jolly sundial
#

sure

#

how long does this thread open?

south arrow
#

Try using express.raw({ type: '*/*' }) maybe.

south arrow
plush jettyBOT
jolly sundial
#

hi os4m37

vocal pier
#

Hey, taking over here. Let me know if there's any follow-up Qs I can answer!

jolly sundial
#

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':
vocal pier
#

firt to check that you are able to verify webhook signature

#

and then include it into your project

jolly sundial