I’m facing an issue with passing values in stripe checkout, I want to pass my shopping cart object to stripe checkout that’s in my mongodb database. I tried finding my cart.products array and passing that in, but I get errors. Can someone please tell me what I’m missing or doing wrong, I’m passing the array in a structure of how stripe likes it to be. If there is any more information that you need Id be happy to send it. Thank you
here is my code
app.js
const express = require('express');
const app = express();
const stripe = require('stripe')(stripeSecretKey);
const User = require('./models/users');
var Cart = require('./models/cart');
app.post('/create-checkout-session', async (req, res) => {
const owner = req.user.id;
const user = await User.findById(owner);
const cart = await Cart.findOne({user: user});
console.log(cart.products);
// console.log(req.session.cart);//undefined
console.log(req.session);
const productsList = [];
for (let i = 0; i < cart.products.length; i++) {
productName = cart.products[i].name;
console.log(productName);
image_url = cart.products[i].image;
price = cart.products[i].price;console.log(price);
id = cart.products[i].id;
console.log(id);
quantity = cart.products[i].quantity;
productsList.push({productName, price, id, quantity})
console.log(productsList)}
const items = productsList.map((product) => {
return {
price_data: {
currency: 'usd',
product_data: {
name: productName,
},
unit_amount: product.price,
},
quantity: product.quantity,
}
});
console.log(items)
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
mode: 'payment',
line_items: items,
success_url: ${process.env.SERVER_URL}/success.html,
cancel_url: ${process.env.SERVER_URL}/cancel.html})
res.json({url: session.url})
} catch(e) {
res.status(500).json({error: e.message})
}// res.redirect(303, session.url);});`
I have created an array that is in the form of price_data, and product_data, to pass in line_items, but I get errors like invalid string, unable to read map of undefined, etc.
console.log results
Invalid string: {:quantity=>"1", :id=>"65b80e868dc64e9eee697279", :productName=>"Black Mug", :price=>"2999"}
terminal results
[ { price_data: { currency: 'usd', product_data: [Object], unit_amount: 2999 }, quantity: 1 }, { price_data: { currency: 'usd', product_data: [Object], unit_amount: 2999 }, quantity: 2 }, { price_data: { currency: 'usd', product_data: [Object], unit_amount: 3999 }, quantity: 4 }, { price_data: { currency: 'usd', product_data: [Object], unit_amount: 3499 }, quantity: 2 }, { price_data: { currency: 'usd', product_data: [Object], unit_amount: 4999 }, quantity: 2 }, { price_data: { currency: 'usd', product_data: [Object], unit_amount: 4999 }, quantity: 1 } ]
so I am able to pass items when I pass them in manually but unable to dynamically insert the array. thank you