Skip to content

cannot pass items and prices into stripe checkout

I am using the embedded nodejs/javascript Stripe Checkout for my custom ecommerce site. I have my own cart created using DB2, and want to pass the name of the products the customer has in the cart, and the matching prices for each product. Stripe is not very clear on how to do this, and i’ve been struggling to find the right way. I am trying right now to use an 2 arrays, (product array and price array) and am trying to pass them into Stripe function, but no luck. here’s the code.

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

var amount = stringify(req.body)
console.log(req.body.sessionID)
var userId = req.body.sessionID
console.log("email: " + req.body.customer_email)
var email = req.body.customer_email;
var deliveryTotal = req.body.totalWithDelivery;
var totalVal = amount.split("=");
var totalPrice = parseFloat(totalVal[1]);
//console.log("TOTAL PRICE: " + totalPrice);
var finalPrice = parseFloat(Math.round(totalPrice * 100) / 100);

var finalTotal = parseFloat(Math.round(totalPrice * 100) / 100) + parseFloat(Math.round(deliveryTotal));
console.log("final total: " + finalTotal);
var itemName = ""
var itemPrice = ""
var totalNewPriceTest = ""

//defining arrays
var productsArray = [];
var priceArray = [];
//query to database

var productsStripe = "select * from " + userId
console.log(userId)
console.log("query to db for displaying cart on stripe page")
ibmdb.open("DATABASE=BLUDB;HOSTNAME=dashdb-txn-sbox-yp-dal09-14.services.dal.bluemix.net;PORT=50000;PROTOCOL=TCPIP;UID=;PWD=", function (err,conn) {
    if (err) return console.log(err);
  conn.query(productsStripe,  async function (err, rows) {
    if (err) {
      console.log(err)
    }
    console.log(rows)
    for(var i = 0; i < rows.length; i++) {
    //   itemName = rows[i]['ITEM']
    //   itemPrice = rows[i]['PRICE']
      totalNewPriceTest = parseFloat(rows[i]['PRICE'])
      console.log("item name : " + itemName + " " + itemPrice )
      totalNewPriceTest = parseFloat(totalNewPriceTest);
      console.log("final overall prcie: " + (totalNewPriceTest))

    //inserting items and prices into arrays
     productsArray.push(rows[i]['ITEM'])
     priceArray.push(rows[i]['PRICE'])
     console.log("ARRAY " + productsArray)
     console.log("PRICE ARRAY " + priceArray)
    }
    console.log("inside productsStripe function.")
    console.log("overall prcie: " + totalNewPriceTest)

    totalNewPriceTest = parseFloat(totalNewPriceTest)
    var grandTotal = totalNewPriceTest;
    var finalGrandTotal = parseFloat(grandTotal)
    console.log(parseFloat(finalGrandTotal))

  
    //stripe
    const session = await stripe.checkout.sessions.create({
      shipping_address_collection: {
        allowed_countries: ['CA'],
      },

      payment_method_types: ['card'],
      line_items: [
        {
          price_data: {
            currency: 'CAD',
            product_data: {
              name: stringify(productsArray),
            },
            unit_amount: parseFloat(priceArray),
            //finalTotal * 100
          },
          quantity: 1,
        },
      ],

      mode: 'payment',
      success_url: 'https://floralfashionboutique.com/successPg',
      cancel_url: 'https://floralfashionboutique.com/catalogue',
      customer_email: email,
    });
    // console.log(session)
    res.json({ id: session.id });
    //console.log("customer id" + customer.id)
    console.log("totalNewPriceTest " + totalNewPriceTest)

  })
})

});

please let me know if anyone has tried to do this before, there isn’t much about it online… also, sorry for the messy code…

Answer

A few things here:

  1. product_data is what you’d use if you want to dynamically create a product in-line. Normally you’d create these beforehand on your dashboard. If you still need to create these dynamically, you should follow the object shape described here: https://stripe.com/docs/api/checkout/sessions/create?lang=node#create_checkout_session-line_items-price_data-product_data

  2. unit_amount needs to be an integer. parseFloat(priceArray) will parse the first value of priceArray and ignore the rest, which is presumably not what you’re trying to do here

  3. If you’re trying to create multiple prices, each with its own product and unit_amount, then you need to create an entry in line_items for each. Something like this:

// loop over your products array to construct the line_items
const items = productsArray.map((product, i) => {
  return {
    price_data: {
      currency: 'CAD',
      product_data: {
        name: product,
      },
      unit_amount: parseInt(priceArray[i], 10),
    },
    quantity: 1,
  };
});

const session = await stripe.checkout.sessions.create({
  shipping_address_collection: {
    allowed_countries: ['CA'],
  },
  payment_method_types: ['card'],
  line_items: items,
  mode: 'payment',
  success_url: 'https://floralfashionboutique.com/successPg',
  cancel_url: 'https://floralfashionboutique.com/catalogue',
  customer_email: email,
});