Skip to content

Latest commit

 

History

History
103 lines (81 loc) · 2.88 KB

getting-started-client-mode.mdx

File metadata and controls

103 lines (81 loc) · 2.88 KB
title id
Getting started (Client Only Mode)
getting-started-client-mode

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'

import App from './App'

ReactDOM.render(
  <CartProvider
    mode="payment"
    cartMode="client-only"
    stripe={YOUR_STRIPE_API_KEY_GOES_HERE}
    successUrl="stripe.com"
    cancelUrl="twitter.com/dayhaysoos"
    currency="USD"
    allowedCountries={['US', 'GB', 'CA']}
    billingAddressCollection={true}
  >
    <App />
  </CartProvider>,
  document.getElementById('root')
)

Note: mode refers to Stripe's payment modes. Refer to the link below:

https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-mode

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.

Products Created on Stripe's Dashboard

To use client only mode, you'll need to add some products on the Stripe Dashboard. Check out Stripe's documentation for more information on how to do this.

Stripe provides you with a Price ID String. You don't need a server(less) set up to use this library this way unless you want more control over how the payments are handled.

import { useShoppingCart } from 'use-shopping-cart'
import { Product } from './Product'
import { CartItems } from './CartItems'

const productData = [
  {
    name: 'Bananas',
    price_id: 'price_GBJ2Ep8246qeeT',
    // price in smallest currency unit (e.g. cent for USD)
    price: 400,
    image: 'https://www.fillmurray.com/300/300',
    currency: 'USD'
  },
  {
    name: 'Tangerines',
    price_id: 'price_GBJ2WWfMaGNC2Z',
    // price in smallest currency unit (e.g. cent for USD)
    price: 100,
    image: 'https://www.fillmurray.com/300/300',
    currency: 'USD'
  }
]

export function App() {
  /* Gets the totalPrice and a method for redirecting to Stripe */
  const { totalPrice, redirectToCheckout, cartCount } = useShoppingCart()

  return (
    <div>
      {/* Renders the products */}
      {productData.map((product) => (
        <Product product={product} />
      ))}

      {/* This is where we'll render our cart */}
      <p>Number of Items: {cartCount}</p>
      <p>Total: {totalPrice}</p>
      <CartItems />

      {/* Redirects the user to Stripe */}
      <button onClick={redirectToCheckout}>Checkout</button>
    </div>
  )
}