# Salvare il metodo di pagamento di un cliente quando lo utilizza per pagare

Scopri come salvare il metodo di pagamento del cliente quando confermi un PaymentIntent.

# Checkout Sessions API

> This is a Checkout Sessions API for when payment-ui is embedded-components. View the full page at https://docs.stripe.com/payments/save-during-payment?payment-ui=embedded-components.

Use the [Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions.md) to save payment details during a purchase. This is useful for situations such as:

- Charging a customer for an e-commerce order and storing the payment details for future purchases.
- Initiating the first payment in a series of recurring payments.
- Charging a deposit and storing the payment details to charge the full amount later.

## Compliance

Sei responsabile del rispetto di tutte le leggi, i regolamenti e le norme di rete applicabili quando salvi i dettagli di pagamento di un cliente per un utilizzo futuro, ad esempio per mostrargli il metodo di pagamento nel flusso di checkout per un acquisto futuro o per addebitargli un importo quando non sta utilizzando attivamente il tuo sito web o la tua app. Prima di salvare o addebitare il metodo di pagamento di un cliente, assicurati di:

- Aggiungere al tuo sito web o alla tua app delle clausole che specificano come intendi salvare i dettagli relativi ai metodi di pagamento, ad esempio:
  - L’accordo del cliente che ti consente di avviare un pagamento o una serie di pagamenti per suo conto per transazioni specifiche.
  - La tempistica e la frequenza dei pagamenti previste (ad esempio, se gli addebiti sono per rate programmate, pagamenti di abbonamenti o ricariche non programmate).
  - Il modo in cui determini l’importo del pagamento.
  - I tuoi termini di cancellazione, se la modalità di pagamento è per un servizio in abbonamento.
- Utilizza un metodo di pagamento salvato solo per lo scopo indicato nei tuoi termini.
- Ottieni il consenso esplicito del cliente per questo specifico utilizzo. Ad esempio, includi una casella di controllo “Salva il mio metodo di pagamento per il futuro”.
- Conserva una copia dell’accordo scritto del cliente con i tuoi termini.

> When using Elements with the Checkout Sessions API, only cards and ACH Direct Debit are supported for saved payment methods. You can’t save other payment methods, such as bank accounts.

## Prerequisites

1. Follow the Checkout guide to [accept a payment](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=stripe-hosted).
1. Segui questa guida per salvare il metodo di pagamento utilizzato durante un pagamento, in modo da poterlo recuperare per utilizzarlo in occasione di futuri pagamenti effettuati dallo stesso cliente.

## Enable saved payment methods

> Le normative globali in materia di privacy sono complesse e presentano molte sfumature. Prima di implementare la funzionalità che consente di memorizzare i dati relativi ai metodi di pagamento dei clienti, consulta il tuo ufficio legale per assicurarti che sia conforme al tuo quadro normativo in materia di privacy e conformità.

Per consentire a un cliente di salvare il proprio metodo di pagamento per un utilizzo futuro, specifica il parametro [saved_payment_method_options.payment_method_save](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_save) durante la creazione della Sessione di checkout.

> #### Utilizza l'API Accounts v2 per rappresentare i clienti
> 
> The Accounts v2 API is generally available for Connect users, and in public preview for other Stripe users. If you’re part of the Accounts v2 preview, you need to specify a [specify a preview version](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning) in your code.
> 
> To request access to the Accounts v2 preview, 
> 
> Nella maggior parte dei casi d’uso, consigliamo di [rappresentare i clienti come oggetti Account configurati dall’utente,](https://docs.stripe.com/connect/use-accounts-as-customers.md) anziché utilizzare oggetti [Customer](https://docs.stripe.com/api/customers.md).

Saving a payment method requires an object that represents your customer. This object can be a customer-configured [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) if you use the Accounts v2 API, or a [Customer](https://docs.stripe.com/api/customers/object.md) if you use the Customers API. Pass an existing customer or create a new one by setting [customer_creation](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_creation) to `always` on the Checkout Session.

```curl
curl https://api.stripe.com/v1/checkout/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "line_items[0][price]={{PRICE_ID}}" \
  -d "line_items[0][quantity]=2" \
  -d mode=payment \
  -d ui_mode=elements \
  -d customer_creation=always \
  -d "saved_payment_method_options[payment_method_save]=enabled"
```

Dopo aver creato la Sessione di Checkout, utilizza la chiave privata [client](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) restituita nella risposta per [creare la pagina](https://docs.stripe.com/payments/quickstart-checkout-sessions.md) di Checkout.

> In the latest version of Stripe.js, specifying `enableSave` to `auto` is optional because that’s the default value when saved payment methods are enabled on the Checkout Session.

#### HTML + JS

The Payment Element automatically displays a consent collection checkbox when saved payment methods are enabled on the Checkout Session. You can explicitly configure this behavior using [elementsOptions](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions) on `initCheckoutElementsSdk`.

```javascript
const checkout = stripe.initCheckoutElementsSdk({
  clientSecret,
  elementsOptions: {savedPaymentMethod: {
      // Default is 'auto' in the latest version of Stripe.js - this configuration is optional
      enableSave: 'auto',
    }
  }
});
```

#### React

The Payment Element automatically displays a consent collection checkbox when saved payment methods are enabled on the Checkout Session. You can explicitly configure this behavior using [elementsOptions](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions) on the `CheckoutElementsProvider`.

```jsx
import React from 'react';
import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout';
import CheckoutForm from './CheckoutForm';

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

  return (
    <CheckoutElementsProvider
      stripe={stripe}
      options={{
        clientSecret,
        elementsOptions: {savedPaymentMethod: {
            // Default is 'auto' in the latest version of Stripe.js - this configuration is optional
            enableSave: 'auto',
          },
        },
      }}
    >
      <CheckoutForm />
    </CheckoutElementsProvider>
  );
};

export default App;
```

## Riutilizza un metodo di pagamento precedentemente salvato

Each saved payment method is linked to an object that represents your customer. This object can be a customer-configured [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) if you use the Accounts v2 API, or a [Customer](https://docs.stripe.com/api/customers/object.md) if you use the Customers API. Before creating the Checkout Session, authenticate your customer, and pass the corresponding object ID to the Checkout Session.

> In the latest version of Stripe.js, `enableRedisplay` defaults to `auto` when saved payment methods are enabled on the Checkout Session.

The Payment Element automatically redisplays previously saved payment methods for your customer to use during checkout when saved payment methods are enabled on the Checkout Session.

#### Accounts v2

```curl
curl https://api.stripe.com/v1/checkout/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "line_items[0][price]={{PRICE_ID}}" \
  -d "line_items[0][quantity]=2" \
  -d mode=payment \
  -d ui_mode=elements \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}"
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/checkout/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "line_items[0][price]={{PRICE_ID}}" \
  -d "line_items[0][quantity]=2" \
  -d mode=payment \
  -d ui_mode=elements \
  -d "customer={{CUSTOMER_ID}}"
```

#### HTML + JS

You can explicitly configure the redisplay behavior using [elementsOptions](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions) on `initCheckoutElementsSdk`.

```javascript
const checkout = stripe.initCheckoutElementsSdk({
  clientSecret,
  elementsOptions: {
    savedPaymentMethod: {
      // Default is 'auto' in the latest version of Stripe.js - this configuration is optional
      enableSave: 'auto',// Default is 'auto' in the latest version of Stripe.js - this configuration is optional
      enableRedisplay: 'auto',
    }
  }
});
```

#### React

You can explicitly configure the redisplay behavior using [elementsOptions](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions) on the `CheckoutElementsProvider`.

```jsx
import React from 'react';
import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout';
import CheckoutForm from './CheckoutForm';

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

  return (
    <CheckoutElementsProvider
      stripe={stripe}
      options={{
        clientSecret,
        elementsOptions: {
          savedPaymentMethod: {
            // Default is 'auto' in the latest version of Stripe.js - this configuration is optional
            enableSave: 'auto',// Default is 'auto' in the latest version of Stripe.js - this configuration is optional
            enableRedisplay: 'auto',
          }
        },
      }}
    >
      <CheckoutForm />
    </CheckoutElementsProvider>
  );
};

export default App;
```

## Optional: Build a saved payment method UI

#### HTML + JS

You can build your own saved payment method UI instead of using the built-in UI provided by the Payment Element.

To prevent the Payment Element from handling consent collection and displaying the previously saved payment methods, pass in additional [elementsOptions](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions) on `initCheckoutElementsSdk`.

```javascript
const checkout = stripe.initCheckoutElementsSdk({
  clientSecret,
  elementsOptions: {savedPaymentMethod: {
      enableSave: 'never',
      enableRedisplay: 'never',
    },
  }
});
```

#### React

You can build your own saved payment method UI instead of using the built-in UI provided by the Payment Element. To prevent the Payment Element from handling consent collection and displaying the previously saved payment methods, pass in additional [elementsOptions](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions) on the `CheckoutElementsProvider`.

```jsx
import React from 'react';
import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout';
import CheckoutForm from './CheckoutForm';

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

  return (
    <CheckoutElementsProvider
      stripe={stripe}
      options={{
        clientSecret,
        elementsOptions: {savedPaymentMethod: {
            enableSave: 'never',
            enableRedisplay: 'never',
          },
        },
      }}
    >
      <CheckoutForm />
    </CheckoutElementsProvider>
  );
};

export default App;
```

### Collect consent

> Le normative globali in materia di privacy sono complesse e presentano molte sfumature. Prima di implementare la funzionalità che consente di memorizzare i dati relativi ai metodi di pagamento dei clienti, consulta il tuo ufficio legale per assicurarti che sia conforme al tuo quadro normativo in materia di privacy e conformità.

In most cases, you must collect a customer’s consent before you save their payment method details. The following example shows how to obtain consent using a checkbox.

#### HTML + JS

```html
<label>
  <input type="checkbox" id="save-payment-method-checkbox" />
  Save my payment information for future purchases
</label>
<button id="pay-button">Pay</button>
<div id="confirm-errors"></div>
```

#### React

```jsx
import React from 'react';

type Props = {
  savePaymentMethod: boolean;
  onSavePaymentMethodChange: (save: boolean) => void;
}
const ConsentCollection = (props: Props) => {
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    props.onSavePaymentMethodChange(e.target.checked);
  };
  return (
    <label>
      <input
        type="checkbox"
        checked={props.savePaymentMethod}
        onChange={handleChange}
      />
      Save my payment information for future purchases
    </label>
  );
};

export default ConsentCollection;
```

When you call [confirm](https://docs.stripe.com/js/custom_checkout/confirm), you can indicate to Stripe that your customer has provided consent by passing the `savePaymentMethod` parameter. When you save a customer’s payment details, you’re responsible for complying with all applicable laws, regulations, and network rules.

#### HTML + JS

```js
const checkout = stripe.initCheckoutElementsSdk({clientSecret});
const button = document.getElementById('pay-button');
const errors = document.getElementById('confirm-errors');
const checkbox = document.getElementById('save-payment-method-checkbox');
const loadActionsResult = await checkout.loadActions();
if (loadActionsResult.type === 'success') {
  const {actions} = loadActionsResult;
  button.addEventListener('click', () => {
    // Clear any validation errors
    errors.textContent = '';
const savePaymentMethod = checkbox.checked;
    actions.confirm({savePaymentMethod}).then((result) => {
      if (result.type === 'error') {
        errors.textContent = result.error.message;
      }
    });
  });
}
```

#### React

```jsx
import React from 'react';
import {useCheckout} from '@stripe/react-stripe-js/checkout';

type Props = {
  savePaymentMethod: boolean;
}
const PayButton = (props: Props) => {
  const checkoutState = useCheckout();
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  if (checkoutState.type === 'loading') {
    return (
      <div>Loading...</div>
    );
  } else if (checkoutState.type === 'error') {
    return (
      <div>Error: {checkoutState.error.message}</div>
    );
  }
  const {confirm} = checkoutState.checkout;
  const handleClick = () => {
    setLoading(true);confirm({savePaymentMethod: props.savePaymentMethod}).then((result) => {
      if (result.type === 'error') {
        setError(result.error)
      }
      setLoading(false);
    })
  };

  return (
    <div>
      <button disabled={!loading} onClick={handleClick}>
        Pay
      </button>
      {error && <div>{error.message}</div>}
    </div>
  )
};

export default PayButton;
```

### Render saved payment methods

Use the [savedPaymentMethods](https://docs.stripe.com/js/custom_checkout/session_object#custom_checkout_session_object-savedPaymentMethods) array on the front end to render the customer’s available payment methods.

> The `savedPaymentMethods` array includes only the payment methods that have [allow_redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) set to `always`. Follow the steps for [collecting consent](https://docs.stripe.com/payments/save-during-payment.md#collect-consent) from your customer and make sure to properly set the `allow_redisplay` parameter.

#### HTML + JS

```html
<div id="saved-payment-methods"></div>
```

```js
const checkout = stripe.initCheckoutElementsSdk({clientSecret});
const loadActionsResult = await checkout.loadActions();
if (loadActionsResult.type === 'success') {
  const container = document.getElementById('saved-payment-methods');
  const {actions} = loadActionsResult;
  actions.getSession().savedPaymentMethods.forEach((pm) => {
    const label = document.createElement('label');
    const radio = document.createElement('input');

    radio.type = 'radio';
    radio.value = pm.id;

    label.appendChild(radio);
    label.appendChild(document.createTextNode(`Card ending in ${pm.card.last4}`));
    container.appendChild(label);
  });
}
```

#### React

```jsx
import React from 'react';
import {useCheckout} from '@stripe/react-stripe-js/checkout';

type Props = {
  selectedPaymentMethod: string | null;
  onSelectPaymentMethod: (paymentMethod: string) => void;
};
const PaymentMethods = (props: Props) => {const checkoutState = useCheckout();

  if (checkoutState.type === 'loading') {
    return (
      <div>Loading...</div>
    );
  } else if (checkoutState.type === 'error') {
    return (
      <div>Error: {checkoutState.error.message}</div>
    );
  }const {savedPaymentMethods} = checkoutState.checkout;

  const handleOptionChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    props.onSelectPaymentMethod(e.target.value);
  };

  return (
    <div>
      {savedPaymentMethods.map((pm) => (
        <label key={pm.id}>
          <input
            type="radio"
            value={pm.id}
            checked={props.selectedPaymentMethod === pm.id}
            onChange={handleOptionChange}
          />
          Card ending in {pm.card.last4}
        </label>
      ))}
    </div>
  );
};

export default PaymentMethods;
```

### Confirm with a saved payment method

When your customer selects a saved payment method and is ready to complete checkout, call [confirm](https://docs.stripe.com/js/custom_checkout/confirm) and pass in the [paymentMethod](https://docs.stripe.com/js/custom_checkout/confirm#custom_checkout_session_confirm-options-paymentMethod) ID.

#### HTML + JS

```html
<button id="pay-button">Pay</button>
```

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

const loadActionsResult = await checkout.loadActions();
if (loadActionsResult.type === 'success') {
  const container = document.getElementById('saved-payment-methods');
  const {actions} = loadActionsResult;
  actions.getSession().savedPaymentMethods.forEach((pm) => {
    const label = document.createElement('label');
    const radio = document.createElement('input');

    radio.type = 'radio';
    radio.value = pm.id;

    label.appendChild(radio);
    label.appendChild(document.createTextNode(`Card ending in ${pm.card.last4}`));
    container.appendChild(label);
  });
}
```

#### React

```jsx
import React from 'react';
import {useCheckout} from '@stripe/react-stripe-js/checkout';

type Props = {
  selectedPaymentMethod: string | null;
}
const PayButton = (props: Props) => {
  const checkoutState = useCheckout();
  const [loading, setLoading] = React.useState(false);

  if (checkoutState.type === 'loading') {
    return (
      <div>Loading...</div>
    );
  } else if (checkoutState.type === 'error') {
    return (
      <div>Error: {checkoutState.error.message}</div>
    );
  }
  const {confirm} = checkoutState.checkout;

  const handleClick = () => {
    setLoading(true);confirm({paymentMethod: props.selectedPaymentMethod}).then((result) => {
      if (result.error) {
        // Confirmation failed. Display the error message.
      }
      setLoading(false);
    })
  };

  return (
    <button disabled={loading} onClick={handleClick}>
      Pay
    </button>
  )
};

export default PayButton;
```


# Payment Intents API

> This is a Payment Intents API for when payment-ui is elements. View the full page at https://docs.stripe.com/payments/save-during-payment?payment-ui=elements.

Usa l’[API Payment Intents](https://docs.stripe.com/api/payment_intents.md) per salvare i dati di pagamento da un acquisto. Esistono più casi d’uso:

- Addebita un pagamento a un cliente per un ordine di e-commerce e memorizza i dati per gli acquisti futuri.
- Avvia il primo di una serie di pagamenti ricorrenti.
- Addebita un deposito e memorizza i dati per addebitare l’intero importo in seguito.

> #### Transazioni con carta presente
> 
> Le transazioni con carta presente, come i pagamenti tramite Stripe Terminal, utilizzano una procedura diversa per salvare il metodo di pagamento. Per i dettagli, consulta [la documentazione di Terminal](https://docs.stripe.com/terminal/features/saving-payment-details/save-after-payment.md).

## Conformità

Sei responsabile del rispetto di tutte le leggi, i regolamenti e le norme di rete applicabili quando salvi i dettagli di pagamento di un cliente per un utilizzo futuro, ad esempio per mostrargli il metodo di pagamento nel flusso di checkout per un acquisto futuro o per addebitargli un importo quando non sta utilizzando attivamente il tuo sito web o la tua app. Prima di salvare o addebitare il metodo di pagamento di un cliente, assicurati di:

- Aggiungere al tuo sito web o alla tua app delle clausole che specificano come intendi salvare i dettagli relativi ai metodi di pagamento, ad esempio:
  - L’accordo del cliente che ti consente di avviare un pagamento o una serie di pagamenti per suo conto per transazioni specifiche.
  - La tempistica e la frequenza dei pagamenti previste (ad esempio, se gli addebiti sono per rate programmate, pagamenti di abbonamenti o ricariche non programmate).
  - Il modo in cui determini l’importo del pagamento.
  - I tuoi termini di cancellazione, se la modalità di pagamento è per un servizio in abbonamento.
- Utilizza un metodo di pagamento salvato solo per lo scopo indicato nei tuoi termini.
- Ottieni il consenso esplicito del cliente per questo specifico utilizzo. Ad esempio, includi una casella di controllo “Salva il mio metodo di pagamento per il futuro”.
- Conserva una copia dell’accordo scritto del cliente con i tuoi termini.

## Prerequisites

1. Follow the Payment Intents API guide to [accept a payment](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents).
1. Segui questa guida per salvare il metodo di pagamento utilizzato durante un pagamento, in modo da poterlo recuperare per utilizzarlo in occasione di futuri pagamenti effettuati dallo stesso cliente.

## Save payment methods during payment [Lato server]

Puoi configurare Payment Element per salvare i metodi di pagamento del cliente per usi futuri. Questa sezione mostra come integrare la [funzione dei metodi di pagamento salvate](https://docs.stripe.com/payments/save-customer-payment-methods.md), che consente a Payment Element di:

- Richiedere agli acquirenti il consenso per il salvataggio di un metodo di pagamento
- Salva le modalità di pagamento quando gli acquirenti forniscono il consenso
- Mostra le modalità di pagamento salvate agli acquirenti per gli acquisti futuri
- [Aggiorna automaticamente le carte smarrite o scadute](https://docs.stripe.com/payments/cards/overview.md#automatic-card-updates) quando gli acquirenti le sostituiscono
![Payment Element e una casella di controllo del metodo di pagamento salvato](https://b.stripecdn.com/docs-statics-srv/assets/spm-save.fe0b24afd0f0a06e0cf4eecb0ce2403a.png)

Salva i metodi di pagamento.
![Payment Element con un metodo di pagamento salvato selezionato](https://b.stripecdn.com/docs-statics-srv/assets/spm-saved.5dba5a8a190a9a0e9f1a99271bed3f4b.png)

Riutilizza un metodo di pagamento salvato in precedenza.

### Abilita il salvataggio del metodo di pagamento in Payment Element

Durante la creazione di un [PaymentIntent](https://docs.stripe.com/api/payment_intents/.md) sul tuo server, crea anche [CustomerSession](https://docs.stripe.com/api/customer_sessions/.md) fornendo l’ID del cliente (utilizzando `customer` per un oggetto `Customer` o `customer_account` per un oggetto `Account` configurato dal cliente) e abilitando il componente [payment_element](https://docs.stripe.com/api/customer_sessions/object.md#customer_session_object-components-payment_element) per la tua sessione. Configura le [funzioni](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components-payment_element-features) del metodo di pagamento salvato che desideri abilitare. Ad esempio, abilitando [payment_method_save](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components-payment_element-features-payment_method_save) viene mostrata una casella di spunta che consente ai clienti di salvare i propri dettagli di pagamento per utilizzo futuro.

Puoi specificare `setup_future_usage` in un PaymentIntent o in una sessione di Checkout per sovrascrivere il comportamento predefinito relativo al salvataggio dei metodi di pagamento. In questo modo si garantisce che il metodo di pagamento venga salvato automaticamente per un utilizzo futuro, anche se il cliente non sceglie esplicitamente di salvarlo. Se si intende specificare `setup_future_usage`, non impostare `payment_method_save_usage` nella stessa transazione di pagamento, poiché ciò causerebbe un errore di integrazione.

> #### Utilizza l'API Accounts v2 per rappresentare i clienti
> 
> The Accounts v2 API is generally available for Connect users, and in public preview for other Stripe users. If you’re part of the Accounts v2 preview, you need to specify a [specify a preview version](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning) in your code.
> 
> To request access to the Accounts v2 preview, 
> 
> Nella maggior parte dei casi d’uso, consigliamo di [rappresentare i clienti come oggetti Account configurati dall’utente,](https://docs.stripe.com/connect/use-accounts-as-customers.md) anziché utilizzare oggetti [Customer](https://docs.stripe.com/api/customers.md).

#### Account v2

#### Ruby

```ruby

# 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('<<YOUR_SECRET_KEY>>')

post '/create-intent-and-customer-session' do
  intent = client.v1.payment_intents.create({
    amount: 1099,
    currency: 'usd',
    automatic_payment_methods: {enabled: true},
    customer_account: {{CUSTOMER_ACCOUNT_ID}},
  })
  customer_session = client.v1.customer_sessions.create({
    customer_account: {{CUSTOMER_ACCOUNT_ID}},
    components: {
      payment_element: {
          enabled: true,
          features: {
            payment_method_redisplay: 'enabled',
            payment_method_save: 'enabled',
            payment_method_save_usage: 'off_session',
            payment_method_remove: 'enabled',
          },
        },
    },
  })
  {
    client_secret: intent.client_secret,
    customer_session_client_secret: customer_session.client_secret
  }.to_json
end
```

#### Clienti v1

#### Ruby

```ruby

# 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('<<YOUR_SECRET_KEY>>')

post '/create-intent-and-customer-session' do
  intent = client.v1.payment_intents.create({
    amount: 1099,
    currency: 'usd',
    # In the latest version of the API, specifying the `automatic_payment_methods` parameter
    # is optional because Stripe enables its functionality by default.
    automatic_payment_methods: {enabled: true},
    customer: {{CUSTOMER_ID}},
  })
  customer_session = client.v1.customer_sessions.create({
    customer: {{CUSTOMER_ID}},
    components: {
      payment_element: {
          enabled: true,
          features: {
            payment_method_redisplay: 'enabled',
            payment_method_save: 'enabled',
            payment_method_save_usage: 'off_session',
            payment_method_remove: 'enabled',
          },
        },
    },
  })
  {
    client_secret: intent.client_secret,
    customer_session_client_secret: customer_session.client_secret
  }.to_json
end
```

La tua istanza Elements utilizza la *chiave privata client* (A client secret is used with your publishable key to authenticate a request for a single object. Each client secret is unique to the object it's associated with) della CustomerSession per accedere ai metodi di pagamento salvati del cliente. [Gestisci gli errori](https://docs.stripe.com/error-handling.md) correttamente quando crei l’oggetto CustomerSession. Se si verifica un errore, non devi fornire la chiave privata client della CustomerSession all’istanza Elements, in quanto è facoltativa.

Crea l’istanza Elements utilizzando le chiavi private client sia per PaymentIntent che per CustomerSession. Poi utilizza questa istanza di Elements per creare un Payment Element.

```javascript
// Create the CustomerSession and obtain its clientSecret
const res = await fetch("/create-intent-and-customer-session", {
  method: "POST"
});

const {
  customer_session_client_secret: customerSessionClientSecret
} = await res.json();

const elementsOptions = {
  clientSecret: '{{CLIENT_SECRET}}',customerSessionClientSecret,
  // Fully customizable with appearance API.
  appearance: {/*...*/},
};

// Set up Stripe.js and Elements to use in checkout form, passing the client secret
// and CustomerSession's client secret obtained in a previous step
const elements = stripe.elements(elementsOptions);

// Create and mount the Payment Element
const paymentElementOptions = { layout: 'accordion'};
const paymentElement = elements.create('payment', paymentElementOptions);
paymentElement.mount('#payment-element');
```

Quando confermi il PaymentIntent, Stripe.js configura automaticamente l’impostazione [setup_future_usage](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-setup_future_usage) sul PaymentIntent e [allow_redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) sul PaymentMethod, a condizione che il cliente abbia selezionato la casella per salvare i propri dati di pagamento.

### Imporre la nuova raccolta del CVC

Facoltativamente, specifica `require_cvc_recollection` [quando crei il PaymentIntent](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-card-require_cvc_recollection) per imporre la nuova raccolta del CVC quando un cliente paga con una carta.

### Rileva la selezione di una modalità di pagamento salvata

Quando viene selezionata una modalità di pagamento salvata, per controllare i contenuti dinamici ascolta l’evento `change` del Payment Element, che viene popolato con la modalità di pagamento selezionata.

```javascript
paymentElement.on('change', function(event) {
  if (event.value.payment_method) {
    // Control dynamic content if a saved payment method is selected
  }
})
```

## Save only payment methods that support reuse [Lato server]

You can’t make all payment methods [reusable](https://docs.stripe.com/payments/accept-a-payment.md#save-payment-method-details) by enabling `setup_future_usage` in the Payment Intent. See [Payment method support](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability) to learn more about which payment methods are compatible with `setup_future_usage`.

Instead, you can save payment method details only when a customer selects a payment method that supports it. For example, if you accept both card payments and Giropay (which you can’t reuse), configure `setup_future_usage=off_session` on the `payment_method_options[card]` object.

Se il cliente rifiuta di salvare i propri dati di pagamento, disabilita `setup_future_usage` in PaymentIntent sul lato server. Non è possibile apportare questa modifica sul lato client.

#### Gestire le modalità di pagamento dalla Dashboard

Puoi gestire le modalità di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods). Stripe determina la restituzione delle modalità di pagamento idonee in base a fattori quali l’importo della transazione, la valuta e il flusso di pagamento.

#### curl

```bash
curl https://api.stripe.com/v1/payment_intents \
  -u <<YOUR_SECRET_KEY>>: \
  -d "amount"=1099 \
  -d "currency"="usd" \
  -d "automatic_payment_methods[enabled]"="true" \
  -d "payment_method_options[card][setup_future_usage]"="off_session"
```

#### Elencare manualmente le modalità di pagamento

In alternativa, puoi indicare `card` e `giropay` utilizzando i [tipi di metodi di pagamento](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types), come nell’esempio riportato di seguito.

#### curl

```bash
curl https://api.stripe.com/v1/payment_intents \
  -u <<YOUR_SECRET_KEY>>: \
  -d "amount"=1099 \
  -d "currency"="usd" \
  -d "payment_method_types[]"="card" \
  -d "payment_method_types[]"="giropay" \
  -d "payment_method_options[card][setup_future_usage]"="off_session"
```

## Addebita in un secondo momento l'importo sulla modalità di pagamento salvata [Lato server]

> Per impostazione predefinita, `bancontact`, `ideal` e `sofort` sono modalità di pagamento una tantum. Se configurate per essere utilizzate in futuro, generano una modalità di pagamento di tipo `sepa_debit` riutilizzabile, per cui devi utilizzare `sepa_debit` per consultare le modalità di pagamento salvate.

> #### Conformità
> 
> Quando salvi i dati di pagamento di un cliente, sei responsabile della conformità a tutte le leggi, le normative e le regole del circuito applicabili. Quando presenti al cliente finale i metodi di pagamento utilizzati in passato per acquisti futuri, accertati di elencare i metodi di pagamento per i quali hai raccolto il consenso a salvare i dati del metodo di pagamento per gli usi futuri specifici. Per differenziare i metodi di pagamento legati ai clienti che possono o non possono essere presentati al cliente finale come metodo di pagamento salvato per acquisti futuri, utilizza il parametro [allow_redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay).

Per individuare il metodo di pagamento da addebitare, elenca i metodi di pagamento associati al tuo cliente. In questo esempio vengono elencate le carte, ma puoi indicare qualsiasi [tipo](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-type) supportato.

> #### Utilizza l'API Accounts v2 per rappresentare i clienti
> 
> The Accounts v2 API is generally available for Connect users, and in public preview for other Stripe users. If you’re part of the Accounts v2 preview, you need to specify a [specify a preview version](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning) in your code.
> 
> To request access to the Accounts v2 preview, 
> 
> Nella maggior parte dei casi d’uso, consigliamo di [rappresentare i clienti come oggetti Account configurati dall’utente,](https://docs.stripe.com/connect/use-accounts-as-customers.md) anziché utilizzare oggetti [Customer](https://docs.stripe.com/api/customers.md).

#### Account v2

```curl
curl -G https://api.stripe.com/v1/payment_methods \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d type=card
```

#### Clienti v1

```curl
curl -G https://api.stripe.com/v1/payment_methods \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer={{CUSTOMER_ID}}" \
  -d type=card
```

Quando è tutto pronto per l’addebito al cliente *off-session* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information), utilizza l’ID del cliente e l’ID del `PaymentMethod` per creare un `PaymentIntent` specificando l’importo e la valuta del pagamento. Imposta alcuni altri parametri per effettuare il pagamento off-session:

- Impostare [off_session](https://docs.stripe.com/api/payment_intents/confirm.md#confirm_payment_intent-off_session) a `true` per indicare che il cliente non è nel flusso di pagamento durante un tentativo di pagamento e non può soddisfare una richiesta di autenticazione effettuata da un partner, come una società emittente della carta, una banca o altro istituto di pagamento. Se, durante il flusso di pagamento, un partner richiede l’autenticazione, Stripe richiede le esenzioni utilizzando le informazioni sul cliente ricavate da una transazione precedente *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 le condizioni per l’esenzione non sono soddisfatte, il `PaymentIntent` potrebbe generare un errore.
- Imposta il valore di [conferma](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-confirm) della proprietà `PaymentIntent` su true, per far sì che la conferma avvenga immediatamente quando crei il `PaymentIntent`.
- Imposta [payment_method](https://docs.stripe.com/api.md#create_payment_intent-payment_method) sull’ID del `PaymentMethod`.
- SA seconda di come rappresenti i clienti nella tua integrazione, imposta [customer_account](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer_account) sull’ID dell’`Account` configurato dal cliente o [cliente](https://docs.stripe.com/api.md#create_payment_intent-customer) sull’ID del `Customer`.

#### Account v2

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d "automatic_payment_methods[enabled]=true" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d payment_method={{PAYMENT_METHOD_ID}} \
  --data-urlencode "return_url=https://example.com/order/123/complete" \
  -d off_session=true \
  -d confirm=true
```

#### Clienti v1

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d "automatic_payment_methods[enabled]=true" \
  -d "customer={{CUSTOMER_ID}}" \
  -d payment_method={{PAYMENT_METHOD_ID}} \
  --data-urlencode "return_url=https://example.com/order/123/complete" \
  -d off_session=true \
  -d confirm=true
```

## Testa l'integrazione

Usa i dettagli di pagamento e la pagina di reindirizzamento di test per verificare se il funzionamento dell’integrazione è quello atteso. Per visualizzare i dettagli relativi a ciascuna modalità di pagamento, fai clic sulle seguenti schede:

#### Carte

| Modalità di pagamento | Scenario                                                                                                                                                                                                                                                                                                                             | Come eseguire il test                                                                                                                              |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Carta di credito      | La configurazione della carta ha esito positivo e non richiede l’*autenticazione* (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). | Compila il modulo per la carta di credito usando il numero di carta di credito `4242 4242 4242 4242` con qualsiasi scadenza, CVC e codice postale. |
| Carta di credito      | La carta richiede l’autenticazione per la configurazione iniziale, poi ha esito positivo per i pagamenti successivi.                                                                                                                                                                                                                 | Compila il modulo per la carta di credito usando il numero di carta di credito `4000 0025 0000 3155` con qualsiasi scadenza, CVC e codice postale. |
| Carta di credito      | La carta richiede l’autenticazione per la configurazione iniziale e per i pagamenti successivi.                                                                                                                                                                                                                                      | Compila il modulo per la carta di credito usando il numero di carta di credito `4000 0027 6000 3184` con qualsiasi scadenza, CVC e codice postale. |
| Carta di credito      | La carta viene rifiutata durante la configurazione.                                                                                                                                                                                                                                                                                  | Compila il modulo per la carta di credito usando il numero di carta di credito `4000 0000 0000 9995` con qualsiasi scadenza, CVC e codice postale. |

#### Reindirizzamenti bancari

| Modalità di pagamento | Scenario                                                                                                                                                      | Come eseguire il test                                                                                                                                                               |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Bancontact            | Il tuo cliente configura una modalità di pagamento con addebito diretto SEPA per uso futuro utilizzando Bancontact.                                           | Usa qualsiasi nome nel modulo Bancontact, quindi fai clic su **Autorizza configurazione test** nella pagina di reindirizzamento.                                                    |
| Bancontact            | Il cliente non riesce a eseguire l’autenticazione nella pagina di reindirizzamento di Bancontact.                                                             | Usa qualsiasi nome nel modulo Bancontact, quindi fai clic su **Interrompi configurazione test** nella pagina di reindirizzamento.                                                   |
| Addebito diretto BECS | Il tuo cliente paga correttamente con addebito diretto BECS                                                                                                   | Compila il modulo usando il numero di conto `900123456`. Il PaymentIntent confermato inizialmente passerà prima nello stato `processing` e, 3 minuti dopo, nello stato `succeeded`. |
| Addebito diretto BECS | Il pagamento del tuo cliente non va a buon fine e restituisce un codice di errore `account_closed`.                                                           | Compila il modulo usando il numero di conto `111111113`.                                                                                                                            |
| iDEAL                 | Il tuo cliente configura un metodo di pagamento con [addebito diretto SEPA](https://docs.stripe.com/payments/sepa-debit.md) per uso futuro utilizzando iDEAL. | Usa qualsiasi nome e banca nel modulo iDEAL, quindi fai clic su **Autorizza configurazione test** nella pagina di reindirizzamento.                                                 |
| iDEAL                 | Il cliente non riesce a eseguire l’autenticazione con la pagina di reindirizzamento di iDEAL.                                                                 | Scegli una banca e usa qualsiasi nome nel modulo iDEAL, quindi fai clic su **Interrompi configurazione test** nella pagina di reindirizzamento.                                     |

#### Addebiti bancari

| Modalità di pagamento | Scenario                                                                                       | Come eseguire il test                                                                                                                                                                                 |
| --------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Addebito diretto SEPA | Il tuo cliente paga correttamente con addebito diretto SEPA                                    | Compila il modulo usando il numero di conto `AT321904300235473204`. Il PaymentIntent confermato passerà inizialmente allo stato in elaborazione e, tre minuti dopo, allo stato di pagamento riuscito. |
| Addebito diretto SEPA | Lo stato del Payment Intent del tuo cliente passa da `processing` a `requires_payment_method`. | Compila il modulo usando il numero di conto `AT861904300235473202`.                                                                                                                                   |

### Eseguire il test dell’addebito con un PaymentMethod con addebito SEPA salvato

La conferma del PaymentIntent  usando iDEAL, Bancontact o Sofort genera un *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) di tipo [addebito diretto SEPA](https://docs.stripe.com/payments/sepa-debit.md). L’addebito diretto SEPA è un metodo di pagamento con [notifica differita](https://docs.stripe.com/payments/payment-methods.md#payment-notification) che transita da uno stato intermedio `processing` prima di passare a uno stato `succeeded` o `requires_payment_method` alcuni giorni dopo.

#### Email

Imposta `payment_method.billing_details.email` su uno dei valori seguenti per effettuare test sulle transizioni di stato del `PaymentIntent`. Puoi inserire del testo personalizzato all’inizio dell’indirizzo email, seguito da un carattere di sottolineatura. Ad esempio, `test_1_generatedSepaDebitIntentsFail@example.com` genera un PaymentMethod con addebito diretto SEPA che ha sempre esito negativo se utilizzato con un `PaymentIntent`.

| Indirizzo email                                                    | Descrizione                                                                                                              |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `generatedSepaDebitIntentsSucceed@example.com`                     | Lo stato del `PaymentIntent` passa da `processing` a `succeeded`.                                                        |
| `generatedSepaDebitIntentsSucceedDelayed@example.com`              | Lo stato di `PaymentIntent` passa da `processing` a `succeeded` dopo almeno tre minuti.                                  |
| `generatedSepaDebitIntentsFail@example.com`                        | Lo stato di `PaymentIntent` passa da `processing` to `requires_payment_method`.                                          |
| `generatedSepaDebitIntentsFailDelayed@example.com`                 | Lo stato di `PaymentIntent` passa da `processing` a `requires_payment_method` dopo almeno tre minuti.                    |
| `generatedSepaDebitIntentsSucceedDisputed@example.com`             | Lo stato del `PaymentIntent` passa da `processing` a `succeeded`, ma viene creata immediatamente una contestazione.      |
| `generatedSepaDebitIntentsFailsDueToInsufficientFunds@example.com` | Lo stato `PaymentIntent` passa da `processing` a `requires_payment_method` con il codice di errore `insufficient_funds`. |

#### PaymentMethod

Utilizza questi `PaymentMethods` per verificare le transizioni di stato del PaymentIntent. Questi token sono utili per eseguire test automatizzati e aggiungere immediatamente il PaymentMethod a SetupIntent sul server.

| Modalità di pagamento                                                | Descrizione                                                                                                              |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `pm_bancontact_generatedSepaDebitIntentsSucceed`                     | Lo stato del `PaymentIntent` passa da `processing` a `succeeded`.                                                        |
| `pm_bancontact_generatedSepaDebitIntentsDelayed`                     | Lo stato di `PaymentIntent` passa da `processing` a `succeeded` dopo almeno tre minuti.                                  |
| `pm_bancontact_generatedSepaDebitIntentsFail`                        | Lo stato di `PaymentIntent` passa da `processing` to `requires_payment_method`.                                          |
| `pm_bancontact_generatedSepaDebitIntentsFailDelayed`                 | Lo stato di `PaymentIntent` passa da `processing` a `requires_payment_method` dopo almeno tre minuti.                    |
| `pm_bancontact_generatedSepaDebitIntentsSucceedDisputed`             | Lo stato del `PaymentIntent` passa da `processing` a `succeeded`, ma viene creata immediatamente una contestazione.      |
| `pm_bancontact_generatedSepaDebitIntentsFailsDueToInsufficientFunds` | Lo stato `PaymentIntent` passa da `processing` a `requires_payment_method` con il codice di errore `insufficient_funds`. |

## See also

- [Salvare i dati di pagamento durante i pagamenti in-app](https://docs.stripe.com/payments/mobile/save-during-payment.md)
- [Salvare i dati di pagamento in una sessione di Checkout](https://docs.stripe.com/payments/checkout/how-checkout-works.md#save-payment-methods)
- [Configurare pagamenti futuri](https://docs.stripe.com/payments/save-and-reuse.md)
- [Handle post-payment events](https://docs.stripe.com/webhooks/handling-payment-events.md)

