#devparry_webhooks

1 messages ยท Page 1 of 1 (latest)

crimson loomBOT
#

๐Ÿ‘‹ 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.

frail osprey
#

Can you share you full webhook handler code please?

lost dawn
#

sure

frail osprey
#

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

lost dawn
#

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 }");
}); `

Listen to events in your Stripe account on your webhook endpoint so your integration can automatically trigger reactions.

#

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 });
};`

lost dawn
frail osprey
#

Checking the code

#

To confirm, you're using the CLI to forward events to a local listener yes?

lost dawn
#

yes

frail osprey
#

Where are you getting the value for your process.env.STRIPE_WEBHOOK_SECRET var from?

lost dawn
frail osprey
#

Perfect, thanks

frail osprey
#

I suspect it's this JSON middleware that will be on that route:

#

Can you remove that and try?

lost dawn
#

okay let me try

#

Its working now

#

but after removing
app.use(express.json());

now my other API not working... ๐Ÿ˜ฆ

lost dawn
frail osprey
#

Great! You need to move that middleware into the other routes directly:

app.use('/auth', express.json(), authRoutes);

Should work

lost dawn
#

you mean in all individual api i have to set it?

frail osprey
#

You will need to set it on a per route basis I think yes

lost dawn
#

checking,,,

frail osprey
lost dawn
#

due to which webhook signature return me error

frail osprey
#

I'm not sure I understand the question

lost dawn
#

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

frail osprey
#

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

lost dawn
#

Thanks man