Aurora
Aurora

Reputation: 177

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?

Upvotes: 1

Views: 181

Answers (2)

Stephen Gilboy
Stephen Gilboy

Reputation: 5825

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

Upvotes: 0

Aurora
Aurora

Reputation: 177

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;

Upvotes: 0

Related Questions