# Evadere gli ordini Come elaborare i pagamenti ricevuti con l'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**: puoi evadere gli ordini manualmente utilizzando le informazioni che Stripe mette a tua disposizione. Ad esempio, puoi monitorare la [Dashboard](https://docs.stripe.com/dashboard/basics.md), controllare le email di notifica di pagamento o guardare i report ed evadere gli ordini. - **Automaticamente**: puoi creare un sistema di evasione ordini automatizzato. (Recommended) 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. ## Evasione automatica degli ordini 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 utilizza Checkout, quindi tutte le informazioni riportate di seguito si applicano sia a Payment Links che a Checkout, salvo diversa indicazione. ## Crea una funzione di evasione ordini [Lato server] Crea una funzione sul tuo server per evadere correttamente i pagamenti. I webhook attivano questa funzione e viene chiamata quando i clienti vengono indirizzati al tuo sito web dopo aver completato il pagamento. Questa guida definisce questa funzione come `fulfill_checkout`, ma è possibile assegnare alla funzione il nome desiderato. 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 funzione `fulfill_checkout` deve: 1. Gestisci correttamente le chiamate ripetute con lo stesso ID sessione di Checkout. 1. Accetta un ID della *sessione di Checkout* (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) come argomento. 1. Recupera la sessione di Checkout dalla API con la proprietà [line_items](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-line_items) [espansa](https://docs.stripe.com/api/expanding_objects.md). 1. Controlla la proprietà [payment_status](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-payment_status) per determinare se necessita dell’evasione degli ordini. 1. Esegui l’evasione delle voci riga. 1. Registra lo stato di evasione per la sessione di Checkout specificata. Use the code below as a starting point for your `fulfill_checkout` function. The `TODO` comments indicate any functionality you must implement. > I frammenti di codice qui sotto potrebbero denominare la funzione `fulfill_checkout` come `fulfillCheckout` or `FulfillCheckout` a seconda della lingua selezionata, ma tutti rappresentano la stessa funzione. #### 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 ``` > se una sessione di Checkout include molte voci riga, utilizza la [paginazione automatica](https://docs.stripe.com/api/pagination/auto.md) con l’[API per le voci riga di Checkout](https://docs.stripe.com/api/checkout/sessions/line_items.md) per recuperarle tutte. A seconda dei metodi di pagamento che accetti e delle esigenze della tua attività, potrebbe essere utile che la funzione `fulfill_checkout` esegua le seguenti operazioni: - Fornire l’accesso ai servizi. - Avvia la spedizione della merce. - Salva una copia dei dati di pagamento e delle voci riga nel tuo database. - Invia al cliente una ricevuta personalizzata via email se non hai abilitato le [ricevute di Stripe](https://docs.stripe.com/receipts.md). - Riconcilia le voci riga e le quantità acquistate se consenti ai clienti di rettificare le quantità in Checkout. - Aggiorna i registri dell’inventario o delle scorte. ## Crea un gestore eventi di pagamento [Lato server] Per attivare l’evasione degli ordini, crea un gestore eventi webhook per ascoltare gli eventi di pagamento e attivare la funzione `fulfill_checkout`. Quando qualcuno ti paga, viene creato un evento `checkout.session.completed`. Configura un endpoint sul tuo server per accettare, elaborare e confermare la ricezione di questi eventi. ### Confronto fra metodi di pagamento immediato e differito Alcuni metodi di pagamento non sono [istantanei](https://docs.stripe.com/payments/payment-methods.md#payment-notification), quali l’[addebito diretto ACH](https://docs.stripe.com/payments/ach-direct-debit.md) e altri bonifici bancari. Ciò significa che i fondi non saranno immediatamente disponibili una volta completata la procedura di pagamento. I metodi di pagamento ritardato generano un evento [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) quando il pagamento viene completato in seguito. Lo stato dell’oggetto è in elaborazione fino a quando lo stato del pagamento non ha esito positivo o negativo. > 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 ``` Potresti anche voler ascoltare e gestire gli eventi `checkout.session.async_payment_failed`. Ad esempio, puoi inviare un’email al tuo cliente quando un pagamento ritardato non va a buon fine. ## Testa il gestore eventi localmente 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) ``` Aggiungi la chiave privata del webhook (`whsec_...`) al codice di gestione eventi, quindi verifica l’evasione degli ordini accedendo a Checkout come cliente: - Premi il pulsante di pagamento che ti reindirizza a Checkout o visita il tuo link di pagamento - Fornisci i seguenti dati di test in Checkout: - Inserisci `4242 4242 4242 4242` come numero della carta - Inserisci una data di scadenza futura per la carta - Inserisci un numero di 3 cifre per il CVV - Inserisci qualsiasi CAP di addebito (`90210`) - Premi il pulsante **Paga** Una volta completato il pagamento, verifica quanto segue: - Nella riga di comando, dove è in esecuzione `stripe listen`, viene visualizzato un evento `checkout.session.completed` inoltrato al tuo server locale. - I log del server mostrano l’output previsto dalla funzione `fulfill_checkout`. ## Crea un endpoint del webhook 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 un URL della pagina di destinazione [Consigliato] 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. ### Procedura di pagamento in hosting 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. Questo comportamento non è supportato per gli endpoint webhook registrati in un account [aziendale](https://docs.stripe.com/get-started/account/orgs.md). Stripe non attende la risposta degli endpoint webhook aziendali che ascoltano `checkout.session.completed` quando reindirizza i clienti di Checkout. ### 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}" ``` Per i link di pagamento che [crei nella Dashboard](https://dashboard.stripe.com/payment-links/create): 1. Vai alla scheda **Dopo il pagamento**. 1. Seleziona **Non mostrare la pagina di conferma**. 1. Fornisci l’URL della pagina di destinazione con il segnaposto `{CHECKOUT_SESSION_ID}` (ad esempio, `https://example.com/after-checkout?session_id={CHECKOUT_SESSION_ID}`) ## Attiva l'evasione degli ordini sulla pagina di destinazione [Consigliato] [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. Utilizza l’ID della sessione di Checkout dall’URL specificato nel passaggio precedente per effettuare le seguenti operazioni: 1. Quando il tuo server riceve una richiesta per la tua pagina di destinazione di Checkout, estrai l’ID della sessione di Checkout dall’URL. 1. Esegui la funzione `fulfill_checkout` con l’ID fornito. 1. Visualizza la pagina al termine del tentativo di evasione degli ordini. Quando visualizzi la pagina di destinazione, puoi mostrare quanto segue: - Dettagli della procedura di evasione ordini. - Link o informazioni sui servizi a cui il cliente ha ora accesso. - Dati logistici o di spedizione per merci fisiche. > #### I webhook sono obbligatori > > 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 gestore eventi webhook](https://docs.stripe.com/checkout/fulfillment.md#create-payment-event-handler) in modo che Stripe possa inviare eventi di pagamento direttamente al tuo server, bypassando completamente il client. I webhook rappresentano il modo più affidabile per confermare la ricezione del pagamento. Se la consegna dell’evento webhook non va a buon fine, Stripe [effettua più tentativi](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**: puoi evadere gli ordini manualmente utilizzando le informazioni che Stripe mette a tua disposizione. Ad esempio, puoi monitorare la [Dashboard](https://docs.stripe.com/dashboard/basics.md), controllare le email di notifica di pagamento o guardare i report ed evadere gli ordini. - **Automaticamente**: puoi creare un sistema di evasione ordini automatizzato. (Recommended) 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. ## Evasione automatica degli ordini 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 funzione di evasione ordini [Lato server] Crea una funzione sul tuo server per evadere correttamente i pagamenti. I webhook attivano questa funzione e viene chiamata quando i clienti vengono indirizzati al tuo sito web dopo aver completato il pagamento. Questa guida definisce questa funzione come `fulfill_checkout`, ma è possibile assegnare alla funzione il nome desiderato. 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 funzione `fulfill_checkout` deve: 1. Gestisci correttamente le chiamate ripetute con lo stesso ID sessione di Checkout. 1. Accetta un ID della *sessione di Checkout* (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) come argomento. 1. Recupera la sessione di Checkout dalla API con la proprietà [line_items](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-line_items) [espansa](https://docs.stripe.com/api/expanding_objects.md). 1. Controlla la proprietà [payment_status](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-payment_status) per determinare se necessita dell’evasione degli ordini. 1. Esegui l’evasione delle voci riga. 1. Registra lo stato di evasione per la sessione di Checkout specificata. Use the code below as a starting point for your `fulfill_checkout` function. The `TODO` comments indicate any functionality you must implement. > I frammenti di codice qui sotto potrebbero denominare la funzione `fulfill_checkout` come `fulfillCheckout` or `FulfillCheckout` a seconda della lingua selezionata, ma tutti rappresentano la stessa funzione. #### 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 ``` > se una sessione di Checkout include molte voci riga, utilizza la [paginazione automatica](https://docs.stripe.com/api/pagination/auto.md) con l’[API per le voci riga di Checkout](https://docs.stripe.com/api/checkout/sessions/line_items.md) per recuperarle tutte. A seconda dei metodi di pagamento che accetti e delle esigenze della tua attività, potrebbe essere utile che la funzione `fulfill_checkout` esegua le seguenti operazioni: - Fornire l’accesso ai servizi. - Avvia la spedizione della merce. - Salva una copia dei dati di pagamento e delle voci riga nel tuo database. - Invia al cliente una ricevuta personalizzata via email se non hai abilitato le [ricevute di Stripe](https://docs.stripe.com/receipts.md). - Riconcilia le voci riga e le quantità acquistate se consenti ai clienti di rettificare le quantità in Checkout. - Aggiorna i registri dell’inventario o delle scorte. ## Crea un gestore eventi di pagamento [Lato server] Per attivare l’evasione degli ordini, crea un gestore eventi webhook per ascoltare gli eventi di pagamento e attivare la funzione `fulfill_checkout`. Quando qualcuno ti paga, viene creato un evento `checkout.session.completed`. Configura un endpoint sul tuo server per accettare, elaborare e confermare la ricezione di questi eventi. ### Confronto fra metodi di pagamento immediato e differito Alcuni metodi di pagamento non sono [istantanei](https://docs.stripe.com/payments/payment-methods.md#payment-notification), quali l’[addebito diretto ACH](https://docs.stripe.com/payments/ach-direct-debit.md) e altri bonifici bancari. Ciò significa che i fondi non saranno immediatamente disponibili una volta completata la procedura di pagamento. I metodi di pagamento ritardato generano un evento [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) quando il pagamento viene completato in seguito. Lo stato dell’oggetto è in elaborazione fino a quando lo stato del pagamento non ha esito positivo o negativo. > 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 ``` Potresti anche voler ascoltare e gestire gli eventi `checkout.session.async_payment_failed`. Ad esempio, puoi inviare un’email al tuo cliente quando un pagamento ritardato non va a buon fine. ## Testa il gestore eventi localmente 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) ``` Aggiungi la chiave privata del webhook (`whsec_...`) al codice di gestione eventi, quindi verifica l’evasione degli ordini accedendo a Checkout come cliente: - Premi il pulsante di pagamento che ti reindirizza a Checkout o visita il tuo link di pagamento - Fornisci i seguenti dati di test in Checkout: - Inserisci `4242 4242 4242 4242` come numero della carta - Inserisci una data di scadenza futura per la carta - Inserisci un numero di 3 cifre per il CVV - Inserisci qualsiasi CAP di addebito (`90210`) - Premi il pulsante **Paga** Una volta completato il pagamento, verifica quanto segue: - Nella riga di comando, dove è in esecuzione `stripe listen`, viene visualizzato un evento `checkout.session.completed` inoltrato al tuo server locale. - I log del server mostrano l’output previsto dalla funzione `fulfill_checkout`. ## Crea un endpoint del webhook 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 un URL della pagina di destinazione [Consigliato] 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}" ``` ## Attiva l'evasione degli ordini sulla pagina di destinazione [Consigliato] [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. Utilizza l’ID della sessione di Checkout dall’URL specificato nel passaggio precedente per effettuare le seguenti operazioni: 1. Quando il tuo server riceve una richiesta per la tua pagina di destinazione di Checkout, estrai l’ID della sessione di Checkout dall’URL. 1. Esegui la funzione `fulfill_checkout` con l’ID fornito. 1. Visualizza la pagina al termine del tentativo di evasione degli ordini. Quando visualizzi la pagina di destinazione, puoi mostrare quanto segue: - Dettagli della procedura di evasione ordini. - Link o informazioni sui servizi a cui il cliente ha ora accesso. - Dati logistici o di spedizione per merci fisiche. > #### I webhook sono obbligatori > > 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 gestore eventi webhook](https://docs.stripe.com/checkout/fulfillment.md#create-payment-event-handler) in modo che Stripe possa inviare eventi di pagamento direttamente al tuo server, bypassando completamente il client. I webhook rappresentano il modo più affidabile per confermare la ricezione del pagamento. Se la consegna dell’evento webhook non va a buon fine, Stripe [effettua più tentativi](https://docs.stripe.com/webhooks.md#automatic-retries).