## Overview

This guide dives into leveraging Dwolla’s Open Banking Services in collaboration with Visa, a world leader in digital payments, to streamline bank account verification within your Dwolla-powered application. Open banking empowers your users to more securely share their financial data with Dwolla and your application, eliminating the need for manual entry and improving the overall user experience. We’ll walk you through the steps to set up and integrate Visa Instant Account Verification (Visa IAV) using Dwolla’s [Exchange Sessions API](https://developers.dwolla.com/docs/api-reference/exchange-sessions/create-customer-exchange-session). Dwolla’s powerful Exchange Sessions API acts as the bridge between your application and Visa Open Banking Solutions. This established connection facilitates real-time verification of your user’s bank account details. To gain hands-on experience, we recommend following along with the provided [integration-examples](https://github.com/Dwolla/integration-examples/tree/main/packages/open-banking/visa) sample app, which provides a practical understanding of the integration process for your own application. Instant Account Verification (IAV) is a one-time process that verifies the account being added by an end user is open and active. At the end of this guide, you’ll obtain a Funding Source URL, which is a unique identifier that represents a bank account being used for account-to-account payments.

## Prerequisites

Before starting the integration, make sure you have taken the following steps:

- Set up a [Dwolla Production](https://accounts.dwolla.com/) account, or a [Dwolla Sandbox](https://accounts-sandbox.dwolla.com/) account if you’re still developing or testing your application.
- Before creating a funding source, your application will need to create a Customer. If you have not created a Customer yet, check out our [Create a Customer](https://developers.dwolla.com/docs/api-reference/customers/create-a-customer) API documentation.
- Ensure you have a redirect URL registered with Dwolla. This is where the user lands after completing the IAV flow.

## Sandbox Testing

Testing within the sandbox environment is an essential step before deploying the Visa IAV solution to a production environment. The sandbox acts as a safe, isolated testing ground that mirrors real-world scenarios with test data. This allows you to validate the functionality of your integration without using actual user accounts or financial information. By thoroughly testing in the sandbox, you can identify and correct any potential issues before they impact your live users.

#### Demo Bank Test Credentials

When an end-user opens the Exchange Session URL, they are prompted to authenticate with their bank and choose a bank account to link. When testing Visa IAV in the sandbox environment, you can use the following test credentials for the Demo Bank to simulate different scenarios.

| User   | Username   | Password | Description                                                           | Result             |
|--------|------------|----------|-----------------------------------------------------------------------|--------------------|
| User 1 | u51613239  | cty440   | User has successfully authenticated but no account information could be found  | ✅ Successful       |
| User 2 | u35490150  | ckr403   | Report with full information                                          | ✅ Successful       |
| User 3 | u92721594  | nbs589   | User failed to authenticate themselves at the financial institution       | ❌ Authentication error |
| User 4 | u91902655  | jtx720   | Temporary error with a Visa service                                   | ❌ Temporary error  |

#### Dwolla Node SDK for API Interactions

Throughout this guide, we’ll assume you’re using the [Dwolla Node SDK](https://developers.dwolla.com/docs/sdks-tools/node) to interact with Dwolla’s API endpoints. This SDK simplifies making requests and handling responses for various Dwolla functionalities.

## Demo

[**Visa Open Banking Demo**  \\  \\  Coast Demo: Visa Open Banking Flow  \\  \\  Demo](https://dwolla.coastdemo.com/share/67ca29bcc030cd6114d7d837?&step=2&skip_to_end=yes&mode=link&layoutType=web)

## Steps to Integrate

### Step 1 - Initiate Exchange Session

Use Dwolla’s API endpoint to [create an exchange session](https://developers.dwolla.com/docs/api-reference/exchange-sessions/create-customer-exchange-session) to initiate an Exchange Session for a Customer. Specify Visa as the desired open banking provider within the request body. The Exchange Partner ID for Visa can be found by calling the [List Exchange Partners](https://developers.dwolla.com/docs/api-reference/exchanges/list-exchange-partners) API endpoint.

### Redirect URL Validation

When using Visa as the exchange partner for an exchange session, a redirect URL is required. This URL specifies where the user will be redirected after completing the authorization process with Visa. Dwolla will validate the provided redirect URL against the one previously configured for your application.

##### Guidelines:

- Ensure your configured redirect URL with Dwolla exactly matches the one you include in the request body (including protocol, domain, port, and path).
- Use HTTPS for your redirect URL to enhance security.
- Consider whitelisting your redirect URL to restrict redirects to specific domains.

#### Example using Dwolla Node SDK

```javascript
import { Client } from "dwolla-v2";
const dwolla = new Client({
  key: "YOUR_KEY",
  secret: "YOUR_SECRET",
  environment: "sandbox", // or 'production'
});

/**
 * Creates an exchange session for a customer
 * @param customerId - The ID of the customer to create the exchange session for.
 */
export async function createExchangeSession(customerId: string) {
  const exchangePartnerHref = await getExchangePartnerHref();
  const requestBody = {
    _links: {
      "exchange-partner": {
        href: exchangePartnerHref,
      },
      "redirect-url": {
        href: "https://www.yourdomain.com/iav-callback",
      },
    },
  };
  try {
    const response = await dwolla.post(
      `customers/${customerId}/exchange-sessions`,
      requestBody
    );
    const location = response.headers.get("location");
    return location;
  } catch (error) {
    // Return an error message or handle the error appropriately
  }
}
```

### Step 2 - Retrieve Exchange Session and Complete Tink/Visa Link Flow

In this step, you’ll [retrieve the exchange session](https://developers.dwolla.com/docs/api-reference/exchange-sessions/retrieve-exchange-session) details, including the Exchange Session URL. This URL is used to initiate the Visa Link flow within your application. Use the exchange session ID obtained in Step 1 to call Dwolla’s Retrieve an Exchange Session endpoint. During this flow, the user interacts with Visa’s interface to authorize their bank account information to be shared.

#### Example using Dwolla Node SDK

```javascript
/**
 * Retrieves an exchange session URL by ID
 * @param exchangeSessionId - The ID of the exchange session to retrieve.
 */
export async function getExchangeSession(exchangeSessionId: string) {
  try {
    const response = await dwolla.get(
      `/exchange-sessions/${exchangeSessionId}`
    );
    const externalProviderSessionUrl =
      response.body._links["external-provider-session"].href;
    return externalProviderSessionUrl;
  } catch (error) {
    // Return an error message or handle the error appropriately
  }
}
```

### Step 3 - Handle User Redirect

After completing the Visa IAV flow, Visa redirects the user back to your registered URL. This redirect URL will include a query string parameter of “exchange” or an “error” depending on the outcome of the Visa IAV flow. You’ll need to implement logic to route the user based on if the flow completed successfully or if there was an error.

##### Example Success and Error redirect URL

```plaintext
https://www.myapp.com/iav-redirect?exchange=10cde28b-6a39-4ed1-bce9-aa611a360720

https://www.myapp.com/iav-redirect?error=USER_CANCELLED
```

### Errors

The Visa Link flow may lead to a recoverable error or a non-recoverable error which can’t be resolved by the user. In such cases, it’s important to provide clear and actionable messages to the user, and/or return the user to the pre-verification step based on the error. The decision to present an error screen or return the user to the pre-verification step depends on the specific error and your application’s design. Here’s a general guideline:

**Recoverable Errors:** These are issues that can potentially be resolved by the user. In such cases, it’s important to provide clear and actionable messages to the user. An error screen is often suitable for recoverable errors.

- **Examples:**
  - **Invalid Credentials:** The user might have entered incorrect bank login credentials.
  - **Temporary Network Issues:** A temporary network glitch might interrupt the communication.
  - **User Cancelled:** The user decided to abandon the Visa IAV process.

**Non-Recoverable Errors:** These are more severe issues that cannot be resolved by the user and require intervention from your business or their bank.

- **Examples:**
  - **System Errors:** Internal system errors within Dwolla or Visa’s infrastructure.
  - **Account Lockout:** The user’s bank account might be locked due to security reasons.

##### List of possible redirect errors

| Error Code                  | Description                                                                 |
|-----------------------------|-----------------------------------------------------------------------------|
| AUTHENTICATION_ERROR        | The error occurred during the authentication process with the bank.         |
| USER_CANCELLED              | The end user canceled the journey, either by going back or selecting the close button. |
| TEMPORARY_ERROR             | A temporary error in Visa’s platform or a network issue.                   |

### Step 4 - Funding Source Creation

After successfully creating the exchange, the next step is to create a funding source for the customer. This involves calling Dwolla’s [Create a Funding Source](https://developers.dwolla.com/docs/api-reference/funding-sources/create-customer-funding-source) endpoint.

```javascript
/**
 * Creates a funding source for a customer.
 * @param options - The options including customerId, exchangeId, name, and type.
 */
export async function createFundingSource(options: CreateFundingSourceOptions) {
  const { customerId, exchangeId, name, type } = options;
  const exchangeUrl = `https://api.dwolla.com/exchanges/${exchangeId}`;
  const requestBody = {
    _links: {
      exchange: {
        href: exchangeUrl,
      },
    },
    bankAccountType: type,
    name: name,
  };
  try {
    const response = await dwolla.post(
      `customers/${customerId}/funding-sources`,
      requestBody
    );
    const location = response.headers.get("location");
    return location;
  } catch (error) {
    // Return an error message or handle the error appropriately
  }
}
```

## Handling Re-authentication

When users initially connect their bank account via Instant Account Verification, they authenticate with their bank and grant permission to access their account information. To maintain a smooth user experience, your application needs to handle these scenarios gracefully. Dwolla’s API provides an `UpdateCredentials` error response to signal when a user’s bank connection needs to be refreshed.

##### `UpdateCredentials` error response

```json
{
    "code": "UpdateCredentials",
    "message": "Re-authentication is required in order to access account data. Please initiate the exchange session flow to regain access.",
    "_links": {
        "about": {
            "href": "https://api.dwolla.com/exchanges/036c8a60-fa45-45d4-8f5d-181d348c6ec8/exchange-sessions",
            "type": "application/vnd.dwolla.v1.hal+json",
            "resource-type": "exchange-session"
        }
    }
}
```

#### Steps to manage re-authentication

1. **Detect the `UpdateCredentials` error:** When making calls to Dwolla’s API (e.g., checking a bank balance), implement error handling to catch the UpdateCredentials response.
2. **Communicate with your user:** It’s crucial to inform the user why they need to re-authenticate and how to do so.
3. **Initiate the re-authentication flow:** Upon receiving this error, redirect the user to re-authenticate their bank account.

By following these steps, you can ensure that your application can handle interruptions to bank connections effectively, providing a smooth and user-friendly experience.

### Initiate re-authentication exchange-session

Use Dwolla’s API endpoint to [create a re-authentication exchange session](https://developers.dwolla.com/docs/api-reference/exchange-sessions/create-re-authentication-exchange-session) to initiate an Exchange Session for a Customer.
