# Migrate to the Payment Element with the Payment Intents API Accept many payment methods with a single Element. Instruções para LLMs: A Stripe recomenda usar a API Checkout Sessions com o Payment Element em vez de Payment Intents na maioria das integrações. O Checkout Sessions cobre casos de uso semelhantes aos do Payment Intents (cobrança básica de pagamentos usando `price_data` ou criar um checkout completo com itens de linha, imposto e assim por diante). Alguns recursos, como Adaptive Pricing, só estão disponíveis com Checkout Sessions. Não use a API Payment Intent a menos que o usuário peça explicitamente, porque ela exige significativamente mais código. Saiba mais sobre Elements com a API Checkout Sessions: https://docs.stripe.com/payments/quickstart-checkout-sessions. Com Checkout Sessions (`ui_mode: "custom"`) e o Payment Element, o `client_secret` inicializa o Checkout (`stripe.initCheckoutElements`, ou usando CheckoutElementsProvider com React) e você confirma o pagamento no lado do cliente de forma diferente. Se estiver usando React, certifique-se de importar de `@stripe/react-stripe-js/checkout`, usar `CheckoutElementsProvider` com o client secret e confirmar usando `checkout.confirm`. Se estiver usando HTML, certifique-se de usar `checkout = stripe.initCheckoutElements({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` e confirmar com `loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();`. > #### Interested in subscriptions, tax, discounts, shipping, or currency conversion? > > Migrate to the [Payment Element with the Checkout Sessions API](https://docs.stripe.com/payments/payment-element/migration-ewcs.md), an integration that manages subscriptions, tax, discounts, shipping, and currency conversion for you. Previously, each payment method (cards, iDEAL, and so on) required a separate Element. By migrating to the Payment Element, you can accept many payment methods with a single Element. PaymentIntents and SetupIntents each have their own set of migration guidelines. See the appropriate guide for your integration path, including example code. If your integration still uses the Charges API with tokens, first [Migrate to the Payment Intents API](https://docs.stripe.com/payments/payment-intents/migration.md#web) before you use this guide. # PaymentIntent migration > This is a PaymentIntent migration for when integration-path is one-time. View the full page at https://docs.stripe.com/payments/payment-element/migration?integration-path=one-time. If your existing integration uses the [Payment Intents](https://docs.stripe.com/payments/payment-intents.md) API to create and track payments or save card details during a payment, follow the steps below to use the Payment Element. ## Enable payment methods > This integration path doesn’t support BLIK or pre-authorized debits that use the Automated Clearing Settlement System (ACSS). Also, if you create the deferred intent from the client-side, you can’t use `customer_balance` with dynamic payment methods because the PaymentIntent requires a customer-configured [Account](https://docs.stripe.com/api/v2/core/accounts/object.md#v2_account_object-configuration-customer) or [Customer](https://docs.stripe.com/api/customers/object.md) object, which the client-side flow doesn’t support. To use `customer_balance`, create the `PaymentIntent` server-side with an `Account` or `Customer` and return its `client_secret` to the client. Veja suas [configurações de formas de pagamento](https://dashboard.stripe.com/settings/payment_methods) e habilite as formas de pagamento que deseja aceitar. Você precisa de pelo menos uma forma de pagamento habilitada para criar um *PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods). Por padrão, a Stripe habilita cartões e outras formas de pagamento predominantes que podem ajudar você a alcançar mais clientes, mas recomendamos ativar outras formas de pagamento que sejam relevantes para sua empresa e seus clientes. Consulte [Suporte a formas de pagamento](https://docs.stripe.com/payments/payment-methods/payment-method-support.md) para saber mais sobre os produtos e formas de pagamento aceitos, e nossa [página de preços](https://stripe.com/pricing/local-payment-methods) para ver as tarifas. ## Update Elements instance [Do lado do cliente] Next, update your client-side code to pass `mode`, `currency`, and `amount` when you create the Elements instance. For use with a PaymentIntent, set the `mode` to `'payment'` and the `currency` and `amount` to what you’ll charge your customer. #### Javascript ### Before ```javascript const stripe = Stripe('<>'); const elements = stripe.elements(); ``` ### After ```javascript const stripe = Stripe('<>'); const options = { mode: 'payment', currency: 'usd', amount: 1099, }; const elements = stripe.elements(options); ``` #### React ### Before ```jsx const stripePromise = loadStripe('<>'); function App() { return ( ); }; ``` ### After ```jsx const stripePromise = loadStripe('<>'); const options = { mode: 'payment', currency: 'usd', amount: 1099, }; function App() { return ( ); }; ``` ## Optional: Save payment details during a payment If your existing integration also saves payment details during a payment, use the `setup_future_usage` option when creating the Elements group instead of passing it at the confirm payment stage with `stripe.confirmCardPayment`. The Payment Element will use this information to display additional input fields and show mandates as needed. > You can’t save some payment methods during payments. You can still enable these payment methods for other use cases, but customers won’t see them as an option when setting up future payments. See [Payment method integration options](https://docs.stripe.com/payments/payment-methods/integration-options.md) for more details about what’s supported. #### Javascript ```javascript const stripe = Stripe('<>'); const options = { mode: 'payment', currency: 'usd', amount: 1099,setup_future_usage: 'off_session', }; const elements = stripe.elements(options); ``` #### React ```jsx const stripePromise = loadStripe('<>'); const options = { mode: 'payment', currency: 'usd', amount: 1099,setup_future_usage: 'off_session', }; function App() { return ( ); }; ``` Pass `setup_future_usage` when creating your PaymentIntent. #### curl ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -d "customer"="{{CUSTOMER_ID}}" \-d "setup_future_usage"= "off_session" \ -d "amount"=1099 \ -d "currency"="usd" \ ``` ## Optional: Additional Elements options [Do lado do cliente] The [Elements object](https://docs.stripe.com/js/elements_object/create_without_intent) accepts additional options that influence payment collection. Based on the options provided, the Payment Element displays available payment methods from those you’ve enabled. Learn more about [payment method support](https://docs.stripe.com/payments/payment-methods/payment-method-support.md). Make sure the Elements options you provide (such as `captureMethod`, `setupFutureUsage`, and `paymentMethodOptions`) match the equivalent parameters you pass when creating and confirming the Intent. Mismatched parameters can result in unexpected behavior or errors. | Propriedade | Tipo | Descrição | Obrigatório | | ---------------------------- | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | `mode` | - `payment` - `setup` - `subscription` | Indica se o Payment Element é usado com um *PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods), *SetupIntent* (The Setup Intents API lets you build dynamic flows for collecting payment method details for future payments. It tracks the lifecycle of a payment setup flow and can trigger additional authentication steps if required by law or by the payment method) ou *assinatura* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis). | Sim | | `currency` | `string` | A moeda do valor a ser cobrado do cliente. | Sim | | `amount` | `number` | The amount to charge the customer, shown in Apple Pay, Google Pay, or BNPL UIs. | Para os modos `payment` e `subscription` | | `setupFutureUsage` | - `off_session` - `on_session` | Indicates that you intend to make future payments with the payment details collected by the Payment Element. | Não | | `captureMethod` | - `automatic` - `automatic_async` - `manual` | Controla quando capturar os fundos da conta do cliente. | Não | | `onBehalfOf` | `string` | Connect only. The Stripe account ID, which is the business of record. See [use cases](https://docs.stripe.com/connect/charges.md) to determine if this option is relevant for your integration. | Não | | `paymentMethodTypes` | `string[]` | A list of payment method types to render. You can omit this attribute to manage your payment methods in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). | Não | | `paymentMethodConfiguration` | `string` | The [payment method configuration](https://docs.stripe.com/api/payment_method_configurations.md) to use when managing your payment methods in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). If not specified, your default configuration is used. | Não | | `paymentMethodCreation` | `manual` | Allows PaymentMethods to be created from the Elements instance using [stripe.createPaymentMethod](https://docs.stripe.com/js/payment_methods/create_payment_method_elements). | Não | | `paymentMethodOptions` | `{us_bank_account: {verification_method: string}}` | Verification options for the `us_bank_account` payment method. Accepts the same verification methods as [Payment Intents](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-us_bank_account-verification_method). | Não | | `paymentMethodOptions` | `{card: {installments: {enabled: boolean}}}` | Allows manually enabling the card installment plan selection UI if applicable when you aren’t managing your payment methods in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). You must set `mode='payment'` *and* explicitly specify `paymentMethodTypes`. Otherwise an error is raised. Incompatible with `paymentMethodCreation='manual'`. | Não | | `paymentMethodOptions` | `{[paymentMethod]: {setup_future_usage: string}}` | Allows you to specify `setup_future_usage` for only payment methods that support reuse. Only applicable when `mode` is `payment`. The value for each payment method must match the corresponding `payment_method_options[paymentMethod][setup_future_usage]` on the PaymentIntent during confirmation. See the [Stripe.js reference](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-paymentMethodOptions) for supported payment methods and values. | Não | ## Add the Payment Element [Do lado do cliente] If you’re using [React Stripe.js](https://github.com/stripe/react-stripe-js), update to the latest package to use the Payment Element. You can now replace the Card Element and individual payment methods Elements with the Payment Element. The Payment Element automatically adjusts to collect input fields based on the payment method and country (for example, full billing address collection for SEPA Direct Debit) so you don’t have to maintain customized input fields anymore. The following example replaces `CardElement` with `PaymentElement`: #### JavaScript ```html
``` ```javascript const paymentElement = elements.create("payment"); paymentElement.mount("#payment-element"); ``` If your payment flow already always collects details like the customer’s name or email address, you can prevent the Payment Element from collecting this information by passing the [fields](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options-fields) option when creating the Payment Element. If you disable the collection of a certain field, you must pass that same data back with [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment). ## Update your PaymentIntent creation call [Do lado do servidor] The Payment Element allows you to accept multiple payment methods. You can manage payment methods from the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow. We prioritize payment methods that increase conversion and are most relevant to the customer’s currency and location. Any of the additional elements options passed when creating the Elements group in the earlier step should also be passed when creating the PaymentIntent. #### curl ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -H "Stripe-Version: 2026-04-22.dahlia" \ -d "amount"=1099 \ -d "currency"="usd" \-d "automatic_payment_methods[enabled]"=true \ ``` > Each payment method needs to support the currency passed in the PaymentIntent and your business needs to be based in one of the countries each payment method supports. For more details about what’s supported, see the [Payment method integration options](https://docs.stripe.com/payments/payment-methods/integration-options.md). ## Update the submit handler [Do lado do cliente] Instead of using individual confirm methods like `stripe.confirmCardPayment` or `stripe.confirmP24Payment`, use [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) to collect payment information and submit it to Stripe. To confirm the PaymentIntent, make the following updates to your submit handler: - Call `await elements.submit()` to trigger form validation and collect any data required for [wallets](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options-wallets). - Optional: Move PaymentIntent creation to the submit handler. This way you only create the PaymentIntent when you’re sure of the final amount. - Pass the `elements` instance you used to create the Payment Element and the `clientSecret` from the PaymentIntent as parameters to `stripe.confirmPayment`. When called, `stripe.confirmPayment` attempts to complete any [required actions](https://docs.stripe.com/payments/paymentintents/lifecycle.md), such as authenticating your customers by displaying a 3DS dialog or redirecting them to a bank authorization page. When confirmation is complete, users are directed to the `return_url` you configured, which normally corresponds to a page on your website that [provides the status of the payment](https://docs.stripe.com/payments/accept-a-payment.md#web-post-payment). If you want to keep the same checkout flow for card payments and only redirect for redirect-based payment methods, you can set [redirect](https://docs.stripe.com/js/payment_intents/confirm_payment#confirm_payment_intent-options-redirect) to `if_required`. The following code example replaces `stripe.confirmCardPayment` with `stripe.confirmPayment`: ### Before ```javascript // Create the PaymentIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", headers: {"Content-Type": "application/json"}, }); const {client_secret: clientSecret} = await res.json(); const handleSubmit = async (event) => { event.preventDefault(); if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } setLoading(true); if (error) { handleError(error); } }; ``` ### After ```javascript const handleSubmit = async (event) => { event.preventDefault(); if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } setLoading(true); // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create the PaymentIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", headers: {"Content-Type": "application/json"}, }); const {client_secret: clientSecret} = await res.json(); // Use the clientSecret and Elements instance to confirm the setup const {error} = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, // Uncomment below if you only want redirect for redirect-based payments // redirect: "if_required", }); if (error) { handleError(error); } }; ``` ## Optional: Recollect a CVC When creating subsequent payments on a saved card, you might want to re-collect the CVC of the card as an additional fraud measure to verify the user. Start by creating a `PaymentIntent` on your server with the amount, currency, the [Account](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer_account) or [Customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) ID, and [require_cvc_recollection](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-card-require_cvc_recollection). [List the PaymentMethods](https://docs.stripe.com/api/payment_methods/list.md) associated with your customer to determine which ones to show for CVC re-collection. After passing the `PaymentIntent`’s client secret to the browser, you can re-collect CVC information with Stripe Elements on your client. Use the `cardCvc` Element to re-collect a CVC value from your customer, then confirm the payment from your client using [stripe.confirmCardPayment](https://docs.stripe.com/js.md#stripe-confirm-card-payment). Set `payment_method` to your PaymentMethod ID, and `payment_method_options[card][cvc]` to your `cardCvc` Element. ```javascript const result = await stripe.confirmCardPayment(clientSecret, { payment_method: '{{PAYMENT_METHOD_ID}}', payment_method_options: { card: { cvc: cardCvcElement } }, }); if (result.error) { // Show error to your customer console.log(result.error.message); } else { if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } ``` O pagamento pode ser aprovado mesmo que o CVC inserido esteja incorreto. Para que isso não aconteça, configure suas [regras do Radar](https://docs.stripe.com/radar/rules.md#traditional-bank-checks) para bloquear pagamentos com falha na verificação do CVC. ## Gerenciar eventos pós-pagamento [Do lado do servidor] Stripe envia um evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) quando o pagamento é concluído. Use a [ferramenta Dashboard webhook](https://dashboard.stripe.com/webhooks) ou siga o [guia de webhooks](https://docs.stripe.com/webhooks/quickstart.md) para receber esses eventos e executar ações, como enviar um e-mail de confirmação do pedido ao cliente, registrar a venda em um banco de dados ou iniciar um fluxo de trabalho de envio. Escute esses eventos em vez de aguardar um retorno de chamada do cliente. No cliente, o consumidor pode fechar a janela do navegador ou sair do aplicativo antes da execução do retorno de chamada, o que permite que clientes mal-intencionados manipulem a resposta. Configurar sua integração para escutar eventos assíncronos é o que permite a você aceitar [diferentes tipos de formas de pagamento](https://stripe.com/payments/payment-methods-guide) com uma única integração. Além de gerenciar o evento `payment_intent.succeeded`, recomendamos gerenciar esses outros eventos ao coletar pagamentos com o Element Pagamento: | Evento | Descrição | Ação | | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded) | Enviado quando um cliente conclui um pagamento com êxito. | Envie ao cliente uma confirmação de pedido e *processe* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected) o pedido. | | [payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing) | Enviado quando um cliente inicia um pagamento, mas o pagamento ainda precisa ser concluído. Esse evento costuma ser enviado quando um cliente inicia um débito bancário. Ele é seguido por um evento `payment_intent.succeeded` ou `payment_intent.payment_failed` no futuro. | Envie ao cliente uma confirmação do pedido que indica que o pagamento está pendente. Para produtos digitais, pode ser necessário executar o pedido antes de aguardar a conclusão do pagamento. | | [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed) | Enviado quando um cliente tenta fazer um pagamento, mas o pagamento falha. | Se um pagamento passa de `processing` para `payment_failed`, ofereça ao cliente outra tentativa para pagar. | ## Testar a integração #### Cartões | Número do cartão | Cenário | Como testar | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | 4242424242424242 | O pagamento com cartão é bem-sucedido e não precisa de autenticação. | Preencha o formulário do cartão de crédito usando o número do cartão de crédito com qualquer validade, CVC e código postal. | | 4000002500003155 | O pagamento com cartão precisa de *autenticação* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase). | Preencha o formulário do cartão de crédito usando o número do cartão de crédito com qualquer validade, CVC e código postal. | | 4000000000009995 | O cartão é recusado com um código de recusa como `insufficient_funds`. | Preencha o formulário do cartão de crédito usando o número do cartão de crédito com qualquer validade, CVC e código postal. | | 6205500000000000004 | O cartão UnionPay tem um comprimento variável de 13 a 19 dígitos. | Preencha o formulário do cartão de crédito usando o número do cartão de crédito com qualquer validade, CVC e código postal. | #### Carteiras | Forma de pagamento | Cenário | Como testar | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Alipay | O cliente paga com uma forma de pagamento baseada em redirecionamento e [notificação imediata](https://docs.stripe.com/payments/payment-methods.md#payment-notification). | Escolha qualquer forma de pagamento baseada em redirecionamento, preencha os dados obrigatórios e confirme o pagamento. Em seguida, clique em **Concluir o pagamento de teste** na página de redirecionamento. | #### Débito bancário autenticado | Forma de pagamento | Cenário | Como testar | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Débito automático BECS | O cliente paga com débito automático BECS. | Preencha o formulário usando o número de conta `900123456` e BSB `000000`. Inicialmente, o status do PaymentIntent muda para `processing` e, 3 minutos depois, para `succeeded`. | | Débito automático BECS | O pagamento do cliente falha com um código de erro `account_closed`. | Preencha o formulário usando o número da conta `111111113` e BSB `000000`. | | Bancontact, EPS, iDEAL, e Przelewy24 | Seu cliente não faz a autenticação na página de redirecionamento de uma forma de pagamento baseada em redirecionamento e notificação imediata. | Escolha qualquer forma de pagamento baseada em redirecionamento, preencha os dados obrigatórios e confirme o pagamento. Em seguida, clique em **Falhar pagamento de teste** na página de redirecionamento. | | Pay by Bank | O cliente paga com uma forma de pagamento baseada em redirecionamento e [notificação posterior](https://docs.stripe.com/payments/payment-methods.md#payment-notification). | Escolha a forma de pagamento, preencha os dados obrigatórios e confirme o pagamento. Em seguida, clique em **Concluir o pagamento de teste** na página de redirecionamento. | | Pay by Bank | Seu cliente não faz a autenticação na página de redirecionamento de uma forma de pagamento baseada em redirecionamento e notificação posterior. | Escolha a forma de pagamento, preencha os dados obrigatórios e confirme o pagamento. Em seguida, clique em **Falhar o pagamento de teste** na página de redirecionamento. | | BLIK | Os pagamentos BLIK falham de várias formas: falhas imediatas (por exemplo, o código está vencido ou inválido), erros atrasados (o banco recusa) ou limites de tempo (o cliente não respondeu a tempo). | Use padrões de e-mail para [simular as diferentes falhas.](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### Débitos bancários | Forma de pagamento | Cenário | Como testar | | ---------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Débito automático SEPA | O cliente paga com débito automático SEPA. | Preencha o formulário usando o número de conta `AT321904300235473204`. Inicialmente, o status do PaymentIntent muda para processando e, três minutos depois, para bem-sucedido. | | Débito automático SEPA | O status da intenção de pagamento do cliente muda de `processing` para `requires_payment_method`. | Preencha o formulário usando o número de conta `AT861904300235473202`. | #### Boletos | Forma de pagamento | Cenário | Como testar | | ------------------ | ------------------------------------------------ | ---------------------------------------------------------------------------------------------- | | Boleto, OXXO | Seu cliente paga com um boleto ou uma guia OXXO. | Selecione boleto ou OXXO como forma de pagamento e envie o pagamento. Feche o diálogo exibido. | Consulte [Testes](https://docs.stripe.com/testing.md) para obter mais informações sobre como testar sua integração. # SetupIntent migration > This is a SetupIntent migration for when integration-path is future. View the full page at https://docs.stripe.com/payments/payment-element/migration?integration-path=future. If your existing integration uses the [Setup Intents](https://docs.stripe.com/payments/setup-intents.md) API for future payments, follow the steps below to use the Payment Element. ## Enable payment methods > This integration path doesn’t support BLIK or pre-authorized debits that use the Automated Clearing Settlement System (ACSS). Also, if you create the deferred intent from the client-side, you can’t use `customer_balance` with dynamic payment methods because the PaymentIntent requires a customer-configured [Account](https://docs.stripe.com/api/v2/core/accounts/object.md#v2_account_object-configuration-customer) or [Customer](https://docs.stripe.com/api/customers/object.md) object, which the client-side flow doesn’t support. To use `customer_balance`, create the `PaymentIntent` server-side with an `Account` or `Customer` and return its `client_secret` to the client. Veja suas [configurações de formas de pagamento](https://dashboard.stripe.com/settings/payment_methods) e habilite as formas de pagamento que deseja aceitar. Você precisa de pelo menos uma forma de pagamento habilitada para criar um *SetupIntent* (The Setup Intents API lets you build dynamic flows for collecting payment method details for future payments. It tracks the lifecycle of a payment setup flow and can trigger additional authentication steps if required by law or by the payment method). Por padrão, a Stripe habilita cartões e outras formas de pagamento predominantes que podem ajudar você a alcançar mais clientes, mas recomendamos ativar outras formas de pagamento que sejam relevantes para sua empresa e seus clientes. Consulte [Suporte a formas de pagamento](https://docs.stripe.com/payments/payment-methods/payment-method-support.md) para saber mais sobre os produtos e formas de pagamento aceitos, e nossa [página de preços](https://stripe.com/pricing/local-payment-methods) para ver as tarifas. ## Update Elements instance [Do lado do cliente] Next, update your client-side code to pass the `mode` and `currency` when you create the Elements instance. For use with a SetupIntent, set the `mode` to `'setup'` and the `currency` to what you’ll charge your customer in the future. #### Javascript ### Before ```javascript const stripe = Stripe('<>'); const elements = stripe.elements(); ``` ### After ```javascript const stripe = Stripe('<>'); const options = { mode: 'setup', currency: 'usd', }; const elements = stripe.elements(options); ``` #### React ### Before ```jsx const stripePromise = loadStripe('<>'); function App() { return ( ); }; ``` ### After ```jsx const stripePromise = loadStripe('<>'); const options = { mode: 'setup', currency: 'usd', }; function App() { return ( ); }; ``` ## Optional: Additional Elements options [Do lado do cliente] The [Elements object](https://docs.stripe.com/js/elements_object/create_without_intent) accepts additional options that influence payment collection. Based on the options provided, the Payment Element displays available payment methods from those you’ve enabled. Learn more about [payment method support](https://docs.stripe.com/payments/payment-methods/payment-method-support.md). Make sure the Elements options you provide (such as `captureMethod`, `setupFutureUsage`, and `paymentMethodOptions`) match the equivalent parameters you pass when creating and confirming the Intent. Mismatched parameters can result in unexpected behavior or errors. | Propriedade | Tipo | Descrição | Obrigatório | | ---------------------------- | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | `mode` | - `payment` - `setup` - `subscription` | Indica se o Payment Element é usado com um *PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods), *SetupIntent* (The Setup Intents API lets you build dynamic flows for collecting payment method details for future payments. It tracks the lifecycle of a payment setup flow and can trigger additional authentication steps if required by law or by the payment method) ou *assinatura* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis). | Sim | | `currency` | `string` | A moeda do valor a ser cobrado do cliente. | Sim | | `amount` | `number` | The amount to charge the customer, shown in Apple Pay, Google Pay, or BNPL UIs. | Para os modos `payment` e `subscription` | | `setupFutureUsage` | - `off_session` - `on_session` | Indicates that you intend to make future payments with the payment details collected by the Payment Element. | Não | | `captureMethod` | - `automatic` - `automatic_async` - `manual` | Controla quando capturar os fundos da conta do cliente. | Não | | `onBehalfOf` | `string` | Connect only. The Stripe account ID, which is the business of record. See [use cases](https://docs.stripe.com/connect/charges.md) to determine if this option is relevant for your integration. | Não | | `paymentMethodTypes` | `string[]` | A list of payment method types to render. You can omit this attribute to manage your payment methods in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). | Não | | `paymentMethodConfiguration` | `string` | The [payment method configuration](https://docs.stripe.com/api/payment_method_configurations.md) to use when managing your payment methods in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). If not specified, your default configuration is used. | Não | | `paymentMethodCreation` | `manual` | Allows PaymentMethods to be created from the Elements instance using [stripe.createPaymentMethod](https://docs.stripe.com/js/payment_methods/create_payment_method_elements). | Não | | `paymentMethodOptions` | `{us_bank_account: {verification_method: string}}` | Verification options for the `us_bank_account` payment method. Accepts the same verification methods as [Payment Intents](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-us_bank_account-verification_method). | Não | | `paymentMethodOptions` | `{card: {installments: {enabled: boolean}}}` | Allows manually enabling the card installment plan selection UI if applicable when you aren’t managing your payment methods in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). You must set `mode='payment'` *and* explicitly specify `paymentMethodTypes`. Otherwise an error is raised. Incompatible with `paymentMethodCreation='manual'`. | Não | | `paymentMethodOptions` | `{[paymentMethod]: {setup_future_usage: string}}` | Allows you to specify `setup_future_usage` for only payment methods that support reuse. Only applicable when `mode` is `payment`. The value for each payment method must match the corresponding `payment_method_options[paymentMethod][setup_future_usage]` on the PaymentIntent during confirmation. See the [Stripe.js reference](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-paymentMethodOptions) for supported payment methods and values. | Não | ## Add the Payment Element [Do lado do cliente] If you’re using [React Stripe.js](https://github.com/stripe/react-stripe-js), update to the latest package to use the Payment Element. You can now replace the Card Element and individual payment methods Elements with the Payment Element. The Payment Element automatically adjusts to collect input fields based on the payment method and country (for example, full billing address collection for SEPA Direct Debit) so you don’t have to maintain customized input fields anymore. The following example replaces `CardElement` with `PaymentElement`: #### JavaScript ```html
``` ```javascript const paymentElement = elements.create("payment"); paymentElement.mount("#payment-element"); ``` If your payment flow already always collects details like the customer’s name or email address, you can prevent the Payment Element from collecting this information by passing the [fields](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options-fields) option when creating the Payment Element. If you disable the collection of a certain field, you must pass that same data back with [stripe.confirmSetup](https://docs.stripe.com/js/setup_intents/confirm_setup). ## Update your SetupIntent creation call [Do lado do servidor] Because the Payment Element allows you to accept multiple payment methods, we recommend using `automatic_payment_methods`. When you enable it, Stripe evaluates the currency, payment method restrictions, and other parameters to determine the list of payment methods available for your customers. We prioritize payment methods that increase conversion and are most relevant to the currency and location of the customer. Add the `automatic_payment_methods` attribute to the endpoint on your server that creates the SetupIntent. Any of the additional elements options passed when creating the Elements group in the earlier step should also be passed when creating the SetupIntent. #### curl ```bash curl https://api.stripe.com/v1/setup_intents \ -u <>: \ -H "Stripe-Version: 2026-04-22.dahlia" \ -d "customer"="{{CUSTOMER_ID}}" \-d "automatic_payment_methods[enabled]"=true ``` > You can’t save some payment methods for future payments. For more information, see [Payment method integration options](https://docs.stripe.com/payments/payment-methods/integration-options.md). ## Update the submit handler [Do lado do cliente] Instead of using individual confirm methods like `stripe.confirmCardSetup` or `stripe.confirmP24Setup`, use [stripe.confirmSetup](https://docs.stripe.com/js/setup_intents/confirm_setup) to collect payment information and submit it to Stripe. To confirm the SetupIntent, make the following updates to your submit handler: - Call `await elements.submit()` to trigger form validation and collect any data required for [wallets](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options-wallets). - Optional: Move SetupIntent creation to the submit handler. This way you only create the SetupIntent when the user is ready to submit their payment method details. - Pass the `elements` instance you used to create the Payment Element and the `clientSecret` from the SetupIntent as parameters to `stripe.confirmSetup`. When called, `stripe.confirmSetup` attempts to complete any [required actions](https://docs.stripe.com/payments/paymentintents/lifecycle.md), such as authenticating your customers by displaying a 3DS dialog or redirecting them to a bank authorization page. When confirmation is complete, users are directed to the `return_url` you configured, which normally corresponds to a page on your website that provides the status of the `SetupIntent`. If you want to keep the same flow for saving card payment details and only redirect for redirect-based payment methods, set [redirect](https://docs.stripe.com/js/setup_intents/confirm_setup#confirm_setup_intent-options-redirect) to `if_required`. The following code examples replaces `stripe.confirmCardSetup` with `stripe.confirmSetup`: ### Before ```javascript // Create the SetupIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", headers: {"Content-Type": "application/json"}, }); const {client_secret: clientSecret} = await res.json(); const handleSubmit = async (event) => { event.preventDefault(); if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } setLoading(true); if (error) { handleError(error); } }; ``` ### After ```javascript const handleSubmit = async (event) => { event.preventDefault(); if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } setLoading(true); // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create the SetupIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", headers: {"Content-Type": "application/json"}, }); const {client_secret: clientSecret} = await res.json(); // Use the clientSecret and Elements instance to confirm the setup const {error} = await stripe.confirmSetup({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, // Uncomment below if you only want redirect for redirect-based payments // redirect: "if_required", }); if (error) { handleError(error); } }; ``` ## Testar a integração Use os detalhes de pagamento de teste e a página de redirecionamento de teste para verificar sua integração. Clique nas guias abaixo para ver os detalhes de cada forma de pagamento. #### Cartões | Forma de pagamento | Cenário | Como testar | | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | Cartão de crédito | A configuração do cartão é realizada e não precisa de *autenticação* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase). | Preencha o formulário do cartão de crédito usando o número de cartão de crédito `4242 4242 4242 4242` com qualquer validade, CVC e código postal. | | Cartão de crédito | O cartão precisa de autenticação para a configuração inicial e depois pode ser utilizado em pagamentos subsequentes. | Preencha o formulário do cartão de crédito usando o número do cartão de crédito `4000 0025 0000 3155` com qualquer validade, CVC e código postal. | | Cartão de crédito | O cartão precisa de autenticação para a configuração inicial e também precisa de autenticação para pagamentos subsequentes. | Preencha o formulário do cartão de crédito usando o número do cartão de crédito `4000 0027 6000 3184` com qualquer validade, CVC e código postal. | | Cartão de crédito | O cartão é recusado durante a configuração. | Preencha o formulário do cartão de crédito usando o número do cartão de crédito `4000 0000 0000 9995` com qualquer validade, CVC e código postal. | #### Débito bancário autenticado | Forma de pagamento | Cenário | Como testar | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Bancontact | Seu cliente configura corretamente uma forma de pagamento de débito automático SEPA para uso futuro usando Bancontact. | Use qualquer nome no formulário do Bancontact e clique em **Autorizar configuração de teste** na página de redirecionamento. | | Bancontact | Seu cliente não faz a autenticação na página de redirecionamento do Bancontact. | Use qualquer nome no formulário do Bancontact e clique em **Falhar a configuração de teste** na página de redirecionamento. | | Débito automático BECS | O cliente paga com débito automático BECS. | Preencha o formulário usando o número de conta `900123456`. Inicialmente, o status confirmado do `PaymentIntent` passa para `em processamento` e, três minutos depois, para `concluído`. | | Débito automático BECS | O pagamento do cliente falha com um código de erro `account_closed`. | Preencha o formulário usando o número de conta `111111113`. | | iDEAL | Seu cliente configura corretamente uma forma de pagamento de [débito automático SEPA](https://docs.stripe.com/payments/sepa-debit.md) para uso futuro usando iDEAL. | Use qualquer nome e banco no formulário do iDEAL e clique em **Autorizar configuração de teste** na página de redirecionamento. | | iDEAL | Seu cliente não faz a autenticação na página de redirecionamento do iDEAL. | Selecione qualquer banco e use qualquer nome no formulário do iDEAL e clique em **Falhar a configuração de teste** na página de redirecionamento. | #### Débitos bancários | Forma de pagamento | Cenário | Como testar | | ---------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Débito automático SEPA | O cliente paga com débito automático SEPA. | Preencha o formulário usando o número de conta `AT321904300235473204`. Inicialmente, o status confirmado do `PaymentIntent` passa para `em processamento` e, três minutos depois, para `concluído`. | | Débito automático SEPA | O status do `PaymentIntent` do cliente passa de `en processamento` para `requires_payment_method`. | Preencha o formulário usando o número de conta `AT861904300235473202`. | ### Teste a cobrança de um PaymentMethod de débito SEPA A confirmação do `SetupIntent` utilizando iDEAL, Bancontact ou Sofort gera um [débito automático SEPA](https://docs.stripe.com/payments/sepa-debit.md) *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs). O débito automático SEPA é uma forma de pagamento com [notificação posterior](https://docs.stripe.com/payments/payment-methods.md#payment-notification) que passa por um estado de `processamento` intermediário antes de, alguns dias depois, passar para um estado de `concluído` ou `requires_payment_method` #### E-mail Defina `payment_method.billing_details.email` para um dos seguintes valores para testar as transições de status do `PaymentIntent`. Você pode incluir seu próprio texto personalizado no início do endereço de e-mail, seguido por um underline. Por exemplo, `test_1_generatedSepaDebitIntentsFail@example.com` resulta em um PaymentMethod de débito automático SEPA que sempre falha quando usado com um `PaymentIntent`. | Endereço de e-mail | Descrição | | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | `generatedSepaDebitIntentsSucceed@example.com` | O status do `PaymentIntent` muda de `processing` para `succeeded`. | | `generatedSepaDebitIntentsSucceedDelayed@example.com` | O status do `PaymentIntent` passa de `processing` para `succeeded` após pelo menos três minutos. | | `generatedSepaDebitIntentsFail@example.com` | O status do `PaymentIntent` muda de `processing` para `requires_payment_method`. | | `generatedSepaDebitIntentsFailDelayed@example.com` | O status do `PaymentIntent` passa de `processing` para `requires_payment_method` após pelo menos três minutos. | | `generatedSepaDebitIntentsSucceedDisputed@example.com` | O status do `PaymentIntent` passa de `processing` para `succeeded`, mas uma contestação é imediatamente criada. | | `generatedSepaDebitIntentsFailsDueToInsufficientFunds@example.com` | O status do `PaymentIntent` passa de `processing` para `requires_payment_method` com o código de falha `insufficient_funds`. | #### PaymentMethod Use estes PaymentMethods para testar as transições de status do `PaymentIntent`. Esses tokens são úteis para testes automatizados, permitindo anexar imediatamente o PaymentMethod ao SetupIntent no servidor. | Forma de pagamento | Descrição | | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `pm_bancontact_generatedSepaDebitIntentsSucceed` | O status do `PaymentIntent` muda de `processing` para `succeeded`. | | `pm_bancontact_generatedSepaDebitIntentsSucceedDelayed` | O status do `PaymentIntent` passa de `processing` para `succeeded` após pelo menos três minutos. | | `pm_bancontact_generatedSepaDebitIntentsFail` | O status do `PaymentIntent` muda de `processing` para `requires_payment_method`. | | `pm_bancontact_generatedSepaDebitIntentsFailDelayed` | O status do `PaymentIntent` passa de `processing` para `requires_payment_method` após pelo menos três minutos. | | `pm_bancontact_generatedSepaDebitIntentsSucceedDisputed` | O status do `PaymentIntent` passa de `processing` para `succeeded`, mas uma contestação é imediatamente criada. | | `pm_bancontact_generatedSepaDebitIntentsFailsDueToInsufficientFunds` | O status do `PaymentIntent` passa de `processing` para `requires_payment_method` com o código de falha `insufficient_funds`. |