# Completa los pedidos Descubre cómo completar los pagos recibidos con la API Checkout Sessions. # Full hosted page > This is a Full hosted page for when payment-ui is stripe-hosted. View the full page at https://docs.stripe.com/checkout/fulfillment?payment-ui=stripe-hosted. When you receive a payment with the Checkout Sessions API (including Payment Links), you might need to take action to provide your customer with what they paid for. For example, you might need to grant them access to a service, or you might need to ship them physical goods. This process is known as fulfillment, and you have two ways to handle this process: - **Manualmente**: Puedes completar los pedidos manualmente con la información que Stripe pone a tu disposición. Por ejemplo, puedes supervisar el [Dashboard](https://docs.stripe.com/dashboard/basics.md), consultar los correos electrónicos de las notificaciones de pago, consultar los informes y, a continuación, completar los pedidos. - **Automáticamente**: puedes crear un sistema de gestión logística automatizado. (Recomendado) The first option works for low volume or experimental ventures, but for most situations we recommend automating fulfillment. The rest of this guide shows you how to build an automatic fulfillment system. ## Tramitación automática de pedidos The automatic fulfillment system outlined below uses a combination of *webhooks* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) and a redirect to your website to trigger fulfillment. You must use webhooks to make sure fulfillment happens for every payment, and redirects let your customers access services or fulfillment details immediately after paying. > Payment Links usa Checkout, por lo que toda la información que aparece a continuación se aplica tanto a Payment Links como a Checkout, a menos que se indique lo contrario. ## Crea una función de tramitación de pedidos [Lado del servidor] Crea una función en tu servidor para completar los pagos realizados correctamente. Los webhooks activan esta función, y se llama cuando los clientes son redirigidos a tu sitio web después de completar el proceso de compra. Esta guía se refiere a esta función como `fulfill_checkout`, pero puedes nombrarla como desees. Perform fulfillment only once per payment. Because of how this integration and the internet work, your `fulfill_checkout` function might be called multiple times, possibly concurrently, for the same Checkout Session. Performing checkout only once ensures this won’t cause undesired behavior. La función `fulfill_checkout` debe: 1. Gestiona correctamente que te llamen varias veces con el mismo ID de la sesión de Checkout. 1. Acepta el ID de *Checkout Sessions* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription) como argumento. 1. Recupera la sesión de Checkout de la API con la propiedad [line_items](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-line_items) [ampliada](https://docs.stripe.com/api/expanding_objects.md). 1. Revisa la propiedad [payment_status](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-payment_status) para determinar si necesita cumplimiento. 1. Lleva a cabo el cumplimiento de las partidas individuales. 1. Registra el estado de cumplimiento de la sesión de Checkout proporcionada. Use the code below as a starting point for your `fulfill_checkout` function. The `TODO` comments indicate any functionality you must implement. > El fragmento de código que figura a continuación puede nombrar la función `fulfill_checkout` `fulfillCheckout` o `FulfillCheckout` según el idioma elegido, pero todos representan la misma función. #### Ruby ```ruby def fulfill_checkout(session_id) # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. client = Stripe::StripeClient.new('<>') puts "Fullfilling Checkout Session #{session_id}" # TODO: Make this function safe to run multiple times, # even concurrently, with the same session ID # TODO: Make sure fulfillment hasn't already been # performed for this Checkout Session # Retrieve the Checkout Session from the API with line_items expanded checkout_session = client.v1.checkout.sessions.retrieve( session_id, {expand: ['line_items']}, ) # Check the Checkout Session's payment_status property # to determine if fulfillment should be performed if checkout_session.payment_status != 'unpaid' # TODO: Perform fulfillment of the line items # TODO: Record/save fulfillment status for this # Checkout Session end end ``` > Si una sesión de Checkout tiene muchas partidas individuales, usa la [autopaginación](https://docs.stripe.com/api/pagination/auto.md) con la [API para partidas individuales del Checkout](https://docs.stripe.com/api/checkout/sessions/line_items.md) para recuperarlas todas. Según los métodos de pago que aceptes y de las necesidades de tu empresa, quizás te convenga que la función `fulfill_checkout` haga lo siguiente: - Facilita el acceso a los servicios. - Activa el envío de bienes. - Guarda una copia de los datos de pago y de las partidas individuales en tu propia base de datos. - Envía al cliente un correo electrónico de recibo personalizado si no tienes habilitados los [recibos de Stripe](https://docs.stripe.com/receipts.md). - Concilia las partidas individuales y las cantidades compradas si permites que los clientes ajusten las cantidades en Checkout. - Actualiza el inventario o los registros de existencias. ## Crea un controlador de eventos de pago [Lado del servidor] Para activar el cumplimiento, crea un controlador de eventos de webhook para recibir notificaciones de los eventos de pago y activar la función `fulfill_checkout`. Cuando alguien te paga, se crea un evento `checkout.session.completed`. Configura un punto de conexión en tu servidor para aceptar, procesar y confirmar la recepción de estos eventos. ### Métodos de pago inmediatos frente a métodos de pago diferidos Algunos métodos de pago no son [instantáneos](https://docs.stripe.com/payments/payment-methods.md#payment-notification), como el [adeudo directo ACH](https://docs.stripe.com/payments/ach-direct-debit.md) y otras transferencias bancarias. Esto significa que los fondos no estarán disponibles de inmediato cuando se complete el proceso de compra. Los métodos de pago diferido generan un evento de [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) cuando el pago se efectúa correctamente más tarde. El estado del objeto es en procesamiento hasta que el pago se realiza correctamente o falla. > The webhook secret (`whsec_...`) shown in the code below comes from either the Stripe CLI or your webhook endpoint. You can use the Stripe CLI for local testing, and Stripe uses a webhook endpoint to send events to your handler when it’s running on a server. See the next section for more details. #### Ruby ```ruby require 'sinatra' # Use the secret provided by Stripe CLI for local testing # or your webhook endpoint's secret. endpoint_secret = 'whsec_...' post '/webhook' do event = nil # Verify webhook signature and extract the event # See https://stripe.com/docs/webhooks#verify-events for more information. begin sig_header = request.env['HTTP_STRIPE_SIGNATURE'] payload = request.body.read event = Stripe::Webhook.construct_event(payload, sig_header, endpoint_secret) rescue JSON::ParserError => e # Invalid payload return status 400 rescue Stripe::SignatureVerificationError => e # Invalid signature return status 400 end if event['type'] == 'checkout.session.completed' || event['type'] == 'checkout.session.async_payment_succeeded' fulfill_checkout(event['data']['object']['id']) end status 200 end ``` Es posible que también quieras recibir notificaciones y manejar eventos `checkout.session.async_payment_failed`. Por ejemplo, puedes enviar un correo electrónico a tu cliente cuando falla un pago retrasado. ## Prueba tu controlador de eventos de forma local The quickest way to develop and test your webhook event handler is with the [Stripe CLI](https://docs.stripe.com/stripe-cli.md). If you don’t have the Stripe CLI, follow the [install guide](https://docs.stripe.com/stripe-cli/install.md) to get started. When the Stripe CLI is installed, you can test your event handler locally. Run your server (for example, on `localhost:4242`), then run the [stripe listen](https://docs.stripe.com/cli/listen) command to have the Stripe CLI forward events to your local server: ```bash stripe listen --forward-to localhost:4242/webhook Ready! Your webhook signing secret is 'whsec_' (^C to quit) ``` Añade el webhook secreto (`whsec_...`) a tu código de gestión de eventos y, a continuación, prueba el cumplimiento accediendo a Checkout como cliente: - Pulsa el botón de finalización de compra que te lleva a Checkout o visita tu Payment Link. - Proporciona los siguientes datos de prueba en Checkout: - Introduce `4242 4242 4242 4242` como número de tarjeta - Introduce cualquier fecha futura como fecha de caducidad - Introduce cualquier número de tres dígitos como CVC - Introduce cualquier código postal de facturación (`90210`) - Pulsa el botón **Pagar** Cuando se efectiviza el pago, verifica lo siguiente: - En tu línea de comandos, donde se está ejecutando `stripe listen`, se muestra un evento `checkout.session.completed` reenviado a tu servidor local. - Los registros de tu servidor muestran la salida esperada de la función `fulfill_checkout`. ## Crea un punto de conexión de webhooks After testing locally, get your webhook event handler up and running on your server. Next, [create a webhook endpoint](https://docs.stripe.com/webhooks.md#register-webhook) to send `checkout.session.completed` events to your server, then test the Checkout flow again. ## Configura la URL de una página de destino [Recomendado] Configure Checkout to send your customer to a page on your website after they complete Checkout. Include the `{CHECKOUT_SESSION_ID}` placeholder in your page’s URL, which is replaced with the Checkout Session ID when your customer is redirected from Checkout. ### Proceso de compra alojado For Checkout Sessions with the default [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) of `hosted_page`, set the `success_url`. ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ --data-urlencode "success_url=https://example.com/after-checkout?session_id={CHECKOUT_SESSION_ID}" ``` When you have a webhook endpoint set up to listen for `checkout.session.completed` events and you set a `success_url`, Checkout waits up to 10 seconds for your server to respond to the webhook event delivery before redirecting your customer. If you use this approach, make sure your server responds to `checkout.session.completed` events as quickly as possible. If you’re using the Stripe CLI for local testing, Checkout redirects to the `success_url` immediately. Los puntos de conexión de webhook registrados en la cuenta de una [organización](https://docs.stripe.com/get-started/account/orgs.md) no soportan este comportamiento. Stripe no espera a que los puntos finales de webhook de la organización escuchen `checkout.session.completed` para dar respuesta a la hora de redirigir a clientes en el proceso de compra. ### Payment Links For Payment Links you create with the API, set the [after_completion.redirect.url](https://docs.stripe.com/api/payment-link/create.md#create_payment_link-after_completion-redirect-url). ```curl curl https://api.stripe.com/v1/payment_links \ -u "<>:" \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d "after_completion[type]=redirect" \ --data-urlencode "after_completion[redirect][url]=https://example.com/after-checkout?session_id={CHECKOUT_SESSION_ID}" ``` Para Payment Links que [crees en el Dashboard](https://dashboard.stripe.com/payment-links/create): 1. Ve a la pestaña **Después del pago**. 1. Selecciona **No mostrar la página de confirmación**. 1. Proporciona la URL de tu página de destino que incluya el marcador de posición `{CHECKOUT_SESSION_ID}` (por ejemplo, `https://example.com/after-checkout?session_id={CHECKOUT_SESSION_ID}`) ## Activa la gestión logística en tu página de destino [Recomendado] [Listening to webhooks](https://docs.stripe.com/checkout/fulfillment.md#create-payment-event-handler) is required to make sure you always trigger fulfillment for every payment, but webhooks can sometimes be delayed. To optimize your payment flow and guarantee immediate fulfillment when your customer is present, trigger fulfillment from your landing page as well. Usa el ID de la sesión de Checkout de la URL que especificaste en el paso anterior para hacer lo siguiente: 1. Cuando tu servidor reciba una solicitud para tu página de destino de Checkout, extrae el ID de la sesión de Checkout de la URL. 1. Ejecuta la función `fulfill_checkout` con el ID proporcionado. 1. Renderiza la página una vez que se complete el intento de completar el pedido. Al renderizar la página de destino, puede mostrar lo siguiente: - Detalles del proceso de cumplimiento de pedidos. - Enlaces o información sobre los servicios a los que el cliente ahora tiene acceso. - Detalles de envío o logística de bienes físicos. > #### Los webhooks son obligatorios > > You can’t rely on triggering fulfillment only from your Checkout landing page, because your customers aren’t guaranteed to visit that page. For example, someone can pay successfully in Checkout and then lose their connection to the internet before your landing page loads. > > [Configura un controlador de eventos de webhook](https://docs.stripe.com/checkout/fulfillment.md#create-payment-event-handler) para que Stripe pueda enviar eventos de pago directamente a tu servidor, sin pasar por el cliente en lo absoluto. Los webhooks son la forma más fiable de confirmar cuándo recibes pagos. Si falla la entrega del evento de webhook, Stripe [lo reintenta varias veces](https://docs.stripe.com/webhooks.md#automatic-retries). # Full embedded page > This is a Full embedded page for when payment-ui is embedded-page. View the full page at https://docs.stripe.com/checkout/fulfillment?payment-ui=embedded-page. When you receive a payment with the Checkout Sessions API (including Payment Links), you might need to take action to provide your customer with what they paid for. For example, you might need to grant them access to a service, or you might need to ship them physical goods. This process is known as fulfillment, and you have two ways to handle this process: - **Manualmente**: Puedes completar los pedidos manualmente con la información que Stripe pone a tu disposición. Por ejemplo, puedes supervisar el [Dashboard](https://docs.stripe.com/dashboard/basics.md), consultar los correos electrónicos de las notificaciones de pago, consultar los informes y, a continuación, completar los pedidos. - **Automáticamente**: puedes crear un sistema de gestión logística automatizado. (Recomendado) The first option works for low volume or experimental ventures, but for most situations we recommend automating fulfillment. The rest of this guide shows you how to build an automatic fulfillment system. ## Tramitación automática de pedidos The automatic fulfillment system outlined below uses a combination of *webhooks* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) and a redirect to your website to trigger fulfillment. You must use webhooks to make sure fulfillment happens for every payment, and redirects let your customers access services or fulfillment details immediately after paying. ## Crea una función de tramitación de pedidos [Lado del servidor] Crea una función en tu servidor para completar los pagos realizados correctamente. Los webhooks activan esta función, y se llama cuando los clientes son redirigidos a tu sitio web después de completar el proceso de compra. Esta guía se refiere a esta función como `fulfill_checkout`, pero puedes nombrarla como desees. Perform fulfillment only once per payment. Because of how this integration and the internet work, your `fulfill_checkout` function might be called multiple times, possibly concurrently, for the same Checkout Session. Performing checkout only once ensures this won’t cause undesired behavior. La función `fulfill_checkout` debe: 1. Gestiona correctamente que te llamen varias veces con el mismo ID de la sesión de Checkout. 1. Acepta el ID de *Checkout Sessions* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription) como argumento. 1. Recupera la sesión de Checkout de la API con la propiedad [line_items](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-line_items) [ampliada](https://docs.stripe.com/api/expanding_objects.md). 1. Revisa la propiedad [payment_status](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-payment_status) para determinar si necesita cumplimiento. 1. Lleva a cabo el cumplimiento de las partidas individuales. 1. Registra el estado de cumplimiento de la sesión de Checkout proporcionada. Use the code below as a starting point for your `fulfill_checkout` function. The `TODO` comments indicate any functionality you must implement. > El fragmento de código que figura a continuación puede nombrar la función `fulfill_checkout` `fulfillCheckout` o `FulfillCheckout` según el idioma elegido, pero todos representan la misma función. #### Ruby ```ruby def fulfill_checkout(session_id) # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. client = Stripe::StripeClient.new('<>') puts "Fullfilling Checkout Session #{session_id}" # TODO: Make this function safe to run multiple times, # even concurrently, with the same session ID # TODO: Make sure fulfillment hasn't already been # performed for this Checkout Session # Retrieve the Checkout Session from the API with line_items expanded checkout_session = client.v1.checkout.sessions.retrieve( session_id, {expand: ['line_items']}, ) # Check the Checkout Session's payment_status property # to determine if fulfillment should be performed if checkout_session.payment_status != 'unpaid' # TODO: Perform fulfillment of the line items # TODO: Record/save fulfillment status for this # Checkout Session end end ``` > Si una sesión de Checkout tiene muchas partidas individuales, usa la [autopaginación](https://docs.stripe.com/api/pagination/auto.md) con la [API para partidas individuales del Checkout](https://docs.stripe.com/api/checkout/sessions/line_items.md) para recuperarlas todas. Según los métodos de pago que aceptes y de las necesidades de tu empresa, quizás te convenga que la función `fulfill_checkout` haga lo siguiente: - Facilita el acceso a los servicios. - Activa el envío de bienes. - Guarda una copia de los datos de pago y de las partidas individuales en tu propia base de datos. - Envía al cliente un correo electrónico de recibo personalizado si no tienes habilitados los [recibos de Stripe](https://docs.stripe.com/receipts.md). - Concilia las partidas individuales y las cantidades compradas si permites que los clientes ajusten las cantidades en Checkout. - Actualiza el inventario o los registros de existencias. ## Crea un controlador de eventos de pago [Lado del servidor] Para activar el cumplimiento, crea un controlador de eventos de webhook para recibir notificaciones de los eventos de pago y activar la función `fulfill_checkout`. Cuando alguien te paga, se crea un evento `checkout.session.completed`. Configura un punto de conexión en tu servidor para aceptar, procesar y confirmar la recepción de estos eventos. ### Métodos de pago inmediatos frente a métodos de pago diferidos Algunos métodos de pago no son [instantáneos](https://docs.stripe.com/payments/payment-methods.md#payment-notification), como el [adeudo directo ACH](https://docs.stripe.com/payments/ach-direct-debit.md) y otras transferencias bancarias. Esto significa que los fondos no estarán disponibles de inmediato cuando se complete el proceso de compra. Los métodos de pago diferido generan un evento de [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) cuando el pago se efectúa correctamente más tarde. El estado del objeto es en procesamiento hasta que el pago se realiza correctamente o falla. > The webhook secret (`whsec_...`) shown in the code below comes from either the Stripe CLI or your webhook endpoint. You can use the Stripe CLI for local testing, and Stripe uses a webhook endpoint to send events to your handler when it’s running on a server. See the next section for more details. #### Ruby ```ruby require 'sinatra' # Use the secret provided by Stripe CLI for local testing # or your webhook endpoint's secret. endpoint_secret = 'whsec_...' post '/webhook' do event = nil # Verify webhook signature and extract the event # See https://stripe.com/docs/webhooks#verify-events for more information. begin sig_header = request.env['HTTP_STRIPE_SIGNATURE'] payload = request.body.read event = Stripe::Webhook.construct_event(payload, sig_header, endpoint_secret) rescue JSON::ParserError => e # Invalid payload return status 400 rescue Stripe::SignatureVerificationError => e # Invalid signature return status 400 end if event['type'] == 'checkout.session.completed' || event['type'] == 'checkout.session.async_payment_succeeded' fulfill_checkout(event['data']['object']['id']) end status 200 end ``` Es posible que también quieras recibir notificaciones y manejar eventos `checkout.session.async_payment_failed`. Por ejemplo, puedes enviar un correo electrónico a tu cliente cuando falla un pago retrasado. ## Prueba tu controlador de eventos de forma local The quickest way to develop and test your webhook event handler is with the [Stripe CLI](https://docs.stripe.com/stripe-cli.md). If you don’t have the Stripe CLI, follow the [install guide](https://docs.stripe.com/stripe-cli/install.md) to get started. When the Stripe CLI is installed, you can test your event handler locally. Run your server (for example, on `localhost:4242`), then run the [stripe listen](https://docs.stripe.com/cli/listen) command to have the Stripe CLI forward events to your local server: ```bash stripe listen --forward-to localhost:4242/webhook Ready! Your webhook signing secret is 'whsec_' (^C to quit) ``` Añade el webhook secreto (`whsec_...`) a tu código de gestión de eventos y, a continuación, prueba el cumplimiento accediendo a Checkout como cliente: - Pulsa el botón de finalización de compra que te lleva a Checkout o visita tu Payment Link. - Proporciona los siguientes datos de prueba en Checkout: - Introduce `4242 4242 4242 4242` como número de tarjeta - Introduce cualquier fecha futura como fecha de caducidad - Introduce cualquier número de tres dígitos como CVC - Introduce cualquier código postal de facturación (`90210`) - Pulsa el botón **Pagar** Cuando se efectiviza el pago, verifica lo siguiente: - En tu línea de comandos, donde se está ejecutando `stripe listen`, se muestra un evento `checkout.session.completed` reenviado a tu servidor local. - Los registros de tu servidor muestran la salida esperada de la función `fulfill_checkout`. ## Crea un punto de conexión de webhooks After testing locally, get your webhook event handler up and running on your server. Next, [create a webhook endpoint](https://docs.stripe.com/webhooks.md#register-webhook) to send `checkout.session.completed` events to your server, then test the Checkout flow again. ## Configura la URL de una página de destino [Recomendado] Configure Checkout to send your customer to a page on your website after they complete Checkout. Include the `{CHECKOUT_SESSION_ID}` placeholder in your page’s URL, which is replaced with the Checkout Session ID when your customer completes the checkout process. ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d ui_mode=embedded_page \ --data-urlencode "return_url=https://example.com/after-checkout?session_id={CHECKOUT_SESSION_ID}" ``` ## Activa la gestión logística en tu página de destino [Recomendado] [Listening to webhooks](https://docs.stripe.com/checkout/fulfillment.md#create-payment-event-handler) is required to make sure you always trigger fulfillment for every payment, but webhooks can sometimes be delayed. To optimize your payment flow and guarantee immediate fulfillment when your customer is present, trigger fulfillment from your landing page as well. Usa el ID de la sesión de Checkout de la URL que especificaste en el paso anterior para hacer lo siguiente: 1. Cuando tu servidor reciba una solicitud para tu página de destino de Checkout, extrae el ID de la sesión de Checkout de la URL. 1. Ejecuta la función `fulfill_checkout` con el ID proporcionado. 1. Renderiza la página una vez que se complete el intento de completar el pedido. Al renderizar la página de destino, puede mostrar lo siguiente: - Detalles del proceso de cumplimiento de pedidos. - Enlaces o información sobre los servicios a los que el cliente ahora tiene acceso. - Detalles de envío o logística de bienes físicos. > #### Los webhooks son obligatorios > > You can’t rely on triggering fulfillment only from your Checkout landing page, because your customers aren’t guaranteed to visit that page. For example, someone can pay successfully in Checkout and then lose their connection to the internet before your landing page loads. > > [Configura un controlador de eventos de webhook](https://docs.stripe.com/checkout/fulfillment.md#create-payment-event-handler) para que Stripe pueda enviar eventos de pago directamente a tu servidor, sin pasar por el cliente en lo absoluto. Los webhooks son la forma más fiable de confirmar cuándo recibes pagos. Si falla la entrega del evento de webhook, Stripe [lo reintenta varias veces](https://docs.stripe.com/webhooks.md#automatic-retries).