#ayushh_webhooks

1 messages · Page 1 of 1 (latest)

civic pollenBOT
#

👋 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/1328273263012614146

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

steady gorge
#

Hi there, this is a payment_intent.created event, can you tell how you want to handle it?

prime wigeon
prime wigeon
#

[Stripe] Successfully created checkout session in 929ms: {
sessionId: 'cs_<id>',
priceId: 'price_id,
userId: 5,
successUrl: 'http://localhost:5000/dashboard?checkout=success&session_id={CHECKOUT_SESSION_ID}',
cancelUrl: 'http://localhost:5000/pricing?checkout=canceled'
}
[Stripe] Checkout session created successfully: {
sessionId: 'cs_test_cs_id',
userId: 5,
url: '<url>',
expiresAt: '2025-01-14T08:00:54.000Z'
}
1:30:55 PM [express] POST /api/create-checkout-session 200 in 1173ms :: {"sessionId":"cs_test_a1K3R1…
[Auth] Deserializing user ID: 5
[Auth] User deserialized successfully: s.aayush3161@gmail.com
[Stripe] Config request received
[Stripe] Providing config to client
1:30:55 PM [express] GET /api/stripe-config 304 in 236ms :: {"publishableKey":"pk_test_51QbIflCAkUDx…
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Stripe] Processing webhook request with raw parser
[Auth] Deserializing user ID: 5

#

thats' all I am getting on my terminal

steady gorge
#

Do you see any errors?

prime wigeon
#

I don't see any errors

#

I used stripe listen --forwarded-to webhook cli

#

I received the webhook succeded status

#

but no update on the console

steady gorge
#

I saw an ERROR in the screenshot.

prime wigeon
steady gorge
#

It looks like your server has a timeout error.

prime wigeon
#

what should I do now?

steady gorge
#

https://support.stripe.com/questions/webhooks-how-to-investigate-and-fix-timed-out can I suggest you to follow this guide and work with your backend engineer to fix the timeout problem?

prime wigeon
#

I am the backend engineer

#

but never had the same error before

#

lemme try to return 200 status

#

I am still getting the same error

slow moth
#

Do you have CSRF protection enabled? make sure it's not blocking the request

prime wigeon
#

I don't think I have CSRF enabled

#

yea, i don't have csrf

slow moth
#

ah okay

prime wigeon
#

any other info I can provide?

#
app.use((req, res, next) => {
    const isStripeWebhook = req.originalUrl === "/api/webhook/stripe";
    if (isStripeWebhook) {
      console.log("[Stripe] Processing webhook request with raw parser");
      let rawBody = "";
      req.setEncoding("utf8");

      req.on("data", (chunk) => {
        console.log("[Stripe] Received webhook data chunk");
        if (rawBody.length + chunk.length <= 65536) {
          // Limit body size to 64KB
          rawBody += chunk;
        } else {
          console.error("[Stripe] Webhook payload too large");
          res.status(413).json({ error: "Payload too large" });
          return;
        }
      });

      req.on("end", () => {
        try {
          console.log("\n\n\n\nRaw body:", rawBody);
          console.log("[Stripe] Finished reading webhook data");
          (req as any).rawBody = Buffer.from(rawBody);
          next();
        } catch (error) {
          console.error("[Stripe] Error processing webhook raw body:", error);
          res.status(400).json({ error: "Invalid request body" });
        }
      });

      req.on("error", (error) => {
        console.error("[Stripe] Error reading webhook request:", error);
        res.status(400).json({ error: "Error reading request" });
      });
    } else {
      next();
    }
  });

``` I doubt this code tbh
steady gorge
#

I can only help with technical inquires directly related to Stripe integraiton, and I'm afraid that I can't help with general technical problems like timeout.

prime wigeon
#

Oh

#

is there any thing else you want me to try

#

?

steady gorge
prime wigeon
#

ok

#

I m unsure

#

how can I get help from stripe?

steady gorge
#

Did you get a chance to try the suggestions outlined in the doc?

prime wigeon
#

I tried

#

I tried to return status 200 on every response

#

I am trying this code

#

now

#

hey

#

  app.post(
    '/api/webhook/stripe',
    // Stripe requires the raw body to construct the event
    express.raw({ type: 'application/json' }),
    (req: express.Request, res: express.Response): void => {
      const sig: any = req.headers['stripe-signature'];
      const webhookSecret = "webhsec";
      let event: Stripe.Event;

      try {
        event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
      } catch (err: any) {
        // On error, log and return the error message
        console.log(`❌ Error message: ${err.message}`);
        res.status(400).send(`Webhook Error: ${err.message}`);
        return;
      }

      // Successfully constructed event
      console.log('✅ Success:', event.id);

      // Cast event data to Stripe object
      if (event.type === 'payment_intent.succeeded') {
        const stripeObject: Stripe.PaymentIntent = event.data
          .object as Stripe.PaymentIntent;
        console.log(`💰 PaymentIntent status: ${stripeObject.status}`);
      } else if (event.type === 'charge.succeeded') {
        const charge = event.data.object as Stripe.Charge;
        console.log(`💵 Charge id: ${charge.id}`);
      } else {
        console.warn(`🤷‍♀️ Unhandled event type: ${event.type}`);
      }

      // Return a response to acknowledge receipt of the event
      res.json({ received: true });
    }
  );
#

I am trying this code and

#

2:12:08 PM [express] POST /api/webhook/stripe 400 in 3ms
❌ Error message: Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the raw request body.Payload was provided as a parsed JavaScript object instead.
Signature verification is impossible without access to the original signed material.

steady gorge
#

Looks like you have a middleware that pre-processes the event

#

Can you disable the middleware and try again?

prime wigeon
#

app.use(express.urlencoded({ extended: false }));

#

I only had this

#

I removed this as well but still no luck haha

steady gorge
#

Do you use bodyParser ?

prime wigeon
#

I removed all middlewares

#

// Use JSON parser for all non-webhook routes
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
if (req.originalUrl === '/api/webhook/stripe') {
next();
} else {
express.json()(req, res, next);
}
}
);

#

I am trying this one

#

still no luck

civic pollenBOT
steady gorge
prime wigeon
#

// Use JSON parser for all non-webhook routes
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
if (req.originalUrl === '/api/webhook/stripe') {
next();
} else {
express.json()(req, res, next);
}
}
);

#

this is what it does

frank notch
#

hi! I'm taking over this thread.

prime wigeon
#

Hey soma

#

still doesn't work

#

not sure what's missing

frank notch
prime wigeon
#

I m not even using bodyParser

frank notch
#

got it. then I'm not sure. I recommend directly asking Stripe support. make sure to include your code and the exact error message you see!
https://support.stripe.com/contact

prime wigeon
#

hey

#

I believe solved

frank notch
#

that's great to hear! what did you change?

prime wigeon
#

actually the code was built by replit ai and there were lot of files

#

and I didn't knew that it was using express.json() middleware

#

I meant, in the routes file I changed to
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
if (req.originalUrl === '/api/webhook/stripe') {
next();
} else {
express.json()(req, res, next);
}
}
);

#

but in the index.ts I came to know there is express.json() middleware being used

#

I replaced

#

and it worked