Webhook Error: Webhook payload must be provided as a string or a Buffer

I’m stuck on this, could someone help me?
I put it in postman: https://my-server/api/webhook

and i receive this:

Webhook Error: 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.

Learn more about webhook signing and explore webhook integration
examples for various frameworks at
https://github.com/stripe/stripe-node#webhook-signing

i’m using ReactJS and Node

index.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const express = require('express');
const Stripe = require('stripe');
const bodyParser = require('body-parser');
const cors = require('cors');
const webhookRoutes = require('./routes/webhook');
const app = express();
const stripe = Stripe(
'sk_test',
);
app.use(cors());
app.use(express.json());
app.use('/webhook', express.raw({ type: 'application/json' }));
app.use('/api', webhookRoutes);
app.post('/create-checkout-session', async (req, res) => {
try {
console.log('Received request to create checkout session');
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'Nome do Produto',
},
unit_amount: 2000,
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'http://localhost:5173/success',
cancel_url: 'http://localhost:5173/cancel',
});
console.log('Checkout session created successfully:', session);
res.json({ id: session.id });
} catch (error) {
console.error('Error creating checkout session:', error.message);
res.status(500).json({
error: 'Failed to create checkout session',
});
}
});
const PORT = process.env.PORT || 4242;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
</code>
<code>const express = require('express'); const Stripe = require('stripe'); const bodyParser = require('body-parser'); const cors = require('cors'); const webhookRoutes = require('./routes/webhook'); const app = express(); const stripe = Stripe( 'sk_test', ); app.use(cors()); app.use(express.json()); app.use('/webhook', express.raw({ type: 'application/json' })); app.use('/api', webhookRoutes); app.post('/create-checkout-session', async (req, res) => { try { console.log('Received request to create checkout session'); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [ { price_data: { currency: 'usd', product_data: { name: 'Nome do Produto', }, unit_amount: 2000, }, quantity: 1, }, ], mode: 'payment', success_url: 'http://localhost:5173/success', cancel_url: 'http://localhost:5173/cancel', }); console.log('Checkout session created successfully:', session); res.json({ id: session.id }); } catch (error) { console.error('Error creating checkout session:', error.message); res.status(500).json({ error: 'Failed to create checkout session', }); } }); const PORT = process.env.PORT || 4242; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); </code>
const express = require('express');
const Stripe = require('stripe');
const bodyParser = require('body-parser');
const cors = require('cors');
const webhookRoutes = require('./routes/webhook');

const app = express();
const stripe = Stripe(
  'sk_test',
);

app.use(cors());
app.use(express.json());
app.use('/webhook', express.raw({ type: 'application/json' }));
app.use('/api', webhookRoutes);

app.post('/create-checkout-session', async (req, res) => {
  try {
    console.log('Received request to create checkout session');

    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      line_items: [
        {
          price_data: {
            currency: 'usd',
            product_data: {
              name: 'Nome do Produto',
            },
            unit_amount: 2000,
          },
          quantity: 1,
        },
      ],
      mode: 'payment',
      success_url: 'http://localhost:5173/success',
      cancel_url: 'http://localhost:5173/cancel',
    });

    console.log('Checkout session created successfully:', session);
    res.json({ id: session.id });
  } catch (error) {
    console.error('Error creating checkout session:', error.message);
    res.status(500).json({
      error: 'Failed to create checkout session',
    });
  }
});

const PORT = process.env.PORT || 4242;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

webhook.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const express = require('express');
const Stripe = require('stripe');
const router = express.Router();
const stripe = Stripe('sk_test');
router.post('/webhook', async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, 'whsec_');
} catch (err) {
console.log(`Webhook Error: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
console.log('Pagamento confirmado:', session);
}
res.json({ received: true });
});
module.exports = router;
</code>
<code>const express = require('express'); const Stripe = require('stripe'); const router = express.Router(); const stripe = Stripe('sk_test'); router.post('/webhook', async (req, res) => { const sig = req.headers['stripe-signature']; let event; try { event = stripe.webhooks.constructEvent(req.body, sig, 'whsec_'); } catch (err) { console.log(`Webhook Error: ${err.message}`); return res.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'checkout.session.completed') { const session = event.data.object; console.log('Pagamento confirmado:', session); } res.json({ received: true }); }); module.exports = router; </code>
const express = require('express');
const Stripe = require('stripe');
const router = express.Router();
const stripe = Stripe('sk_test');

router.post('/webhook', async (req, res) => {
  const sig = req.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, 'whsec_');
  } catch (err) {
    console.log(`Webhook Error: ${err.message}`);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;

    console.log('Pagamento confirmado:', session);
  }

  res.json({ received: true });
});

module.exports = router;

New contributor

LE7- Paulin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

5

It’s because of app.use(express.json()); code.

So the simplest solution would be moving the webhook route before app.use(express.json());

Or You can try this.

index.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>app.use(
express.json({
verify(req, res, buf, encoding) {
if (req.path.includes('webhook')){
req.rawBody = buf.toString(); // sets raw string in req.rawBody variable
}
}
})
);
</code>
<code>app.use( express.json({ verify(req, res, buf, encoding) { if (req.path.includes('webhook')){ req.rawBody = buf.toString(); // sets raw string in req.rawBody variable } } }) ); </code>
app.use(
    express.json({
        verify(req, res, buf, encoding) {
            if (req.path.includes('webhook')){
                req.rawBody = buf.toString(); // sets raw string in req.rawBody variable
            }
        }
    })
);

webhook handler

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const express = require('express');
const Stripe = require('stripe');
const router = express.Router();
const stripe = Stripe('sk_test');
router.post('/webhook', async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
// HERE YOU CAN USE req.rawBody
event = stripe.webhooks.constructEvent(req.rawBody, sig, 'whsec_');
} catch (err) {
console.log(`Webhook Error: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
console.log('Pagamento confirmado:', session);
}
res.json({ received: true });
});
module.exports = router;
</code>
<code>const express = require('express'); const Stripe = require('stripe'); const router = express.Router(); const stripe = Stripe('sk_test'); router.post('/webhook', async (req, res) => { const sig = req.headers['stripe-signature']; let event; try { // HERE YOU CAN USE req.rawBody event = stripe.webhooks.constructEvent(req.rawBody, sig, 'whsec_'); } catch (err) { console.log(`Webhook Error: ${err.message}`); return res.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'checkout.session.completed') { const session = event.data.object; console.log('Pagamento confirmado:', session); } res.json({ received: true }); }); module.exports = router; </code>
const express = require('express');
const Stripe = require('stripe');
const router = express.Router();
const stripe = Stripe('sk_test');

router.post('/webhook', async (req, res) => {
  const sig = req.headers['stripe-signature'];

  let event;

  try {
    // HERE YOU CAN USE req.rawBody
    event = stripe.webhooks.constructEvent(req.rawBody, sig, 'whsec_');
  } catch (err) {
    console.log(`Webhook Error: ${err.message}`);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;

    console.log('Pagamento confirmado:', session);
  }

  res.json({ received: true });
});

module.exports = router;

Finally you don’t need express.raw({ type: 'application/json' }), since we are doing that

router

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>app.use(cors());
app.use(express.json());
app.use('/webhook', webhookRoutes);
</code>
<code>app.use(cors()); app.use(express.json()); app.use('/webhook', webhookRoutes); </code>
app.use(cors());
app.use(express.json());
app.use('/webhook', webhookRoutes);

Note: I’ve modified the api path for webhook

8

The problem is…

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>app.use(express.json());
</code>
<code>app.use(express.json()); </code>
app.use(express.json());

This parses all application/json request bodies into a JavaScript data structure (using JSON.parse()) whereas Stripe wants you to forward the raw request body.

You should simply register your webhook route handler before express.json(). You’ll also need the raw() middleware set for those webhook routes as well.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>app.use(cors());
// 1st - register your webhook routes
app.use('/api', express.raw({ type: 'application/json' }), webhookRoutes);
// 2nd - then register other routes and middleware
app.use(express.json());
app.post('/create-checkout-session', async (req, res) => {
// ...
});
</code>
<code>app.use(cors()); // 1st - register your webhook routes app.use('/api', express.raw({ type: 'application/json' }), webhookRoutes); // 2nd - then register other routes and middleware app.use(express.json()); app.post('/create-checkout-session', async (req, res) => { // ... }); </code>
app.use(cors());

// 1st - register your webhook routes
app.use('/api', express.raw({ type: 'application/json' }), webhookRoutes);

// 2nd - then register other routes and middleware
app.use(express.json());
app.post('/create-checkout-session', async (req, res) => {
  // ...
});

See also https://docs.stripe.com/identity/handle-verification-outcomes#create-webhook

13

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật