Stripe detects that no signatures match the expected payload

Currently working on setting up a checkout session using Stripe that triggers my webhook upon successful completion. The issue I am facing is an error message stating "error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing". Below is a snippet of my code:

const stripeRouter = express.Router({ mergeParams: true });

const endPointSecret = 'Webook_Secret'

stripeRouter.post('/webhook',
express.raw({type: 'application/json'}),
async (req: express.Request, res: express.Response) => {
  const stripe = await getStripe();
  await getStripeSecretKey();

  const sig = req.headers['stripe-signature'];
  console.log(`signature: ${sig}`)
  const payload = req.body;
  console.log(`payload: ${payload}`)

    let eventType;
    let data;

  if (endPointSecret) {
    let event;
    try {
      event = stripe.webhooks.constructEvent(payload, sig, endPointSecret);
      console.log(`$$$$$ Webhook Verification Successful`)
    } catch (err) {
      console.log(`$$$$$ Webhook signature verification failed`, err.message)
      res.status(400).json({error: err.message, signature: req.body});
      return;
    }

    eventType = event.type;
    data = event.data;
    console.log(`$$$ EVENT TYPE: ${eventType}`)
    console.log(`$$$ DATA: ${data}`)
  } else {
    data = req.body.data.object;
    eventType = req.body.type;
  }

I have double-checked the webhook Signing Secret and it is accurate. Additionally, I attempted to use both express.raw() and bodyParser.raw(), but neither solved the problem.

In an effort to resolve the issue, I also implemented custom middleware as shown below, however, the error persists:

stripeRouter.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
  if (req.originalUrl === '/webhook') {
    next();`your text`
  } else {
    express.json()(req, res, next);
  }
})

Answer №1

Verifying webhook signatures can be a bit tricky in this situation. One aspect to consider is the webhook secret being used. While you mentioned that you have already verified it, it's important to note that there are distinct secrets for Test and Live modes. It might be beneficial to double-check this detail.

Additionally, I recommend logging the value of endPointSecret right before constructing the event to ensure that the expected value is passed to the constructEvent() function.

If the endpoint secret matches your expectations and the issue persists, it could be related to the data payload. Although it may require some effort, it could be helpful to start by replicating the functionality of the example webhook verification app available in the stripe-node repository. Once you have it up and running successfully, gradually modify the code and test each change step by step. This approach should assist in pinpointing the specific modification causing the signature validation failure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

Encountering an issue with a Node native module not being found while attempting to import

Encountering an issue while working on a Svelte & TypeScript project where importing native Node modules is causing trouble. For instance, when typing: import { createInterface } from "readline"; in a .ts or .svelte file, a warning pops up saying: Plugin ...

What could be the reason for the cookie not being set in the browser's response headers?

At my localhost server, I run the backend on http://localhost:4000 and the frontend on http://localhost:3000. In the Express server, I have set the cors policy as follows: app.use( cors({ credentials: true, origin: "http://localhost:3000&quo ...

Exploring TypeAhead functionality in Reactjs 18

I have encountered an issue while using react-bootstrap-typeahead version 5.1.8. The problem arises when I try to utilize the typeahead feature, as it displays an error related to 'name'. Below is my code snippet: import { Typeahead } from " ...

Tips for setting up nested folders using Node.js on a Windows machine:

Is there a way to use Nodejs in Windows 10/11 to create a parent folder and then add a new folder inside of that parent folder, like this: parent/child within the Documents folder? ...

Adding a custom property to a React component

Currently, I am facing an issue while attempting to modify an MUI component. Everything works smoothly until I execute the build command, at which point it fails. I have experimented with a few variations of this, but essentially I am looking to introduce ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

update the data source of the material table inside the subscription

Seeking guidance for updating a MatTable datasource within an Angular application. The current Typescript code involves fetching data from an API using AdminService, iterating over the results to make additional API calls for more information about a fleet ...

How to use Sequelize for aggregating data within nested includes on PostgreSQL

The database I'm working with consists of several tables that are relevant to my project, including users, listings, and reviews. Each user can have multiple listings, while each listing can have multiple reviews. A specific column in the reviews ta ...

What is the best way for me to use a ternary operator within this code snippet?

I'm in the process of implementing a ternary operator into this snippet of code, with the intention of adding another component if the condition is false. This method is unfamiliar to me, as I've never utilized a ternary operator within blocks of ...

Is there a way to implement depth-first retrieval in rxjs using the expand method?

Currently, I am engaged in a project utilizing Angular 7, Typescript, and RxJS 6.3.3. In this project, I am working with RxJS Observables and relevant operators to handle hierarchical collections of objects obtained from an http server that interfaces with ...

Route designed for individual element

I am currently working with express 4.9.0 and have the following code in my user.js file located inside the route folder. /* Get User by id. */ router.get('/:id', function(req, res) { console.log('find user ' + req.params.id); User ...

Steps for displaying an ejs file following an event in loopback

I want to display an ejs file after updating certain content in the database within a loopback model js file Here is a snippet of code for reference: Inviteduser.inviteStatusConfirm = function (invitedUserId, callback) { var status = 2; Inviteduser.upse ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

How to send data to middleware functions in Express.js

I've been exploring ways to implement caching in my nodejs application. My goal is to have code that looks like this, app.get('/basement/:id', cache, (req,res) => { client.set('basement' + req.params.id,'hello:'+ ...

Leveraging @types from custom directories in TypeScript

In our monorepo utilizing Lerna, we have two packages - package a and package b - both containing @types/react. Package A is dependent on Package B, resulting in the following structure: Package A: node_modules/PackageB/node_modules/@types This setup le ...

I am interested in using a loop in Angular to highlight my div element

Enhancing my comprehension regarding the mentioned images. If I don't select anything within the div property, the default style (css) should appear like this, at least when one div is selected. However, the issue arises when unable to select. This ...

What is the best way to send props (or a comparable value) to the {children} component within RootLayout when using the app router in Next.js

As I work on updating an e-commerce website's shopping cart to Next.js 13+, I refer back to an old tutorial for guidance. In the previous version of the tutorial, the _app.ts file utilized page routing with the following code snippet: return ( < ...

`A straightforward technique for establishing client-server communication using NodeJS`

Stumbling upon a valuable code snippet on GitHub for enabling straightforward server-client communication in NodeJS has been quite enlightening. Upon making some adjustments, the finalized structure of my code looks like this: The client (Jade + Javascri ...