Issues with Stripe webhook and raw request body

I’m implementing Stripe webhook integration on my Node/Express.ts backend running on Firebase Cloud Functions, and I’m struggling to pass the raw req.body during signature verification.

I’ve made a dozen attempts and fixes, and the error I keep encountering is: “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.

Here is my index.ts:

const app = express();

app.use(cors());
app.use(allowedOriginsHandler);

app.post("/api/v1/stripe/webhook/payment", express.raw({ type: '*/*' }), listenToPaymentEvents);

app.use(express.json());

app.use("/api/v1", routes);

app.use(errorLogger);
app.use(errorResponder);
app.use(failSafeHandler);

export const httpFunction = functions.https.onRequest(app);
//admin.initializeApp();

//MARKETPLACE CLOUD FUNCTIONS
//orders
export const onOrderDocumentCreateFunction = onOrderDocumentCreate;
export const onOrderStatusChangeFunction = onOrderStatusChange;

//check order products availability
export const onOrderByVendorCreateFunction = onCreateOrderByVendor;

//products (create/update subcollections)
export const onProductDocumentCreateFunction = onCreateProduct;
export const onProductDocumentUpdateFunction = onUpdateProduct;

//Update seller public info collection on seller create/update
export const onSellerCreateFunction = onCreateSeller;
export const onSellerUpdateFunction = onUpdateSeller;

export const onUserRegistrationFunction = onUserRegistration;

// Create seller products bulk upload template on seller create
// and update seller document with the template url info
export const createSellerBulkUploadTemplateFunction =
  createSellerBulkUploadTemplate;

Here is the configuration for the other routes:

const router = Router();


router.route("/newsletter").post(addContactToNewsletter);

router.route("/checkout").post(
  firebaseAuthenticationHandler,
  checkProductsAvailabilityHandler,
  checkProductsPriceChangesHandler,
  lockProductsHandler,
  checkout
);

router.route("/order/vendor/cancel/:id").put(
  firebaseAuthenticationHandler,
  orderCancelledByVendor
);

router.route("/order/buyer/cancel").post(orderCancelledByBuyer);

router.route("/order/vendor/processing/:id").put(
  firebaseAuthenticationHandler,
  updateOrderToProcessing
);

export default router;

And this is the controller handling the webhook:

dotenv.config();
const stripePaymentIntentWebhookEndpointSecret =
  process.env.STRIPE_PAYMENT_INTENT_WEBHOOK_ENDPOINT_SECRET ?? "";

export const listenToPaymentEvents: RequestHandler = async (req, res) => {
  const sig = req.headers["stripe-signature"];

  if (!sig) {
    console.log("Missing Stripe signature");
    res.status(400).send("Missing Stripe signature");
    return;
  }

  let event;

  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      stripePaymentIntentWebhookEndpointSecret
    );

    switch (event.type) {
      case "payment_intent.payment_failed": {
        const paymentIntentPaymentFailed = event.data.object;
        console.log(paymentIntentPaymentFailed);
        break;
      }
      case "payment_intent.succeeded": {
        const paymentIntentSucceeded = event.data.object;
        await handlePaymentIntentSuccess(paymentIntentSucceeded);
        break;
      }
      default: {
        console.log(`Unhandled event type ${event.type}`);
      }
    }

    res.status(200).send("Event received");
  } catch (error) {
    if (error instanceof Error) {
      res.status(500).send(`Webhook Error: ${error.message}`);
    } else {
      res.status(500).send("Webhook Error: An unexpected error occurred");
    }
  }
};

What am I doing wrong?

2

Edit: I tried refactoring so that the express.json middleware has no chance of interfering with my webhook endpoint, but I get the same error.

New configuration of index.ts:

const app = express();

app.use(cors());
app.use(allowedOriginsHandler);

app.use("/stripe", stripeRoutes);
app.use("/api/v1", routes);

export const httpFunction = functions.https.onRequest(app);

Newly created route for isolate webhook logic:

const stripeRouter = Router();

stripeRouter
  .route("/webhook/payment")
  .post(express.raw({ type: "application/json" }), listenToPaymentEvents);

export default stripeRouter;

Other routes configuration:

const router = Router();

router.route("/newsletter").post(express.json(), addContactToNewsletter);

router
  .route("/checkout")
  .post(
    express.json(),
    firebaseAuthenticationHandler,
    checkProductsAvailabilityHandler,
    checkProductsPriceChangesHandler,
    lockProductsHandler,
    checkout
  );

router
  .route("/order/vendor/cancel/:id")
  .put(express.json(), firebaseAuthenticationHandler, orderCancelledByVendor);

router.route("/order/buyer/cancel").post(express.json(), orderCancelledByBuyer);

router
  .route("/order/vendor/processing/:id")
  .put(express.json(), firebaseAuthenticationHandler, updateOrderToProcessing);

router.use(errorLogger);
router.use(errorResponder);
router.use(failSafeHandler);

export default router;

1

Looking at these docs, if you’re not defining an endpointSecret then you should skip constructEvent(). In your case you’re not checking if the stripePaymentIntentWebhookEndpointSecret is actually set so I would try that.

  const stripePaymentIntentWebhookEndpointSecret =
       process.env.STRIPE_PAYMENT_INTENT_WEBHOOK_ENDPOINT_SECRET ?? null;
  let event = request.body;
 // Only verify the event if you have an endpoint secret defined.
 // Otherwise use the basic event deserialized with JSON.parse
 if (stripePaymentIntentWebhookEndpointSecret) {
   // Get the signature sent by Stripe
   const signature = request.headers['stripe-signature'];
   try {
     event = stripe.webhooks.constructEvent(
       request.body,
       signature,
       stripePaymentIntentWebhookEndpointSecret
     );
   } catch (err) {
     console.log(`⚠️  Webhook signature verification failed.`, err.message);
     return response.sendStatus(400);
   }
 }

// Handle the event
switch (event.type) {
   case 'payment_intent.succeeded':
     const paymentIntent = event.data.object;
     console.log(`PaymentIntent for ${paymentIntent.amount} was successful!`);
     // Then define and call a method to handle the successful payment intent.
     // handlePaymentIntentSucceeded(paymentIntent);
     break;
  // ....
}

OLD ANSWER

My guess is the app.use(express.json()); middleware is causing the issue since the error message mentions the content is JSON and not a raw string. I would remove that line and see if you get the same error message.

If that does fix it you’ll probably want to refactor your code to move the stripe implementation from app.post(...) to app.use('/api/v1/stripe/webhook/payment', stripeRoutes); since, if the middleware works as I believe it would, the order they are registered is the order they are called so you can add the json middleware back after the stripe one.

Looking at your code again and the docs I think you have to look for the

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