项目作者: stripe

项目描述 :
React components for Stripe.js and Stripe Elements
高级语言: JavaScript
项目地址: git://github.com/stripe/react-stripe-elements.git
创建时间: 2017-02-23T18:04:00Z
项目社区:https://github.com/stripe/react-stripe-elements

开源协议:MIT License

下载


We’ve moved to @stripe/react-stripe-js!

We have decided to rename, rework, and move this project. We have no plans for
any additional major releases of react-stripe-elements. If you have an issue with this package, please open it on the react-stripe-js repo.

If you are starting a new Stripe integration or are looking to update your
existing integration, use
React Stripe.js.


react-stripe-elements

build status
npm version

React components for Stripe.js and Stripe Elements

This project is a thin React wrapper around
Stripe.js and
Stripe Elements. It allows you to add
Elements to any React app, and manages the state and lifecycle of Elements for
you.

The
Stripe.js / Stripe Elements API reference
goes into more detail on the various customization options for Elements (e.g.
styles, fonts).

Table of Contents

Demo

The fastest way to start playing around with react-stripe-elements is with
this JSFiddle: https://jsfiddle.net/f5wxprnc.

You can also play around with the demo locally. The source code is in
demo/. To run it:

  1. git clone https://github.com/stripe/react-stripe-elements
  2. cd react-stripe-elements
  3. # (make sure you have yarn installed: https://yarnpkg.com/)
  4. yarn install
  5. yarn run demo

Now go to http://localhost:8080 to try it out!

:warning: PaymentRequestButtonElement will not render unless the page is
served over HTTPS. To demo PaymentRequestButtonElement, you can tunnel over
HTTPS to the local server using ngrok or a similar service.

Screenshot of the demo running

Installation

First, install react-stripe-elements.

Install with yarn:

  1. yarn add react-stripe-elements

OR with npm:

  1. npm install --save react-stripe-elements

OR using UMD build (exports a global ReactStripeElements object);

  1. <script src="https://unpkg.com/react-stripe-elements@latest/dist/react-stripe-elements.min.js"></script>

Then, load Stripe.js in your application:

  1. <script src="https://js.stripe.com/v3/"></script>

Getting started

The Stripe context (StripeProvider)

In order for your application to have access to
the Stripe object,
let’s add StripeProvider to our root React App component:

  1. // index.js
  2. import React from 'react';
  3. import {render} from 'react-dom';
  4. import {StripeProvider} from 'react-stripe-elements';
  5. import MyStoreCheckout from './MyStoreCheckout';
  6. const App = () => {
  7. return (
  8. <StripeProvider apiKey="pk_test_12345">
  9. <MyStoreCheckout ></MyStoreCheckout>
  10. </StripeProvider>
  11. );
  12. };
  13. render(<App ></App>, document.getElementById('root'));

Element groups (Elements)

Next, when you’re building components for your checkout form, you’ll want to
wrap the Elements component around your form. This groups the set of Stripe
Elements you’re using together, so that we’re able to pull data from groups of
Elements when you’re tokenizing.

  1. // MyStoreCheckout.js
  2. import React from 'react';
  3. import {Elements} from 'react-stripe-elements';
  4. import InjectedCheckoutForm from './CheckoutForm';
  5. class MyStoreCheckout extends React.Component {
  6. render() {
  7. return (
  8. <Elements>
  9. <InjectedCheckoutForm ></InjectedCheckoutForm>
  10. </Elements>
  11. );
  12. }
  13. }
  14. export default MyStoreCheckout;

Setting up your payment form (injectStripe)

Use the injectStripe Higher-Order Component (HOC) to build your payment
form components in the Elements tree. The Higher-Order Component
pattern in React can be unfamiliar to those who’ve never seen it before, so
consider reading up before continuing. The injectStripe HOC provides the
this.props.stripe and this.props.elements properties that manage your
Elements groups. Within an injected component, you can call any of the methods
on the Stripe or Elements objects.

:warning: NOTE injectStripe cannot be used on the same element that renders
the Elements component; it must be used on the child component of
Elements. injectStripe returns a wrapped component that needs to sit
under <Elements> but above any code where you’d like to access
this.props.stripe.

  1. // CheckoutForm.js
  2. import React from 'react';
  3. import {injectStripe} from 'react-stripe-elements';
  4. import AddressSection from './AddressSection';
  5. import CardSection from './CardSection';
  6. class CheckoutForm extends React.Component {
  7. handleSubmit = (ev) => {
  8. // We don't want to let default form submission happen here, which would refresh the page.
  9. ev.preventDefault();
  10. // Use Elements to get a reference to the Card Element mounted somewhere
  11. // in your <Elements> tree. Elements will know how to find your Card Element
  12. // because only one is allowed.
  13. // See our getElement documentation for more:
  14. // https://stripe.com/docs/stripe-js/reference#elements-get-element
  15. const cardElement = this.props.elements.getElement('card');
  16. // From here we can call createPaymentMethod to create a PaymentMethod
  17. // See our createPaymentMethod documentation for more:
  18. // https://stripe.com/docs/stripe-js/reference#stripe-create-payment-method
  19. this.props.stripe
  20. .createPaymentMethod({
  21. type: 'card',
  22. card: cardElement,
  23. billing_details: {name: 'Jenny Rosen'},
  24. })
  25. .then(({paymentMethod}) => {
  26. console.log('Received Stripe PaymentMethod:', paymentMethod);
  27. });
  28. // You can also use confirmCardPayment with the PaymentIntents API automatic confirmation flow.
  29. // See our confirmCardPayment documentation for more:
  30. // https://stripe.com/docs/stripe-js/reference#stripe-confirm-card-payment
  31. this.props.stripe.confirmCardPayment('{PAYMENT_INTENT_CLIENT_SECRET}', {
  32. payment_method: {
  33. card: cardElement,
  34. },
  35. });
  36. // You can also use confirmCardSetup with the SetupIntents API.
  37. // See our confirmCardSetup documentation for more:
  38. // https://stripe.com/docs/stripe-js/reference#stripe-confirm-card-setup
  39. this.props.stripe.confirmCardSetup('{PAYMENT_INTENT_CLIENT_SECRET}', {
  40. payment_method: {
  41. card: cardElement,
  42. },
  43. });
  44. // You can also use createToken to create tokens.
  45. // See our tokens documentation for more:
  46. // https://stripe.com/docs/stripe-js/reference#stripe-create-token
  47. // With createToken, you will not need to pass in the reference to
  48. // the Element. It will be inferred automatically.
  49. this.props.stripe.createToken({type: 'card', name: 'Jenny Rosen'});
  50. // token type can optionally be inferred if there is only one Element
  51. // with which to create tokens
  52. // this.props.stripe.createToken({name: 'Jenny Rosen'});
  53. // You can also use createSource to create Sources.
  54. // See our Sources documentation for more:
  55. // https://stripe.com/docs/stripe-js/reference#stripe-create-source
  56. // With createSource, you will not need to pass in the reference to
  57. // the Element. It will be inferred automatically.
  58. this.props.stripe.createSource({
  59. type: 'card',
  60. owner: {
  61. name: 'Jenny Rosen',
  62. },
  63. });
  64. };
  65. render() {
  66. return (
  67. <form onSubmit={this.handleSubmit}>
  68. <AddressSection ></AddressSection>
  69. <CardSection ></CardSection>
  70. <button>Confirm order</button>
  71. </form>
  72. );
  73. }
  74. }
  75. export default injectStripe(CheckoutForm);

Using individual *Element components

Now, you can use individual *Element components, such as CardElement, to
build your form.

  1. // CardSection.js
  2. import React from 'react';
  3. import {CardElement} from 'react-stripe-elements';
  4. class CardSection extends React.Component {
  5. render() {
  6. return (
  7. <label>
  8. Card details
  9. <CardElement style={{base: {fontSize: '18px'}}} ></CardElement>
  10. </label>
  11. );
  12. }
  13. }
  14. export default CardSection;

Using the PaymentRequestButtonElement

The
Payment Request Button
lets you collect payment and address information from your customers using Apple
Pay and the Payment Request API.

To use the PaymentRequestButtonElement you need to first create a
PaymentRequest object.
You can then conditionally render the PaymentRequestButtonElement based on the
result of paymentRequest.canMakePayment and pass the PaymentRequest Object
as a prop.

  1. class PaymentRequestForm extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. // For full documentation of the available paymentRequest options, see:
  5. // https://stripe.com/docs/stripe.js#the-payment-request-object
  6. const paymentRequest = props.stripe.paymentRequest({
  7. country: 'US',
  8. currency: 'usd',
  9. total: {
  10. label: 'Demo total',
  11. amount: 1000,
  12. },
  13. });
  14. paymentRequest.on('token', ({complete, token, ...data}) => {
  15. console.log('Received Stripe token: ', token);
  16. console.log('Received customer information: ', data);
  17. complete('success');
  18. });
  19. paymentRequest.canMakePayment().then((result) => {
  20. this.setState({canMakePayment: !!result});
  21. });
  22. this.state = {
  23. canMakePayment: false,
  24. paymentRequest,
  25. };
  26. }
  27. render() {
  28. return this.state.canMakePayment ? (
  29. <PaymentRequestButtonElement
  30. paymentRequest={this.state.paymentRequest}
  31. className="PaymentRequestButton"
  32. style={{
  33. // For more details on how to style the Payment Request Button, see:
  34. // https://stripe.com/docs/elements/payment-request-button#styling-the-element
  35. paymentRequestButton: {
  36. theme: 'light',
  37. height: '64px',
  38. },
  39. }}
  40. ></PaymentRequestButtonElement>
  41. ) : null;
  42. }
  43. }
  44. export default injectStripe(PaymentRequestForm);

Advanced integrations

The above Getting started section outlines the most common
integration, which makes the following assumptions:

  • The Stripe.js script is loaded before your application’s code.
  • Your code is only run in a browser environment.
  • You don’t need fine-grained control over the Stripe instance that
    react-stripe-elements uses under the hood.

When all of these assumptions are true, you can pass the apiKey prop to
<StripeProvider> and let react-stripe-elements handle the rest.

When one or more of these assumptions doesn’t hold true for your integration,
you have another option: pass a Stripe instance as the stripe prop to
<StripeProvider> directly. The stripe prop can be either null or the
result of using Stripe(apiKey, options) to construct a [Stripe instance].

We’ll now cover a couple of use cases which break at least one of the
assumptions listed above.

Loading Stripe.js asynchronously

Loading Stripe.js asynchronously can speed up your initial page load, especially
if you don’t show the payment form until the user interacts with your
application in some way.

  1. <html>
  2. <head>
  3. <!-- ... -->
  4. <!-- Note the 'id' and 'async' attributes: -->
  5. <!-- ┌────────────┐ ┌───┐ -->
  6. <script id="stripe-js" src="https://js.stripe.com/v3/" async></script>
  7. <!-- ... -->
  8. </head>
  9. <!-- ... -->
  10. </html>

Initialize this.state.stripe to null in the constructor, then update it in
componentDidMount when the script tag has loaded.

  1. class App extends React.Component {
  2. constructor() {
  3. super();
  4. this.state = {stripe: null};
  5. }
  6. componentDidMount() {
  7. if (window.Stripe) {
  8. this.setState({stripe: window.Stripe('pk_test_12345')});
  9. } else {
  10. document.querySelector('#stripe-js').addEventListener('load', () => {
  11. // Create Stripe instance once Stripe.js loads
  12. this.setState({stripe: window.Stripe('pk_test_12345')});
  13. });
  14. }
  15. }
  16. render() {
  17. // this.state.stripe will either be null or a Stripe instance
  18. // depending on whether Stripe.js has loaded.
  19. return (
  20. <StripeProvider stripe={this.state.stripe}>
  21. <Elements>
  22. <InjectedCheckoutForm ></InjectedCheckoutForm>
  23. </Elements>
  24. </StripeProvider>
  25. );
  26. }
  27. }

When loading Stripe.js asynchronously, the stripe prop provided by
injectStripe will initially be null, and will update to the Stripe instance
once you pass it in to your StripeProvider. You can find a working demo of
this strategy in async.js. If you run the demo locally,
you can view it at http://localhost:8080/async.

For alternatives to calling setStatein componentDidMount, consider using a
setTimeout(), moving the if/else statement to the constructor, or
dynamically injecting a script tag in componentDidMount. For more information,
see stripe/react-stripe-elements.

Server-side rendering (SSR)

If you’re using react-stripe-elements in a non-browser environment
(React.renderToString, etc.), Stripe.js is not available. To use
react-stripe-elements with SSR frameworks, use the following instructions.

The general idea is similar to the async loading snippet from the previous
section (initialize this.state.stripe to null in constructor, update in
componentDidMount), but this time we don’t have to wait for the script tag to
load in componentDidMount; we can use window.Stripe directly.

  1. class App extends React.Component {
  2. constructor() {
  3. super();
  4. this.state = {stripe: null};
  5. }
  6. componentDidMount() {
  7. // Create Stripe instance in componentDidMount
  8. // (componentDidMount only fires in browser/DOM environment)
  9. this.setState({stripe: window.Stripe('pk_test_12345')});
  10. }
  11. render() {
  12. return (
  13. <StripeProvider stripe={this.state.stripe}>
  14. <Elements>
  15. <InjectedCheckoutForm ></InjectedCheckoutForm>
  16. </Elements>
  17. </StripeProvider>
  18. );
  19. }
  20. }

Inside your form, <InjectedCheckoutForm ></InjectedCheckoutForm>, this.props.stripe will either be
null or a valid Stripe instance. This means that it will be null when
rendered server-side, but set when rendered in a browser.

Using an existing Stripe instance

In some projects, part of the project uses React, while another part doesn’t.
For example, maybe you have business logic and view logic separate. Or maybe you
use react-stripe-elements for your credit card form, but use Stripe.js APIs
directly for tokenizing bank account information.

You can use the stripe prop to get more fine-grained control over the Stripe
instance that <StripeProvider> uses. For example, if you have a stripe
instance in a Redux store that you pass to your <App ></App> as a prop, you can
pass that instance directly into <StripeProvider>:

  1. class App extends React.Component {
  2. render() {
  3. return (
  4. <StripeProvider stripe={this.props.stripe}>
  5. <Elements>
  6. <InjectedCheckoutForm ></InjectedCheckoutForm>
  7. </Elements>
  8. </StripeProvider>
  9. );
  10. }
  11. }

As long as <App ></App> is provided a non-null stripe prop, this.props.stripe
will always be available within your InjectedCheckoutForm.

Component reference

<StripeProvider>

All applications using react-stripe-elements must use the <StripeProvider>
component, which sets up the Stripe context for a component tree.
react-stripe-elements uses the provider pattern (which is also adopted by
tools like react-redux and
react-intl) to scope a Stripe context
to a tree of components.

This allows configuration like your API key to be provided at the root of a
component tree. This context is then made available to the <Elements>
component and individual <*Element> components that we provide.

An integration usually wraps the <StripeProvider> around the application’s
root component. This way, your entire application has the configured Stripe
context.

Props shape

There are two distinct props shapes you can pass to <StripeProvider>.

  1. type StripeProviderProps =
  2. | {apiKey: string, ...}
  3. | {stripe: StripeObject | null};

See Advanced integrations for more information on when
to use each.

The ... above represents that this component accepts props for any option that
can be passed into Stripe(apiKey, options). For example, if you are using
Stripe Connect and want to act on behalf of a
connected account, you can pass stripeAccount="acct_123" as a property to
<StripeProvider>. This will get used just like passing stripeAccount in the
options of the Stripe constructor or like using stripe_account when your
backend calls the Stripe API directly

<Elements>

The Elements component wraps groups of Elements that belong together. In most
cases, you want to wrap this around your checkout form.

Props shape

This component accepts all options that can be passed into
stripe.elements(options) as props.

  1. type ElementsProps = {
  2. locale?: string,
  3. fonts?: Array<Object>,
  4. // The full specification for `elements()` options is here: https://stripe.com/docs/elements/reference#elements-options
  5. };

<*Element> components

These components display the UI for Elements, and must be used within
StripeProvider and Elements.

Available components

(More to come!)

  • CardElement
  • CardNumberElement
  • CardExpiryElement
  • CardCvcElement
  • PaymentRequestButtonElement
  • IbanElement
  • IdealBankElement

Props shape

These components accept all options that can be passed into
elements.create(type, options) as props.

  1. type ElementProps = {
  2. id?: string,
  3. className?: string,
  4. // For full documentation on the events and payloads below, see:
  5. // https://stripe.com/docs/elements/reference#element-on
  6. onBlur?: () => void,
  7. onChange?: (changeObject: Object) => void,
  8. onFocus?: () => void,
  9. onReady?: (StripeElement) => void,
  10. };

The props for the PaymentRequestButtonElement are:

  1. type PaymentRequestButtonProps = {
  2. id?: string,
  3. className?: string,
  4. paymentRequest: StripePaymentRequest,
  5. onBlur?: () => void,
  6. onClick?: () => void,
  7. onFocus?: () => void,
  8. onReady?: (StripeElement) => void,
  9. };

Using onReady

Note that the onReady callback gives you access to the underlying Element
created with Stripe.js. You can use this to get access to all the underlying
methods that a Stripe Element supports.

For example, you can use onReady to force your element to focus:

  1. // CardSection.js
  2. import React from 'react';
  3. import {CardElement} from 'react-stripe-elements';
  4. class CardSection extends React.Component {
  5. render = () => {
  6. return (
  7. <label>
  8. Card details
  9. <CardElement onReady={(el) => el.focus()} />
  10. </label>
  11. );
  12. };
  13. }
  14. export default CardSection;

(Note that this functionality is new as of react-stripe-elements v1.6.0.)

injectStripe HOC

  1. function injectStripe(
  2. WrappedComponent: ReactClass,
  3. options?: {
  4. withRef?: boolean = false,
  5. }
  6. ): ReactClass;

Use injectStripe to wrap a component that needs to interact with Stripe.js
to create sources or tokens.

  1. First, create a component that accepts the stripe prop and calls one of
    the Stripe or Elements methods when necessary.
  2. Wrap that component by passing it to injectStripe so that it actually
    receives the stripe and elements props.
  3. Render the component that injectStripe returns.

Example

  1. // 1. Create a component that uses this.props.stripe:
  2. class CheckoutForm extends React.Component {
  3. render() {
  4. /* ... */
  5. }
  6. onCompleteCheckout() {
  7. this.props.stripe
  8. .createPaymentMethod({
  9. type: 'card',
  10. card: this.props.stripe.getElement('card'),
  11. })
  12. .then(/* ... */);
  13. }
  14. }
  15. // 2. Wrap it in a higher-order component that provides the `stripe` prop:
  16. const InjectedCheckoutForm = injectStripe(CheckoutForm);
  17. // 3. Render the wrapped component in your app:
  18. const CheckoutRoute = (props) => (
  19. <div>
  20. <InjectedCheckoutForm ></InjectedCheckoutForm>
  21. </div>
  22. );

injectStripe will work with any method of providing the actual Stripe instance
with StripeProvider, whether you just give it an api key,
load Stripe.js asynchronously, or
pass in an existing instance.

Within the context of Elements, stripe.createToken and stripe.createSource
wrap methods of the same name in
Stripe.js.
Calls to them automatically infer and pass the Element object as the first
argument.

If the withRef option is set to true, the wrapped component instance will be
available with the getWrappedInstance() method of the wrapper component. This
feature can not be used if the wrapped component is a stateless function
component.

Within the wrapped component, the stripe and elements props have the type:

  1. type FactoryProps = {
  2. elements: null | {
  3. getElement: (type: string) => Element | null,
  4. // For more detail and documentation on other methods available on
  5. // the `elements` object, please refer to our official documentation:
  6. // https://stripe.com/docs/elements/reference#the-elements-object
  7. },
  8. stripe: null | {
  9. createToken: (tokenData: {type?: string}) => Promise<{
  10. token?: Object,
  11. error?: Object,
  12. }>,
  13. createSource: (sourceData: {type: string}) => Promise<{
  14. source?: Object,
  15. error?: Object,
  16. }>,
  17. createPaymentMethod: (
  18. paymentMethodData: Object
  19. ) => Promise<{
  20. paymentMethod?: Object,
  21. error?: Object,
  22. }>,
  23. confirmCardPayment: (
  24. clientSecret: string,
  25. paymentIntentData?: Object
  26. ) => Promise<{
  27. paymentIntent?: Object,
  28. error?: Object,
  29. }>,
  30. confirmCardSetup: (
  31. clientSecret: string,
  32. paymentIntentData?: Object
  33. ) => Promise<{
  34. setupIntent?: Object,
  35. error?: Object,
  36. }>,
  37. // For more detail and documentation on other methods available on
  38. // the `stripe` object, please refer to our official documentation:
  39. // https://stripe.com/docs/elements/reference#the-stripe-object
  40. },
  41. };

The stripe and elements props can only be null if you are using one of the
Advanced integrations mentioned above, like loading
Stripe.js asynchronously or providing an existing instance. If you are using a
basic integration where you pass in an api key to <StripeProvider></StripeProvider>, they will
always be present.

Troubleshooting

react-stripe-elements may not work properly when used with components that
implement shouldComponentUpdate. react-stripe-elements relies heavily on
React’s context feature and shouldComponentUpdate does not provide a way to
take context updates into account when deciding whether to allow a re-render.
These components can block context updates from reaching react-stripe-element
components in the tree.

For example, when using react-stripe-elements together with
react-redux doing the following will
not work:

  1. const Component = connect()(injectStripe(_Component));

In this case, the context updates originating from the StripeProvider are not
reaching the components wrapped inside the connect function. Therefore,
react-stripe-elements components deeper in the tree break. The reason is that
the connect function of react-redux
implements shouldComponentUpdate
and blocks re-renders that are triggered by context changes outside of the
connected component.

There are two ways to prevent this issue:

  1. Change the order of the functions to have injectStripe be the outermost
    one:

    1. const Component = injectStripe(connect()(_CardForm));

This works, because injectStripe does not implement shouldComponentUpdate
itself, so context updates originating from the redux Provider will still
reach all components.

  1. You can use the [pure: false][pure-false] option for redux-connect:

    1. const Component = connect(
    2. mapStateToProps,
    3. mapDispatchToProps,
    4. mergeProps,
    5. {
    6. pure: false,
    7. }
    8. )(injectStripe(_CardForm));

[pure-false]:
https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options

Development

Install dependencies:

  1. yarn install

Run the demo:

  1. yarn run demo

Run the tests:

  1. yarn run test

Build:

  1. yarn run build

We use prettier for code formatting:

  1. yarn run prettier

To update the ToC in the README if any of the headers changed:

  1. yarn run doctoc

Checks:

  1. yarn test
  2. yarn run lint
  3. yarn run flow