Firstly thanks for your help. I'm trying to pass a value posted from the client side to the Stripe create-checkout-session object to charge a custom amount for a cake as determined on the client side.
If you would like to view my code in full please see https://github.com/calumbradley/cakeitorleaveit
The price data is received via a route that is called /data in the req.body[0].price
I just cant seem to work out a way to pass this into the create-checkout-session price_data then to the unit_amount value.
Please see my express server code below the error is mentioned in the comment to the right of unit_amount
Please be aware I have asked this question in one form or another previously, unfortunately I am still stuck on it!
app.post('/data', (req, res, next) => {
console.log(req.body[0].price); //logs an int of 7 to the console
res.send({message : "Successful request"})
next()
})
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, //errors with "TypeError: 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);
});
app.listen(4242, () => console.log(`Node server listening on port ${port}!`));
It looks like you expect to receive two separate HTTP requests:
POST /dataPOST /create-checkout-sessionKeep in mind that express handles these two requests completely independently. Each middleware function will receive a req object that contains the data from the current request. So the request to the POST /data route includes the price (as you saw by printing it to the console), but the request to the POST /create-checkout-session will only include the data that was provided directly in that request. If the price wasn't in that request, it won't be available on the req object.
If you need to share data between the requests, you have to do something to make that happen. You could just save it locally, but that isn't a good idea because you would have just one value for all of the users who might be sending requests to your server. You need a way to distinguish the data of one user from another.
A common way to handle that is to use the express-session module. Using this module would allow you to associate data with a particular user session and share it between different routes. But if you're using the Stripe API, it probably has its own way of handling sessions. In that case, you should look through the Stripe documentation to understand how their sessions work.