Ir a contenido
Crea una cuenta o inicia sesión
Logotipo de la documentación de Stripe
/
Pregúntale a la IA
Crear cuentaIniciar sesión
Empezar
Pagos
Ingresos
Plataformas y marketplaces
Gestión del dinero
Recursos para desarrolladores
API y SDKAyuda
ResumenAceptar un pagoActualiza tu integración
Pagos por Internet
ResumenEncuentra tu caso de uso
Utiliza Payment Links
Usa una página de proceso de compra prediseñada
Crea una integración personalizada con Elements
    Resumen
    Guías QuickStart
    Stripe Elements
      Payment Element
      Express Checkout Element
        Aceptar un pago con compra exprés
        Migrar al Express Checkout Element
      Address Element
      Currency Selector Element
      Link Authentication Element
      Elemento de mensajería de método de pago
      Elemento ID fiscal
      Crea una integración con un formulario de pago integrable
    Compara Checkout Sessions con PaymentIntents
    Diseña una integración avanzada
    Personaliza el estilo
    Gestiona los métodos de pago
    Recolecta información adicional
    Crea la integración de las suscripciones
    Actualizaciones dinámicas
    Añadir descuentos
    Recaudar impuestos sobre tus pagos
    Canjear créditos
    Permite que los clientes paguen en su divisa local
    Guarda y recupera los métodos de pago del cliente
    Envía recibos y facturas pagadas
    Acepta pagos manualmente en tu servidor
    Autoriza y captura un pago por separado
    Elements con registro de cambios beta de la API Checkout Sessions
Desarrolla una integración en la aplicación
Usa Managed PaymentsPagos recurrentes
Pagos en persona
Terminal
Métodos de pago
Añadir métodos de pago
Gestiona los métodos de pago
Proceso de compra más rápido con Link
Aspectos básicos de las operaciones de pago
Análisis
Saldos y plazos de liquidación
Cumplimiento de la normativa y seguridad
Divisas
Pagos rechazados
Disputas
Prevención de fraude
Protección antifraude de Radar
Transferencias
RecibosReembolsos y cancelaciones
Integraciones avanzadas
Flujos de pagos personalizados
Capacidad adquirente flexible
Orquestación de varios responsables del tratamiento
Más allá de los pagos
Constituye tu empresa
Criptomonedas
Comercio agéntico
Financial Connections
Climate
Verificar identidades
Estados Unidos
Español (España)
InicioPagosBuild a custom integration with ElementsStripe ElementsExpress Checkout Element

Aceptar un pago con compra exprés

Use a single integration to accept payments through one-click payment buttons.

Express Checkout Element

The Express Checkout Element is an integration for accepting payments through one-click payment method buttons. Supported payment methods include Link, Apple Pay, Google Pay, PayPal, Klarna, and Amazon Pay.

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.

OpciónDescripción
País del comercianteEstablécelo usando la clave publicable que usas para inicializar Stripe.js. 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 fondoDefine los colores con la API Elements Appearance. Los temas de botones se heredan de la API Appearance, pero también puedes definirlos directamente al crear el Element.
Tamaño para ordenadores de sobremesa y móvilesUsa 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 filasEstablece estos valores usando el parámetro layout cuando crees el Express Checkout Element.
Menú de desbordamientoConfigura esto usando el parámetro layout cuando crees el Express Checkout Element.
Recolecta la dirección de envíoPara recolectar la información de envío, debes especificar opciones al crear el Express Checkout Element. Obtén más información sobre cómo recolectar datos del cliente y mostrar partidas individuales.

Cosas a tener en cuenta

  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.
  2. Serve your application over HTTPS. This is required in development and in production. You can use a service such as ngrok.
  3. Register your domain in both a sandbox and live mode.

Configurar Stripe
Lado del servidor

Primero, crea una cuenta de Stripe o inicia sesión.

Usa nuestras bibliotecas oficiales para acceder a la API de Stripe desde tu aplicación:

Command Line
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# Available as a gem sudo gem install stripe
Gemfile
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# 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 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 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 pagoTipo de método de pago
Amazon Payamazon_pay
Apple Paycard
Google Paycard
Linklink, card
PayPalpaypal

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.

Command Line
cURL
Stripe CLI
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
curl https://api.stripe.com/v1/checkout/sessions \ -u "
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:"
\ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d ui_mode=custom \ -d return_url={{RETURN_URL}}

Set ui_mode to custom 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: Collect customer phone numbers
  • shipping_address_collection: Collect shipping addresses
  • shipping_options: Provide shipping rate options
  • automatic_tax: Enable automatic tax calculation

Configura Stripe Elements
Lado del cliente

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.

checkout.html
<head> <title>Checkout</title> <script src="https://js.stripe.com/clover/stripe.js"></script> </head>

Retrieve the client secret from your server:

checkout.js
// 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(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
);

Create a fetchClientSecret function to retrieve the client secret from your server:

checkout.js
const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret);

Create the Checkout instance:

checkout.js
const checkout = stripe.initCheckout({ clientSecret });

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.

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.

checkout.html
<div id="express-checkout-element"> <!-- Express Checkout Element will be inserted here --> </div> <div id="error-message"> <!-- Display an error message to your customers here --> </div>

When the form has loaded, create an instance of the Express Checkout Element and mount it to the container DOM node:

checkout.js
// Create and mount the Express Checkout Element const expressCheckoutElement = checkout.createExpressCheckoutElement(); expressCheckoutElement.mount('#express-checkout-element');

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.

Handle payment confirmation

Listen to the confirm event when your customer finalizes their payment:

checkout.js
const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { expressCheckoutElement.on('confirm', (event) => { loadActionsResult.actions.confirm({expressCheckoutConfirmEvent: event}); }); }

Handle dynamic updates

If you need to update the Checkout Session based on customer selections (such as shipping address or shipping rate changes), you can listen to events and update the session:

checkout.js
expressCheckoutElement.on('shippingaddresschange', async (event) => { const response = await fetch('/update-session-shipping', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ sessionId: checkout.session.id, shippingAddress: event.address }) }); const result = await response.json(); if (result.error) { event.reject(); } else { event.resolve(); } }); expressCheckoutElement.on('shippingratechange', async (event) => { const response = await fetch('/update-session-shipping-rate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ sessionId: checkout.session.id, shippingRateId: event.shippingRate.id }) }); const result = await response.json(); if (result.error) { event.reject(); } else { event.resolve(); } });

OpcionalListen 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. Inspect the availablePaymentMethods value to determine which buttons, if any, display in the Express Checkout Element.

checkout.js
// 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'; } });

OpcionalStyle the button
Lado del cliente

You can style each payment method button differently and control the overall appearance of the Express Checkout Element.

checkout.js
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 });

Prueba la integración

Before you go live, test each payment method integration. To determine a payment method’s browser compatibility, see supported browsers. If you use the Express Checkout Element within an iframe, the iframe must have the allow attribute set to payment *.

Precaución

No almacenes datos de usuarios reales en las cuentas de Link del entorno de prueba. Úsalas como si estuvieran disponibles para el público, porque estas cuentas de prueba están asociadas con tu clave publicable.

Actualmente, Link solo funciona con tarjetas de crédito, tarjetas de débito y compras con cuentas bancarias cualificadas de EE. UU. Link requiere el registro del dominio.

Puedes crear cuentas en el entorno de prueba para Link usando cualquier dirección de correo electrónico válida. La siguiente tabla muestra los valores fijos de código de acceso de un solo uso que Stripe acepta para autenticar las cuentas en el entorno de prueba:

ValorResultado
Otros 6 dígitos que no aparezca a continuaciónCompletado correctamente
000001Error, el código no es válido
000002Error, el código ha caducado
000003Error, se ha superado el número máximo de intentos

OpcionalUse the Express Checkout Element with Stripe Connect

Connect platforms can use the Express Checkout Element with Checkout Sessions by including the connected account in the session.

Compara las referencias de Customers v1 y Accounts v2

Si tu plataforma Connect utiliza Cuentas configuradas por el cliente, utiliza nuestra guía para reemplazar las referencias del cliente y de los eventos en tu código por las referencias equivalentes de la API Accounts v2.

  1. When creating the Checkout Session on your server, include the connected account:

    Command Line
    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"="custom" \ -d "return_url"="https://example.com/return" \ -H "Stripe-Account:
    {{CONNECTED_ACCOUNT_ID}}
    "
  2. Register all of the domains 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.

También podría interesarte...

  • Stripe Elements
  • Checkout Sessions
  • Finalize payments on the server
¿Te ha sido útil la página?
SíNo
  • ¿Necesitas ayuda? Ponte en contacto con el equipo de soporte.
  • Echa un vistazo a nuestro registro de cambios.
  • ¿Tienes alguna pregunta? Ponte en contacto con el equipo de ventas.
  • ¿LLM? Lee llms.txt.
  • Con tecnología de Markdoc