1

I have found a lot of repositories and examples about installing an Stripe complete checkout, but I cannot just use the simple Snippet code that Stripe offers for a product. How can I use that code on a page in my React Project? Here is the code. I just want to redirect the user to the Stripe checkout page for that product, I don't want to use my own formulary and I don't want either to collect data in my app. Thanks a lot.

<!-- Load Stripe.js on your website. -->
<script src="https://js.stripe.com/v3"></script>

<!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. -->
<button
  style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
  id="checkout-button-price_1Heree568gerg54rtretrt"
  role="link"
  type="button"
>
  Checkout
</button>

<div id="error-message"></div>

<script>
(function() {
  var stripe = Stripe('pk_live_t5tyutrytutruytyutyufake....');

  var checkoutButton = document.getElementById('checkout-button-price_1Heree568gerg54rtretrt');
  checkoutButton.addEventListener('click', function () {
    // When the customer clicks on the button, redirect
    // them to Checkout.
    stripe.redirectToCheckout({
      lineItems: [{price: 'price_1Heree568gerg54rtretrt', quantity: 1}],
      mode: 'subscription',
      // Do not rely on the redirect to the successUrl for fulfilling
      // purchases, customers may not always reach the success_url after
      // a successful payment.
      // Instead use one of the strategies described in
      // https://stripe.com/docs/payments/checkout/fulfill-orders
      successUrl: 'https://myweb.com/success',
      cancelUrl: 'https://myweb.com/canceled',
    })
    .then(function (result) {
      if (result.error) {
        // If `redirectToCheckout` fails due to a browser or network
        // error, display the localized error message to your customer.
        var displayError = document.getElementById('error-message');
        displayError.textContent = result.error.message;
      }
    });
  });
})();
</script>

1 Answer 1

2

You can create a dedicated component for that. As stated in the documentation, I am using StripeJS to import it as a module.

// npm install @stripe/stripe-js
import React from 'react';
import {loadStripe} from '@stripe/stripe-js';

const StripeButton = (props) => {
  const [stripeError, setStripeError] = React.useState(null);
  const [stripe, setStripe] = React.useState(null);

  useEffect( async () => {
    if (!stripe) {
      // Here, you can use some `props` instead of hardcoding the API key
      const stripeTmp = await loadStripe('pk_live_t5tyutrytutruytyutyufake....');
      setStripe(stripeTmp);
    }
  });
  const handleClick = () => {
    // Reset error holder
    setStripeError(null);

    // When the customer clicks on the button, redirect
    // them to Checkout.
    stripe.redirectToCheckout({
      // Here you can use another `prop` instead of hard coding it
      lineItems: [{price: 'price_1Heree568gerg54rtretrt', quantity: 1}],
      mode: 'subscription',
      // Do not rely on the redirect to the successUrl for fulfilling
      // purchases, customers may not always reach the success_url after
      // a successful payment.
      // Instead use one of the strategies described in
      // https://stripe.com/docs/payments/checkout/fulfill-orders
      successUrl: 'https://myweb.com/success',
      cancelUrl: 'https://myweb.com/canceled',
    })
    .then(function (result) {
      if (result.error) {
        // If `redirectToCheckout` fails due to a browser or network
        // error, display the localized error message to your customer.
        setStripeError(result.error.message);
      }
    });
  }

  return (
    <>
      { stripe ? (
          <button
            style="background-color:#6772E5;color:#FFF;padding:8px 12px ;border:0;border-radius:4px;font-size:1em"
            id="checkout-button-price_1Heree568gerg54rtretrt"
            role="link"
            type="button"
            onClick={ handleClick }
          >
            Checkout
          </button>
        ) : "Loading..."
      }
      { stripeError ? <div id="error-message">{ stripeError }</div> : null }
    </>
  )
}

export default StripeButton;
Sign up to request clarification or add additional context in comments.

5 Comments

I can not use await: Parsing error: 'await' is only allowed within async functions. Also I have this error: × TypeError: stripe.redirectToCheckout is not a function
Updated the answer adding a useEffect to avoid calling a function with await during render.
We can also avoid any async/await code by adding a then after loadStripe: loadStripe('...').then( setStripe )
I think the problem is here: stripe.redirectToCheckout
Please, provide any error message or what makes you think that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.