node.js - Stripe webhook POST route does not have req.user


Keywords:node.js 


Question: 

I am testing Stripe webhooks locally using ngrok, so that the webhooks can be sent to an endpoint on localhost.

I want to test saving customer and payment information to my database, however, it seems like the middleware isn't attaching req.user (set by Passport) like it is on any other route. This makes it a lot less convenient in terms of accessing the authenticated user.

I could do the database work on the routes where I receive a Stripe token, but the bulk of useful information is sent as a webhook. Another option is to save the charge id or customer id at that stage, and then to look up the user at a later stage, but again this seems like unnecessary work.

I'm a little confused as to why this is, unless I'm missing something super obvious.

router.post('/stripe/webhook', (req, res) => {

   console.log(req.user); //undefined
   res.sendStatus(200);

});

1 Answer: 

You can find the detail of Stripe webhook mechanism here

You need to parse the body of the request which is holding the payload JSON

Example receiving endpoint :

app.post("/my/webhook/url", function(request, response) {

  // Retrieve the request's body and parse it as JSON
  var event_json = JSON.parse(request.body);
  // Do something with event_json
  response.send(200);
});

You can test the your receiving endpoint by test JSON which you can found in Event API of Stripe! And you send test JSON using many app like POSTMAN (having also a chrome app)