truelayer-client
v1.3.2
Published
The official TrueLayer API client library
Downloads
1,106
Readme
TrueLayer - Docs
TrueLayer allows financial applications to connect securely with their customer’s bank data. TrueLayer provides a unified interface between multiple financial institutions and third party applications over a common RESTful API. For more information and for obtaining a new TrueLayer developer account, visit https://truelayer.com.
Client library (JavaScript / TypeScript)
This is the official client library to help with the creation of financial applications that implement TrueLayer APIs. The library has been written in Typescript for a richer development experience. Typescript is a typed superset of Javascript that compiles to plain JavaScript. More information regarding Typescript can be found at: https://www.typescriptlang.org/
The client library can be used within a JavaScript (Node.js) or TypeScript environment.
Installation
$ npm install truelayer-client
Usage
Below is a simple Javascript express app using TrueLayer's API client library. It illustrates the flow of obtaining a JWT access token from the authorization server, before using this token to query the data api /info
endpoint for identity information of the user.
Note: You'll need node (at least > v7.6) and npm or yarn to install and run this example.
const {AuthAPIClient, DataAPIClient} = require("truelayer-client");
const app = require("express")();
const redirect_uri = "http://localhost:5000/truelayer-redirect";
// Create TrueLayer client instance
const client = new AuthAPIClient({
client_id: "INSERT YOUR client_id HERE",
client_secret: "INSERT YOUR client_secret HERE"
});
// Define array of permission scopes
const scopes = ["info", "accounts", "balance", "transactions", "offline_access", "cards"]
// Construct url and redirect to the auth dialog
app.get("/", (req, res) => {
const authURL = client.getAuthUrl({
redirectURI: redirect_uri,
scope: scopes,
nonce: "foobar"
});
res.redirect(authURL);
});
// Retrieve 'code' query-string param, exchange it for access token and hit data api
app.get("/truelayer-redirect", async (req, res) => {
const code = req.query.code;
const tokens = await client.exchangeCodeForToken(redirect_uri, code);
const info = await DataAPIClient.getInfo(tokens.access_token);
res.set("Content-Type", "text/plain");
res.send(`Access Token: ${JSON.stringify(info, null, 2)}`);
});
app.listen(5000, () => console.log("Example app listening on port 5000..."));
Create new package
$ npm init
Install dependencies
$ npm install --save truelayer-client express
Run the app :video_game:
$ node your_file.js
If all goes well you should be able to navigate to http://localhost:5000 and view the app!
Take a look at our sample repo for an easy to digest implementation of the library.
Examples
A simple sample application has been created and lives in a separate repo, here.
This simple node example stands up a bare-bones express server and takes a user through the authentication flow, then hits the data API info
endpoint, and streams the results to a page.
Authentication and tokens
Note: The code snippets below are extracted from the above Express example.
The flow of authorization follows the protocol of OAuth 2.0. For more information about precisely how this customer / client authorization is achieved take a look here. This library serves to streamline this flow for developers and can be summarized in the following steps:
Note: The
responseMode
parameter if omitted will cause the auth server to return the one-time code as a query-string parameter. Passing"form_post"
will intuitively cause the code to be returned as a form/post parameter.
The first step in authentication is to redirect the user to the TrueLayer Authentication Server.
const authURL = client.getAuthUrl({ redirectURI: env.REDIRECT_URI, scope, nonce: "nonce", responseMode: "form_post" }); res.redirect(authURL);
Upon successful redirect and authentication, a one-time code is generated when the HTTP POST is performed to the redirect_uri provided by the client.
app.post("/truelayer-redirect", async (req, res) => { const code = req.body.code; ... });
After the code is obtained, it can be exchanged for an access token.
const tokens = await client.exchangeCodeForToken(env.REDIRECT_URI, code);
The authorization server will respond with:
- access token - short-lived JWT token (default 1h) used to access data on behalf of the customer
- refresh token - long-lived code used to obtain a new access token
In the case that the
access_token
has expired,refreshAccessToken
can be used for refreshing the token. This will return new values for both the access_token and refresh_token (old refresh_token no longer valid).
Project structure
This client library consists of two core pieces of functionality, each represented by a separate class:
1. Authentication - AuthAPIClient
- This is responsible for providing methods that allow developers to perform customer authentication and client authorization.
- The following methods are provided in AuthAPIClient:
getAuthUrl
- builds a correctly formatted authentication url used for redirection to the authentication server.exchangeCodeForToken
- exchanges an authentication code for an access tokenrefreshAccessToken
- refreshes the access token using the refresh token. Access tokens expire after a set period of time (default 1h).
2. Data APIs - DataAPIClient
- Once the authentication is successful, methods are provided for calling the various API endpoints for obtaining information regarding the authenticated bank account such as : accounts, balance, transactions etc.
- The following methods are provided in DataAPIClient:
getMe
- call to the /me endpointgetInfo
- call to the /info endpointgetAccounts
- call to the /accounts endpointgetAccount
- call to the /accounts/{account_id} endpointgetDirectDebits
- call to the /accounts/{account_id}/direct_debits endpointgetStandingOrders
- call to the /accounts/{account_id}/standing_orders endpointgetTransactions
- call to the /accounts/{account_id}/transactions endpointgetPendingTransactions
- call to the /accounts/{account_id}/transactions/pending endpointgetBalance
- call to the /accounts/{account_id}/balance endpointgetCards
- call to the /cards endpointgetCard
- call to the /cards/{account_id} endpointgetCardTransactions
- call to the /cards/{account_id}/transactions endpointgetCardPendingTransactions
- call to the /cards/{account_id}/transactions/pending endpointgetCardBalance
- call to the /cards/{account_id}/balance endpointvalidateToken
- checks whether the current access token is still valid.
Errors
Note: see here for more information about error response structure and here for more error specific information.
Custom error wrapper classes have been used to handle the auth server and data api errors respectively. Errors on the wire have the following format:
{
"error": "<error_code>",
"error_description": "<error_description>"
}
The custom DataApiError
and AuthApiError
error objects have 2 parameters which relate to these properties:
error
: error codemessage
: error description
Tests
The client library has both integration and unit tests.
In order to run the integration tests, an access token needs to be provided. If this is not provided, only the unit tests will be run.
$ export access_token=<access_token>
$ npm run test
Contributions
In order to contribute to the existing code base, please follow these steps:
- Fork the repo
- Create a new branch (
git checkout -b <improvements-branch>
) - Make the appropriate changes
- Write tests for the modified code
- Commit changes (
git commit -m "<message>"
) - Push to the branch (
git push origin <improvements-branch>
) - Create a pull request