# Pagos con Cash App Pay Add support for Cash App Pay to your integration. > Stripe puede mostrar automáticamente a tus clientes los métodos de pago relevantes, ya que considera la moneda, las restricciones de los métodos de pago y otros parámetros. > > - Sigue la guía [Aceptar un pago](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=stripe-hosted) para crear una integración de Checkout que utilice [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). - Si no quieres usar métodos de pago dinámicos, sigue los pasos a continuación para configurar manualmente los métodos de pago en tu integración de Checkout. This guides you through enabling Cash App Pay on [Checkout](https://docs.stripe.com/payments/checkout.md), our hosted checkout form, and shows the differences between accepting a card payment and a Cash App Pay payment. ## Determinar compatibilidad **Ubicaciones comerciales admitidas**: US **Monedas admitidas**: `usd` **Monedas de pago**: `usd` **Modo de pago**: Yes **Modo configuración**: Yes **Modo suscripción**: Yes A Checkout Session must satisfy all of the following conditions to support Cash App Pay payments: - *Prices* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions) for all line items must be expressed in USD. ## Set up Stripe [Server-side] Primero, necesitas una cuenta de Stripe. [Inscríbete ahora](https://dashboard.stripe.com/register). 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' ``` ## Aceptar un pago > This guide builds on the foundational [accept a payment](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout) Checkout integration. ### Enable Cash App Pay as a payment method Al crear una nueva [sesión de Checkout](https://docs.stripe.com/api/checkout/sessions.md), debes: 1. Add `cashapp` to the list of `payment_method_types`. 1. Make sure all your `line_items` use the `usd` currency. #### Stripe-hosted page ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=cashapp" \ --data-urlencode "success_url=https://example.com/success" ``` #### Embedded form ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=cashapp" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### Completa tus pedidos After accepting a payment, learn how to [fulfill orders](https://docs.stripe.com/checkout/fulfillment.md). ## Probar tu integración #### Mobile web app testing To test your integration, choose Cash App Pay as the payment method and tap **Pay**. While testing, this redirects you to a test payment page where you can approve or decline the payment. In live mode, tapping **Pay** redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after the redirect. #### Desktop web app testing To test your integration, scan the QR code with a QR code scanning application on your mobile device. While testing, the QR code payload contains a URL that redirects you to a test payment page where you can approve or decline the test payment. In live mode, scanning the QR code redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after you scan the QR code. ## See also - [Checkout fulfillment](https://docs.stripe.com/checkout/fulfillment.md) - [Customizing Checkout](https://docs.stripe.com/payments/checkout/customization.md) # Checkout Sessions API > This is a Checkout Sessions API for when payment-ui is elements and api-integration is checkout. View the full page at https://docs.stripe.com/payments/cash-app-pay/accept-a-payment?payment-ui=elements&api-integration=checkout. Para determinar qué API satisface las necesidades de tu empresa, consulta la [guía comparativa](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md). Usa [Payment Element](https://docs.stripe.com/payments/payment-element.md) para integrar un formulario de pago de Stripe personalizado en tu sitio web o aplicación y ofrecer métodos de pago a los clientes. Para configuraciones y personalizaciones avanzadas, consulta la guía de integración [Aceptar un pago](https://docs.stripe.com/payments/accept-a-payment.md). ## Determine compatibility **Ubicaciones comerciales admitidas**: US **Monedas admitidas**: `usd` **Monedas de pago**: `usd` **Modo de pago**: Yes **Modo configuración**: Yes **Modo suscripción**: Yes A Checkout Session must satisfy all of the following conditions to support Cash App Pay payments: - *Prices* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions) for all line items must be expressed in USD. ## Set up the server [Lado del servidor] Use the official Stripe libraries to access the API from your application. #### 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' ``` ## Create a Checkout Session [Lado del servidor] Add an endpoint on your server that creates a [Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) and returns its [client secret](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) to your front end. A Checkout Session represents your customer’s session as they pay for one-time purchases or subscriptions. Checkout Sessions expire 24 hours after creation. We recommend using [dynamic payment methods](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md) to dynamically display the most relevant eligible payment methods to each customer to maximize conversion. You can also [manually list payment methods](https://docs.stripe.com/payments/payment-methods/integration-options.md#listing-payment-methods-manually), which disables dynamic payment methods. #### Gestiona los métodos de pago desde el Dashboard #### TypeScript ```javascript import express, {Express} from 'express'; const app: Express = express(); app.post('/create-checkout-session', async (req: Express.Request, res: Express.Response) => { const session = await stripe.checkout.sessions.create({ line_items: [ { price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 1099, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'elements', return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}' }); res.json({checkoutSessionClientSecret: session.client_secret}); }); app.listen(3000, () => { console.log('Running on port 3000'); }); ``` #### Manually list payment methods #### TypeScript ```javascript import express, {Express} from 'express'; const app: Express = express(); app.post('/create-checkout-session', async (req: Express.Request, res: Express.Response) => { const session = await stripe.checkout.sessions.create({ line_items: [ { price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 1099, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'elements', payment_method_types: ['cashapp'], return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}' }); res.json({checkoutSessionClientSecret: session.client_secret}); }); app.listen(3000, () => { console.log('Running on port 3000'); }); ``` ## Set up the front end [Lado del cliente] #### HTML + JS Incluye el script de Stripe.js en tu página de confirmación de compra agregándolo al `head` del archivo HTML. Carga siempre Stripe.js directamente desde js.stripe.com para cumplir con la normativa PCI. No incluyas el guion en un paquete ni alojes una copia por tu cuenta. Asegúrate de tener la última versión de Stripe.js mediante la siguiente etiqueta de script ``. Obtén más información sobre [las versiones de Stripe.js](https://docs.stripe.com/sdks/stripejs-versioning.md). ```html Checkout ``` > Stripe proporciona un paquete npm que puedes usar para cargar Stripe.js como módulo. Ver el [proyecto en GitHub](https://github.com/stripe/stripe-js). Se requiere la versión [7.0.0](https://www.npmjs.com/package/%40stripe/stripe-js/v/7.0.0) o posterior. Inicia Stripe.js. ```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( '<>', ); ``` #### React Instala [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) y el [cargador Stripe.js](https://www.npmjs.com/package/@stripe/stripe-js) desde el registro público npm. Necesitas al menos la versión 5.0.0 para React Stripe.js y la versión 8.0.0 para el cargador Stripe.js. ```bash npm install --save @stripe/react-stripe-js@^5.0.0 @stripe/stripe-js@^8.0.0 ``` Inicializa una instancia `stripe` en tu front-end con tu clave publicable. ```javascript import {loadStripe} from '@stripe/stripe-js'; const stripe = loadStripe("<>"); ``` ## Initialize Checkout [Lado del cliente] #### HTML + JS Llama a [initCheckoutElementsSdk](https://docs.stripe.com/js/custom_checkout/init) y pasa `clientSecret`. `initCheckoutElementsSdk` resuelve un objeto de [Checkout](https://docs.stripe.com/js/custom_checkout) que contiene datos de la Checkout Session y métodos para actualizarla. Lee el `total` y los `lineItems` de [actions.getSession()](https://docs.stripe.com/js/custom_checkout/session) y muéstralos en tu interfaz de usuario (IU). Esto te permite activar nuevas funcionalidades con cambios mínimos en el código. Por ejemplo, si agregas [precios manuales de monedas](https://docs.stripe.com/payments/custom/localize-prices/manual-currency-prices.md), no es necesario hacer cambios en la interfaz de usuario (IU) si muestras el `total`. ```html
``` ```javascript const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); const checkout = stripe.initCheckoutElementsSdk({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const session = loadActionsResult.actions.getSession(); const checkoutContainer = document.getElementById('checkout-container'); checkoutContainer.append(JSON.stringify(session.lineItems, null, 2)); checkoutContainer.append(document.createElement('br')); checkoutContainer.append(`Total: ${session.total.total.amount}`); } ``` #### React Integra la solicitud con el componente [CheckoutProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider), pasa `clientSecret` y la instancia `stripe`. ```jsx import React from 'react'; import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout'; import CheckoutForm from './CheckoutForm'; const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); const App = () => { return ( ); }; export default App; ``` Accede al objeto [Checkout](https://docs.stripe.com/js/custom_checkout) en el componente del formulario de confirmación de compra con el hook `useCheckout()`. El objeto `Checkout` contiene datos de la sesión de confirmación de compra y métodos para actualizarla. Lee el `total` y los `lineItems` del objeto `Checkout` y muéstralos en tu interfaz de usuario (IU). Esto te permite habilitar funcionalidades con cambios mínimos de código. Por ejemplo, agregar [precios manuales de monedas](https://docs.stripe.com/payments/custom/localize-prices/manual-currency-prices.md) no requiere cambios en la interfaz de usuario (IU) si muestras el `total`. ```jsx import React from 'react'; import {useCheckout} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => {const checkoutState = useCheckout(); if (checkoutState.type === 'loading') { return (
Loading...
); } if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } return (
{JSON.stringify(checkoutState.checkout.lineItems, null, 2)} {/* A formatted total amount */} Total: {checkoutState.checkout.total.total.amount}
); }; ``` ## Collect customer email [Lado del cliente] #### HTML + JS Debes proporcionar un correo electrónico del cliente válido cuando completas una sesión de Checkout. Estas instrucciones crean una entrada de correo electrónico y utilizan [updateEmail](https://docs.stripe.com/js/custom_checkout/update_email) desde el objeto de `Checkout`. Como alternativa, puedes hacer lo siguiente: - Pass in [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email), [customer_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) (for customers represented as customer-configured `Account` objects), or [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) (for customers represented as `Customer` objects) when creating the Checkout Session. Stripe validates emails provided this way. - Especifica un correo electrónico que ya validaste en [checkout.confirm](https://docs.stripe.com/js/custom_checkout/confirm). ```html
``` ```javascript const checkout = stripe.initCheckoutElementsSdk({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const emailInput = document.getElementById('email'); const emailErrors = document.getElementById('email-errors'); emailInput.addEventListener('input', () => { // Clear any validation errors emailErrors.textContent = ''; }); emailInput.addEventListener('blur', () => { const newEmail = emailInput.value;actions.updateEmail(newEmail).then((result) => { if (result.error) { emailErrors.textContent = result.error.message; } }); }); } ``` #### React Debes proporcionar un correo electrónico del cliente válido cuando completas una sesión de Checkout. Estas instrucciones crean una entrada de correo electrónico y utilizan [updateEmail](https://docs.stripe.com/js/react_stripe_js/checkout/update_email) desde el objeto de `Checkout`. Como alternativa, puedes hacer lo siguiente: - Pass in [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email), [customer_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) (for customers represented as customer-configured `Account` objects), or [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) (for customers represented as `Customer` objects) when creating the Checkout Session. Stripe validates emails provided this way. - Especifica un correo electrónico que ya validaste en la [confirmación](https://docs.stripe.com/js/react_stripe_js/checkout/confirm). ```jsx import React from 'react'; import {useCheckout} from '@stripe/react-stripe-js/checkout'; const EmailInput = () => { const checkoutState = useCheckout(); const [email, setEmail] = React.useState(''); const [error, setError] = React.useState(null); if (checkoutState.type === 'loading') { return (
Loading...
); } else if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } const handleBlur = () => {checkoutState.checkout.updateEmail(email).then((result) => { if (result.type === 'error') { setError(result.error); } }) }; const handleChange = (e) => { setError(null); setEmail(e.target.value); }; return (
{error &&
{error.message}
}
); }; export default EmailInput; ``` ## Recopilación de datos de pago [Lado del cliente] Recopila los datos de pago del cliente con el [Payment Element](https://docs.stripe.com/payments/payment-element.md). Payment Element es un componente de interfaz de usuario prediseñado que simplifica la recopilación de datos de pago para una variedad de métodos de pago. El Payment Element contiene un iframe que envía la información de pago a Stripe de manera segura mediante una conexión HTTPS. No coloques el Payment Element dentro de otro iframe porque, para algunos métodos de pago, se requiere la redirección a otra página para la confirmación del pago. Si optas por usar un iframe y quieres aceptar Apple Pay o Google Pay, el iframe debe tener el atributo [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) establecido en `«payment*»`. Para que la integración funcione, la dirección de la página del proceso de compra debe empezar con `https://` rather en lugar de `http://` for. Puedes probar tu integración sin usar HTTPS, pero recuerda [habilitarla](https://docs.stripe.com/security/guide.md#tls) cuando todo esté listo para aceptar pagos activos. #### HTML + JS En primer lugar, crea un elemento DOM contenedor para montar el [Payment Element](https://docs.stripe.com/payments/payment-element.md). Luego, crea una instancia del `Payment Element` usando [checkout.createPaymentElement](https://docs.stripe.com/js/custom_checkout/create_payment_element) y móntala llamando a [element.mount](https://docs.stripe.com/js/element/mount), proporcionando un selector CSS o el elemento DOM contenedor. ```html
``` ```javascript const paymentElement = checkout.createPaymentElement(); paymentElement.mount('#payment-element'); ``` Consulta la [documentación Stripe.js](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options) para ver las opciones admitidas. Puedes [personalizar el aspecto](https://docs.stripe.com/payments/checkout/customization/appearance.md) de todos los Elements pasando [elementsOptions.appearance](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions-appearance) al inicializar Checkout en el front-end. #### React Arma el componente [Payment Element](https://docs.stripe.com/payments/payment-element.md) dentro del [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider). ```jsx import React from 'react';import {PaymentElement, useCheckout} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckout(); if (checkoutState.type === 'loading') { return (
Loading...
); } if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } return (
{JSON.stringify(checkoutState.checkout.lineItems, null, 2)} {/* A formatted total amount */} Total: {checkoutState.checkout.total.total.amount} ); }; export default CheckoutForm; ``` Consulta la [documentación Stripe.js](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options) para ver las opciones admitidas. Puedes [personalizar el aspecto](https://docs.stripe.com/payments/checkout/customization/appearance.md) de todos los Elements especificando [elementsOptions.appearance](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions-appearance) en el [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider). ## Submit the payment [Lado del cliente] #### HTML + JS Presenta un botón **Pagar** que llame a [confirmar](https://docs.stripe.com/js/custom_checkout/confirm) desde la instancia de `Checkout` para enviar el pago. ```html
``` ```js const checkout = stripe.initCheckoutElementsSdk({clientSecret}); checkout.on('change', (session) => { document.getElementById('pay-button').disabled = !session.canConfirm; }); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const button = document.getElementById('pay-button'); const errors = document.getElementById('confirm-errors'); button.addEventListener('click', () => { // Clear any validation errors errors.textContent = ''; actions.confirm().then((result) => { if (result.type === 'error') { errors.textContent = result.error.message; } }); }); } ``` #### React Renderiza un botón **Pagar** que pase de[confirmar](https://docs.stripe.com/js/custom_checkout/confirm) a[useCheckout](https://docs.stripe.com/js/react_stripe_js/checkout/use_checkout) para enviar el pago. ```jsx import React from 'react'; import {useCheckout} from '@stripe/react-stripe-js/checkout'; const PayButton = () => { const checkoutState = useCheckout(); const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState(null); if (checkoutState.type !== "success") { return null; } const handleClick = () => { setLoading(true);checkoutState.checkout.confirm().then((result) => { if (result.type === 'error') { setError(result.error) } setLoading(false); }) }; return (
{error &&
{error.message}
}
) }; export default PayButton; ``` ## Prueba tu integración #### Mobile web app testing To test your integration, choose Cash App Pay as the payment method and tap **Pay**. While testing, this redirects you to a test payment page where you can approve or decline the payment. In live mode, tapping **Pay** redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after the redirect. #### Desktop web app testing To test your integration, scan the QR code with a QR code scanning application on your mobile device. While testing, the QR code payload contains a URL that redirects you to a test payment page where you can approve or decline the test payment. In live mode, scanning the QR code redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after you scan the QR code. # Payment Intents API > This is a Payment Intents API for when payment-ui is elements and api-integration is paymentintents. View the full page at https://docs.stripe.com/payments/cash-app-pay/accept-a-payment?payment-ui=elements&api-integration=paymentintents. This guide shows you how to embed a custom Stripe payment form in your website or application using the [Payment Element](https://docs.stripe.com/payments/payment-element.md). The Payment Element allows you to support Cash App Pay and other payment methods automatically. For advanced configurations and customizations, refer to the [Accept a Payment](https://docs.stripe.com/payments/accept-a-payment.md) integration guide. ## Configurar Stripe [Lado del servidor] En primer lugar, necesitas una cuenta de Stripe. [Inscríbete ahora](https://dashboard.stripe.com/register). 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' ``` ## Crear un PaymentIntent [Lado del servidor] Stripe uses a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process. #### Gestiona los métodos de pago desde el Dashboard Create a PaymentIntent on your server with an amount and currency. You can manage payment methods from the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow. Before creating the Payment Intent, make sure to turn **Cash App Pay** on in the [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) page. Decide cuánto cobrar siempre del lado del servidor, un entorno de confianza, y no del lado del cliente. Esto impide que clientes maliciosos puedan elegir sus propios precios. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" ``` #### Enumerar métodos de pago manualmente If you don’t want to use the Dashboard or want to manually specify payment methods, you can list them using the `payment_method_types` attribute. Crea un PaymentIntent en tu servidor con un importe, una moneda y una lista de métodos de pago. Decide cuánto cobrar siempre del lado del servidor, que es un entorno de confianza, y no del lado del cliente. Esto impide que clientes malintencionados puedan elegir sus propios precios. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=cashapp" ``` ### Recuperar el secreto de cliente El PaymentIntent incluye un *secreto de cliente* (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)) que el lado del cliente usa para completar el proceso de pago de forma segura. Puedes usar diferentes métodos para pasar el secreto del cliente al lado del cliente. #### Aplicación de una sola página Recupera el secreto de cliente de un punto de conexión de tu servidor con la funcionalidad `fetch` del navegador. Este método es más conveniente si tu lado del cliente es una aplicación de una sola página, especialmente, si fue diseñada con un marco de front-end moderno como React. Crea el punto de conexión del servidor que se usa para el secreto de cliente: #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` Luego recupera el secreto de cliente con JavaScript del lado del cliente: ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### Renderización del lado del servidor Especifica el secreto de cliente desde tu servidor al cliente. Este enfoque funciona mejor si tu aplicación genera contenido estático en el servidor antes de enviarlo al navegador. Agrega [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) en tu formulario de finalización de compra. En el código del lado de tu servidor, recupera el secreto de cliente de PaymentIntent: #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## Recopilación de datos de pago [Lado del cliente] Recopila los datos de pago del cliente con el [Payment Element](https://docs.stripe.com/payments/payment-element.md). Payment Element es un componente de interfaz de usuario prediseñado que simplifica la recopilación de datos de pago para una variedad de métodos de pago. El Payment Element contiene un iframe que envía la información de pago a Stripe de manera segura mediante una conexión HTTPS. No coloques el Payment Element dentro de otro iframe porque, para algunos métodos de pago, se requiere la redirección a otra página para la confirmación del pago. Si optas por usar un iframe y quieres aceptar Apple Pay o Google Pay, el iframe debe tener el atributo [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) establecido en `«payment*»`. Para que la integración funcione, la dirección de la página del proceso de compra debe empezar con `https://` rather en lugar de `http://` for. Puedes probar tu integración sin usar HTTPS, pero recuerda [habilitarla](https://docs.stripe.com/security/guide.md#tls) cuando todo esté listo para aceptar pagos activos. #### HTML + JS ### Configurar Stripe.js El Payment Element se encuentra disponible automáticamente como funcionalidad de Stripe.js. Incluye el script de Stripe.js en tu página de finalización de compra agregándolo al `head` de tu archivo HTML. Siempre debes cargar Stripe.js directamente desde js.stripe.com para cumplir con la normativa PCI. No incluyas el script en un paquete ni alojes una copia en tus sistemas. ```html Checkout ``` Crea una instancia de Stripe con el siguiente código JavaScript en tu página de pago: ```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('<>'); ``` ### Agrega el Payment Element a tu página de pago El Payment Element necesita un lugar específico en tu página de pago. Crea un nodo DOM vacío (contenedor) con un ID único en tu formulario de pago: ```html
``` Cuando se cargue el formulario anterior, crea una instancia de Payment Element y móntala en el nodo DOM del contenedor. Especifica el [secreto de cliente](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) del paso anterior en `options` cuando crees la instancia [Elements](https://docs.stripe.com/js/elements_object/create): Debes administrar el secreto de cliente con cuidado porque sirve para completar el cargo. No lo registres, no lo insertes en direcciones URL ni lo expongas a nadie que no sea el cliente. ```javascript const options = { clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in a previous stepconst elements = stripe.elements(options); // Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement on mount: // // linkAuthenticationElement.mount("#link-authentication-element", { // defaultValues: { // email: 'jenny.rosen@example.com', // } // }) // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### React ### Configurar Stripe.js Instala [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) y el [cargador de Stripe.js](https://www.npmjs.com/package/@stripe/stripe-js) desde el registro público de npm: ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Agrega y configura el proveedor Elements en tu página de pago Para usar el componente Payment Element, envuelve el componente de tu página de confirmación de compra con un [proveedor Elements](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider). Llama a `loadStripe` con tu clave publicable y especifica el valor `Promise` devuelto en el proveedor `Elements`. También debes especificar el [secreto de cliente](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) del paso anterior como `options` al proveedor `Elements`. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; 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('<>'); function App() { const options = { // passing the client secret obtained in step 3 clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Agregar el componente Payment Element Usa el componente `PaymentElement` para crear tu formulario: ```jsx import React from 'react'; import {PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { return (
// Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement // // ); }; export default CheckoutForm; ``` ## Enviar el pago a Stripe [Lado del cliente] Usa [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) para completar el pago con los datos del Payment Element. Proporciona una [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) a esta función para indicar a dónde Stripe debe redirigir al usuario después de completar el pago. Es posible que primero se redirija al usuario a un sitio intermedio, como una página de autorización del banco y, luego, a la`return_url`. Los pagos con tarjeta redirigen inmediatamente a la `return_url` cuando un pago se realiza correctamente. #### HTML + JS ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }); ``` #### React Para llamar a [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) desde el componente del formulario de pago, usa los hooks [useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) y [useElements](https://docs.stripe.com/sdks/stripejs-react.md#useelements-hook). Si prefieres componentes de clase tradicionales en lugar de hooks, puedes usar un [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). ```jsx import React, {useState} from 'react'; import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return (
{/* Show error message to your customers */} {errorMessage &&
{errorMessage}
} ); }; export default CheckoutForm; ``` Asegúrate de que la `return_url` corresponda a una página de tu sitio web que proporcione el estado del pago. Cuando Stripe redirige al cliente a la `return_url`, proporcionamos los siguientes parámetros de consulta de URL: | Parámetro | Descripción | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | El identificador único del `PaymentIntent`. | | `payment_intent_client_secret` | El [secreto de cliente](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) del objeto `PaymentIntent`. | > Si tienes herramientas que rastrean la sesión del navegador del cliente, es posible que debas agregar el dominio `stripe.com` a la lista de exclusión de referentes. Los redireccionamientos hacen que algunas herramientas creen nuevas sesiones, lo que te impide realizar un seguimiento de la sesión completa. Usa uno de los parámetros de consulta para recuperar el PaymentIntent. Examina el [estado del PaymentIntent](https://docs.stripe.com/payments/paymentintents/lifecycle.md) para decidir qué mostrarás a tus clientes. También puedes adjuntar tus propios parámetros de consulta cuando proporciones la `return_url`, que se mantendrán durante el proceso de redireccionamiento. #### HTML + JS ```javascript // Initialize Stripe.js using your publishable key const stripe = Stripe('<>'); // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { const message = document.querySelector('#message') // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': message.innerText = 'Success! Payment received.'; break; case 'processing': message.innerText = "Payment processing. We'll update you when payment is received."; break; case 'requires_payment_method': message.innerText = 'Payment failed. Please try another payment method.'; // Redirect your user back to your payment page to attempt collecting // payment again break; default: message.innerText = 'Something went wrong.'; break; } }); ``` #### React ```jsx import React, {useState, useEffect} from 'react'; import {useStripe} from '@stripe/react-stripe-js'; const PaymentStatus = () => { const stripe = useStripe(); const [message, setMessage] = useState(null); useEffect(() => { if (!stripe) { return; } // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe .retrievePaymentIntent(clientSecret) .then(({paymentIntent}) => { // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': setMessage('Success! Payment received.'); break; case 'processing': setMessage("Payment processing. We'll update you when payment is received."); break; case 'requires_payment_method': // Redirect your user back to your payment page to attempt collecting // payment again setMessage('Payment failed. Please try another payment method.'); break; default: setMessage('Something went wrong.'); break; } }); }, [stripe]); return message; }; export default PaymentStatus; ``` ## Redirect and authenticate transactions Customers can authenticate Cash App Pay transactions with mobile or desktop apps. The client the customer is using determines the authentication method after calling `confirmPayment`. #### Mobile app authentication After calling `confirmPayment`, the customers are redirected to Cash App to approve or decline the payment. After the customers authorize the payment, they’re redirected to the Payment Intent’s `return_url`. Stripe adds `payment_intent`, `payment_intent_client_secret`, `redirect_pm_type`, and `redirect_status` as URL query parameters (along with any existing query parameters in the `return_url`). An authentication session expires after 60 minutes, and the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, the customer sees a payment error and must restart the payment process. #### Desktop web app authentication After calling confirmPayment, a QR code displays on the webpage. Your customers can scan the QR code using either their mobile device’s camera or the Cash App mobile app and authenticate the payment using Cash App Pay. A few seconds after customers authenticate the payment successfully, the QR code modal closes automatically and you can fulfill the order. Stripe redirects to the `return_url` when payment is complete. If you don’t want to redirect after payment on web, pass `redirect: if_required` to the Payment Element. An authentication session expires after 60 minutes. You can refresh the QR code up to 20 times before the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, the customer sees a payment error and must restart the payment process. ## Optional: Separar la autorización de la captura You can separate authorization and capture to create a charge now, but capture funds later. Stripe cancels the PaymentIntent and sends a [payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) event if the payment isn’t captured during the 7-day window. If you know that you can’t capture the payment, we recommend [canceling the PaymentIntent](https://docs.stripe.com/refunds.md#cancel-payment) instead of waiting for the 7-day window to elapse. ### 1. Tell Stripe to authorize only To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s Cash App Pay account. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 2. Capture the funds After the authorization succeeds, the PaymentIntent [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture`. To capture the authorized funds, make a PaymentIntent [capture](https://docs.stripe.com/api/payment_intents/capture.md) request. ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` The total authorized amount is captured by default. You can also specify `amount_to_capture` which can be less or equal to the total. ### (Opcional) Cancel the authorization If you need to cancel an authorization, you can [cancel the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md). ## Optional: Gestionar eventos posteriores al pago Stripe envía un evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) cuando se completa el pago. Usa el Dashboard, un *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) personalizado o una solución de un socio para recibir estos eventos y ejecutar acciones como enviar un correo electrónico para confirmarle el pedido al cliente, registrar la venta en una base de datos o iniciar el flujo de envío. Recibe notificaciones de estos eventos en lugar de esperar una devolución de llamada del cliente. Del lado del cliente, este podría cerrar la ventana del navegador o salir de la aplicación antes de que se ejecute la devolución de llamada, y clientes malintencionados podrían manipular la respuesta. Si configuras tu integración para recibir notificaciones de estos eventos asincrónicos, también podrás aceptar más métodos de pago en el futuro. Descubre las [diferencias entre todos los métodos de pago admitidos](https://stripe.com/payments/payment-methods-guide). - **Gestionar eventos manualmente en el Dashboard** Usa el Dashboard para [ver tus pagos de prueba en el Dashboard](https://dashboard.stripe.com/test/payments), enviar recibos por correo electrónico, gestionar transferencias (a cuenta bancaria) o reintentar pagos con error. - **Crear un webhook personalizado** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **Integrar una aplicación prediseñada** Gestiona eventos empresariales comunes, como la [automatización](https://stripe.partners/?f_category=automation) o la [comercialización y las ventas](https://stripe.partners/?f_category=marketing-and-sales), integrando la aplicación de un socio. ## Prueba tu integración #### Mobile web app testing To test your integration, choose Cash App Pay as the payment method and tap **Pay**. While testing, this redirects you to a test payment page where you can approve or decline the payment. In live mode, tapping **Pay** redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after the redirect. #### Desktop web app testing To test your integration, scan the QR code with a QR code scanning application on your mobile device. While testing, the QR code payload contains a URL that redirects you to a test payment page where you can approve or decline the test payment. In live mode, scanning the QR code redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after you scan the QR code. ## Failed payments Cash App Pay uses multiple data points to decide when to decline a transaction (for example, their AI model detected high consumer fraud risk for the transaction, or the consumer has revoked your permission to charge them in Cash App). In these cases, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. Other than a payment being declined, for a Cash App Pay [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) with a status of `requires_action`, customers must complete the payment within 10 minutes after they’re redirected to Cash App. If no action is taken after 10 minutes, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. When this happens, the Payment Element renders error messages and instructs your customer to retry using a different payment method. ## Error codes The following table details common error codes and recommended actions: | Error Code | Acción recomendada | | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent_invalid_currency` | Enter the appropriate currency. Cash App Pay only supports `usd`. | | `missing_required_parameter` | Check the error message for more information about the required parameter. | | `payment_intent_payment_attempt_failed` | This code can appear in the [last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) field of a PaymentIntent. Check the error message for a detailed failure reason and suggestion on error handling. | | `payment_intent_redirect_confirmation_without_return_url` | Provide a `return_url` when confirming a PaymentIntent with Cash App Pay. | # API Direct > This is a API Direct for when payment-ui is direct-api. View the full page at https://docs.stripe.com/payments/cash-app-pay/accept-a-payment?payment-ui=direct-api. We recommend that you implement the [Elements](https://docs.stripe.com/payments/cash-app-pay/accept-a-payment.md?payment-ui=elements) integration. An Elements integration allows you to add Cash App Pay and other payment methods with significantly less effort than a Direct API integration. Accepting Cash App Pay using a Direct API integration consists of: - Creating a [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object to track a payment. - Submitting the payment to Stripe for processing. - Authenticating the payment (through a mobile application redirect or QR code). - Handling post-payment events to redirect the customer after an order succeeds or fails. ## Configurar Stripe [Lado del servidor] En primer lugar, necesitas una cuenta de Stripe. [Inscríbete ahora](https://dashboard.stripe.com/register). 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' ``` ## Crear un PaymentIntent [Lado del servidor] A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. To create a `PaymentIntent` on your server: - Specify the amount to collect and the currency. - Add `cashapp` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types) for your `PaymentIntent`. Make sure Cash App Pay is enabled in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" ``` ### Recuperar el secreto de cliente El PaymentIntent incluye un *secreto de cliente* (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)) que el lado del cliente usa para completar el proceso de pago de forma segura. Puedes usar diferentes métodos para pasar el secreto del cliente al lado del cliente. #### Aplicación de una sola página Recupera el secreto de cliente de un punto de conexión de tu servidor con la funcionalidad `fetch` del navegador. Este método es más conveniente si tu lado del cliente es una aplicación de una sola página, especialmente, si fue diseñada con un marco de front-end moderno como React. Crea el punto de conexión del servidor que se usa para el secreto de cliente: #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` Luego recupera el secreto de cliente con JavaScript del lado del cliente: ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### Renderización del lado del servidor Especifica el secreto de cliente desde tu servidor al cliente. Este enfoque funciona mejor si tu aplicación genera contenido estático en el servidor antes de enviarlo al navegador. Agrega [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) en tu formulario de finalización de compra. En el código del lado de tu servidor, recupera el secreto de cliente de PaymentIntent: #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## Submit the payment to Stripe and authenticate transactions client-side In this step, you’ll complete Cash App Pay payments on the client with [Stripe.js](https://docs.stripe.com/payments/elements.md). To authenticate a transaction, you must redirect the customer to Cash App. Include the Stripe.js script on your checkout page by adding it to the `head` of your HTML file. ```html Checkout ``` Create an instance of Stripe.js with the following JavaScript on your checkout page: ```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('<>'); ``` Use `stripe.confirmCashappPayment` to confirm the PaymentIntent on the client side. ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); // Pass the clientSecret obtained from the server in step 2 as the first argument stripe.confirmCashappPayment( clientSecret, { payment_method: { type: 'cashapp', }, return_url: 'https://www.example.com/checkout/done', }, ); }); ``` > `confirmCashappPayment` only redirects mobile browsers to your `return_url`, it doesn’t redirect desktop browsers. You can manually redirect customers using desktop browsers to your return URL after the returned promise resolves. Customers can authenticate Cash App Pay transactions with mobile or desktop apps. The client the customer is using determines the authentication method after calling `confirmCashappPayment`. #### Mobile application authentication After calling `confirmCashappPayment`, the customers are redirected to Cash App to approve or decline the payment. After the customers authorize the payment, they’re redirected to the Payment Intent’s `return_url`. Stripe adds `payment_intent`, `payment_intent_client_secret`, `redirect_pm_type`, and `redirect_status` as URL query parameters (along with any existing query parameters in the `return_url`). An authentication session expires after 60 minutes, and the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, the customer sees a payment error and must restart the payment process. #### Desktop web app authentication After calling `confirmCashappPayment`, a QR code displays on the webpage. Your customers can scan the QR code using either their mobile device’s camera or the Cash App mobile application and authenticate the payment. A few seconds after customers authenticate the payment successfully, the QR code modal closes automatically and you can fulfill the order. An authentication session expires after 60 minutes. You can refresh the QR code up to 20 times before the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, the customer sees a payment error and must restart the payment process. ## Optional: Handle redirect and authentication manually We recommend using Stripe.js to handle redirects and authentication with `confirmCashappPayment`. However, you can also handle redirects and authentication manually on your server. Specify `handleActions: false` in the `confirmCashappPayment` call. ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); // Set the clientSecret here you got in Step 2 stripe.confirmCashappPayment( clientSecret, { payment_method_data: { type: 'cashapp', }, return_url: 'https://www.example.com/checkout/done', }, { handleActions: false }, ).then((result) => { if (result.error) { // Display error to your customer. } else if (result.paymentIntent.status === "requires_action") { const nextAction = result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code; const expiresAt = nextAction.qr_code.expires_at; if (IS_MOBILE) { // This URL redirects the customer to Cash App to approve or decline the payment. const mobileAuthUrl = nextAction.mobile_auth_url; } else if (IS_DESKTOP) { // Render the QR code and display it to the customer using the below image source. const imageUrlSvg = nextAction.qr_code.image_url_svg; const imageUrlPng = nextAction.qr_code.image_url_png; } } }); }); ``` #### Mobile application authentication If a customer is paying with Cash App Pay on a mobile device: 1. Redirect the customer to the URL set as the `result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code.mobile_auth_url` property. This redirects the customer to Cash App to approve or decline the payment. 1. After the customer authorizes the payment, they’re redirected to the Payment Intent’s `return_url`. Stripe adds `payment_intent`, `payment_intent_client_secret`, `redirect_pm_type`, and `redirect_status` as URL query parameters (along with any existing query parameters in the `return_url`). 1. Note that the `mobile_auth_url` expires after 30 seconds. In case the customer isn’t redirected to `mobile_auth_url` before expiration, call [stripe.retrievePaymentIntent](https://docs.stripe.com/js/payment_intents/retrieve_payment_intent) to get a new `mobile_auth_url`. #### Desktop web app authentication If a customer is paying with Cash App Pay from a desktop web app: 1. Render the QR code and display it to the customer. Use `result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code.qr_code.image_url_png` or `image_url_svg` as an image source. For example: ```html ``` 1. The customer can scan the QR code using either their mobile device’s camera or the Cash App mobile application. They can then authenticate the payment. 1. Make the customer wait on the QR code page until Stripe fulfills the order and you know the outcome of the payment. Stripe sends the outcome in a [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) or a [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) webhook. You can either consume these payment intent webhooks server-side and return the results to the client (for example, with a persistent connection using web-socket) or implement client-side polling on your webpage to periodically fetch the status of the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md). 1. The QR code expires after 30 seconds. On expiration, call [stripe.retrievePaymentIntent](https://docs.stripe.com/js/payment_intents/retrieve_payment_intent) to get a new QR code from `result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code.qr_code`. An authentication session expires after 60 minutes. You can refresh the QR code up to 20 times before the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, the customer sees a payment error and must restart the payment process. ## Optional: Separar la autorización de la captura You can separate authorization and capture to create a charge now, but capture funds later. Stripe cancels the PaymentIntent and sends a [payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) event if the payment isn’t captured during the 7-day window. If you know that you can’t capture the payment, we recommend [canceling the PaymentIntent](https://docs.stripe.com/refunds.md#cancel-payment) instead of waiting for the 7-day window to elapse. ### 1. Tell Stripe to authorize only To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s Cash App Pay account. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 2. Capture the funds After the authorization succeeds, the PaymentIntent [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture`. To capture the authorized funds, make a PaymentIntent [capture](https://docs.stripe.com/api/payment_intents/capture.md) request. ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` The total authorized amount is captured by default. You can also specify `amount_to_capture` which can be less or equal to the total. ### (Opcional) Cancel the authorization If you need to cancel an authorization, you can [cancel the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md). ## Optional: Gestionar eventos posteriores al pago Stripe envía un evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) cuando se completa el pago. Usa el Dashboard, un *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) personalizado o una solución de un socio para recibir estos eventos y ejecutar acciones como enviar un correo electrónico para confirmarle el pedido al cliente, registrar la venta en una base de datos o iniciar el flujo de envío. Recibe notificaciones de estos eventos en lugar de esperar una devolución de llamada del cliente. Del lado del cliente, este podría cerrar la ventana del navegador o salir de la aplicación antes de que se ejecute la devolución de llamada, y clientes malintencionados podrían manipular la respuesta. Si configuras tu integración para recibir notificaciones de estos eventos asincrónicos, también podrás aceptar más métodos de pago en el futuro. Descubre las [diferencias entre todos los métodos de pago admitidos](https://stripe.com/payments/payment-methods-guide). - **Gestionar eventos manualmente en el Dashboard** Usa el Dashboard para [ver tus pagos de prueba en el Dashboard](https://dashboard.stripe.com/test/payments), enviar recibos por correo electrónico, gestionar transferencias (a cuenta bancaria) o reintentar pagos con error. - **Crear un webhook personalizado** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **Integrar una aplicación prediseñada** Gestiona eventos empresariales comunes, como la [automatización](https://stripe.partners/?f_category=automation) o la [comercialización y las ventas](https://stripe.partners/?f_category=marketing-and-sales), integrando la aplicación de un socio. ## Prueba tu integración #### Mobile web app testing To test your integration, choose Cash App Pay as the payment method and tap **Pay**. While testing, this redirects you to a test payment page where you can approve or decline the payment. In live mode, tapping **Pay** redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after the redirect. #### Desktop web app testing To test your integration, scan the QR code with a QR code scanning application on your mobile device. While testing, the QR code payload contains a URL that redirects you to a test payment page where you can approve or decline the test payment. In live mode, scanning the QR code redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after you scan the QR code. ## Failed payments Cash App Pay uses multiple data points to decide when to decline a transaction (for example, their AI model detected high consumer fraud risk for the transaction, or the consumer has revoked your permission to charge them in Cash App). In these cases, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. Other than a payment being declined, for a Cash App Pay [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) with a status of `requires_action`, customers must complete the payment within 10 minutes after they’re redirected to Cash App. If no action is taken after 10 minutes, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. When this happens, the Payment Element renders error messages and instructs your customer to retry using a different payment method. ## Error codes The following table details common error codes and recommended actions: | Error Code | Acción recomendada | | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent_invalid_currency` | Enter the appropriate currency. Cash App Pay only supports `usd`. | | `missing_required_parameter` | Check the error message for more information about the required parameter. | | `payment_intent_payment_attempt_failed` | This code can appear in the [last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) field of a PaymentIntent. Check the error message for a detailed failure reason and suggestion on error handling. | | `payment_intent_redirect_confirmation_without_return_url` | Provide a `return_url` when confirming a PaymentIntent with Cash App Pay. | # iOS > This is a iOS for when payment-ui is mobile and platform is ios. View the full page at https://docs.stripe.com/payments/cash-app-pay/accept-a-payment?payment-ui=mobile&platform=ios. We recommend you use the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios), an embeddable payment form, to add Cash App Pay and other payment methods to your integration with the least amount of effort. This guide covers how to accept Cash App Pay from your native mobile application using your own custom payment form. If you’re accepting Cash App Pay from your native mobile application, your customers are redirected to the Cash App mobile application for authentication. The purchase is completed in the Cash App mobile application, and the customer is redirected back to your native mobile application. ## Configurar Stripe [Lado del servidor] [Lado del cliente] Primero, necesitas una cuenta de Stripe. [Inscríbete ahora](https://dashboard.stripe.com/register). ### Lado del servidor Esta integración necesita puntos de conexión en tu servidor que se comuniquen con la API de Stripe. Usa las bibliotecas oficiales para acceder a la API de Stripe desde tu servidor: #### 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' ``` ### Lado del cliente El [SDK para iOS de Stripe](https://github.com/stripe/stripe-ios) es de código abierto, está [plenamente documentado](https://stripe.dev/stripe-ios/index.html) y es compatible con aplicaciones que admiten iOS 13 o posterior. #### Swift Package Manager Para instalar el SDK, sigue estos pasos: 1. En Xcode, selecciona **Archivo** > **Agregar dependencias de paquetes…** e introduce `https://github.com/stripe/stripe-ios-spm` como URL del repositorio. 1. Selecciona el número de versión más reciente en nuestra [página de versiones](https://github.com/stripe/stripe-ios/releases). 1. Agrega el producto **StripePaymentsUI** al [objetivo de tu aplicación](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app). #### CocoaPods 1. Si aún no lo has hecho, instala la última versión de [CocoaPods](https://guides.cocoapods.org/using/getting-started.html). 1. Si no tienes un [Podfile](https://guides.cocoapods.org/syntax/podfile.html), crea uno al ejecutar el siguiente comando: ```bash pod init ``` 1. Agrega esta línea a tu `Podfile`: ```podfile pod 'StripePaymentsUI' ``` 1. Ejecuta el siguiente comando: ```bash pod install ``` 1. De ahora en adelante, no olvides usar el archivo `.xcworkspace` en lugar del archivo `.xcodeproj` para abrir tu proyecto en Xcode. 1. En el futuro, para actualizar a la última versión del SDK, ejecuta lo siguiente: ```bash pod update StripePaymentsUI ``` #### Carthage 1. Si aún no lo has hecho, instala la última versión de [Carthage](https://github.com/Carthage/Carthage#installing-carthage). 1. Agrega esta línea a tu `Cartfile`: ```cartfile github "stripe/stripe-ios" ``` 1. Sigue las [instrucciones de instalación de Carthage](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos). Asegúrate de incrustar todos los frameworks obligatorios enumerados [aquí](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking). 1. En el futuro, para actualizar a la última versión del SDK, ejecuta el siguiente comando: ```bash carthage update stripe-ios --platform ios ``` #### Framework manual 1. Ve a nuestra [página de versiones de GitHub](https://github.com/stripe/stripe-ios/releases/latest) y descarga y descomprime **Stripe.xcframework.zip**. 1. Arrastra **StripePaymentsUI.xcframework** a la sección **Binarios incrustados** de la configuración **General** de tu proyecto en Xcode. Asegúrate de seleccionar **Copiar elementos si es necesario**. 1. Repite el paso 2 para todos los frameworks obligatorios enumerados [aquí](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking). 1. En el futuro, para actualizar a la última versión de nuestro SDK, repite los pasos 1 a 3. > Para obtener más detalles sobre la última versión del SDK y las versiones anteriores, consulta la página [Versiones](https://github.com/stripe/stripe-ios/releases) en GitHub. Para recibir notificaciones cuando se publique una nueva versión, [mira las versiones](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository) del repositorio. Configura el SDK con tu [clave publicable](https://dashboard.stripe.com/test/apikeys) de Stripe al iniciar la aplicación. Esto permite que tu aplicación haga solicitudes a la API de Stripe. #### Swift ```swift import UIKitimportStripePaymentsUI @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {StripeAPI.defaultPublishableKey = "<>" // do any other necessary launch configuration return true } } ``` > Usa las [claves de prueba](https://docs.stripe.com/keys.md#obtain-api-keys) durante las pruebas y el desarrollo, y tus claves para [modo activo](https://docs.stripe.com/keys.md#test-live-modes) cuando publiques tu aplicación. ## Crear un PaymentIntent [Lado del servidor] [Lado del cliente] ### Lado del servidor A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and the currency. - Add `cashapp` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types) for your `PaymentIntent`. Make sure Cash App Pay is enabled in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). - Set `payment_method_data[type]` to `cashapp` to create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) and immediately use it with this PaymentIntent. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` 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)), that you’ll use to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent. Send the client secret back to the client so you can use it in the next step. ### Lado del cliente Del lado del cliente, solicita un PaymentIntent desde tu servidor y almacena el *secreto de cliente* (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)). #### Swift ```swift class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? // ...continued from previous step override func viewDidLoad() { // ...continued from previous step startCheckout() } func startCheckout() { // Request a PaymentIntent from your server and store its client secret // Click View full sample to see a complete implementation } } ``` ## Enviar el pago a Stripe [Lado del cliente] When a customer taps to pay with Cash App Pay, confirm the `PaymentIntent` to complete the payment. Configure an `STPPaymentIntentParams` object with the `PaymentIntent` [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret). The client secret is different from your API keys that authenticate Stripe API requests. Handle it carefully, as it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer. ### Configurar una URL de retorno The iOS SDK presents a webview in your app to complete the Cash App Pay payment. When authentication is finished, the webview can automatically dismiss itself instead of having your customer close it. To enable this behavior, configure a custom URL scheme or universal link and set up your app delegate to forward the URL to the SDK. #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } return false } // This method handles opening universal link URLs (for example, "https://example.com/stripe_ios_callback") func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if userActivity.activityType == NSUserActivityTypeBrowsingWeb { if let url = userActivity.webpageURL { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } } } return false } ``` Pass the URL as the `return_url` when you confirm the PaymentIntent. After webview-based authentication finishes, Stripe redirects the user to the `return_url`. ### Confirm Cash App Pay payment Complete the payment by calling `STPPaymentHandler confirmPayment`. This presents a webview where the customer can complete the payment with Cash App Pay. Upon completion, the completion block is called with the result of the payment. #### Swift ```swift let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) // Cash App Pay doesn't require additional parameters so we only need to pass the initialized // STPPaymentMethodCashAppParams instance to STPPaymentMethodParams let cashApp = STPPaymentMethodCashAppParams() let paymentMethodParams = STPPaymentMethodParams(cashApp: cashApp, billingDetails: nil, metadata: nil) paymentIntentParams.paymentMethodParams = paymentMethodParams paymentIntentParams.returnURL = "payments-example://stripe-redirect" STPPaymentHandler.shared().confirmPayment(paymentIntentParams, with: self) { (handlerStatus, paymentIntent, error) in switch handlerStatus { case .succeeded: // Payment succeeded // ... case .canceled: // Payment canceled // ... case .failed: // Payment failed // ... @unknown default: fatalError() } } ``` ## Optional: Separar la autorización de la captura You can separate authorization and capture to create a charge now, but capture funds later. Stripe cancels the PaymentIntent and sends a [payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) event if the payment isn’t captured during the 7-day window. If you know that you can’t capture the payment, we recommend [canceling the PaymentIntent](https://docs.stripe.com/refunds.md#cancel-payment) instead of waiting for the 7-day window to elapse. ### 1. Tell Stripe to authorize only To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s Cash App Pay account. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 2. Capture the funds After the authorization succeeds, the PaymentIntent [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture`. To capture the authorized funds, make a PaymentIntent [capture](https://docs.stripe.com/api/payment_intents/capture.md) request. ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` The total authorized amount is captured by default. You can also specify `amount_to_capture` which can be less or equal to the total. ### (Opcional) Cancel the authorization If you need to cancel an authorization, you can [cancel the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md). ## Optional: Gestionar eventos posteriores al pago Stripe envía un evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) cuando se completa el pago. Usa el Dashboard, un *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) personalizado o una solución de un socio para recibir estos eventos y ejecutar acciones como enviar un correo electrónico para confirmarle el pedido al cliente, registrar la venta en una base de datos o iniciar el flujo de envío. Recibe notificaciones de estos eventos en lugar de esperar una devolución de llamada del cliente. Del lado del cliente, este podría cerrar la ventana del navegador o salir de la aplicación antes de que se ejecute la devolución de llamada, y clientes malintencionados podrían manipular la respuesta. Si configuras tu integración para recibir notificaciones de estos eventos asincrónicos, también podrás aceptar más métodos de pago en el futuro. Descubre las [diferencias entre todos los métodos de pago admitidos](https://stripe.com/payments/payment-methods-guide). - **Gestionar eventos manualmente en el Dashboard** Usa el Dashboard para [ver tus pagos de prueba en el Dashboard](https://dashboard.stripe.com/test/payments), enviar recibos por correo electrónico, gestionar transferencias (a cuenta bancaria) o reintentar pagos con error. - **Crear un webhook personalizado** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **Integrar una aplicación prediseñada** Gestiona eventos empresariales comunes, como la [automatización](https://stripe.partners/?f_category=automation) o la [comercialización y las ventas](https://stripe.partners/?f_category=marketing-and-sales), integrando la aplicación de un socio. ## Prueba tu integración Test your Cash App Pay integration with your test API keys by viewing the redirect page. You can test the successful payment case by authenticating the payment on the redirect page. The [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) transitions from `requires_action` to `succeeded`. To test the case where the user fails to authenticate, use your test API keys and view the redirect page. On the redirect page, click **Fail test payment**. The [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) transitions from `requires_action` to `requires_payment_method`. For test manual capture PaymentIntents, the uncaptured [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) auto-expires 7 days after successful authorization. In live mode, tapping **Pay** redirects you to the Cash App mobile application—you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after the redirect. ## Failed payments Cash App Pay uses multiple data points to decide when to decline a transaction (for example, their AI model detected high consumer fraud risk for the transaction, or the consumer has revoked your permission to charge them in Cash App). In these cases, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. Other than a payment being declined, for a Cash App Pay [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) with a status of `requires_action`, customers must complete the payment within 10 minutes after they’re redirected to Cash App. If no action is taken after 10 minutes, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. When this happens, the Payment Element renders error messages and instructs your customer to retry using a different payment method. ## Error codes The following table details common error codes and recommended actions: | Error Code | Acción recomendada | | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent_invalid_currency` | Enter the appropriate currency. Cash App Pay only supports `usd`. | | `missing_required_parameter` | Check the error message for more information about the required parameter. | | `payment_intent_payment_attempt_failed` | This code can appear in the [last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) field of a PaymentIntent. Check the error message for a detailed failure reason and suggestion on error handling. | | `payment_intent_redirect_confirmation_without_return_url` | Provide a `return_url` when confirming a PaymentIntent with Cash App Pay. | # Android > This is a Android for when payment-ui is mobile and platform is android. View the full page at https://docs.stripe.com/payments/cash-app-pay/accept-a-payment?payment-ui=mobile&platform=android. We recommend you use the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android), an embeddable payment form, to add Cash App Pay and other payment methods to your integration with the least amount of effort. This guide covers how to accept Cash App Pay from your native mobile application using your own custom payment form. If you’re accepting Cash App Pay from your native mobile application, your customers are redirected to the Cash App mobile application for authentication. The purchase is completed in the Cash App mobile application, and the customer is redirected back to your native mobile application. ## Configurar Stripe [Lado del servidor] [Lado del cliente] Primero, necesitas una cuenta de Stripe. [Inscríbete ahora](https://dashboard.stripe.com/register). ### Lado del servidor Esta integración necesita puntos de conexión en tu servidor que se comuniquen con la API de Stripe. Usa las bibliotecas oficiales para acceder a la API de Stripe desde tu servidor: #### 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' ``` ### Lado del cliente El [SDK para Android de Stripe](https://github.com/stripe/stripe-android) es de código abierto y está [completamente documentado](https://stripe.dev/stripe-android/). Para instalar el SDK, agrega `stripe-android` al bloque `dependencies` de tu archivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Stripe Android SDK implementation("com.stripe:stripe-android:23.2.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.2.0") } ``` > Para conocer detalles de la última versión y de versiones anteriores del SDK, consulta la página [Versiones](https://github.com/stripe/stripe-android/releases) en GitHub. Para recibir una notificación cuando se publique una nueva versión, [mira las versiones del repositorio](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository). Configura el SDK con tu [clave publicable](https://dashboard.stripe.com/apikeys) de Stripe para que pueda hacer solicitudes a la API de Stripe, así como en tu subclase `Application`: #### Kotlin ```kotlin import com.stripe.android.PaymentConfiguration class MyApp : Application() { override fun onCreate() { super.onCreate() PaymentConfiguration.init( applicationContext, "<>" ) } } ``` > Usa las [claves de prueba](https://docs.stripe.com/keys.md#obtain-api-keys) durante las pruebas y el desarrollo, y tus claves para [modo activo](https://docs.stripe.com/keys.md#test-live-modes) cuando publiques tu aplicación. Los ejemplos de Stripe también utilizan [OkHttp](https://github.com/square/okhttp) y [GSON](https://github.com/google/gson) para hacer solicitudes HTTP a un servidor. ## Crear un PaymentIntent [Lado del servidor] [Lado del cliente] ### Lado del servidor A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and the currency. - Add `cashapp` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types) for your `PaymentIntent`. Make sure Cash App Pay is enabled in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). - Set `payment_method_data[type]` to `cashapp` to create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) and immediately use it with this PaymentIntent. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` 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)), that you’ll use to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent. Send the client secret back to the client so you can use it in the next step. ### Lado del cliente Del lado del cliente, solicita un PaymentIntent desde tu servidor y almacena el *secreto de cliente* (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)). #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... startCheckout() } private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click View full sample to see a complete implementation } } ``` ## Enviar el pago a Stripe [Lado del cliente] When a customer taps to pay with Cash App Pay, confirm the `PaymentIntent` to complete the payment. Configure a `ConfirmPaymentIntentParams` object with the `PaymentIntent` [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret). The client secret is different from your API keys that authenticate Stripe API requests. Handle it carefully, as it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer. ### Confirm Cash App Pay payment Complete the payment by calling [PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/confirm.html). This presents a webview where the customer can complete the payment with Cash App Pay. Upon completion, the provided `PaymentResultCallback` is called with the result of the payment. #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { // ... private val paymentLauncher: PaymentLauncher by lazy { val paymentConfiguration = PaymentConfiguration.getInstance(applicationContext) PaymentLauncher.create( activity = this, publishableKey = paymentConfiguration.publishableKey, stripeAccountId = paymentConfiguration.stripeAccountId, callback = ::onPaymentResult, ) } // … private fun startCheckout() { // ... val cashAppPayParams = PaymentMethodCreateParams.createCashAppPay() val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = cashAppPayParams, clientSecret = paymentIntentClientSecret, // Add a mandate ID or MandateDataParams if you // want to set this up for future use… ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { // Handle the payment result… } } ``` ## Optional: Separar la autorización de la captura You can separate authorization and capture to create a charge now, but capture funds later. Stripe cancels the PaymentIntent and sends a [payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) event if the payment isn’t captured during the 7-day window. If you know that you can’t capture the payment, we recommend [canceling the PaymentIntent](https://docs.stripe.com/refunds.md#cancel-payment) instead of waiting for the 7-day window to elapse. ### 1. Tell Stripe to authorize only To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s Cash App Pay account. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 2. Capture the funds After the authorization succeeds, the PaymentIntent [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture`. To capture the authorized funds, make a PaymentIntent [capture](https://docs.stripe.com/api/payment_intents/capture.md) request. ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` The total authorized amount is captured by default. You can also specify `amount_to_capture` which can be less or equal to the total. ### (Opcional) Cancel the authorization If you need to cancel an authorization, you can [cancel the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md). ## Optional: Gestionar eventos posteriores al pago Stripe envía un evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) cuando se completa el pago. Usa el Dashboard, un *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) personalizado o una solución de un socio para recibir estos eventos y ejecutar acciones como enviar un correo electrónico para confirmarle el pedido al cliente, registrar la venta en una base de datos o iniciar el flujo de envío. Recibe notificaciones de estos eventos en lugar de esperar una devolución de llamada del cliente. Del lado del cliente, este podría cerrar la ventana del navegador o salir de la aplicación antes de que se ejecute la devolución de llamada, y clientes malintencionados podrían manipular la respuesta. Si configuras tu integración para recibir notificaciones de estos eventos asincrónicos, también podrás aceptar más métodos de pago en el futuro. Descubre las [diferencias entre todos los métodos de pago admitidos](https://stripe.com/payments/payment-methods-guide). - **Gestionar eventos manualmente en el Dashboard** Usa el Dashboard para [ver tus pagos de prueba en el Dashboard](https://dashboard.stripe.com/test/payments), enviar recibos por correo electrónico, gestionar transferencias (a cuenta bancaria) o reintentar pagos con error. - **Crear un webhook personalizado** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **Integrar una aplicación prediseñada** Gestiona eventos empresariales comunes, como la [automatización](https://stripe.partners/?f_category=automation) o la [comercialización y las ventas](https://stripe.partners/?f_category=marketing-and-sales), integrando la aplicación de un socio. ## Prueba tu integración Test your Cash App Pay integration with your test API keys by viewing the redirect page. You can test the successful payment case by authenticating the payment on the redirect page. The [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) transitions from `requires_action` to `succeeded`. To test the case where the user fails to authenticate, use your test API keys and view the redirect page. On the redirect page, click **Fail test payment**. The [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) transitions from `requires_action` to `requires_payment_method`. For test manual capture PaymentIntents, the uncaptured [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) auto-expires 7 days after successful authorization. There are some differences between how *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 payments work. For example, in live mode, tapping **Pay** redirects you to the Cash App mobile application. Within Cash App, you don’t have the option to approve or decline the payment within Cash App. The payment is automatically approved after the redirect. ## Failed payments Cash App Pay uses multiple data points to decide when to decline a transaction (for example, their AI model detected high consumer fraud risk for the transaction, or the consumer has revoked your permission to charge them in Cash App). In these cases, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. Other than a payment being declined, for a Cash App Pay [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) with a status of `requires_action`, customers must complete the payment within 10 minutes after they’re redirected to Cash App. If no action is taken after 10 minutes, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. When this happens, the Payment Element renders error messages and instructs your customer to retry using a different payment method. ## Error codes The following table details common error codes and recommended actions: | Error Code | Acción recomendada | | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent_invalid_currency` | Enter the appropriate currency. Cash App Pay only supports `usd`. | | `missing_required_parameter` | Check the error message for more information about the required parameter. | | `payment_intent_payment_attempt_failed` | This code can appear in the [last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) field of a PaymentIntent. Check the error message for a detailed failure reason and suggestion on error handling. | | `payment_intent_redirect_confirmation_without_return_url` | Provide a `return_url` when confirming a PaymentIntent with Cash App Pay. | # React Native > This is a React Native for when payment-ui is mobile and platform is react-native. View the full page at https://docs.stripe.com/payments/cash-app-pay/accept-a-payment?payment-ui=mobile&platform=react-native. Cash App Pay is a payment method available to all Cash App customers for single use and recurring payments to businesses. Cash App Pay uses the customer’s stored balance or linked debit card to fund the payment. The customer can confirm the payment in one of two ways: - During checkout from a mobile device, your site redirects customers to the Cash App mobile application for authentication. The payment is authenticated during the redirect. No additional action is needed in the Cash App mobile application to complete the purchase. The customer is then redirected back to your site. - During checkout from a desktop web application, the customer scans a QR code with their mobile device to authenticate the transaction. Customers can also authorize the use of Cash App Pay for future, on-file payments. ## Configurar Stripe [Lado del servidor] [Lado del cliente] En primer lugar, necesitas una cuenta de Stripe. [Inscríbete ahora](https://dashboard.stripe.com/register). ### Lado del servidor Esta integración necesita puntos de conexión en tu servidor que se comuniquen con la API de Stripe. Usa las bibliotecas oficiales para acceder a la API de Stripe desde tu servidor: #### 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' ``` ### Lado del cliente El [SDK para React Native](https://github.com/stripe/stripe-react-native) es de código abierto y está plenamente documentado. Internamente, utiliza SDK para [iOS nativo](https://github.com/stripe/stripe-ios) y [Android](https://github.com/stripe/stripe-android). Para instalar el SDK para React Native de Stripe, ejecuta uno de los siguientes comandos en el directorio del proyecto (según el administrador de paquetes que utilices): #### hilado ```bash yarn add @stripe/stripe-react-native ``` #### npm ```bash npm install @stripe/stripe-react-native ``` A continuación, instala otras dependencias necesarias: - Para iOS, vaya al directorio **ios** y ejecute `pod install` para asegurarse de que también instala las dependencias nativas necesarias. - Para Android, no hay más dependencias para instalar. > Recomendamos seguir la [guía oficial de TypeScript](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project) para agregar soporte para TypeScript. ### Inicialización de Stripe Para inicializar Stripe en tu aplicación React Native, ajusta tu pantalla de pago con el componente `StripeProvider` o usa el método de inicialización `initStripe`. Solo se requiere la [clave publicable](https://docs.stripe.com/keys.md#obtain-api-keys) de la API en `publishableKey`. El siguiente ejemplo muestra cómo inicializar Stripe usando el componente `StripeProvider`. ```jsx import { useState, useEffect } from 'react'; import { StripeProvider } from '@stripe/stripe-react-native'; function App() { const [publishableKey, setPublishableKey] = useState(''); const fetchPublishableKey = async () => { const key = await fetchKey(); // fetch key from your server here setPublishableKey(key); }; useEffect(() => { fetchPublishableKey(); }, []); return ( {/* Your app code here */} ); } ``` > Usa las [claves de prueba](https://docs.stripe.com/keys.md#obtain-api-keys) de la API durante las pruebas y el desarrollo, y tus claves para [modo activo](https://docs.stripe.com/keys.md#test-live-modes) cuando publiques tu aplicación. ## Crear un PaymentIntent [Lado del servidor] [Lado del cliente] ### Lado del servidor A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and the currency. - Add `cashapp` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types) for your `PaymentIntent`. Make sure Cash App Pay is enabled in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` 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)), that you’ll use to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent. Send the client secret back to the client so you can use it in the next step. ### Lado del cliente Del lado del cliente, solicita un PaymentIntent desde tu servidor y almacena el *secreto de cliente* (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)): ```javascript function PaymentScreen() { const fetchPaymentIntentClientSecret = async () => { const response = await fetch(`${API_URL}/create-payment-intent`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ currency: 'usd', }), }); const {clientSecret} = await response.json(); return clientSecret; }; const handlePayPress = async () => { // See below }; return (