# Aceptar un pago con compra exprés Use a single integration to accept payments through one-click payment buttons. ![Express Checkout Element](https://b.stripecdn.com/docs-statics-srv/assets/link-in-express-checkout-element.67be6745e5a37c1c09074b0f43763cff.png) El Express Checkout Element es una integración para aceptar pagos mediante botones de métodos de pago con un solo clic. Los métodos de pago compatibles incluyen [Link](https://docs.stripe.com/payments/link.md), [Apple Pay](https://docs.stripe.com/apple-pay.md), [Google Pay](https://docs.stripe.com/google-pay.md), [PayPal](https://docs.stripe.com/payments/paypal.md), [Klarna](https://docs.stripe.com/payments/klarna.md) y [Amazon Pay](https://docs.stripe.com/payments/amazon-pay.md). Customers see different payment buttons depending on their device and browser. Compatible devices automatically support Google Pay and Link. You must complete additional steps to support Apple Pay and PayPal. ## Try the demo Toggle the prebuilt options in the demo to change the background color, layout, size, and shipping address collection. The demo displays Google Pay and Apple Pay only on their available platforms. Payment method buttons are only shown in their supported countries. If you don’t see the demo, try viewing this page in a [supported browser](https://docs.stripe.com/elements/express-checkout-element.md#supported-browsers). | Opción | Descripción | | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **País del comerciante** | Establécelo usando la [clave publicable](https://docs.stripe.com/keys.md#obtain-api-keys) que usas para [inicializar Stripe.js](https://docs.stripe.com/js/initializing). Para cambiar el país, debes desmontar el Express Checkout Element, actualizar la clave publicable y, a continuación, volver a montar el Express Checkout Element. | | **Color de fondo** | Define los colores con la [API Elements Appearance](https://docs.stripe.com/elements/appearance-api.md). Los temas de botones se heredan de la API Appearance, pero también puedes [definirlos directamente al crear el Element](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-buttonTheme). | | **Tamaño para ordenadores de sobremesa y móviles** | Usa el menú desplegable para establecer el ancho de píxel máximo del elemento principal en el que se monta el Express Checkout Element. Puedes configurarlo en 750 px (escritorio) o 320 px (móvil). | | **Máximo de columnas y filas** | Establece estos valores usando el parámetro [layout](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-layout) cuando [crees el Express Checkout Element](https://docs.stripe.com/js/elements_object/create_express_checkout_element). | | **Menú de desbordamiento** | Configura esto usando el parámetro [layout](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-layout) cuando [crees el Express Checkout Element](https://docs.stripe.com/js/elements_object/create_express_checkout_element). | | **Recolecta la dirección de envío** | Para recolectar la información de envío, debes especificar opciones al [crear](https://docs.stripe.com/js/elements_object/create_express_checkout_element) el Express Checkout Element. Obtén más información sobre [cómo recolectar datos del cliente y mostrar partidas individuales](https://docs.stripe.com/elements/express-checkout-element/accept-a-payment.md#handle-create-event). | # Checkout Sessions API > This is a Checkout Sessions API for when payment-ui is embedded-components. View the full page at https://docs.stripe.com/elements/express-checkout-element/accept-a-payment?payment-ui=embedded-components. ## Before you begin 1. Add a payment method to your browser. For example, you can add a card to your Google Pay account or to your Wallet for Safari. 1. Serve your application over HTTPS. This is required in development and in production. You can use a service such as [ngrok](https://ngrok.com/). 1. [Register your domain](https://dashboard.stripe.com/settings/payment_method_domains) in both a *sandbox* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes) and live mode. ## Configurar Stripe [Lado del servidor] Primero, [crea una cuenta de Stripe](https://dashboard.stripe.com/register) o [inicia sesión](https://dashboard.stripe.com/login). Usa nuestras bibliotecas oficiales para acceder a la API de Stripe desde tu aplicación: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Habilitar los métodos de pago By default, Stripe uses your [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) to determine which payment methods the Express Checkout Element presents. You can also configure specific payment methods on your Checkout Session using the [payment_method_types](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_method_types) attribute. ### Métodos de pago admitidos The `card` payment method type automatically enables Apple Pay and Google Pay. When using Link, you must also pass the `card` payment method type. | Método de pago | Tipo de método de pago | | -------------- | ---------------------- | | Amazon Pay | `amazon_pay` | | Apple Pay | `card` | | Google Pay | `card` | | Link | `link`, `card` | | PayPal | `paypal` | ## Create a Checkout Session [Lado del servidor] Create a Checkout Session on your server to control the payment flow. The Checkout Session defines your line items, shipping options, and other settings for the payment. ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d ui_mode=elements \ -d return_url={{RETURN_URL}} ``` Set `ui_mode` to `elements` to integrate with the Express Checkout Element. The returned Checkout Session includes a client secret, which the client uses to securely display the checkout interface. You can configure additional options on the Checkout Session: - [phone_number_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-phone_number_collection): Collect customer phone numbers - [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection): Collect shipping addresses - [shipping_options](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_options): Provide shipping rate options - [automatic_tax](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-automatic_tax): Enable automatic tax calculation ## Configura Stripe Elements [Lado del cliente] #### HTML + JS The Express Checkout Element is automatically available as a feature of Stripe.js. Include the Stripe.js script on your checkout page by adding it to the head of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Don’t include the script in a bundle or host a copy of it yourself. ```html Checkout ``` Retrieve the client secret from your server: ```javascript // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` Create a `fetchClientSecret` function to retrieve the client secret from your server: ```javascript const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); ``` Create the Checkout instance: ```javascript const checkout = stripe.initCheckoutElementsSdk({ clientSecret }); ``` #### React The Express Checkout Element is automatically available as a feature of Stripe.js. Install [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) and the [Stripe.js loader](https://www.npmjs.com/package/@stripe/stripe-js) from the npm public registry. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` Crea `clientSecret` como `Promise | string` que contenga el secreto de cliente devuelto por tu servidor. Envuelve tu solicitud de acceso con el componente [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider), especificando `clientSecret` y la instancia `Stripe`. ```jsx import React from 'react'; import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component's render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); const App = () => { return ( ); }; export default App; ``` ## Create and mount the Express Checkout Element [Lado del cliente] The Express Checkout Element contains an iframe that securely sends the payment information to Stripe over an HTTPS connection. The checkout page address must also start with `https://`, rather than `http://`, for your integration to work. #### HTML + JS The Express Checkout Element needs a place to live on your payment page. Create an empty DOM node (container) with a unique ID in your payment form. ```html
``` When the form has loaded, create an instance of the Express Checkout Element and mount it to the container DOM node: ```javascript // Create and mount the Express Checkout Element const expressCheckoutElement = checkout.createExpressCheckoutElement(); expressCheckoutElement.mount('#express-checkout-element'); ``` #### React Add the `ExpressCheckoutElement` component to your payment page: ```jsx import React from 'react'; import {useCheckout, ExpressCheckoutElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckout(); if (checkoutState.type === 'error') { return
Error: {checkoutState.error.message}
; } return (
); }; ``` ## Collect customer details and display line items [Lado del cliente] The Checkout Session you created on the server automatically determines the line items, total amount, and available payment methods. The Express Checkout Element uses this information to display the appropriate interface. #### HTML + JS ### Handle payment confirmation Listen to the [confirm event](https://docs.stripe.com/js/elements_object/express_checkout_element_confirm_event) when your customer finalizes their payment: ```javascript const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { expressCheckoutElement.on('confirm', (event) => { loadActionsResult.actions.confirm({expressCheckoutConfirmEvent: event}); }); } ``` #### React ### Handle payment confirmation Handle the `confirm` event when your customer finalizes their payment: ```jsx import {useCheckout, ExpressCheckoutElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckout(); if (checkoutState.type === 'loading') { return
Loading...
; } else if (checkoutState.type === 'error') { return
Error: {checkoutState.error.message}
; } const handleConfirmExpressCheckout = (event) => { if (checkoutState.type === 'success') { checkoutState.checkout.confirm({expressCheckoutConfirmEvent: event}); } }; return (
{checkoutState.type === 'success' && (
          {JSON.stringify(checkoutState.checkout.lineItems, null, 2)}
          Total: {checkoutState.checkout.total?.amount}
        
)}
); }; ``` ## Optional: Listen to the ready event [Lado del cliente] After mounting, the Express Checkout Element won’t show buttons for a brief period. To animate the Element when buttons appear, listen to the [ready event](https://docs.stripe.com/js/element/events/on_ready). Inspect the `availablePaymentMethods` value to determine which buttons, if any, display in the Express Checkout Element. #### HTML + JS ```javascript // Optional: If you're doing custom animations, hide the Element const expressCheckoutDiv = document.getElementById('express-checkout-element'); expressCheckoutDiv.style.visibility = 'hidden'; expressCheckoutElement.on('ready', ({availablePaymentMethods}) => { if (!availablePaymentMethods) { // No buttons will show } else { // Optional: Animate in the Element expressCheckoutDiv.style.visibility = 'initial'; } }); ``` #### React ```jsx import React, {useState} from 'react'; import {ExpressCheckoutElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { // Optional: If you're doing custom animations, hide the Element const [visibility, setVisibility] = useState('hidden'); const onReady = ({availablePaymentMethods}) => { if (!availablePaymentMethods) { // No buttons will show } else { // Optional: Animate in the Element setVisibility('initial'); } }; return (
); }; ``` ## Optional: Style the button [Lado del cliente] You can style each payment method button differently and control the overall appearance of the Express Checkout Element. #### HTML + JS ```javascript const expressCheckoutElement = checkout.createExpressCheckoutElement({ // Specify a type per payment method buttonType: { googlePay: 'checkout', applePay: 'check-out', paypal: 'buynow', }, // Specify a theme per payment method buttonTheme: { applePay: 'white-outline' }, // Height in pixels. Defaults to 44. The width is always '100%'. buttonHeight: 55 }); ``` #### React ```jsx const expressCheckoutOptions = { // Specify a type per payment method buttonType: { googlePay: 'checkout', applePay: 'check-out', paypal: 'buynow' }, // Specify a theme per payment method buttonTheme: { applePay: 'white-outline' }, // Height in pixels. Defaults to 44. The width is always '100%'. buttonHeight: 55 }; ``` ## Prueba la integración Before you go live, [test](https://docs.stripe.com/testing.md) each payment method integration. To determine a payment method’s browser compatibility, see [supported browsers](https://docs.stripe.com/elements/express-checkout-element.md#supported-browsers). If you use the Express Checkout Element within an iframe, the iframe must have the [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) attribute set to `payment *`. #### Link > No almacenes datos reales de usuarios en las cuentas *sandbox* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes) Link. Trátalas como si fueran de dominio público, ya que estas cuentas de prueba están asociadas a tu clave de publicación. Actualmente, Link solo funciona con tarjetas de crédito, tarjetas de débito y compras elegibles realizadas con cuentas bancarias de EE. UU. Link requiere el [registro de dominio](https://docs.stripe.com/payments/payment-methods/pmd-registration.md). Puedes crear cuentas de prueba (sandbox) para Link utilizando cualquier dirección de correo electrónico válida. La siguiente tabla muestra los valores fijos de códigos de verificación de un solo uso que Stripe acepta para autenticar cuentas de prueba. | Valor | Resultado | | ---------------------------------------------- | -------------------------------------------------- | | Otros 6 dígitos que no aparezca a continuación | Completado correctamente | | 000001 | Error, el código no es válido | | 000002 | Error, el código ha caducado | | 000003 | Error, se ha superado el número máximo de intentos | #### Monederos > #### Regional testing > > Stripe Elements no es compatible con Google Pay ni Apple Pay para cuentas y clientes de Stripe en la India. Por lo tanto, no puedes probar tu integración de Google Pay o Apple Pay si la dirección IP del probador está en la India, incluso si la cuenta de Stripe se encuentra fuera de la India. ### Apple Pay You can’t save Stripe test card information to Apple Pay. Instead, Stripe recognizes when you’re using your test [API keys](https://docs.stripe.com/keys.md) and returns a successful test card token for you to use. This allows you to make test payments using a live card without charging it. Make sure you’re on a [registered domain](https://docs.stripe.com/payments/payment-methods/pmd-registration.md), [supported browser](https://docs.stripe.com/elements/express-checkout-element.md#supported-browsers), and have an active card saved to your Apple Pay wallet. ### Google Pay You can’t save Stripe test card information to Google Pay. Instead, Stripe recognizes when you’re using your test API keys and returns a successful test card token for you to use. This allows you to make test payments using a live card without charging it. You can also use Google Pay’s [test card suite](https://developers.google.com/pay/api/web/guides/resources/test-card-suite) to test your integration. Make sure you’re on a [registered domain](https://docs.stripe.com/payments/payment-methods/pmd-registration.md) and [supported browser](https://docs.stripe.com/elements/express-checkout-element.md#supported-browsers), and have an active card saved to your Google Pay wallet. ### PayPal To test your PayPal integration: 1. Create a [sandbox test account](https://developer.paypal.com/dashboard/accounts), ensuring you’re in sandbox mode. 1. Click the **PayPal** button in the Express Checkout Element and use the generated email and password from the sandbox account to log in. You can’t use a personal PayPal account in a sandbox. 1. If you haven’t yet, [register](https://dashboard.stripe.com/settings/payment_method_domains) your domain. #### Amazon Pay To create a sandbox test account for Amazon Pay: 1. Click the **Amazon Pay** button in sandbox mode. 1. Click **Create your Amazon Account**. 1. Use your sandbox account to test your integration using your test [API keys](https://docs.stripe.com/keys.md). Use the following cards to simulate payments in the Amazon Pay sandbox: | Card | Outcome | | ----------------------- | --------- | | Discover ending in 9424 | Success | | Visa ending in 1111 | Success | | Visa ending in 0701 | 3D Secure | | Amex ending in 0005 | Decline | | JCB ending in 0000 | Decline | ## Optional: Use the Express Checkout Element with Stripe Connect *Connect* (Connect is Stripe's solution for multi-party businesses, such as marketplace or software platforms, to route payments between sellers, customers, and other recipients) platforms can use the Express Checkout Element with Checkout Sessions by including the connected account in the session. > #### Usa la API Accounts v2 para representar a los clientes > > Si tu integración utiliza [cuentas configuradas por](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) clientes, sustituye las referencias de `clientes` y eventos en los ejemplos de código por las referencias equivalentes de la API Accounts v2. Para obtener más información, consulta [Representar clientes con objetos Account](https://docs.stripe.com/connect/use-accounts-as-customers.md). 1. When creating the Checkout Session on your server, include the connected account: ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_...: \ -d "line_items[0][price]"="price_..." \ -d "line_items[0][quantity]"=1 \ -d "mode"="payment" \ -d "ui_mode"="elements" \ -d "return_url"="https://example.com/return" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" ``` 1. [Register all of the domains](https://docs.stripe.com/payments/payment-methods/pmd-registration.md?dashboard-or-api=api#register-your-domain-while-using-connect) where you plan to show the Express Checkout Element. ## Comunica a tus clientes qué es Stripe Stripe recoge información sobre las interacciones de los clientes con Elements para brindarte servicios, prevenir el fraude y mejorar sus servicios. Entre los datos recogidos, se incluyen el uso de cookies y direcciones IP para identificar qué Elements ha visto un cliente durante una sola sesión del proceso de compra. Tú eres responsable de divulgar y obtener todos los derechos y consentimientos necesarios para que Stripe use los datos de estas maneras. Para obtener más información, visita nuestro [centro de privacidad](https://stripe.com/legal/privacy-center#as-a-business-user-what-notice-do-i-provide-to-my-end-customers-about-stripe). ## See also - [Stripe Elements](https://docs.stripe.com/payments/elements.md) - [Checkout Sessions](https://docs.stripe.com/payments/checkout.md) - [Finalize payments on the server](https://docs.stripe.com/payments/finalize-payments-on-the-server.md) # Payment Intents API > This is a Payment Intents API for when payment-ui is elements. View the full page at https://docs.stripe.com/elements/express-checkout-element/accept-a-payment?payment-ui=elements. We recommend that you collect payment details before creating an Intent when using the Express Checkout Element. If you previously integrated with the [Payment Element](https://docs.stripe.com/payments/payment-element.md), you might need to [update your integration](https://docs.stripe.com/payments/accept-a-payment-deferred.md) to this preferred approach. ## Before you begin - Add a payment method to your browser. For example, you can add a card to your Google Pay account or to your Wallet for Safari. - Serve your application over HTTPS. This is required in development and in production. You can use a service such as [ngrok](https://ngrok.com/). - [Register your domain](https://dashboard.stripe.com/settings/payment_method_domains) in both a *sandbox* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes) and live mode. ## Configurar Stripe [Lado del servidor] Primero, [crea una cuenta de Stripe](https://dashboard.stripe.com/register) o [inicia sesión](https://dashboard.stripe.com/login). Usa nuestras bibliotecas oficiales para acceder a la API de Stripe desde tu aplicación: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Habilitar los métodos de pago By default, Stripe uses your [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) to determine which payment methods are enabled in the Express Checkout Element. To manually override which payment methods are enabled, list any that you want to enable using the `payment_method_types` attribute. - If you collect payments before creating an intent, then list payment methods in the [`paymentMethodTypes` attribute on your Elements provider options](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-paymentMethodTypes). - If you create an intent before rendering Elements, then list payment methods in the [`payment_method_types` attribute on your Intent](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-payment_method_types). ### Supported payment methods Apple Pay and Google Pay are automatically enabled when using `card` payment method type. When using Link, you must also pass the `card` payment method type. | Payment method name | Payment method API parameters | | ------------------- | ----------------------------- | | Apple Pay | `card` | | Google Pay | `card` | | Link | `link, card` | | PayPal | `paypal` | | Amazon Pay | `amazon_pay` | | Klarna | `klarna` | ## Configura Stripe Elements [Lado del cliente] #### HTML + JS The Express Checkout Element is automatically available as a feature of Stripe.js. Include the Stripe.js script on your checkout page by adding it to the head of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Don’t include the script in a bundle or host a copy of it yourself. ```html Checkout ``` Crea una instancia de Stripe con el siguiente JavaScript en tu página de finalización del proceso de compra: ```javascript // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` Then, create an instance of Elements with the [mode](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-mode) (payment, setup, or subscription), [amount](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-amount), and [currency](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-currency). These values determine which payment methods to show to your customer. See the next step for more configurable Elements options. ```javascript const options = { mode: 'payment', amount: 1099, currency: 'usd', // Customizable by using the Appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form. const elements = stripe.elements(options); ``` #### React The Express Checkout Element is automatically available as a feature of Stripe.js. Install [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) and the [Stripe.js loader](https://www.npmjs.com/package/@stripe/stripe-js) from the npm public registry. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` To use the Express Checkout Element component, wrap your checkout page component in an [Elements provider](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider). Call `loadStripe` with your publishable key, and pass the returned `Promise` to the `Elements` provider. The `Elements` provider also accepts the mode (payment, setup, or subscription), amount, and currency. Many payment methods, including Apple Pay and Google Pay, use these values within their UI. See the next step for more configurable Elements options. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutPage from './CheckoutPage'; // Make sure to call `loadStripe` outside of a component's render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const options = {mode: 'payment', amount: 1099, currency: 'usd', // Customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ## Optional: Additional Elements options [Lado del 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 Express Checkout 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. | Propiedad | Tipo | Descripción | Obligatorio | | ---------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | `mode` | - `payment` - `setup` - `subscription` | Indica si Express Checkout Element se utiliza con un *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) o *Subscription* (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). | Sí | | `currency` | `string` | La divisa del importe a cobrar al cliente. | Sí | | `amount` | `number` | The amount to charge the customer, shown in Apple Pay, Google Pay, or BNPL UIs. | Para el modo `payment` y `subscription` | | `setupFutureUsage` | - `off_session` - `on_session` | Indicates that you intend to make future payments with the payment details collected by the Express Checkout Element. Not supported for Klarna using the Express Checkout Element. | No | | `captureMethod` | - `automatic` - `automatic_async` - `manual` | Controla cuándo capturar los fondos de la cuenta del cliente. | No | | `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. | No | | `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). | No | | `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. | No | | `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). | No | | `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). | No | | `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'`. | No | | `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. | No | ## Create and mount the Express Checkout Element [Lado del cliente] The Express Checkout Element contains an iframe that securely sends the payment information to Stripe over an HTTPS connection. The checkout page address must also start with `https://`, rather than `http://`, for your integration to work. #### HTML + JS The Express Checkout Element needs a place to live on your payment page. Create an empty DOM node (container) with a unique ID in your payment form. ```html
``` When the form has loaded, create an instance of the Express Checkout Element and mount it to the container DOM node: ```javascript // Create and mount the Express Checkout Element const expressCheckoutElement = elements.create('expressCheckout'); expressCheckoutElement.mount('#express-checkout-element'); ``` #### React Add the `ExpressCheckoutElement` component to your payment page: ```jsx import React from 'react'; import {ExpressCheckoutElement} from '@stripe/react-stripe-js'; const CheckoutPage = () => { return (
); }; ``` ## Collect customer details and display line items [Lado del cliente] Pass options when [creating](https://docs.stripe.com/js/elements_object/create_express_checkout_element) the Express Checkout Element. #### HTML + JS ### Collect payer information Set `emailRequired: true` to collect emails, and `phoneNumberRequired: true` to collect phone numbers. The `billingAddressRequired` default depends on your integration: - If you pass `allowedShippingCountries`, `phoneNumberRequired`, `shippingAddressRequired`, `emailRequired`, `applePay`, `lineItems`, or `business` when creating the Express Checkout Element, `billingAddressRequired` defaults to false. - Otherwise, `billingAddressRequired` defaults to true. ```javascript elements.create('expressCheckout', { emailRequired: true, phoneNumberRequired: true }); ``` PayPal normally doesn’t provide the customer’s billing address (except for the country) or phone number. If they aren’t provided, the confirm event has empty strings for those properties. If you require the customer’s billing address or phone number, then the Express Checkout Element doesn’t display the PayPal button unless that information is available. ### Collect shipping information Set `shippingAddressRequired: true` and pass an array of [shippingRates](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-shippingRates). ```javascript elements.create('expressCheckout', { shippingAddressRequired: true, allowedShippingCountries: ['US'], shippingRates: [ { id: 'free-shipping', displayName: 'Free shipping', amount: 0, deliveryEstimate: { maximum: {unit: 'day', value: 7}, minimum: {unit: 'day', value: 5} } }, ] }); ``` Listen to the [shippingaddresschange event](https://docs.stripe.com/js/elements_object/express_checkout_element_shippingaddresschange_event) to detect when a customer selects a shipping address. You must call either `resolve` or `reject` if you choose to handle this event. > #### Shipping address privacy > > To maintain privacy, browsers might anonymize the shipping address by removing sensitive information that isn’t necessary to calculate shipping costs. Depending on the country, some fields can be missing or partially redacted. For example, the shipping address in the US can only contain a city, state, and postal code. The full shipping address appears in the [confirm event](https://docs.stripe.com/js/elements_object/express_checkout_element_confirm_event#express_checkout_element_on_confirm-handler-shippingAddress) object after the purchase is confirmed in the browser’s payment interface. ```javascript expressCheckoutElement.on('shippingaddresschange', async (event) => { const response = await fetch('/calculate-shipping', { data: JSON.stringify({ shippingAddress: event.address }) }); const result = await response.json(); event.resolve({ lineItems: result.updatedLineItems, }); }); ``` Listen to the [shippingratechange event](https://docs.stripe.com/js/elements_object/express_checkout_element_shippingratechange_event) to detect when a customer selects a shipping rate. You must call either `resolve` or `reject` if you choose to handle this event. ```javascript expressCheckoutElement.on('shippingratechange', async (event) => { const response = await fetch('/calculate-and-update-amount', { data: JSON.stringify({ shippingRate: event.shippingRate }) }); const result = await response.json(); elements.update({amount: result.amount}) event.resolve({ lineItems: result.updatedLineItems, }); }); ``` Listen to the [cancel event](https://docs.stripe.com/js/elements_object/express_checkout_element_cancel_event) to detect when a customer dismisses the payment interface. Reset the amount to the initial amount. ```javascript expressCheckoutElement.on('cancel', () => { elements.update({amount: 1099}) }); ``` ### Display line items Pass in an array of [lineItems](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-lineItems): ```javascript elements.create('expressCheckout', { lineItems: [ { name: 'Sample item', amount: 1000 }, { name: 'Tax', amount: 100 }, { name: 'Shipping cost', amount: 1000 } ] }); ``` ### Configure the Apple Pay interface Learn how to configure the Apple Pay interface. ### Merchant initiated transactions (MIT) You can set up recurring payments, deferred payments, or automatic reload payments when a user checks out with Apple Pay by requesting the relevant [merchant token type](https://docs.stripe.com/apple-pay/merchant-tokens.md?pay-element=ece&mpan=auto-reload#merchant-token-types) in the Express Checkout Element `click` event. We recommend implementing Apple Pay merchant tokens to align with Apple Pay’s latest guidelines and to future proof your integration. #### React ### Collect payer information Set `emailRequired: true` to collect emails, and `phoneNumberRequired: true` to collect phone numbers. The `billingAddressRequired` default depends on your integration: - If you pass `allowedShippingCountries`, `phoneNumberRequired`, `shippingAddressRequired`, `emailRequired`, `applePay`, `lineItems`, or `business` when creating the Express Checkout Element, `billingAddressRequired` defaults to false. - Otherwise, `billingAddressRequired` defaults to true. ```jsx const options = { emailRequired: true, phoneNumberRequired: true }; ``` ### Collect shipping information Set `shippingAddressRequired: true` and pass an array of [shippingRates](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-shippingRates): ```jsx const options = { emailRequired: true, phoneNumberRequired: true, shippingAddressRequired: true, allowedShippingCountries: ['US'], shippingRates: [ { id: 'free-shipping', displayName: 'Free shipping', amount: 0, deliveryEstimate: { maximum: {unit: 'day', value: 7}, minimum: {unit: 'day', value: 5} } }, ] }; ``` Listen to the [shippingaddresschange event](https://docs.stripe.com/js/elements_object/express_checkout_element_shippingaddresschange_event) to detect when a customer selects a shipping address. You must call either `resolve` or `reject` if you choose to handle this event. ```jsx const onShippingAddressChange = async ({resolve, address}) => { const response = await fetch('/calculate-shipping', { data: JSON.stringify({ shippingAddress: address }) }); const result = await response.json(); resolve({ lineItems: result.updatedLineItems, }); }; ``` Listen to the [shippingratechange event](https://docs.stripe.com/js/elements_object/express_checkout_element_shippingratechange_event) to detect when a customer selects a shipping rate. You must call either `resolve` or `reject` if you choose to handle this event. ```jsx const onShippingRateChange = async ({resolve, shippingRate}) => { const response = await fetch('/calculate-and-update-amount', { data: JSON.stringify({ shippingRate: shippingRate }) }); const result = await response.json(); elements.update({amount: result.amount}) resolve({ lineItems: result.updatedLineItems, }); }; ``` Listen to the [cancel event](https://docs.stripe.com/js/elements_object/express_checkout_element_cancel_event) to detect when a customer dismisses the payment interface. Reset the amount to the initial amount. ```jsx const onCancel = () => { elements.update({amount: 1099}) }; ``` Add the event handlers when creating the Element. ```jsx ``` ### Display line items Pass in an array of [lineItems](https://docs.stripe.com/js/elements_object/express_checkout_element_click_event#express_checkout_element_on_click-handler-resolve-lineItems). ```jsx const options = { lineItems: [ { name: 'Sample item', amount: 1000 }, { name: 'Tax', amount: 100 }, { name: 'Shipping cost', amount: 1000 } ] }; ``` ### Configure the Apple Pay interface Learn how to configure the Apple Pay interface. ### Merchant initiated transactions (MIT) We provide specific options to configure for Apple Pay. Set the `applePay.recurringPaymentRequest` [option](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-applePay-recurringPaymentRequest) to specify a request to set up a recurring payment. When specified, Apple Pay issues a [merchant token](https://developer.apple.com/apple-pay/merchant-tokens/) and provides the customer with a way to manage payment methods for a recurring payment. ```jsx const options = { applePay: { recurringPaymentRequest: { paymentDescription: 'My subscription', managementURL: 'https://example.com/billing', regularBilling: { amount: 2500, label: 'Monthly subscription fee', recurringPaymentIntervalUnit: 'month', recurringPaymentIntervalCount: 1, }, } } }; ``` ## Optional: Listen to the ready event [Lado del cliente] After mounting, the Express Checkout Element won’t show buttons for a brief period. To animate the Element when buttons appear, listen to the [ready event](https://docs.stripe.com/js/element/events/on_ready). Inspect the `availablePaymentMethods` value to determine which buttons, if any, display in the Express Checkout Element. #### HTML + JS ```javascript // Optional: If you're doing custom animations, hide the Element const expressCheckoutDiv = document.getElementById('express-checkout-element'); expressCheckoutDiv.style.visibility = 'hidden'; expressCheckoutElement.on('ready', ({availablePaymentMethods}) => { if (!availablePaymentMethods) { // No buttons will show } else { // Optional: Animate in the Element expressCheckoutDiv.style.visibility = 'initial'; } }); ``` #### React ```jsx import React, {useState} from 'react'; import {ExpressCheckoutElement} from '@stripe/react-stripe-js'; import {onConfirm} from './confirmHandler'; const CheckoutPage = () => { // Optional: If you're doing custom animations, hide the Element const [visibility, setVisibility] = useState('hidden'); const onReady = ({availablePaymentMethods}) => { if (!availablePaymentMethods) { // No buttons will show } else { // Optional: Animate in the Element setVisibility('initial'); } }; return (
); }; ``` ## Optional: Control when to show payment buttons [Lado del cliente] You can manage the payment methods that appear in the Express Checkout Element in several ways: - In the Stripe Dashboard’s [payment methods settings](https://dashboard.stripe.com/settings/payment_methods). - By using the [paymentMethods property](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-paymentMethods) to disable payment buttons. Using this property gives you finer control over what your customers see. The Express Checkout Element displays Apple Pay or Google Pay when the customer is on a supported platform and has an active card. If you want to always display Apple Pay and Google Pay even when the customer doesn’t have an active card, you can also configure this with `paymentMethods`. ## Optional: Style the button [Lado del cliente] You can [style](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-buttonTheme) each payment method button differently. For examples of button themes and types, see [Google’s](https://developers.google.com/pay/api/web/guides/resources/customize) and [Apple’s](https://developer.apple.com/design/human-interface-guidelines/apple-pay#Using-Apple-Pay-buttons) resources. You can also use the `borderRadius` variable in the [Appearance API](https://docs.stripe.com/elements/appearance-api.md?platform=web#commonly-used-variables): #### HTML + JS ```javascript const appearance = { variables: { // This controls the border-radius of the rendered Express Checkout Element borderRadius: '4px', } }; // Pass the appearance object to the Elements instance const elements = stripe.elements({clientSecret, appearance}); elements.create('expressCheckout', { // Specify a type per payment method // Defaults to 'buy' for Google, 'plain' for Apple, and 'paypal' for PayPal buttonType: { googlePay: 'checkout', applePay: 'check-out', paypal: 'buynow', }, // Specify a theme per payment method // Default theme is based on appearance API settings buttonTheme: { applePay: 'white-outline' }, // Height in pixels. Defaults to 44. The width is always '100%'. buttonHeight: 55 }); ``` #### React ```jsx const options = { mode: 'payment', amount: 1099, currency: 'usd',appearance: { variables: { // This controls the border-radius of the rendered Express Checkout Element borderRadius: '4px' } } }; const expressCheckoutOptions = { // Specify a type per payment method // Defaults to 'buy' for Google and 'plain' for Apple buttonType: { googlePay: 'checkout', applePay: 'check-out' }, // Specify a theme per payment method // Default theme is based on appearance API settings buttonTheme: { applePay: 'white-outline' }, // Height in pixels. Defaults to 44. The width is always '100%'. buttonHeight: 55 }; ``` Pass in these `options` while creating the Element and `Elements` provider. ```jsx ``` ## Optional: Create a ConfirmationToken [Client-side] When the customer authorizes a payment, you can create a *ConfirmationToken* (ConfirmationTokens help capture data from your client, such as your customer's payment instruments and shipping address, and are used to confirm a PaymentIntent or SetupIntent) to send to your server for additional validation or business logic prior to confirmation. You must immediately use the created ConfirmationToken to confirm a PaymentIntent or SetupIntent. #### HTML + JS ```javascript const handleError = (error) => { const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } expressCheckoutElement.on('confirm', async (event) => { ... const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create a ConfirmationToken using the details collected by the Express Checkout Element const {error, confirmationToken} = await stripe.createConfirmationToken({ elements, params: { payment_method_data: { billing_details: { name: 'Jenny Rosen', } }, return_url: 'https://example.com/order/123/complete' } }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(error); return; } // Send the ConfirmationToken ID to your server for additional logic and attach the ConfirmationToken const res = await fetch('/create-intent', { method: 'POST', body: confirmationToken.id }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent const {error: confirmError} = await stripe.confirmPayment({ clientSecret, confirmParams: { confirmation_token: confirmationToken.id }, }); if (confirmError) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(confirmError); } else { // The payment UI automatically closes with a success animation. // Your customer is redirected to your `return_url`. } }); ``` #### React ```jsx import React, { useState } from 'react'; import {useStripe, useElements, ExpressCheckoutElement} from '@stripe/react-stripe-js'; const CheckoutPage = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(); const onConfirm = async (event) => { if (!stripe) { // Stripe.js hasn't loaded yet. // Make sure to disable form submission until Stripe.js has loaded. return; } const {error: submitError} = await elements.submit(); if (submitError) { setErrorMessage(submitError.message); return; } // Create a ConfirmationToken using the details collected by the Express Checkout Element const {error, confirmationToken} = await stripe.createConfirmationToken({ elements, params: { payment_method_data: { billing_details: { name: 'Jenny Rosen', }, }, return_url: 'https://example.com/order/123/complete', } }); if (error) { // This point is only reached if there's an immediate error when // creating the ConfirmationToken. Show the error to your customer (for example, payment details incomplete) setErrorMessage(error.message); } // Send the ConfirmationToken ID to your server for additional logic and attach the ConfirmationToken const res = await fetch('/create-intent', { method: 'POST', body: confirmationToken.id }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent const {error: confirmError} = await stripe.confirmPayment({ clientSecret, confirmParams: { confirmation_token: confirmationToken.id }, }); if (confirmError) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) setErrorMessage(confirmError.message); } else { // The payment UI automatically closes with a success animation. // Your customer is redirected to your `return_url`. } }; return (
{errorMessage &&
{errorMessage}
}
); }; ``` ## Cree un PaymentIntent [Lado del servidor] Stripe uses a *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) object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process. Create a PaymentIntent on your server with an amount and currency. This must match what you set on the `stripe.elements` instance in [step 3](https://docs.stripe.com/elements/express-checkout-element/accept-a-payment.md#set-up-elements). Always decide how much to charge on the server-side, a trusted environment, as opposed to the client-side. This prevents malicious customers from choosing their own prices. #### Accounts v2 #### Ruby ```ruby require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. Stripe.api_key = '<>' post '/create-intent' do # If you used a Tax Calculation, optionally recalculate taxes # confirmation_token = Stripe::ConfirmationToken.retrieve(params[:confirmation_token_id]) # summarized_payment_details = summarize_payment_details(confirmation_token) intent = Stripe::PaymentIntent.create({ # To allow saving and retrieving payment methods, provide the Account ID. customer_account: customer_account.id, # If you used a Tax Calculation, use its `amount_total`. # amount: summarized_payment_details.amount_total, amount: 1099, currency: 'usd', # Specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: {enabled: true}, # If you used a Tax Calculation, link it to the PaymentIntent to make sure any transitions accurately reflect the tax. # hooks: { # inputs: { # tax: { # calculation: tax_calculation.id # } # } #} }, #{ # stripe_version: '2025-09-30.preview' } ) {client_secret: intent.client_secret}.to_json end ``` #### Customers v1 #### Ruby ```ruby require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = Stripe::StripeClient.new('<>') post '/create-intent' do # If you used a Tax Calculation, optionally recalculate taxes # confirmation_token = client.v1.confirmation_tokens.retrieve(params[:confirmation_token_id]) # summarized_payment_details = summarize_payment_details(confirmation_token) intent = client.v1.payment_intents.create({ # To allow saving and retrieving payment methods, provide the Customer ID. customer: customer.id, # If you used a Tax Calculation, use its `amount_total`. # amount: summarized_payment_details.amount_total, amount: 1099, currency: 'usd', # Specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: {enabled: true}, # If you used a Tax Calculation, link it to the PaymentIntent to make sure any transitions accurately reflect the tax. # hooks: { # inputs: { # tax: { # calculation: tax_calculation.id # } # } #} }, #{ # stripe_version: '2025-09-30.preview' } ) {client_secret: intent.client_secret}.to_json end ``` The returned PaymentIntent includes a *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)), which the client-side uses to securely complete the payment process instead of passing the entire PaymentIntent object. You can use different approaches to pass the client secret to the client-side. ## Envía el pago a Stripe [Lado del cliente] Use [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) to complete the payment using details from the Express Checkout Element. > #### Pre-authorized amounts > > For Amazon Pay, Klarna, and PayPal, the amount you confirm in the PaymentIntent must match the amount the buyer pre-authorized. If the amounts don’t match, the payment is declined. Provide a [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) to this function to indicate where Stripe should redirect the user after they complete the payment. Your user might be initially redirected to an intermediate site before being redirected to the `return_url`. Payments immediately redirect to the `return_url` when a payment is successful. If you don’t want to redirect after payment completion, set [redirect](https://docs.stripe.com/js/payment_intents/confirm_payment#confirm_payment_intent-options-redirect) to `if_required`. This only redirects customers that check out with redirect-based payment methods. #### HTML + JS ```javascript const handleError = (error) => { const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } expressCheckoutElement.on('confirm', async (event) => { 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', }); const {client_secret: clientSecret} = await res.json(); const {error} = await stripe.confirmPayment({ // `elements` instance used to create the Express Checkout Element elements, // `clientSecret` from the created PaymentIntent clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(error); } else { // The payment UI automatically closes with a success animation. // Your customer is redirected to your `return_url`. } }); ``` #### React ```jsx import React from 'react'; import {useStripe, useElements, ExpressCheckoutElement} from '@stripe/react-stripe-js'; const CheckoutPage = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(); const onConfirm = async (event) => { if (!stripe) { // Stripe.js hasn't loaded yet. // Make sure to disable form submission until Stripe.js has loaded. return; } const {error: submitError} = await elements.submit(); if (submitError) { setErrorMessage(submitError.message); return; } // Create the PaymentIntent and obtain clientSecret const res = await fetch('/create-intent', { method: 'POST', }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent using the details collected by the Express Checkout Element const {error} = await stripe.confirmPayment({ // `elements` instance used to create the Express Checkout Element elements, // `clientSecret` from the created PaymentIntent clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) setErrorMessage(error.message); } else { // The payment UI automatically closes with a success animation. // Your customer is redirected to your `return_url`. } }; return (
{errorMessage &&
{errorMessage}
}
); }; ``` ## Prueba la integración Before you go live, [test](https://docs.stripe.com/testing.md) each payment method integration. To determine a payment method’s browser compatibility, see [supported browsers](https://docs.stripe.com/elements/express-checkout-element.md#supported-browsers). If you use the Express Checkout Element within an iframe, the iframe must have the [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) attribute set to `payment *`. #### Link > No almacenes datos reales de usuarios en las cuentas *sandbox* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes) Link. Trátalas como si fueran de dominio público, ya que estas cuentas de prueba están asociadas a tu clave de publicación. Actualmente, Link solo funciona con tarjetas de crédito, tarjetas de débito y compras elegibles realizadas con cuentas bancarias de EE. UU. Link requiere el [registro de dominio](https://docs.stripe.com/payments/payment-methods/pmd-registration.md). Puedes crear cuentas de prueba (sandbox) para Link utilizando cualquier dirección de correo electrónico válida. La siguiente tabla muestra los valores fijos de códigos de verificación de un solo uso que Stripe acepta para autenticar cuentas de prueba. | Valor | Resultado | | ---------------------------------------------- | -------------------------------------------------- | | Otros 6 dígitos que no aparezca a continuación | Completado correctamente | | 000001 | Error, el código no es válido | | 000002 | Error, el código ha caducado | | 000003 | Error, se ha superado el número máximo de intentos | #### Monederos > #### Regional testing > > Stripe Elements no es compatible con Google Pay ni Apple Pay para cuentas y clientes de Stripe en la India. Por lo tanto, no puedes probar tu integración de Google Pay o Apple Pay si la dirección IP del probador está en la India, incluso si la cuenta de Stripe se encuentra fuera de la India. ### Apple Pay You can’t save Stripe test card information to Apple Pay. Instead, Stripe recognizes when you’re using your test [API keys](https://docs.stripe.com/keys.md) and returns a successful test card token for you to use. This allows you to make test payments using a live card without charging it. Make sure you’re on a [registered domain](https://docs.stripe.com/payments/payment-methods/pmd-registration.md), [supported browser](https://docs.stripe.com/elements/express-checkout-element.md#supported-browsers), and have an active card saved to your Apple Pay wallet. Alternatively, set the [paymentMethods](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-paymentMethods) `applePay` option to `always` to remove the requirement for an active saved card. ### Google Pay You can’t save Stripe test card information to Google Pay. Instead, Stripe recognizes when you’re using your test API keys and returns a successful test card token for you to use. This allows you to make test payments using a live card without charging it. You can also use Google Pay’s [test card suite](https://developers.google.com/pay/api/web/guides/resources/test-card-suite) to test your integration. Make sure you’re on a [registered domain](https://docs.stripe.com/payments/payment-methods/pmd-registration.md), [supported browser](https://docs.stripe.com/elements/express-checkout-element.md#supported-browsers) and have an active card saved to your Google Pay wallet. Alternatively, set the [paymentMethods](https://docs.stripe.com/js/elements_object/create_express_checkout_element#express_checkout_element_create-options-paymentMethods) `googlePay` option to `always` to remove the requirement for an active saved card. ### PayPal To test your PayPal integration: 1. Create a [sandbox test account](https://developer.paypal.com/dashboard/accounts), ensuring you’re in sandbox mode. 1. Click the **PayPal** button in the Express Checkout Element and use the generated email and password from the sandbox account to log in. You can’t use a personal PayPal account in a sandbox. 1. If you haven’t yet, [register](https://docs.stripe.com/payments/payment-methods/pmd-registration.md) your domain. #### Amazon Pay To create a sandbox test account for Amazon Pay: 1. Click the Amazon Pay button in sandbox mode. 1. Click **Create your Amazon Account**. 1. Use your sandbox account to test your integration using your test [API keys](https://docs.stripe.com/keys.md). Use the following cards to simulate payments in Amazon Pay Sandbox: | Card | Outcome | | ----------------------- | --------- | | Discover ending in 9424 | Success | | Visa ending in 1111 | Success | | Visa ending in 0701 | 3D Secure | | Amex ending in 0005 | Decline | | JCB ending in 0000 | Decline | #### Klarna Klarna requires [domain registration](https://docs.stripe.com/payments/payment-methods/pmd-registration.md). > Klarna utiliza cookies para el seguimiento de sesiones. Para probar diferentes ubicaciones de clientes, cierra la sesión del entorno de prueba de Klarna de la sesión anterior y utiliza los activadores pertinentes. A continuación, tenemos datos de prueba especialmente elegidos para los países de los clientes actualmente aceptados. En un entorno de prueba, Klarna aprueba o rechaza una transacción en función de la dirección de correo electrónico proporcionada. #### Australia | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 03/05/1994 | | Nombre | Modo de prueba | John | | Apellidos | Person-au | snow | | Calle | Wharf St | Silverwater Rd. | | Número de casa | 4 | 1-5 | | Código postal | 4877 | 2128 | | Ciudad | Port Douglas | Silverwater | | Región | QLD | NSW | | Teléfono | +61473752244 | +61473763254 | | Correo electrónico | customer@email.au | customer+denied@email.au | #### Austria | | Aprobado | Denegado | | ------------------- | ------------------ | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-at | Person-at | | Correo electrónico | customer@email.at | customer+denied@email.at | | Calle | Mariahilfer Straße | Mariahilfer Straße | | Número de casa | 47 | 47 | | Ciudad | Viena | Viena | | Código postal | 1060 | 1060 | | Teléfono | +4306762600456 | +4306762600745 | #### Bélgica | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-be | Person-be | | Correo electrónico | customer@email.be | customer+denied@email.be | | Calle | Grote Markt | Grote Markt | | Número de casa | 1 | 1 | | Ciudad | Bruselas | Bruselas | | Código postal | 1000 | 1000 | | Teléfono | +32485121291 | +32485212123 | #### Canadá | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Modo de prueba | Modo de prueba | | Apellidos | Person-ca | Person-ca | | Calle | 2693 Byron Rd | 2693 Byron Rd | | Código postal | V7H 1L9 | V7H 1L9 | | Ciudad | North Vancouver | North Vancouver | | Región | BC | BC | | Teléfono | +15197438620 | +15197308624 | | Correo electrónico | customer@email.ca | customer+denied@email.ca | #### Chequia | | Aprobado | Denegado | | ------------------- | ------------------ | ------------------------ | | Fecha de nacimiento | 01-01-1970 | 27/06/1992 | | Nombre | Prueba | Prueba | | Apellidos | Person-cz | Person-cz | | Correo electrónico | customer@email.cz | customer+denied@email.cz | | Calle | Zazvorkova 1480/11 | Zázvorkova 1480/11 | | Código postal | 155 00 | 155 00 | | Ciudad | Praha | PRAHA 13 | | Teléfono | +420771613715 | +420771623691 | #### Dinamarca | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 01-01-1980 | 10-07-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-dk | Person-dk | | Correo electrónico | customer@email.dk | customer+denied@email.dk | | Calle | Dantes Plads | Nygårdsvej | | Número de casa | 7 | 65 | | Ciudad | København Ø | København Ø | | Código postal | 1556 | 2100 | | Teléfono | +4542555628 | +4552555348 | #### Finlandia | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 01/01/1999 | 01/01/1999 | | Nombre | Prueba | Person FI | | Apellidos | Person-fi | Prueba | | Correo electrónico | customer@email.fi | customer+denied@email.fi | | Calle | Mannerheimintie | Mannerheimintie | | Número de casa | 34 | 34 | | Ciudad | Helsinki | Helsinki | | Código postal | 00100 | 00100 | | Teléfono | +358401234567 | +358401234568 | #### Francia | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 10/07/1990 | 10/07/1990 | | Lugar de nacimiento | París | París | | Nombre | Prueba | Prueba | | Apellidos | Person-fr | Person-fr | | Correo electrónico | customer@email.fr | customer+denied@email.fr | | Calle | rue La Fayette | rue La Fayette | | Número de casa | 33 | 33 | | Ciudad | París | París | | Código postal | 75009 | 75009 | | Teléfono | +33689854321 | +33687984322 | #### Alemania | | Aprobado | Denegado | | ------------------- | --------------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Mock | Prueba | | Apellidos | Mock | Person-de | | Correo electrónico | customer@email.de | customer+denied@email.de | | Calle | Neue Schönhauser Str. | Neue Schönhauser Str. | | Número de casa | 2 | 2 | | Ciudad | Berlín | Berlín | | Código postal | 10178 | 10178 | | Teléfono | +49017614284340 | +49017610927312 | #### Grecia | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Número fiscal | 090000045 | 090000045 | | Fecha de nacimiento | 01/01/1960 | 11/11/1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-gr | Test-gr | | Correo electrónico | customer@email.gr | customer+denied@email.gr | | Calle | Kephisias | Baralo | | Número de casa | 37 | 56 | | Código postal | 151 23 | 123 67 | | Ciudad | Athina | Athina | | Teléfono | +306945553624 | +306945553625 | #### Irlanda | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-ie | Person-ie | | Correo electrónico | customer@email.ie | customer+denied@email.ie | | Calle | King Street South | King Street South | | Número de casa | 30 | 30 | | Ciudad | Dublín | Dublín | | Código EIR | D02 C838 | D02 C838 | | Teléfono | +353855351400 | +353855351401 | #### Italia | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 01-01-1980 | 01-01-1980 | | Nombre | Prueba | Prueba | | Apellidos | Person-it | Person-it | | Correo electrónico | customer@email.it | customer+denied@email.it | | Código fiscal | RSSBNC80A41H501B | RSSBNC80A41H501B | | Calle | Via Enrico Fermi | Via Enrico Fermi | | Número de casa | 150 | 150 | | Ciudad | Roma | Roma | | Código postal | 00146 | 00146 | | Teléfono | +393339741231 | +393312232389 | #### Países Bajos | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-nl | Person-nl | | Correo electrónico | customer@email.nl | customer+denied@email.nl | | Calle | Osdorpplein | Osdorpplein | | Número de casa | 137 | 137 | | Ciudad | Ámsterdam | Ámsterdam | | Código postal | 1068 SR | 1068 SR | | Teléfono | +31689124321 | +31632167678 | #### Nueva Zelanda | | Aprobado | Denegado | | ------------------- | ------------------------ | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Modo de prueba | Modo de prueba | | Apellidos | Person-nz | Person-nz | | Calle | Mount Wellington Highway | Mount Wellington Highway | | Número de casa | 286 | 286 | | Código postal | 6011 | 6011 | | Ciudad | Auckland | Wellington | | Teléfono | +6427555290 | +642993007712 | | Correo electrónico | customer@email.nz | customer+denied@email.nz | #### Noruega | | Aprobado | Denegado | | ------------------- | ------------------- | ------------------------ | | Fecha de nacimiento | 01/08/1970 | 01/08/1970 | | Nombre | Jane | Prueba | | Apellidos | Prueba | Person-no | | Correo electrónico | customer@email.no | customer+denied@email.no | | Número personal | NO1087000571 | NO1087000148 | | Calle | Edvard Munchs Plass | Sæffleberggate | | Número de casa | 1 | 56 | | Ciudad | Oslo | Oslo | | Código postal | 0194 | 0563 | | Teléfono | +4740123456 | +4740123457 | #### Polonia | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 05/05/1967 | 05/05/1967 | | Nombre | Modo de prueba | Modo de prueba | | Apellidos | Person-pl | Person-pl | | Calle | Ul. Górczewska | Ul. Górczewska | | Número de casa | 124 | 124 | | Código postal | 01-460 | 01-460 | | Ciudad | Warszawa | Warszawa | | Teléfono | +48795222223 | +48795223325 | | Correo electrónico | customer@email.pl | customer+denied@email.pl | #### Portugal | | Aprobado | Denegado | | ------------------- | ------------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Modo de prueba | Modo de prueba | | Apellidos | Person-pt | Person-pt | | Calle | Avenida Dom João II | Avenida Dom João II | | Número de casa | 40 | 40 | | Código postal | 1990-094 | 1990-094 | | Ciudad | Lisboa | Lisboa | | Teléfono | +351935556731 | +351915593837 | | Correo electrónico | customer@email.pt | customer+denied@email.pt | #### Rumania | | Aprobado | Denegado | | --------------------------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 25-12-1970 | 25-12-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-ro | Person-ro | | Correo electrónico | customer@email.ro | customer+denied@email.ro | | Calle | Drumul Taberei | Drumul Taberei | | Número de casa | 35 | 35 | | Localidad | Bucarest | Bucarest | | Sector | Sectorul 6 | Sectorul 6 | | Código postal | 061357 | 061357 | | Teléfono | +40741209876 | +40707127444 | | Número de identificación personal (CNP) | 1701225193558 | | #### España | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | DNI/NIE | 99999999R | 99999999R | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-es | Person-es | | Correo electrónico | customer@email.es | customer+denied@email.es | | Calle | C. de Atocha | C. de Atocha | | Número de casa | 27 | 27 | | Ciudad | Madrid | Madrid | | Código postal | 28012 | 28012 | | Teléfono | +34672563009 | +34682425101 | #### Suecia | | Aprobado | Denegado | | ------------------- | ----------------------- | ------------------------ | | Fecha de nacimiento | 21/03/1941 | 28/10/1941 | | Nombre | Alice | Prueba | | Apellidos | Prueba | Person-se | | Correo electrónico | customer@email.se | customer+denied@email.se | | Calle | Södra Blasieholmshamnen | Karlaplan | | Número de casa | 2 | 3 | | Ciudad | Estocolmo | Estocolmo | | Código postal | 11 148 | 11 460 | | Teléfono | +46701740615 | +46701740620 | #### Suiza | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 01-01-1990 | 01/01/2000 | | Nombre | Aceptado | Cliente | | Apellidos | Person-ch | Person-ch | | Calle | Augustinergasse | Bahnhofstrasse | | Número de casa | 2 | 77 | | Código postal | 4051 | 8001 | | Ciudad | Basilea | Zürich | | Teléfono | +41758680000 | +41758680001 | | Correo electrónico | customer@email.ch | customer+denied@email.ch | #### Reino Unido | | Aprobado | Denegado | | ------------------- | --------------------- | ------------------------ | | Fecha de nacimiento | 10-07-1970 | 10-07-1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-uk | Person-uk | | Correo electrónico | customer@email.uk | customer+denied@email.uk | | Calle | New Burlington Street | New Burlington Street | | Número de casa | 10 | 10 | | Apartamento | Apt 214 | Apt 214 | | Código postal | W1S 3BE | W1S 3BE | | Ciudad | Londres | Londres | | Teléfono | +447755564318 | +447355505530 | #### Estados Unidos | | Aprobado | Denegado | | ------------------- | ----------------- | ------------------------ | | Fecha de nacimiento | 07/10/1970 | 07/10/1970 | | Nombre | Prueba | Prueba | | Apellidos | Person-us | Person-us | | Correo electrónico | customer@email.us | customer+denied@email.us | | Calle | Amsterdam Ave | Amsterdam Ave | | Número de casa | 509 | 509 | | Ciudad | Nueva York | Nueva York | | Estado | Nueva York | Nueva York | | Código postal | 10024-3941 | 10024-3941 | | Teléfono | +13106683312 | +13106354386 | ### Autenticación en dos pasos Cualquier número de seis dígitos es un código válido de autenticación en dos pasos. Utiliza `999999` para que la autenticación no se complete. ### Método de reembolso En el flujo de Klarna, puedes usar los siguientes valores de prueba para probar varios tipos de reembolso: | Tipo | Valor | | ---------------------- | ----------------------------------------------------------------------------------------------- | | Adeudo directo | DE11520513735120710131 | | Transferencia bancaria | Banco de demostración | | Tarjeta de crédito | - Número: 4111 1111 1111 1111 - CVV: 123 - Vencimiento: cualquier fecha válida en el futuro | | Tarjeta de débito | - Número: 4012 8888 8888 1881 - CVV: 123 - Vencimiento: cualquier fecha válida en el futuro | ## Optional: Use the Express Checkout Element with Stripe Connect *Connect* (Connect is Stripe's solution for multi-party businesses, such as marketplace or software platforms, to route payments between sellers, customers, and other recipients) platforms that either create direct charges or add the token to a `Customer` on the connected account must take additional steps. > #### Usa la API Accounts v2 para representar a los clientes > > Si tu integración utiliza [cuentas configuradas por](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) clientes, sustituye las referencias de `clientes` y eventos en los ejemplos de código por las referencias equivalentes de la API Accounts v2. Para obtener más información, consulta [Representar clientes con objetos Account](https://docs.stripe.com/connect/use-accounts-as-customers.md). 1. On your frontend, before creating the `ExpressCheckoutElement`, set the `stripeAccount` option on the Stripe instance: ```javascript const stripe = Stripe('<>', { apiVersion: "2026-04-22.dahlia", stripeAccount: '{{CONNECTED_ACCOUNT_ID}}', }); ``` 1. [Register all of the domains](https://docs.stripe.com/payments/payment-methods/pmd-registration.md?dashboard-or-api=api#register-your-domain-while-using-connect) where you plan to show the Express Checkout Element. ## Comunica a tus clientes qué es Stripe Stripe recoge información sobre las interacciones de los clientes con Elements para brindarte servicios, prevenir el fraude y mejorar sus servicios. Entre los datos recogidos, se incluyen el uso de cookies y direcciones IP para identificar qué Elements ha visto un cliente durante una sola sesión del proceso de compra. Tú eres responsable de divulgar y obtener todos los derechos y consentimientos necesarios para que Stripe use los datos de estas maneras. Para obtener más información, visita nuestro [centro de privacidad](https://stripe.com/legal/privacy-center#as-a-business-user-what-notice-do-i-provide-to-my-end-customers-about-stripe). ## See also - [Stripe Elements](https://docs.stripe.com/payments/elements.md) - [Collect payment details before creating an Intent](https://docs.stripe.com/payments/accept-a-payment-deferred.md) - [Finalize payments on the server](https://docs.stripe.com/payments/finalize-payments-on-the-server.md)