node.jsexpressstripe-paymentsbody-parserstripes

Webhook payload must be provided as a string or a Buffer instance representing the _raw_ request body


const express = require("express");
const app = express();

app.set("port", process.env.PORT);

app.post(
  "/webhook",
  express.raw({ type: "application/json" }),
  (request, response) => {
    const sig = request.headers["stripe-signature"];

    // console.log('endpointSecret', process.env.END_POINT_SECRET)
    // console.log('sig', sig)
    console.log("request.body", request.body);

    let event;

    try {
      event = stripe.webhooks.constructEvent(
        request.body,
        sig,
        process.env.END_POINT_SECRET
      );
    } catch (err) {
      console.log(`Webhook Error: ${err.message}`);
      return response.status(400).send(`Webhook Error: ${err.message}`);
    }

    // Handle the event
    let resData = "";

    switch (event.type) {
      case "payment_intent.succeeded":
        const paymentIntent = event.data.object;
        resData = `PaymentIntent for ${paymentIntent.amount} was successful!`;

        break;
      case "payment_method.attached":
        resData = event.data.object;
        // Then define and call a method to handle the successful attachment of a PaymentMethod.
        // handlePaymentMethodAttached(paymentMethod);
        break;

      case "customer.created":
        resData = event.data.object;
        break;
      case "customer.deleted":
        resData = event.data.object;
        break;
      case "customer.updated":
        resData = event.data.object;
        break;
      case "customer.subscription.created":
        resData = event.data.object;
        break;
      case "customer.subscription.trial_will_end":
        resData = event.data.object;
        break;
      case "payment_intent.succeeded":
        resData = event.data.object;
        break;
      case "customer.subscription.deleted":
        resData = event.data.object;
        break;
      default:
        console.log(`Unhandled event type ${event.type}`);
    }

    console.log(resData);

    return response.status(200).send(resData);
  }
);

// Start server
app.listen(app.get("port"), () => {
  console.log("Server listening on : ", app.get("port"));
});

I try to trigger an event when the subscription is created successfully but get an error for body data when I pass buffer data then get an error like:- No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? When I pass JSON data then get an error like webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the raw request body. The payload was provided as a parsed JavaScript object instead. Signature verification is impossible without access to the original signed material.


Solution

  • Issue in process.env.END_POINT_SECRET key.

    It is solved.