# Mastercard Data Connect Components Web SDK
source: https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md

The Mastercard Data Connect Components SDK provides a collection of custom web components that can be used to build login forms for legacy institutions, initiate OAuth authentication flow for institutions, and render Multi-Factor Authorization (MFA) challenges encountered during legacy institution login. This section describes how to integrate Data Connect Components with different Financial Institutions (FIs), how to set up MFA so end users can connect to their FI securely, and how Data Connect Components elements and events can be used to create a clean interface through the authentication process.

* [First Steps](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#first-steps)
* [Login Form Usage](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#login-form-usage)
* [OAuth Usage](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#oauth-usage)
* [Data Connect Components Styling Interface](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#data-connect-components-styling-interface)
* [Elements](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#elements)
* [Events](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#events)

## First Steps {#first-steps}

The implementation steps depend on whether you are using login forms or an OAuth URL (in other words, whether the FI is a legacy or OAuth connection):

* [Login Form Usage](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#login-form-usage) - For connections that do not leverage direct connectivity (such as OAuth), a means to create and embed a login form is provided.

* [OAuth URL Usage](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#oauth-usage) - For OAuth connections, the handling of credentials is facilitated directly by the FI. An API is provided to obtain a suitable URL.

See also the [Legacy and OAuth Connections](https://developer.mastercard.com/open-finance-us/documentation/connect/components/flows/index.md#legacy-and-oauth-connections) part of the [Data Connect Components Flows](https://developer.mastercard.com/open-finance-us/documentation/connect/components/flows/index.md) section.

### Configuration Objects (Optional) {#configuration-objects-optional}

If you want to control which account types the user can connect with, you must first specify a configuration object. To do this, call the following endpoint and provide an array of the account types you want to allow.

API Reference: `POST /connect-components/configurations`

The response includes a configuration ID value which you can use when creating either a login form or OAuth URL. We provide the following endpoint to query what configuration objects have already been created:

API Reference: `GET /connect-components/configurations`

To query the details of an existing configuration use the following:

API Reference: `GET /connect-components/configurations/{configuration\_id}`

You can delete an unwanted configuration using this endpoint:

API Reference: `DELETE /connect-components/configurations/{configuration_id}`

## Login Form Usage {#login-form-usage}

For connections that do not use OAuth (legacy connections), the first step is to create a login form. If you created a configuration object in the previous step, then you should pass the configuration ID in the request body.

API Reference: `POST /connect-components/institutions/{institution_id}/login-forms`

The response from the Data Connect Components API to *create a login form* looks like this:

```json
{
  "id": "8d9d8f5e-2c5f-4f49-bf9b-276a7df0367f",
  "eventStreamId": "8859489f-12aa-4fd3-bcf5-ba0249e643a3",
  "elements": [
    {
      "id": "26410b1f-0347-4d57-bb03-f44d00e785e2",
      "label": "username",
      "sortOrder": 0
    },
    {
      "id": "f2ce62c2-877f-4c26-9935-d1ab6084e6d0",
      "label": "password",
      "sortOrder": 1
    }
  ]
}
```

This response must be provided to the Data Connect Components SDK to render the login form elements. Each item in the `elements` property represents a single `<mastercard-input>` for a customer to interact with.
Note: Input Element Quantities Vary.

It is important to note that the names and quantities of form elements in the create login form response depend entirely on what is required by the selected financial institution. For most institutions, two elements should be expected (one to capture a username and one to capture a password), but this is not always the case. **Take care to account for variations in the number of Elements, and for different labels for each element.**

### Render Login Form {#render-login-form}

The above response would be rendered using the SDK with the `<mastercard-form>` and `<mastercard-input>` elements. Notice that the top level `id` and `eventStreamId` properties from the response are attributes on the `mastercard-form` element. Additionally, each `id` from the items in the elements array should be used as the `id` attribute for separate `<mastercard-input>` elements. These `id` attributes provide the SDK with all of the information needed to render the login form. The `sortOrder` property indicates the ascending order the elements are displayed on the original bank login form.

```html
<mastercard-form
  id="8d9d8f5e-2c5f-4f49-bf9b-276a7df0367f"
  event-stream-id="8859489f-12aa-4fd3-bcf5-ba0249e643a3">
    <label>Username</label>
    <mastercard-input id="26410b1f-0347-4d57-bb03-f44d00e785e2"></mastercard-input>
    <label>Password</label>
    <mastercard-input id="f2ce62c2-877f-4c26-9935-d1ab6084e6d0"></mastercard-input>
    <button id="submit-credentials">Submit</button>
</mastercard-form>
```

### Submit Login Form {#submit-login-form}

To submit this `<mastercard-form>` and initiate the connection to the customer's financial institution, the correct SDK submit method must be called. The following example shows the method as expressed in simple Javascript:

```javascript
const mastercardForm = document.querySelector('mastercard-form');
const submitButton = document.querySelector('#submit-credentials');
submitButton.addEventListener('click', browserClickEvent => {
  browserClickEvent.preventDefault();
  mastercardForm.submit();
});
```

Once the `.submit()` method has been called on the `<mastercard-form>` element, the SDK handles sending the customer's credentials to Mastercard to begin the process of connecting to the customer's financial institution.

For your application to know how the connection is progressing, you need to have event listeners for `success`, `error`, and `mfaChallenge`. To add an event listener, call the `addEventListener()` method on the `mastercard-form` element's `events` property.

```javascript
const mastercardForm = document.querySelector('mastercard-form');
mastercardForm.events.mfaChallengeEvent('success', successEvent => {
  // This simple example handles the done event by posting the event payload
  // to the application's server and displaying a dialog to the user.
  const successfulConnection = new Request(`https://app.example.com/customers/${customerId}/success`, {
    method: 'POST',
    body: JSON.stringify(successEvent)
  })
  fetch(successfulConnection)
    .then(response => response.json())
    .then(serverMessage => {
      const notificationElement = document.querySelector('#customer-notification');
      const userDialog = `
      <dialog open>
        <p>${serverMessage.customerSuccessNotification}</p>
        <form method="dialog">
          <button>OK</button>
        </form>
      </dialog>`
      notificationElement.setHTML(userDialog);
    })
    .catch(console.error);
});

mastercardForm.events.addEventListener('error', errorEvent => {
  // This example handles the error event by posting the error payload to the
  // application's server and notifying the customer that an error has occurred.
  const errorDuringLogin = new Request(`https://app.example.com/customers/${customerId}/error`, {
    method: 'POST',
    body: JSON.stringify(errorEvent)
  })
  fetch(errorDuringLogin)
    .then(response => response.json())
    .then(serverMessage => {
      const notificationElement = document.querySelector('#customer-notification');
      const userDialog = `
      <dialog open>
        <p>${serverMessage.customerErrorNotification}</p>
        <form method="dialog">
          <button>OK</button>
        </form>
      </dialog>`
      notificationElement.setHTML(userDialog);
    })
    .catch(console.error);
});
mastercardForm.events.addEventListener('mfaChallenge', successEvent => {
  // The types of MFA challenges differ, refer to the MFA Required For Connection section below for more details.
});
```

### Successful Financial Institution Connection {#successful-financial-institution-connection}

If the connection to the financial institution is successful, the `success` [event](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#events) payload contains these fields: `customerId`, `institutionId`, `accountId`, and `institutionLoginId`.

Detailed documentation for these fields can be found in the main [US Open Finance API Reference](https://developer.mastercard.com/drafts/open-finance-us/components-mfa-updates/documentation/api-reference/):

* [customerId](https://developer.mastercard.com/drafts/open-finance-us/components-mfa-updates/documentation/api-reference/?view=model#Customer)
* [institutionId](https://developer.mastercard.com/drafts/open-finance-us/components-mfa-updates/documentation/api-reference/?view=model#Institutions)
* [accountId](https://developer.mastercard.com/drafts/open-finance-us/components-mfa-updates/documentation/api-reference/?view=model#CustomerAccount)
* [institutionLoginId](https://developer.mastercard.com/drafts/open-finance-us/components-mfa-updates/documentation/api-reference/?view=api#GetCustomerAccountsByInstitutionLogin)

With these values, your application's server can request the customer's financial information from the Mastercard Open Finance API.

```json
[{
  "customerId": "<customerId>",
  "institutionId": "<institutionId>",
  "accountId": "<accountId>",
  "institutionLoginId": "<institutionLoginId>"
}]
```

#### MFA Required for Connection {#mfa-required-for-connection}

If an MFA challenge is encountered during connection, the [`mfaChallenge`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#mfachallenge-legacy-login-only) event is emitted. There are five types of [MFA challenges](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#mfa-challenge-types) that a financial institution can choose to send:

* [`TFA_TEXT`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#tfa_text)
* [`TFA_CHOICE`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#tfa_choice)
* [`TFA_MULTI`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#tfa_multi)
* [`TFA_IMAGE`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#tfa_image)
* [`TFA_IMAGE_PROMPT`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#tfa_image_prompt).

The `mfaChallenge` event payload contains an array of one or more challenge objects. The `mfaType` determines what properties are present in each challenge object. All challenge objects contain the following properties: `id`, `eventStreamId`, `mfaType`, `prompt`, and `choiceIds`. `TFA_IMAGE_PROMPT` challenges also contain a `promptImage` property.
Note: The MFA challenge renderings below are provided to illustrate how the challenge could look. The final styling is up to your application. Please refer to the [Data Connect Components Styling Interface](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#data-connect-components-styling-interface) section for guidance.

##### TFA_TEXT {#tfa_text}

The `TFA_TEXT` challenge type presents a single input box to the customer and is commonly used for things like One-Time Passwords. Below is the expected response for this type:

```json
[{
  "id": "3ea29b1a-0c2c-4052-a3e1-0cdb856163e8",
  "eventStreamId": "da03e052-915b-4ddc-9098-1ecbcc757bea",
  "mfaType": "TFA_TEXT",
  "prompt": "Enter name of your first pet.",
  "choiceIds": [
    "28bc340a-3b84-4dd1-85eb-cfacf8e0a0e9"
  ],
}]
```

The following is an example of the HTML to render the challenge:

```html
<mastercard-form
  id="3ea29b1a-0c2c-4052-a3e1-0cdb856163e8"
  event-stream-id="da03e052-915b-4ddc-9098-1ecbcc757bea">
    <label>Enter name of your first pet.</label>
    <mastercard-mfa-choice id="28bc340a-3b84-4dd1-85eb-cfacf8e0a0e9"></mastercard-mfa-choice>
    <button id="submit-mfa">Submit</button>
</mastercard-form>
```

This is a styled example of the `TFA_TEXT` challenge. Your application's rendering depends on the styling passed to the Styling Interface:
![Security Question Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_text_1.png) ![One-Time Password Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_otp_1.png)

##### TFA_CHOICE {#tfa_choice}

The `TFA_CHOICE` object represents a multiple-choice question and answer selection. Below is the expected response for this type:

```json
[{
  "id": "3ea29b1a-0c2c-4052-a3e1-0cdb856163e8",
  "eventStreamId": "da03e052-915b-4ddc-9098-1ecbcc757bea",
  "mfaType": "TFA_CHOICE",
  "prompt": "Which high school did you attend?",
  "choiceIds": [
    "372e703a-70db-4cf1-8b1f-23be24c50d74",
    "eeecb2b8-c55a-4ce1-9fd0-ae560a363adb",
    "1c012d39-ebf3-46ea-a5fe-b6460400520b",
    "b4e727df-cf8d-42d3-bfe9-8456c0178077"
  ]
}]
```

The following is an example of the HTML to render the challenge:

```html
<mastercard-form
  id="3ea29b1a-0c2c-4052-a3e1-0cdb856163e8"
  event-stream-id="da03e052-915b-4ddc-9098-1ecbcc757bea">
    <label>Which high school did you attend?</label>
    <mastercard-mfa-choice id="372e703a-70db-4cf1-8b1f-23be24c50d74"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="eeecb2b8-c55a-4ce1-9fd0-ae560a363adb"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="1c012d39-ebf3-46ea-a5fe-b6460400520b"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="b4e727df-cf8d-42d3-bfe9-8456c0178077"></mastercard-mfa-choice>
    <button id="submit-mfa">Submit</button>
</mastercard-form>
```

This is a styled example of the `TFA_CHOICE` challenge. Your application's rendering depends on the styling passed to the Styling Interface:
![Multiple-Choice Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_choice_1.png)

##### TFA_MULTI {#tfa_multi}

The `TFA_MULTI` challenge type presents the customer with multiple images to select from. Below is the expected response for this type:

```json
[{
  "id": "3ea29b1a-0c2c-4052-a3e1-0cdb856163e8",
  "eventStreamId": "da03e052-915b-4ddc-9098-1ecbcc757bea",
  "mfaType": "TFA_MULTI",
  "prompt": "Choose your favorite sport.",
  "choiceIds": [
    "55684c30-ff18-4b2a-a7ab-7ed6d3fa3fc0",
    "2a395968-0610-44e7-a379-96d4bfbcd0d3",
    "2847e882-882e-4c18-8c89-309673dc730d",
    "52fcac64-0d3d-4e7f-aa0b-36d6be003b62"
  ],
}]
```

The following is an example of the HTML to render the challenge:

```html
<mastercard-form
  id="3ea29b1a-0c2c-4052-a3e1-0cdb856163e8"
  event-stream-id="da03e052-915b-4ddc-9098-1ecbcc757bea">
    <label>Choose your favorite sport.</label>
    <mastercard-mfa-choice id="55684c30-ff18-4b2a-a7ab-7ed6d3fa3fc0"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="2a395968-0610-44e7-a379-96d4bfbcd0d3"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="2847e882-882e-4c18-8c89-309673dc730d"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="52fcac64-0d3d-4e7f-aa0b-36d6be003b62"></mastercard-mfa-choice>
    <button id="submit-mfa">Submit</button>
</mastercard-form>
```

This is a styled example of the `MFA_MULTI` challenge. Your application's rendering depends on the styling passed to the Styling Interface:
![Multiple Image Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_multi_1.png)

##### TFA_IMAGE {#tfa_image}

The `TFA_IMAGE` challenge presents a CAPTCHA-style image the customer needs to decipher. The `prompt` for this challenge is a [base64 URI encoded](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) image, with a single choice element that is a text box to enter the unscrambled image text into. Following is the expected response for this type:

```json
[{
  "id": "2f7069e5-751d-47c4-9f41-4f00089c0c56",
  "prompt": "<base64-encoded-image-data>",
  "mfaType": "TFA_IMAGE",
  "choiceIds": [
    "89427fa8-1383-43b0-87c0-6df9d9709247"
  ],
  "eventStreamId": "38d75027-cc9e-4aaa-b828-86cace5bf2df"
}]
```

The following is an example of the HTML to render the challenge:

```html
<mastercard-form
  id="2f7069e5-751d-47c4-9f41-4f00089c0c56"
  event-stream-id="38d75027-cc9e-4aaa-b828-86cace5bf2df">
    <img src="<base64-encoded-image-data>">
    <mastercard-mfa-choice id="89427fa8-1383-43b0-87c0-6df9d9709247"></mastercard-mfa-choice>
    <button id="submit-mfa">Submit</button>
</mastercard-form>
```

This is a styled example of the `TFA_IMAGE` challenge. Your application's rendering depends on the styling passed to the Styling Interface:
![Decode Image](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_image_1.png)

##### TFA_IMAGE_PROMPT {#tfa_image_prompt}

The `TFA_IMAGE_PROMPT` challenge type presents an image prompt in addition to a text prompt. Below is the expected response for this type:

```json
[{
  "id": "3ea29b1a-0c2c-4052-a3e1-0cdb856163e8",
  "eventStreamId": "da03e052-915b-4ddc-9098-1ecbcc757bea",
  "mfaType": "TFA_IMAGE_PROMPT",
  "prompt": "Choose the correct response.",
  "promptImage": "<base64-encoded-image-data>",
  "choiceIds": [
    "28bc340a-3b84-4dd1-85eb-cfacf8e0a0e9",
    "88fbb54f-5013-430b-9be8-46a0472464ca",
    "d86461aa-31eb-4eb0-a1d1-39595f4fc170",
    "4456f8d3-b546-4da6-bd52-075c8cfe2970"
  ],
}]
```

The following is an example of the HTML to render the challenge:

```html
<mastercard-form
  id="3ea29b1a-0c2c-4052-a3e1-0cdb856163e8"
  event-stream-id="da03e052-915b-4ddc-9098-1ecbcc757bea">
    <img src= "<base64-encoded-image-data>"/>
    <p>Choose the correct response.</p>
    <mastercard-mfa-choice id="28bc340a-3b84-4dd1-85eb-cfacf8e0a0e9"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="88fbb54f-5013-430b-9be8-46a0472464ca"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="d86461aa-31eb-4eb0-a1d1-39595f4fc170"></mastercard-mfa-choice>
    <mastercard-mfa-choice id="4456f8d3-b546-4da6-bd52-075c8cfe2970"></mastercard-mfa-choice>
    <button id="submit-mfa">Submit</button>
</mastercard-form>
```

This is a styled example of the `TFA_IMAGE_PROMPT` challenge. Your application's rendering depends on the styling passed to the Styling Interface:
![Image Prompt](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_image_prompt_2.png)

#### Submit MFA challenge {#submit-mfa-challenge}

Submitting the MFA challenge is nearly identical to [submitting the login form](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#submit-login-form).

```javascript
const mastercardForm = document.querySelector('mastercard-form');
const submitButton = document.querySelector('#submit-mfa');
submitButton.addEventListener('click', (browserClickEvent) => {
  browserClickEvent.preventDefault();
  mastercardForm.submit();
});
```

#### Error Occurred During Connection Attempt {#error-occurred-during-connection-attempt}

If the connection to the financial institution fails, an `error` event is emitted. The payload contains the information needed to guide the customer through error resolution, if possible. Potential errors are described in the [Error Handling](https://developer.mastercard.com/open-finance-us/documentation/errors/index.md) and [Aggregation Status Codes](https://developer.mastercard.com/open-finance-us/documentation/products/manage/aggregation-status-codes/index.md) sections.

Based on the error code, you can determine the best method to guide the customer through the error resolution process.

```json
{
  "code": 103
}
```

## OAuth Usage {#oauth-usage}

The OAuth implementation path begins with a call to **Create OAuth URL**.

If you created a configuration object in the previous step then you should pass the configuration ID in the request body.

API Reference: `POST /connect-components/institutions/{institution_id}/oauth-urls`

```curl
curl --location --request POST ' /connect-components/institutions/{institution\_id}/oauth-urls' \
--header 'Finicity-App-Key: <appKey>' \
--header 'Accept: application/json' \
--header 'Finicity-App-Token: <appToken>' \
--data-raw '{
  "redirectURI": "https://oauth.example.com/redirect",
  "customerId": "6021877507",
  "customerViewedAcceptedTermsPolicies": "true"
}'
```

Note: The `redirectURI` is required for popup and redirection flows.

The response includes the OAuth URL, a session ID, and an event stream ID:

```json
{
  "id": "c315dc0d-fa08-488c-9601-77dea69acaeb",
  "url": "https://bank.example.com/oauth/login",
  "eventStreamId": "8859489f-12aa-4fd3-bcf5-ba0249e643a3"
}
```

With the `url` value, there are two ways to navigate the customer to their FI's OAuth authentication page:

* [Popup](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#popup)
* [Redirection](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#redirection)

Regardless of the method that is used to direct the customer to the OAuth authentication flow, the application will need to listen for the [`loggedIn`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#login-oauth-only) event describe above.

#### Popup {#popup}

The `url` can be opened into a popup window using the [`open()` method](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) on the window object of the browser:

```javascript
const mastercardForm = document.querySelector('mastercard-form');

/** Call to Data Connect Component API to create a oauth url */
const oauthUrlResponse = requestOauthUrl();

/** Save the target name as a secondary way to get a reference to the popup window */
const targetName = 'financialInstitutionOauthLoginPage';

function openOauthUrl(url, target){
  const windowFeatures = 'popup=true,width=320,height=320';
  return window.open(url, target, windowFeatures);
}

/** Save a reference to the popup window returned by window.open. */
const oauthPopupRef = openOauthUrl(oauthUrlResponse.url, targetName);

mastercardForm.events.addEventListener('loggedIn', loginEvent => {
  let popupWindow = oauthPopupRef;
  if (!popupWindow){
    popupWindow = window.open('', targetName);
  }
  if (popupWindow && popupWindow.closed !== true){
    popupWindow.close();
  }
  oauthPopupRef = undefined;
});
```

Tip: The [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) of the OAuth url will be different than your application's origin. This means that your application will have [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) restrictions on how your application can interact with it. While limiting your ability to manipulate the popup, it is an inherent security feature of the OAuth authentication flow.

Once the customer has completed the OAuth authentication flow with their institution and the institution has provided the OAuth token or error to the Data Connect Component API, the SDK emits the [`loggedIn`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#login-oauth-only) event. In the `loggedIn` event handler, your application needs to close the popup.

#### Redirection {#redirection}

Like the popup method, the redirection method starts with the call to **create an OAuth url**.

```curl
curl --location --request POST ' /connect-components/institutions/{institution\_id}/oauth-urls' \
--header 'Finicity-App-Key: <appKey>' \
--header 'Accept: application/json' \
--header 'Finicity-App-Token: <appToken>' \
--data-raw '{
  "redirectURI": "https://oauth.example.com/redirect",
  "customerId": "6021877507",
  "customerViewedAcceptedTermsPolicies": "true"
}'
```

Your application redirects to the `url` from the create OAuth url request. Redirecting to the OAuth flow url could look like this:

```javascript
window.location.replace(oauthUrlResponse.url);
```

When the OAuth authentication process is complete, the Data Connect Components API redirects to the `uri` that was provided as the value of the `redirectURI` property on the original request to create the OAuth url. It is **your application's responsibility** to ensure that the Data Connect Components Web SDK is loaded with the page that it is redirected to. This is vital, as the Web SDK is needed so that you can also initialize event listeners to receive the [`success`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#success) or [`error`](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#error) events emitted by the SDK and move the customer through the remainder of your customer flow.

Again, it is *vital* that the page that the customer is redirected to does the following:

1. Loads the Data Connect Components Web SDK.
2. Creates a `<mastercard-form>` element with the appropriate `event-stream-id` attribute.
3. Adds event listeners for the `success` and `error` events.
4. Adds an event listener for `loggedIn` if using the popup flow.

Below is a basic example of what is required on the redirection page for the SDK to properly listen for the `success` event, which is emitted after account discovery has been completed.

`index.html`:

```html
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <script src="mastercard-data-connect-components-sdk.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <mastercard-form event-stream-id="8859489f-12aa-4fd3-bcf5-ba0249e643a3"></mastercard-form>
    <!-- Your page contents -->
  </body>
</html>
```

`script.js`:

```javascript
window.addEventListener('DOMContentLoaded', () => {
  const mastercardForm = document.querySelector('mastercard-form');
  
  mastercardForm.events.addEventListener('success', successData => {
    // handle success here
  });
  mastercardForm.events.addEventListener('error', errorData => {
    // handle errors here
  });
});
```

Note: The value of `event-stream-id` is provided in the URL as a query parameter during the redirection at the end of the OAuth flow, in addition to a `code` indicating the status of the OAuth flow (`200` or `202` indicating success). Using the above example data, Data Connect Components would redirect to [https://oauth.example.com/redirect?event-stream-id=8859489f-12aa-4fd3-bcf5-ba0249e643a3\&code=200](https://oauth.example.com/redirect?event-stream-id=8859489f-12aa-4fd3-bcf5-ba0249e643a3&code=200) if the login was successful.

## Data Connect Components Styling Interface {#data-connect-components-styling-interface}

Internally, the Data Connect Components Web SDK leverages iFrames to create a secured, sandboxed environment. Because of this, extra considerations must be made in regard to styling the Data Connect Component elements.

### Understanding Outer Components and Inner Elements {#understanding-outer-components-and-inner-elements}

Styling the outer components (that is, `<mastercard-input>` and `<mastercard-mfa-choice>`) can be done in much the same way as any other native HTML element using standard CSS concepts and frameworks. Attributes such as box-sizing, position, display, width, and height should be set here. Below is an example:

```css
mastercard-input {
  display: block;
  height: 45px;
  width: 100%;
}
```

The inner elements, such as the underlying text boxes, labels, and images used in the Legacy Login Forms and various MFA challenges cannot be styled directly and may only be styled using the provided Styling Interface.

The `<mastercard-input>` and `<mastercard-mfa-choice>` elements accept a `component-styles` attribute. This attribute must be a stringified JSON object. The JSON object must contain one or more of the following top-level properties:

* `image`
* `radio`
* `label`
* `input`
* `image.tfa_multi`
* `image.tfa_image`
* `image.tfa_image_prompt`
* `radio.tfa_multi`
* `radio.tfa_choice`
* `radio.tfa_image_prompt`
* `label.tfa_choice`
* `input.tfa_image`
* `input.tfa_text`

Each top-level property represents a selector for the inner element that will be styled. The value of each top-level property is another JSON object that contains key-value pairs representing CSS properties and their values. Below is an example:

```html
<mastercard-input
  component-styles='{"input":{"boxSizing":"border-box","fontFamily":"sans-serif"}}'
  id="22ad8d21-a3c1-4b53-8e83-4442226d535e"></mastercard-input>
```

Note: The Styling Interface does not provide a means for cascading style rules. For example, if both `input` and `input.tfa_text` are provided, only the more appropriate rule will be applied (`input.tfa_text` in the case of a `TFA_TEXT` challenge, or `input` otherwise).

The `component-styles` attribute is reactive and the inner elements re-render when a change to this attribute is detected. Any user generated content (such as `username`) persist between renders.

The following baseline formatting is applied to the inner elements by default:

```css
body { 
  box-sizing: border-box; 
  margin: 0; 
  height: 100%; 
  width: 100%; 
  display: block; 
  padding: 0; 
} 

label { 
  display: block; 
  height: 100%; 
  width: 100%; 
} 

img { 
  box-sizing: border-box; 
} 

input { 
  box-sizing: border-box; 
} 
```

### Allowed Properties {#allowed-properties}

The Styling Interface accepts the following allowed CSS properties. Please note that sanitization is performed on all incoming values and values that rely on CSS functions (for example, `calc()`) may not work as intended and are subject to removal in future SDK updates.

* backgroundColor
* border
* borderBottom
* borderBottomLeftRadius
* borderBottomRightRadius
* borderLeft
* borderRadius
* borderRight
* borderTop
* borderTopLeftRadius
* borderTopRightRadius
* bottom
* boxSizing
* color
* cursor
* display
* fontFamily
* fontKerning
* fontSize
* fontStretch
* fontWeight
* height
* left
* letterSpacing
* lineHeight
* margin
* marginBottom
* marginLeft
* marginRight
* marginTop
* maxHeight
* maxWidth
* opacity
* outline
* padding
* paddingBottom
* paddingLeft
* paddingRight
* paddingTop
* position
* right
* textAlign
* textIndent
* textShadow
* textTransform
* top
* verticalAlign
* width
* writingMode
* zIndex

### Examples {#examples}

In many cases, it may be appropriate to only pass in styles needed to render the elements currently being displayed.

```html
<mastercard-input
  component-styles='{"input":{"boxSizing":"border-box","fontFamily":"sans-serif","fontSize":"16px","display":"block","backgroundColor":"#eee","borderLeft":"0 none","borderRight":"0 none","borderTop":"0 none","borderBottom":"1px solid #141414","height":"45px","width":"100%","outline":"none","paddingLeft":"8px"}}'
  id="22ad8d21-a3c1-4b53-8e83-4442226d535e"
  form-id="77a7eea0-242c-45a9-97d3-3ce1ae65ebe4">
</mastercard-input>
```

The SDK also supports larger, re-usable objects that contain multiple styles. In these cases, the SDK uses the most appropriate top-level style object.

```html
<mastercard-input
  component-styles='{"image.tfa_image":{"height":"100px","margin":"10px auto 20px","display":"block"},"image.tfa_multi":{"height":"200px","margin":"10px auto","display":"block","cursor":"pointer"},"radio.tfa_multi":{"margin":"0 auto","display":"block","marginTop":"10px","width":"100%"},"label.tfa_choice":{"fontFamily":"sans-serif","marginRight":"15px"},"input":{"boxSizing":"border-box","fontFamily":"sans-serif","fontSize":"16px","display":"block","backgroundColor":"#eee","borderLeft":"0 none","borderRight":"0 none","borderTop":"0 none","borderBottom":"1px solid #141414","height":"45px","width":"100%","outline":"none","paddingLeft":"8px"}}'
  id="22ad8d21-a3c1-4b53-8e83-4442226d535e"
  form-id="77a7eea0-242c-45a9-97d3-3ce1ae65ebe4">
</mastercard-input>
```

## Elements {#elements}

All elements are custom [web components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) and provide a framework-agnostic way to encapsulate logic needed for each element. These elements enable developers to have complete control over the customer experience.

* Mastercard Form
* Mastercard Input
* Mastercard MFA Choice

### Mastercard Form {#mastercard-form}

```html
<mastercard-form id="" event-stream-id=""></mastercard-form> 
```

The custom form element is responsible for brokering `postMessage` connections to the `<mastercard-input>` and `<mastercard-mfa-choice>` elements. The element requires the `id` and `event-stream-id` attributes to be set and match the `id` and `eventStreamId` properties returned from the Data Connect Components API.

#### Mastercard Input {#mastercard-input}

```html
<mastercard-input id=""></mastercard-input>
```

These elements provide the core functionality for **legacy** institution login forms. There needs to be one `<mastercard-input>` for each of the login form inputs that is returned by the Data Connect Components API.

This is typically just `username` and `password`, but there are some login forms that have a third or even fourth required input. Each `<mastercard-input>` element should have a single `id` attribute so the Data Connect Components SDK can render the correct login form data. This `id` must match the `elements[].id` property returned from the Data Connect Components API.

### Mastercard MFA Choice {#mastercard-mfa-choice}

```html
<mastercard-mfa-choice id=""></mastercard-mfa-choice>
```

This is the element type that is used to capture a response from a customer. It can be an image or text box and depends on the MFA Challenge response. All that is needed from the calling application is an `id` attribute on the `mastercard-mfa-choice` so the Data Connect Components SDK can render the correct MFA challenge data. This `id` attribute must match the `choices[]` value returned from the Data Connect Components `mfaChallenge` event body.
Note: MFA Challenge
The MFA challenge will use the same `mastercard-form` element as the login forms. All of the `<mastercard-mfa-choice>` elements should be children of a single `mastercard-form` element.

```html
<mastercard-form>
  <mastercard-mfa-choice id=""></mastercard-mfa-choice>
</mastercard-form>
```

## Events {#events}

### `formStateChange` (*Legacy login only*) {#formstatechange-_legacy-login-only_}

When a login form is initially rendered, the state of the form is 'isReady=false', as no user input has been entered. After all necessary fields have been entered, the state of the form will change to 'isReady=true'. This value changes again if the user clears one or more required fields on the login form or MFA challenge. This event can be used to determine if the user should be allowed to proceed. The only information provided by this event is the `isReady` flag.

```json
{
  "isReady": "true"
}
```

### `focus` (*Legacy login only*) {#focus-_legacy-login-only_}

This event behaves the same as the native Javascript focus event and may be used to modify the UI to reflect user interactions. The payload of this event contains the `id` of the element (login form or MFA challenge choice) that the user has selected.

```json
{
  "elementId": "string"
}
```

### `blur` (*Legacy login only*) {#blur-_legacy-login-only_}

This event behaves the same as the native Javascript blur event and may be used to modify the UI to reflect user interactions. The payload of this event contains the `id` of the element (login form or MFA challenge choice) that the user has navigated away from.

```json
{
  "elementId": "string"
}
```

### `loggedIn` (OAuth only) {#loggedin-oauth-only}

This event is triggered once the customer has completed the **OAuth** login flow with their financial institution. At this point, the calling application may close the **OAuth** popup window. An `id` is provided in the `loggedIn` event payload and is unique to each `loggedIn` event emitted.

```json
{
  "id": "f1ec72c0-8376-44b3-99ec-f8f1ac0ae77d"
}
```

### `success` {#success}

When the Mastercard Data Connect Components API has successfully connected to a customer's account(s), the `success` event is emitted. The payload for this event is an array of objects. Each object represents a single successful account connection.

```json
[
  {
  "customerId": "6021877507",
  "institutionId": "101732",
  "institutionLoginId": 6018508414,
  "accountId": "6038699817"
  }
]
```

### `error` {#error}

When an error is encountered during the login process, this error is captured and returned in the `error` event. The event payload scales down the needed information to enable your application to guide the customer in resolving the error, if resolvable. The payload on the `error` event contains a `code` property:

```json
{
  "code": 103
}
```

For further information about error codes see the [Error Handling](https://developer.mastercard.com/open-finance-us/documentation/errors/index.md) section.

### `mfaChallenge` (*Legacy login only*) {#mfachallenge-_legacy-login-only_}

While attempting to connect to customer accounts, a financial institution may send back a multi-factor challenge that the customer must complete to continue the login process. When an MFA Challenge is raised by an institution, an `mfaChallenge` event will be emitted. The `mfaChallenge` payload is an array of objects. Each object represents a single MFA challenge that needs to be resolved by the customer.

The `mfaChallenge` event payload will contain an array of one or more challenge objects. The `mfaType` determines what properties are present in each challenge object. All challenge objects contain the following properties: `id`, `eventStreamId`, `mfaType`, `prompt`, and `choiceIds`. The `TFA_IMAGE_PROMPT` challenge type also contains a `promptImage` property.

```json
[{
  "id": "3ea29b1a-0c2c-4052-a3e1-0cdb856163e8",
  "eventStreamId": "da03e052-915b-4ddc-9098-1ecbcc757bea",
  "mfaType": "TFA_TEXT",
  "prompt": "What is your favorite color",
  "choiceIds": [
    "497f6eca-6276-4993-bfeb-53cbbbba6f08"
    ]
  }
]
```

#### MFA Challenges Types {#mfa-challenges-types}

There are five types of MFA challenges that may be returned.
Note: The MFA challenge renderings below are provided to illustrate how the challenge could look. The final styling is up to your application. Please refer to the [Data Connect Components Styling Interface](https://developer.mastercard.com/open-finance-us/documentation/connect/components/integration/ccwebsdk/index.md#data-connect-components-styling-interface) section for guidance.

##### `TFA_TEXT` {#tfa_text-1}

A `TFA_TEXT` challenge type presents a prompt and a single input box to the customer. These are commonly used for One-Time Passwords or challenge questions. Example of rendered `TFA_TEXT` challenge:
![Security Question Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_text_1.png)
![One-Time Password Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_otp_1.png)

##### `TFA_CHOICE` {#tfa_choice-1}

A `TFA_CHOICE` challenge type presents a question and a multiple-choice answer selection. Example of rendered `TFA_CHOICE` challenge:
![Multiple-Choice Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_choice_1.png)

##### `TFA_MULTI` {#tfa_multi-1}

A `TFA_MULTI` challenge type presents the customer with multiple images to select from. The prompt for this challenge is text, with multiple-choice elements that the customer needs to select. Example of rendered `TFA_MULTI` challenge:
![Multiple Image Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_multi_1.png)

##### `TFA_IMAGE` {#tfa_image-1}

A `TFA_IMAGE` challenge presents a CAPTCHA-style image that the customer needs to decipher. The prompt for this challenge is an image, rendered by applying the payload to an `<img>` element, with a `<mastercard-mfa-choice>` element being a text box where the customer enters the deciphered image text. Example of rendered `TFA_IMAGE` challenge:
![Decode Image Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_image_1.png)

##### `TFA_IMAGE_PROMPT` {#tfa_image_prompt-1}

A `TFA_IMAGE_PROMPT` challenge type presents an image prompt in addition to a text prompt. The prompt for this challenge is an image, with multiple-choice elements that the customer needs to select. Example of rendered `TFA_IMAGE_PROMPT` challenge:
![Image Prompt Challenge](https://static.developer.mastercard.com/content/open-finance-us/uploads/cc_tfa_image_prompt_2.png)
