Pular para o conteúdo
Criar conta ou Entrar
O logotipo da documentação da Stripe
/
Pergunte à IA
Criar contaLogin
Comece já
Pagamentos
Receita
Plataformas e marketplaces
Gestão de valores
Recursos para desenvolvedores
APIs e SDKsAjuda
Visão geral
Controle de versão
Changelog
Atualize sua versão da API
Faça upgrade da sua versão do SDK
Essentials
SDKs
    Visão geral
    SDKs do lado do servidor
    Web
    Módulo ES do Stripe.js
    Stripe.js do React
    Assistente de teste do Stripe.js
    Celular
    SDK para iOS
    SDK para Android
    SDK do React Native
    Terminal
    SDK para iOS
    SDK para Android
    SDK do React Native
    Comunidade
    SDks da comunidade
API
Testes
Stripe CLI
Projetos de exemplo
Ferramentas
Stripe Dashboard
Workbench
Dashboard de desenvolvedores
Stripe para Visual Studio Code
Terraform
Recursos
Fluxos de trabalho
Destinos de evento
Alertas de integridade da StripeCarregamento de arquivos
Soluções de IA
Kit de ferramentas para agentes
Protocolo de contexto do modeloCrie fluxos de cobrança SaaS com IA agentiva
Segurança e privacidade
Segurança
Rastreador da Web Stripebot
Privacidade
Amplie a Stripe
Desenvolva aplicativos da Stripe
Usar os aplicativos da Stripe
Parceiros
Ecossistema de parceiros
Certificação de parceiro
Estados Unidos
Português (Brasil)
Página inicialRecursos para desenvolvedoresSDKs

Referências sobre React Stripe.js

Learn about React components for Stripe.js and Stripe Elements.

See the code

Want to see how React Stripe.js works or help develop it? Check out the project on GitHub. You can also view the changelog on the Releases tab.

React Stripe.js is a thin wrapper around Stripe Elements. It allows you to add Elements to any React app.

The Stripe.js reference covers complete Elements customization details.

You can use Elements with any Stripe product to collect online payments. To find the right integration path for your business, explore our docs.

Nota

This reference covers the full React Stripe.js API. If you prefer to learn by doing, check out our documentation on accepting a payment or take a look at a sample integration.

Antes de começar

This doc assumes that you already have a basic working knowledge of React and that you have already set up a React project. If you’re new to React, we recommend that you take a look at the Getting Started guide before continuing.

Configuração

Install React Stripe.js and the Stripe.js loader from the npm public registry.

Command Line
npm install --save @stripe/react-stripe-js @stripe/stripe-js

Checkout provider

The CheckoutProvider allows you to use Element components and access the Stripe object in any nested component. Render a CheckoutProvider at the root of your React app so that it’s available everywhere you need it.

To use the CheckoutProvider, call loadStripe from @stripe/stripe-js with your publishable key. The loadStripe function asynchronously loads the Stripe.js script and initializes a Stripe object. Pass the returned Promise to the CheckoutProvider.

See Create a Checkout Session for an example of what your endpoint might look like.

index.jsx
import {CheckoutProvider} from '@stripe/react-stripe-js/checkout'; import {loadStripe} from '@stripe/stripe-js'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
); export default function App() { const promise = useMemo(() => { return fetch('/create-checkout-session', { method: 'POST', }) .then((res) => res.json()) .then((data) => data.clientSecret); }, []); return ( <CheckoutProvider stripe={stripePromise} options={{clientSecret: promise}}> <CheckoutForm /> </CheckoutProvider> ); }
propdescrição

stripe

obrigatório Stripe | null | Promise<Stripe | null>

A Stripe object or a Promise resolving to a Stripe object. We recommend using the Stripe.js wrapper module to initialize a Stripe object. After you set this prop, you can’t change it.

You can also pass in null or a Promise resolving to null if you’re performing an initial server-side render or when generating a static site.

options

obrigatório Object

CheckoutProvider configuration options. See available options. You must provide the clientSecret of the created Checkout Session. See Create a Checkout Session for an example.

Element components

Element components allow you to securely collect payment information in your React app and place the Elements wherever you want on your checkout page. You can also customize the appearance.

You can mount individual Element components inside of your CheckoutProvider tree. You can only mount one of each type of Element in a single <CheckoutProvider>.

CheckoutForm.jsx
import {PaymentElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { return ( <form> <PaymentElement /> <button>Submit</button> </form> ); }; export default CheckoutForm;
prop descrição

options

opcional Object

An object containing Element configuration options. See available options for the Payment Element.

onBlur

opcional () => void

Triggered when the Element loses focus.

onChange

opcional (event: Object) => void

Triggered when data exposed by this Element changes.

For more information, refer to the Stripe.js reference.

onEscape

opcional (event: Object) => void

Triggered when the escape key is pressed within an Element.

For more information, refer to the Stripe.js reference.

onFocus

opcional () => void

Triggered when the Element receives focus.

onLoaderror

opcional (event: Object) => void

Triggered when the Element fails to load.

For more information, refer to the Stripe.js reference.

onLoaderStart

opcional (event: Object) => void

Triggered when the loader UI is mounted to the DOM and ready to be displayed.

You only receive these events from the payment and address Elements.

For more information, refer to the Stripe.js reference.

onReady

opcional (element: Element) => void

Triggered when the Element is fully rendered and can accept imperative element.focus() calls. Called with a reference to the underlying Element instance.

Available Element components

You can use several different kinds of Elements for collecting information on your checkout page. These are the available Elements:

ComponenteUso
BillingAddressElementCollects billing address details for more than 236 regional formats. See the Address Element documentation to learn more.
ShippingAddressElementCollects shipping address details for more than 236 regional formats. See the Address Element documentation to learn more.
ExpressCheckoutElementAllows you to accept card or wallet payments through one or more payment buttons, including Apple Pay, Google Pay, Link, or PayPal. See the Express Checkout Element documentation to learn more.
PaymentElementCollects payment details for more than 25 payment methods from around the globe. See the Payment Element documentation to learn more.

useCheckout hook

useCheckout(): CheckoutValue

Use the useCheckout hook in your components to get the Checkout object, which contains data from the Checkout Session, and methods to update and confirm the Session.

CheckoutForm.jsx
import {useCheckout, PaymentElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckout(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (checkoutState.type === 'loading') { return ( <div>Loading...</div> ); } else if (checkoutState.type === 'error') { return ( <div>Error: {checkoutState.error.message}</div> ); } // checkoutState.type === 'success' const {checkout} = checkoutState; const result = await checkout.confirm(); if (result.type === 'error') { // Show error to your customer (for example, payment details incomplete) console.log(result.error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return ( <form onSubmit={handleSubmit}> <PaymentElement /> <button>Submit</button> </form> ) }; export default CheckoutForm;

Customization and styling

Why we use iframes

We recognize that the use of iframes makes styling an Element more difficult, but they shift the burden of securely handling payment data to Stripe and allows you to keep your site compliant with industry regulations.

Each element is mounted in an iframe, which means that Elements probably won’t work with any existing styling and component frameworks that you have. Despite this, you can still configure Elements to match the design of your site. To customize Elements, you respond to events and configure Elements with the appearance option. The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and so on.

Localização do cliente
Tamanho
Tema
Layout
Esta demonstração só exibe o Google Pay ou Apple Pay se você tiver um cartão ativo com qualquer uma das carteiras.

Next steps

Build an integration with React Stripe.js and Elements with the Checkout Sessions API.

  • Accept a payment
  • Add the Express Checkout Element
  • The Elements Appearance API
  • Stripe.js reference
Esta página foi útil?
SimNão
  • Precisa de ajuda? Fale com o suporte.
  • Confira nosso changelog.
  • Dúvidas? Fale com a equipe de vendas.
  • LLM? Read llms.txt.
  • Powered by Markdoc