use-shopping-cart

redirectToCheckout()

redirectToCheckout()

To send the buyer to Stripe's Checkout experience, use redirectToCheckout

redirectToCheckout is configured for you by the props passed to CartProvider. You can pass it a sessionId (the preferred way) or refer to products in your Stripe dashboard to fulfill purchases.

With use-shopping-cart's redirectToCheckout, you don't need to pass anything more than the sessionId you get from Stripe because all of the config is handled in the CartProvider props.

This is how you'd use redirectToCheckout() with a serverless function:

{}
import React, { useState } from 'react'
import { Link } from 'gatsby'
import { useShoppingCart } from 'use-shopping-cart'
export function Cart() {
const [status, setStatus] = useState('idle')
const { redirectToCheckout, cartCount } = useShoppingCart()
async function handleClick(event) {
event.preventDefault()
if (cartCount > 0) {
setStatus('idle')
const error = await redirectToCheckout()
if (error) setStatus('redirect-error')
} else {
setStatus('missing-items')
}
}
return (
<article
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: '50%'
}}
>
{status === 'missing-items' && (
<p>
Your cart is empty. Please go to{' '}
<Link to={'/usage/addItem()'}>addItem()</Link> and add an item to the
cart
</p>
)}
{status === 'redirect-error' && (
<p>Unable to redirect to Stripe checkout page.</p>
)}
<button
onClick={handleClick}
style={{ height: 50, width: 100, marginBottom: 30 }}
>
Checkout
</button>
</article>
)
}

Please refer to Stripe's official documentation to learn more about redirectToCheckout.

Edit this page on GitHub