use-shopping-cart logouse-shopping-cart
Serverless

validateCartItems

validateCartItems(inventory, cartItems)

validateCartItems checks the items in the current cart and compares them with a source of truth to make sure that the prices and quantities are correct. This is necessary because it's possible that malicious users could change the prices in cartDetails before sending the cart to your checkout endpoint.

From each cart entry it keeps only the quantity and product_data.metadata. Keys set in your inventory's product_data.metadata win over the cart's, so the browser can add metadata but can't change yours.

It also validates input shapes and throws if inventory products or cart entries are not objects or if the inventory source is not iterable.

inventory: Source of truth. This should be the object of products you sell. It can come from anywhere that is secure. An API call, or a json file that sits on a server.

cartItems: the cartItems that comes from the use-shopping-cart

const stripe = require('stripe')(process.env.REACT_APP_STRIPE_API_SECRET)
const { validateCartItems } = require('use-shopping-cart/utilities')

/*
 * Product data can be loaded from anywhere. In this case, we’re loading it from
 * a local JSON file, but this could also come from an async call to your
 * inventory management service, a database query, or some other API call.
 *
 * The important thing is that the product info is loaded from somewhere trusted
 * so you know the pricing information is accurate.
 */
const inventory = require('./data/products.json')

exports.handler = async (event) => {
  try {
    const productJSON = JSON.parse(event.body)
    const line_items = validateCartItems(inventory, productJSON)

    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      billing_address_collection: 'auto',
      shipping_address_collection: {
        allowed_countries: ['US', 'CA']
      },

      /*
       * This env var is set by Netlify and inserts the live site URL. If you want
       * to use a different URL, you can hard-code it here or check out the
       * other environment variables Netlify exposes:
       * https://docs.netlify.com/configure-builds/environment-variables/
       */
      success_url: `${process.env.URL}/success.html`,
      cancel_url: process.env.URL,
      line_items
    })

    return {
      statusCode: 200,
      body: JSON.stringify({ sessionUrl: session.url })
    }
  } catch (error) {
    console.error(error)
  }
}

Errors

validateCartItems throws a CartError when the cart can't be trusted. Use error.code to choose a response:

import { validateCartItems, isCartError } from 'use-shopping-cart/utilities'

try {
  const line_items = validateCartItems(inventory, cartDetails)
} catch (error) {
  if (isCartError(error)) {
    return { statusCode: 400, body: JSON.stringify({ code: error.code }) }
  }
  throw error
}
CodeCause
INVALID_INVENTORYinventory isn't an iterable of objects
INVALID_CARTcartDetails or one of its cart entries isn't an object
NOT_IN_INVENTORYa cart entry's ID doesn't match any product's id, price_id, sku_id or sku
INVALID_QUANTITYa cart entry's quantity isn't a positive integer

Take a look at the Netlify example here:

https://github.com/dayhaysoos/use-shopping-cart/blob/legacy-examples/examples/cra/functions/create-session.js

On this page

Shopping Cart

Your cart is empty

Try the interactive demos on the docs pages!