Express pass req.body data into the Stripe route to pay

Express pass req.body data into the Stripe route to pay

在我的快递应用程序中,我有一条路线可以从 req.body

中的客户端获取蛋糕价格

app.post("/data", (req, res) => {
      let price = req.body[0].price * 1000;
      console.log(`Cake price is: £${price}`);
    });

这很好用并在控制台中记录价格

我有另一条路线,我想将这个可变价格从 req.body 传递给 Stripe 并向客户收费。

app.post("/create-checkout-session", async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "gbp",
          unit_amount: req.body[0].price,
          product_data: {
            name: "CakeItOrLeaveIt",
            // description: "", cake it or leave it description
            // images: [], cake it or leave it logo
          },
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: `http://localhost:4242/success.html`,
    cancel_url: `http://localhost:4242/cancel.html`,
  });
  res.redirect(303, session.url);
});

当我将 req.body[0].price 传递到我的 Stripe 路由时,出现以下错误。

unit_amount: req.body[0].price, TypeError: Cannot read properties of undefined (reading 'price')

提前致谢

您是否将价格发送到客户端的 /create-checkout-session 路由?可能发生的情况是,您将价格传递给客户端的 /data 路由,但没有将价格传递给 /create-checkout-session。如果不了解您如何将数据发送到 API。

,则很难判断

如果您想使用一条路线 - 例如 /data 路线,您可以将 /create-checkout-session 转移到一个函数中并在 /data 路线中调用该函数并传递价格作为 /create-checkout-session function.

的参数

谢谢我能够修改我的代码以在 /create-checkout-session 路由中请求蛋糕价格

app.post("/create-checkout-session", async (req, res) => {

  console.log(req.body[0].price * 1000); //this works and gets the cake price

  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "gbp",
          unit_amount: req.body[0].price * 1000, //this errors with Cannot read properties of undefined (reading 'price')
          product_data: {
            name: "CakeItOrLeaveIt",
            // description: "", cake it or leave it description
            // images: [], cake it or leave it logo
          },
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: `http://localhost:4242/success.html`,
    cancel_url: `http://localhost:4242/cancel.html`,
  });
  
  res.redirect(303, session.url);
});