简体   繁体   中英

How can I use Stripe checkout with React?

This library makes it easy to use Stripe checkout in React projects. But I don't want all of the extra options, and I want to understand how to achieve this functionality myself.

How can I get a basic Stripe checkout button , like the one below, in my React project ? I do not want to use any external libraries. I do not want to use Stripe.js.

Here's the code for the basic Stripe checkout button as distinct from Stripe.js checkout :

<form action="" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="KEY"
    data-amount="999"
    data-name="Company Name"
    data-description="Widget"
    data-image="/img/documentation/checkout/marketplace.png"
    data-locale="auto">
  </script>
</form>

Here's a live example , in case that code snippet can't be run.


Problem

I can't get the button to display if it is within a React class. I think this has to do with rendering and loading the Stripe script.

A direct translation of your code to make it work in react could be:

const script = document.createElement("script");
script.src="https://checkout.stripe.com/checkout.js" ;
script.className="stripe-button";
script.dataset.key="KEY";
script.dataset.amount="999";
script.dataset.name="Company Name";
script.dataset.description="Widget";
script.dataset.image="img/documentation/checkout/marketplace.png";
script.dataset.locale="auto";
script.dataset.zipCode="true"; // Note camelCase!
let form = document.getElementById('THEFORM');
form.appendChild(script);

This code can be placed in componentDidMount and THEFORM is the form element that you put in the render function. But take a look at this answer to see how it really should be done.

If you're using jsx , class is a reserved keyword. Use className instead:

<form action="" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" className="stripe-button"
    data-key="KEY"
    data-amount="999"
    data-name="Company Name"
    data-description="Widget"
    data-image="/img/documentation/checkout/marketplace.png"
    data-locale="auto">
  </script>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM