Home > Software design >  UnhandledPromiseRejectionWarning: Error: Invalid integer: NaN
UnhandledPromiseRejectionWarning: Error: Invalid integer: NaN

Time:11-10

I'm having a problem trying to pass data into the "amount" param.

I am sending the "price" from the client to the server.

When I output the data into the console, I get the correct information.

When I check the "typeOf", i get "number" which is the expected output.

However, when I run the application, I am getting the error

"UnhandledPromiseRejectionWarning: Error: Invalid integer: NaN"

It seems like the "paymentIntents.create" method isnt reading the data. your text

What am I doing wrong here?

How can I pass by price field into the amount param.

Here is my code:

`

const express = require("express");
const app = express();
const { resolve } = require("path");
const stripe = require("stripe")(process.env.secret_key); // https://stripe.com/docs/keys#obtain-api-keys

app.use(express.static("."));
app.use(express.json());

 const calculateOrderAmount = price =>{
  const total = price * 100 
  return total
}

// An endpoint for your checkout
app.post("/payment-sheet", async (req, res) => {
  const price = req.body.price
  console.log(typeof calculateOrderAmount(price))
  
  
  const paymentIntent = await stripe.paymentIntents.create({
    amount: calculateOrderAmount(price),
    currency: "usd",
    //customer: customer.id,
    automatic_payment_methods: {
      enabled: true,
    },
  });

  // Send the object keys to the client
  res.json({
    publishableKey: process.env.publishable_key, // https://stripe.com/docs/keys#obtain-api-keys
    paymentIntent: paymentIntent.client_secret,
    //customer: customer.id,
    //ephemeralKey: ephemeralKey.secret
  });
});

app.listen(process.env.PORT, () =>
  console.log(`Node server listening on port ${process.env.PORT}!`)
);

`

Ive tried to send the "price" field directly without doing the calculation and the error returned is:

Error: Missing required param: amount.

CodePudding user response:

The issue was that I was sending 2 POST requests to my server from the client. The 1st one was sending the client intent and the other was sending the amount, hence the amount not being sent in the payment intent.

Once I fixed that and edited my code as per @bismarcks advice, it works fine.

CodePudding user response:

You are attempting to set the value of the amount parameter to a function. The function never actually runs before being sent to the Stripe API, thus NaN.

Instead, try running that function just before your const paymentIntent = await stripe.paymentIntents.create({ so like:

app.post("/payment-sheet", async (req, res) => {
  const price = req.body.price
  const amountToCharge = calculateOrderAmount(price)
  
  
  const paymentIntent = await stripe.paymentIntents.create({
    amount: amountToCharge,
    ...
  • Related