In my express application I have route that gets a cake price from the client side in the req.body
app.post("/data", (req, res) => {
let price = req.body[0].price * 1000;
console.log(`Cake price is: £${price}`);
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This works fine and logs the price in the console
I have another route that I would like to pass this variable price from the req.body to Stripe and charge the customer.
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);
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
When I pass the req.body[0].price into my Stripe route I get the below error.
unit_amount: req.body[0].price, TypeError: Cannot read properties of undefined (reading 'price')
Thanks in advance
CodePudding user response:
Are you sending the price through to /create-checkout-session
route on the client-side? What might be occurring is that you passing the price to the /data
route on the client-side, but you aren't passing the price to the /create-checkout-session
. It's hard to tell without seeing how you send your data to your API.
If you wanted to use one route - for instance the /data
route you could transfer the /create-checkout-session
into a function and call that function in the /data
route and pass the price as a parameter to the /create-checkout-session function
.
CodePudding user response:
Thanks I was able to modify my code to req the cake price in the /create-checkout-session route
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);
});
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>