Sample App Guide

Introduction

Our goal with this guide is to help you understand the steps required to develop and run a simple Web-based application using the Yodlee core API. If you haven’t already, please read the API Overview before proceeding.

This guide covers the basics of authenticating accounts, linking accounts, and retrieving basic account data with requests. To help you understand how these steps work together in a real application, the discussion and code snippets that follow are provided in the context of a fully functional (but simple) sample application. We first discuss what the application does and how to run it, and then walk through the code to understand how the Yodlee core API is used. The sample exercises use only the API endpoints required for connecting and retrieving basic account and transaction information. To understand the full range of capabilities offered by the API, please review  our reference documentation.

The sample is developed using a Java servlet, JavaScript, and JQuery. The discussion below assumes familiarity with the basic syntax for Java and JavaScript and how to build/deploy a servlet-based Web application (although some helpful links are provided). You can obtain the full sample application code here.

If you have further questions, please do not hesitate to contact us at YIZen@yodlee.com


Sample Application Description

What does the sample application do? The application allows a user to log in, link one or more accounts from a financial institution of their choosing, and then inspect the account metadata and transaction data that are returned. By default, the application links to dummy account data. The application also showcases additional processing performed by the Yodlee platform such as transaction categorization and simplification of complex transaction descriptions into more human readable form.

The first page of the sample application provides a login screen that allows the user to log in. The application authenticates the user in a two-step process; step 1 occurs during page loading and step 2 occurs after the login form is submitted. This is explained in greater detail in the code walk-through below.

Once the user is logged in, the main page of the application shows a list of accounts that have been linked before (left pane) and allows the user to link new accounts (by providing the account credentials) so Yodlee can fetch account information. The user can also choose to log out to return to the main screen.

Using the default configuration, the application works with the sandbox API environment and accepts the credentials of the sample users who are automatically created when the sandbox is provisioned. Each user has some dummy accounts already associated with it. Thus, on initial login, the application will show several (dummy) accounts already linked. 

When a user selects one of the linked accounts, the application fetches and displays account metadata (“Account Details” section) and the recent transactions (“Transaction Summary” section) for the selected account. For each transaction, it shows the transaction date, amount, and category (automatically assigned); and the raw description returned by the financial institution and the cleansed, simpler description provided by the Yodlee platform. The user can also choose to unlink the currently selected account. Unlinking the account removes the account from the application account list (left pane) and deletes the account from the API back end so the platform stops collecting data for the account. 

The user can add a new account by clicking Link Account. This launches the FastLink application to guide the user through the process of linking their account(s) with the Yodlee platform. The Yodee platform can then aggregate data on the user’s behalf. FastLink allows the user to search for an institution or select one from the list of common financial sites in the pick list. (FastLink’s look and feel can be customized.)

Once the appropriate provider site is selected, FastLink collects the user’s credentials. The Yodlee platform then attempts to authenticate the user with the site, and fetch account and transaction data. The FastLink application shields developers from the complicated process of collecting credentials and authenticating them across thousands of financial institution sites.


Once the Yodlee platform is able to authenticate the user with the provider site, it returns basic account information so the user can confirm the correct account has been linked. In the meantime, the Yodlee platform continues retrieving account and transaction information. The user can link additional sites and accounts or quit FastLink. 


Getting the Sample Running

The sample application is distributed as a maven project. To try the application and understand the source code, you need to do the following:

  1. Set up a free Yodlee developer portal account that provides an API sandbox environment and several dummy consumers.
  2. Log in to your developer account and navigate to the API Dashboard.
    1. Save the API Keys (Cobrand Login, Cobrand Password) and the Yodlee core API URL for the sandbox API environment from the dashboard as shown below.


       
    2. Although the API lets you create new user accounts, for this sample application, we use pre-provisioned user accounts. Each developer account comes with five test user accounts that are automatically provided and associated with the developer account when it is created. The credentials for the user accounts are listed on the API Dashboard. Save any of the username/password pairs for use with the sample application.

  3. Download the sample application code (“Web Application (using Java Servlets)”) from here and unzip it into a local folder.

    Inspect the source code folder to understand the directory structure and identify the key files you will be working with. The directory structure shown below highlights the key files: config.properties, YodleeSampleApp.java, index.html, and accounts.html.

  4. Authenticating users with the Yodlee core API requires using two sets of credentials: the cobrand login/password and the consumer’s username/password. A cobrand refers to a Yodlee customer, and consumer refers to an application’s end user. The application authenticates with a particular API environment identified by the base URL for the API. 

    For this sample, we use the developer portal’s sandbox API environment (https://developer.api.yodlee.com/ysl/restserver/) and the corresponding cobrand and consumer credentials provided in the dashboard. 

    Navigate to the /src directory and open the config.properties file. Set the config properties based on the credentials and URLs copied from the developer dashboard. Also set the CobrandName and ApiVersion here. Starting with version 1.1 we require these to be set in the HTTP request header for all API calls.
     

    yodlee.APIURL=https://developer.api.yodlee.com/ysl/
    ##Set your cobrand name and api version to be passed in the HTTP Header request
    yodlee.cobrandName=restserver
    yodlee.apiVersion=1.1
    ##Set the cobrand login name and password from your Yodlee developer dashboard
    yodlee.coBrandUserName=XXXXXXXXX
    yodlee.coBrandPassword= XXXXXXXXX
    ##Set nodeUrl for FastLink app
    yodlee.nodeUrl=https://node.developer.yodlee.com/authenticate/restserver/

    config.properties

  5. Download and set up a java servlet container/engine, e.g.  Apache Tomcat.
  6. Import maven project into your preferred IDE. Instructions for importing into Eclipse or IntelliJ can be found here and here
  7. Build the sample and export the built sample app as a Web application archive (.war) file. Instructions for exporting a .war file from Eclipse or IntelliJ are available here and here.
  8. Start Apache Tomcat and deploy the .war file.
  9. Open your Web browser and navigate to the application URL. If you have used the default settings so far, the application should be available at localhost: 8080/YodleeSampleApp.
  10. Log in to the application using the username/password obtained from the API dashboard.

Understanding the Application Code

Once you have the application running, you can try linking accounts to see it in action. The Java back end for the application has intentionally been kept simple by keeping all the relevant code in the same servlet and credentials are placed in the configuration file. When you move to production code, use your organization’s security best practices for credential management and other safety aspects of building your application.

API Authentication

Cobrand Authentication

Yodlee's core API authentication requires two steps: cobrand authentication and user/consumer authentication. The former authenticates the Yodlee customer whereas the latter authenticates the user in the customer’s API environment and sets the context of the financial data that is returned; the API returns data for the accounts associated with the user that have been authenticated.

Cobrand authentication (with cobrand credentials) must occur first, and returns a cobrand session token. User authentication requires the cobrand session token and user credentials, and returns the user session token. The remaining data retrieval API calls require both the cobrand and user session tokens to ensure authorization and set the context of the user for whom the data is being returned.

In this sample application, the cobrand login occurs while the first page is being loaded. To understand the cobrand authentication better, open index.html and find the snippet of code listed below in the JQuery $(document).ready() function.

$.get("/YodleeSampleApp/YodleeSampleApp", {
        action: "init"
    })
    .done(function(data) {

            data = data.replace(/\'/g, '\"');

            var responseObj = jQuery.parseJSON(data);

            if (responseObj && responseObj.cobSession) {
                $("#initCheck").append("Cobrand Configuration Check Successful!

                    Use test accounts from API Dashboard to login

                    ");

                    $('#submitButton').prop('disabled', false);

                } else {

                    $("#initCheck").removeClass("alert-info");
                    $("#initCheck").addClass("alert-danger");

                    if (responseObj && responseObj.error) {

                        $("#initCheck").append("" + responseObj.message + "

                            ");

                        } else {
                            $("#initCheck").append("Error during initialization. Please check settings in config.properties and user credentials

                                ");
                            }
                        }

                    });
	
	

Once the index.html document has finished loading in the browser (i.e. when the $(document).ready() function is called), the JavaScript code snippet above invokes GET/YodleeSampleApp (with an “action” parameter set to “init”) to initialize the sample application. During initialization, the sample application attempts to authenticate the API back end using the cobrand credentials from the config.properties file that were set earlier (see below). If the cobrand authentication succeeds, a success status message is shown and the Submit button for the login form is enabled so the user can log in using the user credentials (obtained earlier from the dashboard). Otherwise, it shows an error message stating that initialization failed (and the Submit button remains disabled).

The YodleeSampleApp Java servlet (YodleeSampleApp.java) that receives the application initialization request, retrieves the cobrand authentication credentials from the config.properties file, i.e. the API URL, cobrand login name, and cobrand password (as shown below).

	static ResourceBundle resourceBundle = ResourceBundle.getBundle("config");
	public static final String  localURLVer1= resourceBundle.getString("yodlee.APIURL");
	static String coBrandUserName = resourceBundle.getString("yodlee.coBrandUserName");
	static String coBrandPassword = resourceBundle.getString("yodlee.coBrandPassword");

When the request is received, the servlet attempts to authenticate to the Yodlee core API back end (using POST /cobrand/login) and obtain a session token as shown below.

 /**
  * Helper method which performs /cobrand/login API call with Yodlee core API server.
  * 
  */
 private String getCobrandSession() {

     String cobSession = "";

     try {

         //Request Body - refer to full API reference at https://developer.yodlee.com/apidocs/index.php

         final String requestBody = "{" +
             "\"cobrand\":{" +
             "\"cobrandLogin\":\"" + coBrandUserName + "\"" + "," +
             "\"cobrandPassword\": " + "\"" + coBrandPassword + "\"" + "," +
             "\"locale\": \"en_US\"" +
             "}" +
             "}";

         String coBrandLoginURL = localURLVer1 + "v1/cobrand/login";
         String cobrandjsonResponse = HTTP.doPost(coBrandLoginURL,
             requestBody);
         CobrandContext coBrand = (CobrandContext) GSONParser.handleJson(
             cobrandjsonResponse, beans.CobrandContext.class);


         if (!cobrandjsonResponse.contains("errorCode")) {
             cobSession = coBrand.getSession().getCobSession();
         }
     } catch (Exception e) {
         e.printStackTrace();
     }
     return cobSession;
 }

The session token is stored in the application session context for future reference.

if (cobSession != null && cobSession.length() > 0) {
request.getSession().setAttribute("cobSession", cobSession);
sendAjaxResponse(response, "{'cobSession':'" + cobSession + "'}");
} else {
sendAjaxResponse(response, "{'error':'true', 'message':'Cobrand Configuration Check Failed. Please check settings in config.properties'}");
}

This cobrand login process occurs in the background while the index.html page is being loaded. 


User Authentication

If the cobrand authentication process succeeds, the user can enter his/her credentials in the user login form on the login page (index.html) of the application.

Once the user presses Submit on the login form, the Submit button handler initiates a request to authenticate the user with the application. 

//User login
$('#submitButton').click(function() {

    window.console.log('submitButton');

    var userName = $("#username").val();
    var password = $("#password").val();
    $('#submitButton').prop('disabled', true);
    $('#submitButton').html("Loading...");

    $.post("/YodleeSampleApp/YodleeSampleApp", {
            username: userName,
            password: password
        })
        .done(function(data) {

            data = data.replace(/\'/g, '\"');
            var dataObj = jQuery.parseJSON(data);

            if (dataObj && dataObj.error && dataObj.error == "false") {
                window.location.href = "accounts.html";
            } else {
                $("#initCheck").removeClass("alert-info");
                $("#initCheck").addClass("alert-danger");
                $("#initCheck").append("<p>Error in User login, please check your test user credentials (from the Yodlee API Dashboard).</p>");

                $('#submitButton').prop('disabled', false);
                $('#submitButton').html("Login");


            }

        });

});
	

The user login request arrives at the same servlet as the cobrand authentication request, YodleeSampleApp (YodleeSampleApp.java) and is handled by the POST request handler. Normally, successful application authentication would trigger a separate API user credential lookup and API user authentication. The notion of (and credentials of) the application user could be separated from the API user if desired. However, for simplicity, the sample application does not perform application user authentication and instead uses the supplied credentials to immediately perform an API user authentication. 

The POST method handler invokes the userLogin() method below and stores the user session token in the session context, similar to how the cobrand session token is stored. The userLogin() method invokes the Yodlee core API to authenticate the user through POST /user/login. SAML based authentication is also supported. See SAML login.

/**
 * Helper method to call user login Yodlee's core API - /user/login
 * 
 */
private String userLogin(String cobSession, String userName, String password) {

    String userSession = null;

    try {
        Map & lt;
        String, String & gt;
        loginTokens = new HashMap & lt;
        String, String & gt;
        ();
        loginTokens.put("cobSession", cobSession);

        // User login
        String userLoginURL = localURLVer1 + "v1/user/login";

        //Request Body JSON - refer to full API reference at https://developer.yodlee.com/apidocs/v1.1/index.php
        final String requestBody2 = "{" +
            "\"user\":{" +
            "\"loginName\":\"" + userName + "\"" + "," +
            "\"password\":\"" + password + "\"" + "," +
            "\"locale\": \"en_US\"" +
            "}" +
            "}";


        String userjsonResponse = HTTP.doPostUser(userLoginURL,
            loginTokens, requestBody2, true);
        UserContext member = (UserContext) GSONParser.handleJson(
            userjsonResponse, beans.UserContext.class);

        if (!userjsonResponse.contains("errorCode")) {
            userSession = member.getUser().getSession().getUserSession();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return userSession;
}
	

After successfully logging in, the user is presented with the main application page (accounts.html). From here, the user can choose to invoke FastLink to link accounts to the Yodlee platform. Invoking FastLink is a two-step process. 

First, the front end must obtain the FastLink token and user session token from the application back end. 

The code snippet below shows the button handler for invoking FastLink which invokes GET /YodleeSampleApp with the “action” parameter set to “getFastLinkToken” to get the required tokens. In addition if you would like to override the default dataset configuration you can pass in the “extraParams” parameter set to the desired combination of datasets and attributes. While it’s possible in production environment to request all datasets, the sandbox environment restricts it to Basic Aggregation Data and Account Profile. Refer to Retrieving and Sending Datasets FastLink Integration Guide for examples of datasets

	//Call sample appl servlet to get FastLink token.
	//Lauches FastLink by doing form POST in iFrame.
	
	$('#fastlinkbutton').click(function() {
		
	  $.get( "/YodleeSampleApp/YodleeSampleApp",{ action: "getFastLinkToken"} )
	  .done(function( data ) {
		  
		window.console.log('getFastLinkToken - '+data);
		var fastlinkTokensObj = jQuery.parseJSON(data);
		
		 $('#rsessionPost').attr('action', fastlinkTokensObj.nodeUrl);
		$("#rsession").val(fastlinkTokensObj.userSession);
		$("#token").val(fastlinkTokensObj.fastlinkToken);
		$('#extraParams').val(fastlinkTokensObj.dataset);
		
		//window.console.log('rsession from form: '+$("#rsession").val());
		
		document.getElementById('rsessionPost').submit();
	
					  
	   });  
		
	});
	

Once the FastLink token and user session information is obtained by the front end from the application back end, it is bound to a hidden form which is submitted to the FastLink application back end. (Note, this is a browser form submission, not a HTTP POST used in a REST API call) The results of the form submission are redirected to a new iFrame that launches the FastLink application. This is shown below.

<form action='' method='post' id='rsessionPost' target='iframeID' style="display: none">
RSession :
<input type='text' name='rsession' placeholder='rsession' value='' id='rsession' />
<br /> FinappId :
<input type='text' name='app' placeholder='FinappId' value='10003600' id='finappId' />
<br /> Redirect :
<input type='text' name='redirectReq' placeholder='true/false' value='true' />
<br /> Token :
<input type='text' name='token' placeholder='token' value='' id='token' />
<br /> Extra Params :
<input type='text' name='extraParams' placeholer='Extra Params' value='' id='extraParams' />
<br />
</form>

On the receiving end of the FastLink token request (YodleeSampleApp.java), the servlet GET handler invokes getFastLinkToken() below to get a valid access token required for invoking FastLink from the application front end (see below). The getFastLinkToken() method invokes the GET /user/accessTokens endpoint with an appId parameter set to “10003600” corresponding to the fixed value used by Yodlee to identify the FastLink application for data aggregation (versus other Yodlee applications). 

/**
 * Helper method to obtain FastLink launch token from Yodlee's core API
 * GET /user/accessTokens
 * Refer to full API references - https://developer.yodlee.com/apidocs/v1.1/index.php
 */
private String getFastLinkToken(String cobSession, String userSession) {

    String fastLinkToken = null;
    String accesstokenJsonResponse = null;
    String accessTokenURL = localURLVer1 + "v1/user/accessTokens?appIds=10003600";

    try {
        Map & lt;
        String, String & gt;
        loginTokens = new HashMap & lt;
        String, String & gt;
        ();
        loginTokens.put("cobSession", cobSession);
        loginTokens.put("userSession", userSession);

        accesstokenJsonResponse = HTTP.doGet(accessTokenURL, loginTokens);

        AccessToken userAccess = (AccessToken) GSONParser.handleJson(accesstokenJsonResponse, beans.AccessToken.class);
        fastLinkToken = userAccess.getUser().getAccessTokens()[0].getValue();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return fastLinkToken;

}
	

Getting Accounts

Linked accounts are populated in the application UI when the accounts.html document loads as shown below. The application UI invokes the GET /YodleeSampleApp endpoint for the application with the “action” parameter set to “getAccounts.” This returns the account information on all linked accounts for the user. 

//Load user accounts in Sample Web App
$.get("/YodleeSampleApp/YodleeSampleApp", {
        action: "getAccounts"
    })
    .done(function(data) {

        data = data.replace(/\'/g, '\"');
        var responseObj = jQuery.parseJSON(data);

        $("#accountsListDiv").empty();

        var accountsListHTML = "";

        $.each(responseObj.account, function(i, item) {
            var paramsList = "'" + item.id + "', '" + item.accountType + "', '" + item.balance.amount + "', '" + item.CONTAINER + "', '" + item.accountName + "'";
            accountsListHTML += '<div class="panel panel-default accnames"><div class="panel-heading"><a href="#" onClick="loadAccount(' + paramsList + ');" ><strong>' + item.accountName + '</strong></a></div></div>';
        });

        $("#accountsListDiv").html(accountsListHTML);
    });
	

For each returned account, the JavaScript code creates a new panel with a specific link for each account. When the link is clicked, the account metadata and transactions are populated in the right pane through the loadAccount() function (see Get Transactions below). 

The Java servlet handler code in the back end that receives the request to get account information invokes the GET /accounts Yodlee's core API endpoint (using the stored cobrand and user session tokens) to return the account information on all linked accounts. The code snippet below shows how this is done:

/**
 * Helper method to load user accounts from Yodlee's core API
 * GET /accounts call
 * Refer to full API references - https://developer.yodlee.com/apidocs/v1.1/index.php
 */
private String getUserAccounts(String cobSession, String userSession) {
    String accountURL = localURLVer1 + "v1/accounts";
    Map & lt;
    String, String & gt;
    loginTokens = new HashMap & lt;
    String, String & gt;
    ();
    loginTokens.put("cobSession", cobSession);
    loginTokens.put("userSession", userSession);

    String accountJsonResponse = null;

    try {
        accountJsonResponse = HTTP.doGet(accountURL, loginTokens);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return accountJsonResponse;
}
	

Get Transactions

The loadAccount() function populates the account specific information in the right pane of the accounts.html page. It populates the account metadata and then invokes the application GET /YodleeSampleApp endpoint with the “action” parameter set to “getTransactions” to retrieve transaction information.

//Load user selected account details and then call to get transactions for selected account
function loadAccount(accountId, type, amount, container, name) {

        $("#accountType").text(type);
        $("#accountName").text(name);
        $("#accountBalance").text(amount);
        $("#accountContainer").text(container);
        $('#unlinkButtonDiv').data('accountId', accountId); //setter

        $('#emptyAccountDetailsDiv').addClass("hidden");
        $('#accountDetailsDiv').removeClass("hidden");

        $('#txnTable tbody').empty();
        $("#txnTable").append('<body><tr><td colspan="5" class="text-center"><div align="center" class="alert alert-info"><p>Loading Transactions.... & lt; i class = "fa fa-spinner fa-spin"
            style = "font-size:24px" & gt; & lt;
            /i></p & gt; & lt;
            /div></td & gt; & lt;
            /tr></tbody & gt;
            ');


            $.get("/YodleeSampleApp/YodleeSampleApp", {
                action: "getTransactions",
                accountId: accountId
            })
            .done(function(data) {

                var responseObj = jQuery.parseJSON(data);
                window.console.log(responseObj);
                var trHTML = '';
                $.each(responseObj.transaction, function(i, item) {
                    trHTML += '<tr><td>' + item.transactionDate + '</td><td class="text-right">' + item.amount.amount + '</td><td>' + item.category + '</td><td>' + item.description.simple + '</td> & lt;
                    td & gt;
                    ' + item.description.original + ' & lt;
                    /td></tr & gt;
                    ');
                });

                //$('#txnTable tbody').empty();
                $('#txnTable tbody').remove();
                $("#txnTable").append('<tbody>' + trHTML + '</tbody>');

            });

        }
	

The Java servlet code that handles the request to retrieve transaction data (getTransactions()) in turn invokes the GET /transactions API endpoint to get all transactions since January 1, 2013. 

/**
 * Helper method to get transactions for specific account (id)
 * GET /transactions
 * Refer to full API references - https://developer.yodlee.com/apidocs/v1.1/index.php
 */
private String getTranactions(String cobSession, String userSession,
    String accountId) {

    String txnJson = "";

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -30);
    Date todate1 = cal.getTime();
    String date = dateFormat.format(todate1);
    System.out.println("Date = " + date);

    String TransactionUrl = localURLVer1 + "v1/transactions" + "?fromDate=" + date + "+&accountId=" + accountId;

    try {
        Map & lt;
        String, String & gt;
        loginTokens = new HashMap & lt;
        String, String & gt;
        ();
        loginTokens.put("cobSession", cobSession);
        loginTokens.put("userSession", userSession);

        txnJson = HTTP.doGet(TransactionUrl, loginTokens);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return txnJson;
}
	

Deleting Accounts

Users can also unlink (delete) accounts from the application. The code below shows the JavaScript handler for the Unlink Account button that invokes the GET /YodleeSampleApp application endpoint with “action” set to “deleteAccount”. 

//calls sample app servlet to unlink selected account.
function unlinkAccount() {

    window.console.log('unlink acct');
    var id = $('#unlinkButtonDiv').data('accountId');

    $.get("/YodleeSampleApp/YodleeSampleApp", {
            action: "deleteAccount",
            accountId: id
        })
        .done(function(data) {
            $('#unlinkAccountModal').modal('show')
        });

}
	

The Java code in YodleeSampleApp.java below shows the handler logic for the application delete action, which simply invokes the DELETE /accounts/{accountId} Yodlee's core API endpoint with the accountId specified as a URL parameter. This essentially deletes the account from the Yodlee platform such that the information for that account is no longer aggregated.

/**
 * Helper method to delete(unlink) specific user account
 * DELETE /accounts/
 * Refer to full API references - https://developer.yodlee.com/apidocs/v1.1/index.php
 */
private String deleteAccount(String cobSession, String userSession,
        String accountId) {
        String deleteAccountResponse = null;

        String deleteAccountURL = localURLVer1 + "v1/accounts/";
        try {

            Map & lt;
            String, String & gt;
            loginTokens = new HashMap & lt;
            String, String & gt;
            ();
            loginTokens.put("cobSession", cobSession);
            loginTokens.put("userSession", userSession);

            HTTP.doDelete(deleteAccountURL + accountId, loginTokens);

            deleteAccountResponse = "success";

        } catch (Exception e) {
            e.printStackTrace();
        }
	

Logout

Finally, the user can log out of the application (accounts.html). When the user chooses to log out, the application is redirected to the main login page (index.html) as shown below.

//Logout from Yodlee Sample Web App
$("#logout").click(function() {
    window.location.href = "/YodleeSampleApp/";
});
	

Next Steps

Now that you understand the basics of getting a simple application working with the Yodlee core API, spend some time diving into the API reference documentation to gain a deeper understanding of the remaining API endpoints. If you have any questions, please get in touch through YIZen@yodlee.com