loading...
Stripe

Importing Stripe.js as an ES Module

thorwebdev profile image Thor 雷神 Updated on ・3 min read

Stripe.js allows you to collect sensitive data, like credit card details, in a secure and PCI compliant manner. To make sure your application always uses the latest version and therefore stays secure and compliant, you must load Stripe.js directly from https://js.stripe.com rather than including it in a bundle or hosting it yourself.

This can be challenging when building modern web applications, for example with React and Vue, or in general server-side rendered applications, where you can't easily include a script tag.

That's why we provide a stripe-js module which you can install via your package manager and import into your application to load Stripe.js in a compliant manner.

Installation

Use npm or yarn to install the Stripe.js module:

npm install @stripe/stripe-js
# or
yarn add @stripe/stripe-js

Usage

loadStripe

This function returns a Promise that resolves with a newly created Stripe object once Stripe.js has loaded. If necessary, it will load Stripe.js for you by inserting the Stripe.js script tag. If you call loadStripe in a server environment it will resolve to null.

import { loadStripe } from '@stripe/stripe-js';

const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

Replace the test API key above with your own publishable API key.

For more information on how to use Stripe.js once it loads, please refer to the Stripe.js API reference or follow the accept a payment guide.

Optimizing performance

To improve your site's performance, you can hold off instantiating Stripe until the first render of your checkout page. To make sure that you don't reinstate Stripe on every render, we recommend that you use the singleton pattern to create/retrieve the Stripe instance:

let stripePromise;
const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY);
  }
  return stripePromise;
};

const CheckoutPage = () => (
  <Elements stripe={getStripe()}>
    <CheckoutForm />
  </Elements>
);

Defer loading Stripe.js

You can defer loading Stripe.js (lazy loading) until you call loadStripe by using the /pure import path:

// Stripe.js will not be loaded until `loadStripe` is called
import { loadStripe } from '@stripe/stripe-js/pure';

Do note that this will cause Stripe to not collect any fraud signals on your page until loadStripe has been called, which can impact fraud detection performance.

Disabling advanced fraud detection signals

If you would like to disable advanced fraud detection altogether, use loadStripe.setLoadParameters:

import { loadStripe } from '@stripe/stripe-js/pure';

loadStripe.setLoadParameters({ advancedFraudSignals: false });
const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

The loadStripe.setLoadParameters function is only available when importing loadStripe from @stripe/stripe-js/pure.

React Hooks

In React, once you've loaded Stripe.js initially with loadStripe and passed it to the Elements component, you can use the useStripe hook throughout your child components to get a reference to the stripe object.

import React from 'react';
import ReactDOM from 'react-dom';
import { loadStripe } from '@stripe/stripe-js';
import {
  CardElement,
  Elements,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';

const CheckoutForm = () => {
  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async (event) => {
    event.preventDefault();
    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: 'card',
      card: elements.getElement(CardElement),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardElement />
      <button type="submit" disabled={!stripe}>
        Pay
      </button>
    </form>
  );
};

let stripePromise;
const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY);
  }
  return stripePromise;
};

const App = () => (
  <Elements stripe={getStripe()}>
    <CheckoutForm />
  </Elements>
);

ReactDOM.render(<App />, document.body);

Examples

Stripe.js Documentation

Posted on by:

thorwebdev profile

Thor 雷神

@thorwebdev

Hello, I'm Thor (雷神), a Developer Advocate at Stripe working with many different technologies on the web to grow the GDP of the internet 💸

Stripe

Stripe builds financial tools and economic infrastructure for the internet. We love to help you build products, create business models, and scale your efforts globally. Stripe is built for developers, makers, and creators.

Discussion

markdown guide
 

That looks quite easy :)

Thanks for sharing and linked resources~