Dealing with the mystery of the Next.js Stripe webhook elusive function error

I've been working on setting up a Stripe webhook in my NextJS app to write data to Firebase Firestore, but for some reason, stripe.webhook.constructEvent is showing up as undefined even though everything seems to be properly configured.

I'm using the following command with Stripe CLI:

stripe listen --forward-to localhost:3000/api/webhook

The output I'm getting is:

2022-12-20 16:57:18   --> charge.succeeded [evt_3MH8BsL1z8EG1fYg1HgxX6Fm]
2022-12-20 16:57:18   --> payment_intent.succeeded [evt_3MH8BsL1z8EG1fYg1ExIxxZ7]
2022-12-20 16:57:18   --> checkout.session.completed [evt_1MH8BuL1z8EG1fYgo2lLPZkC]
2022-12-20 16:57:18   --> payment_intent.created [evt_3MH8BsL1z8EG1fYg1ezapckU]
2022-12-20 16:57:18  <--  [400] POST http://localhost:3000/api/webhook [evt_3MH8BsL1z8EG1fYg1HgxX6Fm]
2022-12-20 16:57:18  <--  [400] POST http://localhost:3000/api/webhook [evt_3MH8BsL1z8EG1fYg1ExIxxZ7]
2022-12-20 16:57:18  <--  [400] POST http://localhost:3000/api/webhook [evt_1MH8BuL1z8EG1fYgo2lLPZkC]
2022-12-20 16:57:18  <--  [400] POST http://localhost:3000/api/webhook [evt_3MH8BsL1z8EG1fYg1ezapckU]

However, in the app console, I'm encountering the following errors:

Error Cannot read properties of undefined (reading 'constructEvent')
Error Cannot read properties of undefined (reading 'constructEvent')
Error Cannot read properties of undefined (reading 'constructEvent')
Error Cannot read properties of undefined (reading 'constructEvent')

Here's the code from webhook.js:

import { buffer } from "micro";
import * as admin from "firebase-admin";

const serviceAccount = require("../../../credentials.json");

const app = !admin.apps.length
  ? admin.initializeApp({
      credentials: admin.credential.cert(serviceAccount),
    })
  : admin.app();

//connect to stripe

const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);

const endpointSecret = process.env.SIGNING_SECRET;

const fulfillOrder = async (session) => {
  // Code omitted for brevity 
};

export default async (req, res) => {
  // Code omitted for brevity 
};

export const config = {
  api: {
    bodyParser: false,
    externalResolver: true,
  },
};

I have confirmed that none of the arguments for constructEvent are empty, yet it still returns as UNDEFINED. I'm running out of ideas and would appreciate any help or insights. Thank you.

Answer №1

There seems to be a mistake in this line of code

event = stripe.webhook.constructEvent
, it should actually be
event = stripe.webhooks.constructEvent
according to the API documentation here.

Furthermore, if you are using the library micro, keep in mind that Stripe's signature verification requires passing the raw request body. Some libraries may alter the body by default, potentially causing issues. To address this, ensure you pass the raw request body.

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

why doesn't the promise return the record after it has been updated

After completing the form, I proceed to send it as an object to the API NodeJS. The following is the execution function: .post('/create/card', function (req, res) { var rb = req.body, obj = { query: { $set ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

Node.js Express - Setting the route for the main folder of the application

When working on my app, I encountered an issue while trying to access a folder containing .js controller modules. In one of my .html files, I have the following script declared in the head section: The problem arises when the application is running, as i ...

Issue with sending multiple values or a collection as a query parameter in Express.js request

Is there a way to pass multiple values, such as a collection, for a specific query key in express? I vaguely remember seeing something like this on the internet: http://<somehost>/<somepath>?id[]=10&id[]=11&id[]=12 I know that Ruby o ...

Saving this object in Mongodb - here's how it's done

click here for imageCan you provide guidance on creating a schema and saving API data for this specific object in MongoDB? I am looking to store the information related to 'btcinr' as it will be fetched from an external API. Below is the sample ...

NodeJs google analytics reporting API returning null response object

Just getting started with a question. In my project, I am utilizing NodeJS to interact with the Google Analytics Reporting API. I have successfully obtained the necessary OAuth 2 token and even receive a 200 response when querying the API. However, instea ...

What is the method to acquire the firestore reference type in TypeScript?

Here is the code I am working with: import { DocumentReference } from '@firebase/firestore-types' export type Recipe = { author: string title: string ingredients: { quantity: number ingredient: DocumentReference["path"] ...

Send a request to the uClassify API using the Node request module

I'm currently working on integrating the uClassify API into my Node project, but I'm encountering some issues with my code. Here's what I have so far: const req = JSON.stringify('Hello, my love!'); const options = { body: ...

Issue with Laravel Spark due to NPM Dependencies

Trying to install Spark within Laravel on a Docker container running Debian 8, but encountering an error when running NPM update. Not sure how to resolve this issue. Installing NPM Dependencies... npm WARN deprecated <a href="/cdn-cgi/ ...

Do you need to include 'passHref' when using NextJS <Link> with Semantic UI React as the child component?

After diving into the nextjs docs, I came across a section here that discusses: If the child component of Link is a function component, it's necessary to use passHref and wrap the component in React.forwardRef: As someone new to Semantic UI React, ...

The files fail to respond after executing npm and initiating npm starts

I'm completely new to AngularJS. When I run npm start, the server status shows "serving from :. /" but it doesn't seem to pick up the file even though I've specified the file name as index.html. Can someone please assist me in resolving this ...

Issue: Failure to generate models using Loopback's discoverAndBuildModels

I'm currently working on implementing Loopback for table discovery and creation. I have followed the example provided on their documentation page, which can be found at the following link: After executing the code, I am able to see the output of the ...

How to effectively execute async MySQL queries in Node.js?

Just starting out with nodejs and struggling to grasp asynchronous programming/callbacks. Here's my current challenge: I need to retrieve all the words from a table in my database whenever a 'post' request is made. I'm trying to achiev ...

There was a failure to establish a Redis connection to the server with the address 127.0.0.1 on port 6379

Currently, I am working with node.js using expressjs. My goal is to store an account in the session. To test this out, I decided to experiment with sessions by following the code provided on expressjs var RedisStore = require('connect-redis')(ex ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

a guide on utilizing nested populate with node.js and mongoose

I am currently working on the Populate method in Mongoose. Here is my query: await User.findOne({_id: req.params.userId}).populate({ path: 'review' }).then(result=>{ console.log("here" + result) if(result && r ...

Update of component triggered only upon double click

I'm encountering an issue with my parent component passing products and their filters down to a subcomponent as state. Whenever I add a filter, I have to double click it for the parent component to rerender with the filtered products. I know this is d ...

Responsive Container MUI containing a grid

I am attempting to replicate the functionality seen on YouTube's website, where they dynamically adjust the grid layout based on the container size when a Drawer is opened or closed. Essentially, it seems that YT adjusts the grid count based on the c ...

Mongoose encountering an issue with undefined properties (specifically 'prototype') and cannot read them

I am currently using Mongoose 7.0.1 on Next JS 13.2.2 and React 18.2.0. After tirelessly searching for a solution to my problem, I am still struggling with connecting to a MongoDB. Every time I try to import mongoose into my project for the connection, an ...

Using the useState hook in React, you can manipulate a deeply nested object by changing its values, adding new fields,

The structure of the nested state object is as follows: key1: { key2: [ { field1: "value", field2: ["value", "value"], field3: [ { ff1: "val", ...