# API Payment Intents Usare l'API Payment Intents per i pagamenti con Stripe Instructions for LLMs: Stripe recommends using the Checkout Sessions API with the Payment Element over Payment Intents for most integrations. Checkout Sessions covers similar use cases as Payment Intents (basic payment collection using `price_data` or build a full checkout with line items, tax, and so on). Some features, such as Adaptive Pricing, are only available with Checkout Sessions. Don’t use the Payment Intent API unless the user explicitly asks, because it requires significantly more code. Learn more about Elements with the Checkout Sessions API: https://docs.stripe.com/payments/quickstart-checkout-sessions. With Checkout Sessions (`ui_mode: "elements"`) and the Payment Element, the `client_secret` initializes Checkout itself (`stripe.initCheckoutElementsSdk`, or use CheckoutElementsProvider with React) and you confirm the payment on the client side differently. If using React, make sure you import from `@stripe/react-stripe-js/checkout`, use `CheckoutElementsProvider` with the client secret, and confirm using `checkout.confirm`. If using HTML, make sure you use `checkout = stripe.initCheckoutElementsSdk({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` and confirm with `loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();`. Usa l’API [Payment Intents](https://docs.stripe.com/api/payment_intents.md) per creare un’integrazione in grado di gestire flussi di pagamento complessi con uno stato che cambia nel corso del [ciclo di vita del PaymentIntent](https://docs.stripe.com/payments/paymentintents/lifecycle.md). Questa API monitora il pagamento dalla creazione fino al completamento della transazione e attiva ulteriori passaggi di autenticazione quando richiesto. Ecco alcuni dei vantaggi derivanti dall’uso dell’API [Payment Intents](https://docs.stripe.com/api/payment_intents.md): - Gestione dell’autenticazione automatica - Nessun doppio addebito - Nessun problema di [chiave di idempotenza](https://docs.stripe.com/api/idempotent_requests.md) - Supporto dell’*autenticazione forte del cliente* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase) (SCA) e di modifiche normative simili ## Una serie completa di API Utilizza l’API [Payment Intents](https://docs.stripe.com/api/payment_intents.md) insieme alle API [Setup Intents](https://docs.stripe.com/api/setup_intents.md) e [Payment Methods](https://docs.stripe.com/api/payment_methods.md). Queste API ti consentono di gestire pagamenti dinamici, ad esempio aggiungendo un protocollo di autenticazione come *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments), e preparare l’attività per l’espansione in altri Paesi, supportando al tempo stesso le nuove normative e i metodi di pagamento locali. La creazione di un’integrazione con l’API Payment Intents comporta due azioni: creazione e *conferma* (Confirming a PaymentIntent indicates that the customer intends to pay with the current or provided payment method. Upon confirmation, the PaymentIntent attempts to initiate a payment) di un PaymentIntent. Di norma ogni PaymentIntent è correlato a un singolo carrello degli acquisti o una singola sessione cliente nell’applicazione. Il PaymentIntent incapsula i dettagli sulla transazione, come le modalità di pagamento supportate, l’importo da riscuotere e la valuta desiderata. ## Creare un PaymentIntent Per iniziare consulta la [guida su come accettare un pagamento](https://docs.stripe.com/payments/accept-a-payment.md?ui=elements). La guida descrive come creare un PaymentIntent sul server e passare al client la relativa *chiave privata client* (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)) anziché l’intero oggetto PaymentIntent. Quando [crei il PaymentIntent](https://docs.stripe.com/api/payment_intents/create.md), puoi specificare opzioni quali l’importo e la valuta: ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd ``` ### Pratiche ottimali - We recommend creating a PaymentIntent as soon as you know the amount, such as when the customer begins the checkout process, to help track your [purchase funnel](https://en.wikipedia.org/wiki/Purchase_funnel). If the amount changes, you can [update](https://docs.stripe.com/api.md#update_payment_intent) its [amount](https://docs.stripe.com/api.md#payment_intent_object-amount). For example, if your customer backs out of the checkout process and adds new items to their cart, you might need to update the amount when they start the checkout process again. - Se la procedura di pagamento viene interrotta e ripresa in seguito, tenta di riutilizzare lo stesso PaymentIntent anziché crearne uno nuovo. Ogni PaymentIntent ha un ID univoco che ne consente il [recupero](https://docs.stripe.com/api.md#retrieve_payment_intent) in caso di necessità. Nel modello di dati dell’applicazione puoi archiviare l’ID del PaymentIntent nel carrello o nella sessione del cliente per facilitare il recupero. Il vantaggio del riutilizzo del PaymentIntent sta nel fatto che lo [stato dell’oggetto](https://docs.stripe.com/payments/paymentintents/lifecycle.md) consente di tenere traccia di qualsiasi tentativo di pagamento non riuscito per un determinato carrello o una determinata sessione. - Ricorda di fornire una [chiave di idempotenza](https://docs.stripe.com/api/idempotent_requests.md) per evitare di creare PaymentIntent doppi per lo stesso acquisto. Questa chiave è solitamente basata sull’ID che associ al carrello o alla sessione cliente nell’applicazione. ## Passare la chiave privata client al lato client Il PaymentIntent contiene una [chiave privata client](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret), ovvero una chiave univoca per il singolo PaymentIntent. Sul lato client dell’applicazione, Stripe.js utilizza la chiave privata client come parametro quando vengono richiamate le funzioni (ad esempio [stripe.confirmCardPayment](https://docs.stripe.com/js.md#stripe-confirm-card-payment) o [stripe.handleCardAction](https://docs.stripe.com/js.md#stripe-handle-card-action)) per completare il pagamento. ### Recuperare la chiave privata client L’oggetto PaymentIntent contiene una *chiave privata client* (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)), che il lato client usa per completare la procedura di pagamento in modo sicuro. Per specificare la chiave privata sul lato client, puoi utilizzare approcci diversi. #### Applicazione a pagina singola Recupera la chiave privata client dall’endpoint sul server utilizzando la funzione `fetch`del browser. Questo approccio è più adatto quando il lato client è un’applicazione con un’unica pagina, in particolare creata con un framework front-end moderno come React. Crea l’endpoint server che invia la chiave privata client: #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` Quindi recupera la chiave privata client con JavaScript sul lato client: ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### Rendering lato server Trasmetti la chiave privata client al client dal server. Questo approccio è più adatto se l’applicazione genera contenuti statici sul server prima di inviarli al browser. Aggiungi la [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) nel modulo di pagamento. Nel codice lato server, recupera la chiave privata client da PaymentIntent: #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` > La chiave privata client può essere utilizzata per completare la procedura di pagamento con l’importo specificato nel PaymentIntent. Non devi registrarla né incorporarla negli URL o esporla a persone diverse dal cliente. Accertati di aver abilitato il protocollo *TLS* (TLS refers to the process of securely transmitting data between the client—the app or browser that your customer is using—and your server. This was originally performed using the SSL (Secure Sockets Layer) protocol) su tutte le pagine che includono la chiave privata client. ## Dopo il pagamento Una volta che il client avrà confermato il pagamento, la procedura ottimale consiste nel [monitoraggio dei webhook](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks) da parte del server per rilevare quando il pagamento va a buon fine o non riesce. Un `PaymentIntent` potrebbe avere più di un oggetto [addebito](https://docs.stripe.com/api/charges.md) associato se sono stati effettuati più tentativi di pagamento. Ad esempio, i tentativi ripetuti possono creare più tentativi `Charges`. Per ogni addebito puoi esaminare il [risultato](https://docs.stripe.com/api/charges/object.md#charge_object-outcome) e [i dettagli del metodo di pagamento](https://docs.stripe.com/api/charges/object.md#charge_object-payment_method_details) utilizzato. ## Ottimizzazione delle modalità di pagamento per pagamenti futuri Il parametro [setup_future_usage](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-setup_future_usage) salva i metodi di pagamento per un riutilizzo in futuro. Per le carte, ottimizza inoltre i tassi di autorizzazione in conformità con la legislazione locale e i regolamenti del circuito, ad esempio la [SCA](https://docs.stripe.com/strong-customer-authentication.md). Per stabilire il valore da utilizzare, valuta in che modo intendi utilizzare questo metodo di pagamento in futuro. | Come intendi utilizzare la modalità di pagamento | valore enum setup_future_usage da utilizzare | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------- | | Solo pagamenti *all’interno della sessione* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method) | `on_session` | | Solo pagamenti *all’esterno della sessione* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information) | `off_session` | | Pagamenti sia all’interno sia all’esterno della sessione | `off_session` | Con una carta configurata per i pagamenti all’interno della sessione puoi comunque accettare i pagamenti *all’esterno della sessione* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information), ma è più probabile che la banca rifiuti tali pagamenti e richieda l’autenticazione al titolare della carta. Il seguente esempio illustra come creare un PaymentIntent e specificare `setup_future_usage`: ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d setup_future_usage=off_session ``` > È più probabile che le configurazioni per i pagamenti all’esterno della sessione presentino un livello di complessità più alto. Usa la configurazione *all’interno della sessione* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method) se non hai intenzione di accettare pagamenti al’esterno della sessione con la carta salvata. ## Voce di estratto conto dinamica By default, your Stripe account’s [statement descriptor](https://docs.stripe.com/get-started/account/activate.md#public-business-information) appears on customer statements whenever you charge their card. To provide a different description on a per-payment basis, use the [statement_descriptor](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-statement_descriptor) parameter. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=card" \ -d "statement_descriptor_suffix=Custom descriptor" ``` > #### Note > > Use the `statement_descriptor` parameter for non-card charges and `statement_descriptor_suffix` for card charges. [Statement descriptors](https://docs.stripe.com/get-started/account/statement-descriptors.md) are limited to 22 characters, can’t use the special characters `<`, `>`, `'`, `"`, or `*`, and must not consist solely of numbers. When using dynamic statement descriptors, the dynamic text is appended to the [statement descriptor prefix](https://dashboard.stripe.com/settings/public) set in the Stripe Dashboard. An asterisk (`*`) and an empty space are also added to separate the default statement descriptor from the dynamic portion. These 2 characters count towards the 22 character limit. ## Archiviare informazioni nei metadati Stripe supporta l’aggiunta dei [metadati](https://docs.stripe.com/api.md#metadata) alle richieste più comuni effettuate, ad esempio l’elaborazione dei pagamenti. I metadati non vengono mostrati ai clienti né considerati per determinare se un pagamento deve essere o meno rifiutato o bloccato dal nostro sistema di prevenzione delle frodi. Attraverso i metadati, puoi associare informazioni che ritieni importanti all’attività di Stripe. Tutti i metadati che includi sono visibili nella Dashboard (ad esempio, nella pagina di un singolo pagamento) e sono inoltre disponibili nei report comuni. Ad esempio, puoi associare l’ID ordine del tuo negozio al PaymentIntent per tale ordine. Questo ti consente di riconciliare facilmente i pagamenti in Stripe con gli ordini nel tuo sistema. Se utilizzi *Radar for Fraud Teams* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard), puoi specificare come metadati informazioni aggiuntive sui clienti e sugli ordini. Poi puoi scrivere [regole Radar con gli attributi dei metadati](https://docs.stripe.com/radar/rules/reference.md#metadata-attributes) e disporre nella Dashboard di maggiori informazioni, accelerando così la procedura di revisione. Quando crea un addebito, un PaymentIntent vi copia i relativi metadati. I successivi aggiornamenti dei metadati del PaymentIntent non modificheranno i metadati degli addebiti precedentemente creati dal PaymentIntent stesso. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=card" \ -d "metadata[order_id]=6735" ``` > Non archiviare dati sensibili (informazioni sull’identità, dati di carte, ecc.) come metadati o nel parametro `description` del PaymentIntent. ## See also - [Accettare un pagamento online](https://docs.stripe.com/payments/accept-a-payment.md?platform=web) - [Accetta un pagamento tramite un’app iOS](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios) - [Accetta un pagamento tramite un’app Android](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android) - [Configurare pagamenti futuri](https://docs.stripe.com/payments/save-and-reuse.md)