Design+Code logo

Quick links

Suggested search

Pre-requirement

Before continuing, make sure to have completed the Creating Stripe Account and Product and Adding Stripe.js to React tutorials. You may start with this code sandbox project if you haven't followed the Adding Stripe.js to React tutorial yet. You can find the final project here.

Checkout Item

Let's set things up for creating a checkout session. First, we need to define a cart item in the Checkout.js . For the price , copy the price ID from your Stripe dashboard. Set the quantity to 1. image

// Checkout.js
const item = {
  price: "<price_id>",
  quantity: 1
};

Checkout Options

Furthermore, define another object for checkout options. Add the item variable from earlier to lineItems , and payment as mode . Set your successUrl and cancelUrl to redirect your user after checking out wether they have completed the payment successfully or cancelled their checkout process. The domain is the current domain by reading window.location.origin.

// Checkout.js
const checkoutOptions = {
  lineItems: [item],
  mode: "payment",
  successUrl: `${window.location.origin}/success`,
  cancelUrl: `${window.location.origin}/cancel`
  };

There are many more options to add, for example you may add a customer email if the user is already logged in to your website. See Stripe redirectToCheckout reference to find out more.

Redirect to Checkout

Next, create a function redirectToCheckout that calls getStripe to get an instance of Stripe and then uses Stripe's function redirectToCheckout . Pass the checkoutOptions as the argument. This function returns a promised error if there is any, which we console log it for the moment.

// Checkout.js
const redirectToCheckout = async () => {
  console.log("redirectToCheckout");

  const stripe = await getStripe();
  const { error } = await stripe.redirectToCheckout(checkoutOptions);
  console.log("Stripe checkout error", error);
};

Attach this function to the onClick event of the checkout button.

// Checkout.js
<button className="checkout-button" onclick={redirectToCheckout}>

Now, let's test this. You will get an error like so.

Stripe Checkout Client Only image 1

You'd have to follow the mentioned link and allow it with clicking on the button Enable client-only integration at the bottom right of the page.

Let's try again. As you click on the checkout button, nothing happens though you see that the redirectToCheckout function is being called. That's because Stripe checkout is not supported in code sandbox and I am not sure why. Just open the browser in a new window and everything works fine now.

Rerouting After Checkout

If you cancel the checkout process and click on the Back button, you are headed to the cancel page. However, the page is blank. Even though we have established the success and cancel urls in the checkout options, we haven't created the components yet. Let's do that with adding new files Success.js and Cancel.js in the components folder.

// Success.js
const Success = () => {
  return (
    <div>
      <h1>Success</h1>
      <h2>Thank you for your purchase!</h2>
    </div>
  );
};

export default Success;

// Cancel.js
const Cancel = () => {
  return (
    <div>
      <h1>Cancel</h1>
      <h2>Your payment was canceled.</h2>
    </div>
  );
};

export default Cancel;

Then, import those components and add their respective routes to App.js.

// App.js
import Success from "./components/Success";
import Canceled from "./components/Cancel";

export default function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route index element={<Checkout />} />
          <Route path="success" element={<Success />} />
          <Route path="cancel" element={<Cancel />} />
        </Routes>
      </Router>
    </div>
  );
}

So now when you cancel the checkout, you are being redirected to the appropriate cancel page not an inexistent route.

Testing Payment

It's time to test a payment. On Stripe Checkout page, enter a test email, postal code and the following test card information. This test card is for a successful payment.

  • Number: 4242 4242 4242 4242- Expiration date: Any date in the future- CVC code: Any numberAs you can see, once the payment is processed, you are being redirected to your site's success page.

Error Handling

In the event of a checkout error, we should be displaying an error message to the user of the failure reason. Let's import useState from React add a state to capture that error with an initial value of null.

Remember that redirectToCheckout returns a promised error, if any. We can then save the message of that error to the state and alert the user of it.

// Checkout.js
import { useState } from "react";

const Checkout = () => {
	const [stripeError, setStripeError] = useState(null);

	const redirectToCheckout = async () => {
		...
		if (error) setStripeError(error.message);
	};

  if (stripeError) alert(stripeError);
}

Checkout Button State

It would be a good idea to disable the button if the user is being redirected to Stripe checkout. For this, we add another state for loading. It is set to true right after the user clicks on the checkout button and back to false after the checkout.

// Checkout.js
const [isLoading, setLoading] = useState(false);

const redirectToCheckout = async () => {
  setLoading(true);

  ...
  if (error) setStripeError(error.message);
  setLoading(false);
};

...

<button className="checkout-button" onClick={redirectToCheckout} disabled={isLoading}>

For feedback, show the user that they are being redirected and wait patiently.

// Checkout.js
<button className="checkout-button" onClick={redirectToCheckout} disabled={isLoading}>
  ...
  <div className="text-container">
    <p className="text">{isLoading ? "Loading..." : Buy}</p>
  </div>
</button>

In this tutorial, you have learned how to create a checkout session only with front-end code. You have also set up routes to lead your customer back to your website after the payment is done or when they cancel.

Although client-only integration is quick, simple and easy, for a sustainable real application, it is preferable to use the method server integration as it is more customizable, powerful and supports more features.

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Adding Stripe.js to React

READ NEXT

PayPal Checkout

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Browse all downloads