Skip to content

Latest commit

 

History

History
190 lines (156 loc) · 5.2 KB

getting-started-serverless.mdx

File metadata and controls

190 lines (156 loc) · 5.2 KB
title id
Getting started (Serverless)
getting-started-serverless

Installation

npm install --save use-shopping-cart

or

yarn add use-shopping-cart

The package needs to be configured with your account's publishable key, which is available in the Stripe Dashboard. Require it with the key's value.

At the root level of your app, wrap your root component in the <CartProvider />

import ReactDOM from 'react-dom'
import { CartProvider } from 'use-shopping-cart/react'

import App from './App'

ReactDOM.render(
  <CartProvider
    mode="payment"
    cartMode="checkout-session"
    stripe={YOUR_STRIPE_API_PUBLISHABLE_KEY_GOES_HERE}
    currency="USD"
  >
    <App />
  </CartProvider>,
  document.getElementById('root')
)

Using the hook

The hook useShoppingCart() provides several utilities and pieces of data for you to use in your application. The examples below won't cover every part of the useShoppingCart() API but you can explore the documentation to find out more.

Serverless implementation

If your data source isn't coming from Stripe's dashboard, you can still make products and process payments.

Your product data should look like this:

const productData = [
  {
    name: 'Bananas',
    id: 'some_unique_id_1',
    // price in smallest currency unit (e.g. cent for USD)
    price: 400,
    image: 'https://www.fillmurray.com/300/300',
    currency: 'USD'
    product_data: {
      metadata: {
        type: 'fruit'
      }
    },
    price_data: {
      recurring: {
        interval: 'week'
      }
    }
  },
  {
    name: 'Tangerines',
    id: 'some_unique_id_2',
    // price in smallest currency unit (e.g. cent for USD)
    price: 100,
    image: 'https://www.fillmurray.com/300/300',
    currency: 'USD',
    product_data: {
      metadata: {
        type: 'fruit'
      }
    },
    price_data: {
      recurring: {
        interval: 'week'
      }
    }
  }
]

Note: price_data and product_data are not required for use-shopping-cart to work, but they are required for creating Sessions with Stripe.

This library manages price_data and product_data for you, but if you need to pass extra data to your Sessions, you can add them directly to your product objects.

Also keep in mind that product_data is a child of price_data when being sent to Stripe, but you don't need to nest for use-shopping-cart. Learn more about creating Sessions here: https://stripe.com/docs/api/checkout/sessions/create

Once you have successfully installed stripe, use-shopping-cart, and wrapped your root component with <CartProvider>, you are ready to go! 🚀

Netlify Functions

Create a functions directory in your project. Create a file called create-session.js

Note: You should have a way to reference products from a backend. In this small example we're just referencing from a JSON file.

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

const inventory = require('./data/products.json')

exports.handler = async (event) => {
  let product
  try {
    product = JSON.parse(event.body)
  } catch (error) {
    return {
      statusCode: 400,
      body: JSON.stringify({
        message: 'Received malformed JSON.',
        error: error.message
      })
    }
  }

  let line_items
  try {
    line_items = validateCartItems(inventory, product)
  } catch (error) {
    return {
      statusCode: 422,
      body: JSON.stringify({
        message: 'Some of the items in your cart are invalid.',
        error: error.message
      })
    }
  }

  let session
  try {
    session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      billing_address_collection: 'auto',
      shipping_address_collection: {
        allowed_countries: ['US', 'CA']
      },
      mode: 'payment',
      success_url: `${process.env.URL}/success.html`,
      cancel_url: process.env.URL,
      line_items
    })
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({
        message: 'While communicating with Stripe, we encountered an error.',
        error: error.message
      })
    }
  }

  return {
    statusCode: 200,
    body: JSON.stringify({ sessionId: session.id })
  }
}

Alternatively, you could use the session.url value to take users to checkout without needing redirectToCheckout on the client side.

return {
  statusCode: 302,
  headers: {
    Location: session.url
  },
  body: ''
}

Note: price_data and product_data are not required for use-shopping-cart to work, but they are required for creating Sessions with Stripe.

This library manages price_data and product_data for you, but if you need to pass extra data to your Sessions, you can add them directly to your product objects.

Also keep in mind that product_data is a child of price_data when being sent to Stripe, but you don't need to nest for use-shopping-cart. Learn more about creating Sessions here: https://stripe.com/docs/api/checkout/sessions/create

Once you have successfully installed stripe, use-shopping-cart, and wrapped your root component with <CartProvider>, you are ready to go! 🚀