# Managing payment sessions

A payment session tracks a customer's payment throughout the checkout process. Although you're not required to, we highly [recommend you use payment sessions](#why-use-payment-sessions) to reduce the complexity of building DigitalRiver.js payment collection flows and to comply with [PSD2 and SCA](https://docs.digitalriver.com/commerce-api/payments/psd2-and-sca) regulations.&#x20;

[Migrating to payment sessions](#migrating-to-payment-sessions) is relatively straightforward and mostly involves [updating the code](#update-your-code) for each of your approved payment methods.

## Why use payment sessions?

Payment sessions allow you to comply with [PSD2 and SCA](https://docs.digitalriver.com/commerce-api/payments/psd2-and-sca) regulations. Digital River automatically collects the required authentication data from the customer's PSD2 transactions when using payment sessions to [create credit card sources](#credit-card).

Payment sessions also simplify source creation by reducing the data you're required to provide. If you don't use payment sessions, you'll need to copy numerous data points returned in the cart and ensure it is properly formatted before passing them to the [create source method](https://docs.digitalriver.com/commerce-api/resources/reference/digitalriver-object#digitalriver-createsource-element-sourcedata). &#x20;

However, when [creating a source with payment sessions](#creating-a-source-with-payment-sessions), you can provide the session's unique identifier, thereby minimizing the data you must transfer.&#x20;

Payment sessions also allow you to [gain access to Drop-in payments](https://docs.digitalriver.com/commerce-api/payments/payments-solutions/drop-in/drop-in-integration-guide), which lessens your front-end development burden. For each transaction, [Drop-in payments](https://docs.digitalriver.com/commerce-api/payments/payments-solutions/drop-in) [retrieve the available payment methods](#retrieving-available-payment-methods) applicable to the transaction and display them as options to customers.

## Creating a source with payment sessions

When [creating a payment source,](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#creating-payment-sources) specify the `sessionId` in the payload that you pass to the DigitalRiver.js [create source method](https://docs.digitalriver.com/commerce-api/resources/reference/digitalriver-object#creating-sources). The data our payment services need to create the source is then retrieved from that session.

{% hint style="success" %}
We highly recommend using payment sessions when creating a payment source in a cart flow to reduce the complexity of building the [DigitalRiver.js](#digitalriver.js-with-elements) payment collection flows and to comply with [PSD2 and SCA](https://docs.digitalriver.com/commerce-api/payments/psd2-and-sca) regulations.
{% endhint %}

{% tabs %}
{% tab title="Drop-in payments" %}

```json
let configuration = {
    "sessionId": "172deb0f-de6f-4d2c-9555-53f3894b6318",
    "options": {
        "flow": "checkout",
        "showComplianceSection": true
    }, 
    onSuccess: function(data) {}, 
    onError: function(data) {}, 
    onReady: function(data) {}, 
    onCancel: function(data) {}
}
                                    
let dropin = digitalriverpayments.createDropin(configuration);
dropin.mount("drop-in");
```

{% endtab %}

{% tab title="DigitalRiver.js with elements" %}

```json
let payload = {
    "sessionId": "ea03bf6f-84ef-4993-b1e7-b7d5ecf71d1f",
    "type": "payPal",
    "payPal": {
        "returnUrl": "https://yourReturnUrl.com",
        "cancelUrl": "https://yourCancelUrl.com"
    }
}
 
digitalriver.createSource(payload).then(function(result) {
     
    if(result.state === "chargeable") {
        sendToBackEnd(result);
    } else {
        doErrorScenario();
    }
});
```

{% endtab %}
{% endtabs %}

## How to determine when to create an order

A cart's `payment.session` can be used to determine when to create an order. Specifically, we provide you information on the [payment session's state](#session-state), the [amount contributed, and the amount remaining to be contributed](#amount-contributed-and-amount-remaining-to-be-contributed).

{% code title="Cart" %}

```json
{
"    id": "47278010023",
.    ..
    "paymentSession": 
    {
        "id": "string",
        "status": "string",
        "clientSecret": "string",
        "redirectUrl": "https://api.digitalriver.com:80/payments/redirects/12759bb0-xxxx-4bdb-bfeb-9095ba8059fc?apiKey=a88fxxxx1eef47eb95bc609c22e593c8",
        "amountContributed": 
        {},
        "amountRemainingToBeContributed": 
        {}
    }
}
```

{% endcode %}

### Session state

The following are the payment session states most important when building your integration:

* [Requires confirmation](#requires-confirmation)
* [Requires source](#requires-source)
* [Complete](#complete)

#### Requires confirmation

The cart's `payment.session.state` must be `requires_confirmation` before you convert that cart to an order.

This `state` indicates that the cart's payment sources\[] are sufficient to fund the transaction. For example, when you [attach ](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#attaching-sources-to-a-cart)a [`chargeable` ](https://docs.digitalriver.com/commerce-api/payments/sources#source-state)[primary source](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#primary-payment-sources) to a checkout, the [amount remaining to contribute](#amount-contributed-and-amount-remaining-to-be-contributed) drops to zero, and the session's `state` transitions to `requires_confirmation`.

#### Requires source

A cart's `payment.session.state` can be `requires_source` for either of the following reasons:

* No [primary ](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#primary-payment-sources)or [secondary payment sources](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#secondary-payment-sources) have yet been applied.
* No primary payment source is applied, and there are not enough [secondary payment sources](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#secondary-payment-sources), such as [store credit](https://docs.digitalriver.com/commerce-api/shopper-apis/shopper-basics/common-use-cases/applying-store-credit), to fully fund the transaction.

In both of these scenarios, we won't be able to generate a charge amount large enough to cover the checkout's `totalAmount`. So, the [amount remaining to contribute](#amount-contributed-and-amount-remaining-to-be-contributed) remains greater than zero, and any attempt to create an order is blocked.

#### Complete

The payment session `state` typically transitions to `complete` once the order is created.

### Amount contributed and amount remaining to be contributed

Once a [primary payment source](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#primary-payment-sources) is attached to a cart, we use it to fully fund the transaction.

But when only [secondary payment sources](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#secondary-payment-sources) are attached, you need to confirm sufficient funds exist to cover the [cart's ](https://www.digitalriver.com/docs/commerce-api-reference/#tag/Carts)`totalAmount`. If this isn't the case, when you convert the cart to an order, you receive the following error:

{% tabs %}
{% tab title="400 Bad Request" %}

```json
{
    "type": "bad_request",
    "errors": [
        {
            "code": "order_submit_failed",
            "message": "Payment session status is invalid."
        }
    ]
}
```

{% endtab %}
{% endtabs %}

By comparing values in the cart's `payment.session`, you can determine how much additional funding, if any, is still required. The `amountContributed` represents the aggregated amount of all the cart's `payment.sources[]`. The `amountRemainingToBeContributed` is how much is needed to fully fund the transaction.

If the `amountContributed` is equal to the cart's `totalAmount` or the `amountRemainingToBeContributed` is zero, then you don't need to request any more payment methods from the customer. This means that once the [payment session is in the correct state](#session-state), and all [address requirements](https://docs.digitalriver.com/commerce-api/shopper-apis/cart/creating-or-updating-a-cart/providing-address-information) are met, you can convert the cart to an order.

But if the `amountContributed` is less than the cart's `totalAmount` or the `amountRemainingToBeContributed` is greater than zero, the customer needs to supply additional payment methods before an order can be successfully created. However, this will only be the case when a [primary payment source](https://docs.digitalriver.com/commerce-api/payments/sources/using-the-source-identifier#primary-payment-sources) is not yet attached to the checkout. Once that's done, we use it to fully fund the transaction and `amountRemainingToBeContributed` drops to zero.

## Attaching a source

You can [attach a source to a customer](https://docs.digitalriver.com/commerce-api/payments/sources#attaching-a-payment-method-to-an-order-or-cart) or [an order or cart](https://docs.digitalriver.com/commerce-api/payments/sources#attaching-a-payment-method-to-an-order-or-cart). See [Source basics](https://docs.digitalriver.com/commerce-api/payments/sources) for more information.

## Retrieving available payment methods

In DigitalRiver.js, you can use the payment session identifier to [return the payment methods available for each transaction](https://docs.digitalriver.com/commerce-api/resources/reference/digitalriver-object#retrieving-available-payment-methods) and present them to the customer during checkout.

The method also returns the data required to use one-click payment methods like Apple Pay and Google Pay and the data needed to retrieve compliance information via the DigitalRiver.js [compliance methods](https://docs.digitalriver.com/commerce-api/resources/reference/digitalriver-object#digitalriver-compliance-getdetails-businessentitycode-locale).&#x20;

{% tabs %}
{% tab title="JavaScript" %}

```json
digitalriver.retrieveAvailablePaymentMethods({
    "sessionId": "ea03bf6f-84ef-4993-b1e7-b7d5ecf71d1f"
}).then(function(result) {
    //do something with the data
});
```

{% endtab %}
{% endtabs %}

## Migrating to payment sessions

Although we generally recommend using [Drop-in payments](https://docs.digitalriver.com/commerce-api/payments/payments-solutions/drop-in) to handle payments, you can also migrate your existing integration directly to payment sessions. For the Commerce API, [payment sessions must be enabled](#enable-payment-sessions).

Once you have completed this migration process, you must [build your SCA workflows](https://docs.digitalriver.com/commerce-api/payments/building-your-workflows) using [Drop-in payments](https://docs.digitalriver.com/commerce-api/payments/payments-solutions/drop-in) or [DigitalRiver.js with elements](https://docs.digitalriver.com/commerce-api/payments/payments-solutions/digitalriver.js).&#x20;
