Compare commits

..

No commits in common. "master" and "main" have entirely different histories.
master ... main

23 changed files with 27713 additions and 7981 deletions

141
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,141 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
before_script:
- npm install -g @shipzone/npmci
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

View File

@ -1,132 +0,0 @@
# Changelog
## 2024-06-24 - 3.1.13 - fix(dependencies)
Update dependencies to latest versions
- Updated @git.zone/tsbuild to version ^2.1.82
- Updated @git.zone/tsrun to version ^1.2.49
- Updated @git.zone/tstest to version ^1.0.90
- Updated @push.rocks/tapbundle to version ^5.0.23
- Updated @types/node to version ^20.14.8
- Updated @push.rocks/smartpromise to version ^4.0.4
- Updated @push.rocks/smartrequest to version ^2.0.22
## 2024-04-08 - 3.1.12 - core
Routine maintenance updates
- Updated core dependencies
## 2024-04-08 - 3.1.11 - core
Routine maintenance updates
- Updated core functionality
## 2024-04-08 - 3.1.10 - core
Routine maintenance updates
- Updated dependencies for core components
## 2023-06-03 - 3.1.9 - core
Routine maintenance updates
- Updated core functionality
## 2023-05-25 - 3.1.8 - core
Routine maintenance updates
- Updated core functionality
## 2023-05-25 - 3.1.7 - core
Routine maintenance updates
- Updated core functionality
## 2022-10-30 - 3.1.6 - core
Routine maintenance updates
- Updated core functionality
## 2022-10-30 - 3.1.5 - core
Routine maintenance updates
- Updated core functionality
## 2022-10-30 - 3.1.4 - core
Routine maintenance updates
- Updated core functionality
## 2022-10-29 - 3.1.3 - core
Minor bug fixes and improvements
- Used correct power function in core components
## 2022-10-29 - 3.1.2 - core
Routine maintenance updates
- Updated core functionality
## 2022-10-29 - 3.1.1 - core
Routine maintenance updates
- Updated core functionality
## 2022-10-29 - 3.1.0 - core
Routine maintenance updates
- Updated core functionality
## 2022-08-23 - 3.0.0 - BankAccount and BankTransaction
New feature additions
- Now supporting the full retrieval process for BankAccount and BankTransaction
## 2022-05-12 - 2.0.0 - TinkUser
**BREAKING CHANGE**
- `new TinkUser().getTinkLink()` now expects a `tinkLinkOptionsArg`
## 2022-04-18 - 1.0.17 - core
**BREAKING CHANGE**
- Switch to ESM and allow specification of redirect URL
## 2022-02-19 - 1.0.16 to 1.0.10 - core
Routine maintenance updates
- Updated core functionality
## 2022-02-19 - 1.0.9 - core
Routine maintenance updates
- Updated core functionality
## 2022-02-19 - 1.0.8 - core
Routine maintenance updates
- Updated core functionality
## 2022-02-19 - 1.0.7 - core
Routine maintenance updates
- Updated core functionality
## 2022-02-19 - 1.0.6 to 1.0.5 - core
Routine maintenance updates
- Updated core functionality
## 2022-02-17 - 1.0.4 to 1.0.3 - core
Routine maintenance updates
- Updated core functionality
## 2022-02-15 - 1.0.2 - core
Routine maintenance updates
- Updated core functionality
## 2022-01-25 - unknown - initial commit
Initial commit
- Project started

View File

@ -8,23 +8,11 @@
"description": "an unofficial api abstraction for tink.com", "description": "an unofficial api abstraction for tink.com",
"npmPackagename": "@mojoio/tink", "npmPackagename": "@mojoio/tink",
"license": "MIT", "license": "MIT",
"projectDomain": "mojo.io", "projectDomain": "mojo.io"
"keywords": [
"tink.com",
"API abstraction",
"TypeScript",
"financial data",
"transactions",
"accounts",
"banking API"
]
} }
}, },
"npmci": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
} }
} }

27504
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,10 @@
{ {
"name": "@apiclient.xyz/tink", "name": "@mojoio/tink",
"version": "3.1.13", "version": "1.0.2",
"private": false, "private": false,
"description": "an unofficial api abstraction for tink.com", "description": "an unofficial api abstraction for tink.com",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
@ -13,20 +12,15 @@
"build": "(tsbuild --web)" "build": "(tsbuild --web)"
}, },
"devDependencies": { "devDependencies": {
"@git.zone/tsbuild": "^2.1.82", "@gitzone/tsbuild": "^2.1.25",
"@git.zone/tsbundle": "^2.0.8", "@gitzone/tsbundle": "^1.0.78",
"@git.zone/tsrun": "^1.2.49", "@gitzone/tstest": "^1.0.44",
"@git.zone/tstest": "^1.0.90", "@pushrocks/tapbundle": "^3.2.9",
"@push.rocks/qenv": "^6.0.5", "@types/node": "^14.11.2",
"@push.rocks/tapbundle": "^5.0.23", "tslint": "^6.1.3",
"@types/node": "^20.14.8" "tslint-config-prettier": "^1.15.0"
},
"dependencies": {
"@push.rocks/smartdelay": "^3.0.1",
"@push.rocks/smartpromise": "^4.0.4",
"@push.rocks/smartrequest": "^2.0.22",
"@push.rocks/smarturl": "^3.0.6"
}, },
"dependencies": {},
"browserslist": [ "browserslist": [
"last 1 chrome versions" "last 1 chrome versions"
], ],
@ -41,14 +35,5 @@
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
],
"keywords": [
"tink.com",
"API abstraction",
"TypeScript",
"financial data",
"transactions",
"accounts",
"banking API"
] ]
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +0,0 @@
required:
- TINK_CLIENT_ID
- TINK_CLIENT_SECRET

View File

123
readme.md
View File

@ -1,108 +1,39 @@
# @apiclient.xyz/tink # @mojoio/tink
an unofficial api abstraction for tink.com an unofficial api abstraction for tink.com
## Install ## Availabililty and Links
To install @apiclient.xyz/tink, use either `npm` or `yarn` as per your preference. Run the following command in your project directory: * [npmjs.org (npm package)](https://www.npmjs.com/package/@mojoio/tink)
* [gitlab.com (source)](https://gitlab.com/mojoio/tink)
* [github.com (source mirror)](https://github.com/mojoio/tink)
* [docs (typedoc)](https://mojoio.gitlab.io/tink/)
```bash ## Status for master
npm install @apiclient.xyz/tink --save
```
Or if you prefer yarn, use:
```bash
yarn add @apiclient.xyz/tink
```
This will add the package to your project's dependencies. Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/mojoio/tink/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/mojoio/tink/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@mojoio/tink)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/mojoio/tink)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@mojoio/tink)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@mojoio/tink)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@mojoio/tink)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage ## Usage
The `@apiclient.xyz/tink` library provides an unofficial TypeScript API abstraction for interacting with tink.com. To make the most out of this library, it's recommended to have a basic understanding of TypeScript and asynchronous programming in JavaScript.
### Getting Started Use TypeScript for best inclass intellisense
First, you need to import the necessary classes from the `@apiclient.xyz/tink` package. Heres how you can get started with creating a `TinkAccount` instance and utilizing it to perform operations:
```typescript ## Contribution
import { TinkAccount, TinkUser, TinkProviderConsent } from '@apiclient.xyz/tink';
// Initialize a new TinkAccount with your clientId and clientSecret We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
const myTinkAccount = new TinkAccount('<YOUR_CLIENT_ID>', '<YOUR_CLIENT_SECRET>');
```
### Creating and Managing Tink Users For further information read the linked docs at the top of this readme.
To interact with user-specific APIs, create a `TinkUser` object. You can also retrieve an already existing user or create a new one as follows:
```typescript > MIT licensed | **&copy;** [Lossless GmbH](https://lossless.gmbh)
// Creating a new Tink User | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
const newUser = await myTinkAccount.createTinkUser('unique_external_user_id');
console.log('New TinkUser created:', newUser);
// Retrieving an existing Tink User [![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
const existingUser = await myTinkAccount.getTinkUser('existing_unique_external_user_id');
console.log('Existing TinkUser retrieved:', existingUser);
```
### Generating Tink Link for Account Connection
To connect bank accounts to the Tink platform, you will need to generate a Tink Link URL and present it to your users. Here's how you can obtain it:
```typescript
const tinkLinkUrl = await existingUser.getTinkLinkForMarket({
countryId: 'SE', // Specify the market code, e.g., SE for Sweden
redirectUrl: 'https://yourapplication.com/callback', // Redirect URL after account connection
customState: 'your_custom_state', // Optional custom state to be included in the callback
testProviderBool: true // Set to true if using test providers
});
console.log('Tink Link URL:', tinkLinkUrl);
```
### Fetching Bank Accounts and Transactions
After the user has connected their bank accounts through the Tink Link, you can retrieve the connected accounts and their transactions:
```typescript
// Fetching provider consents to get bank accounts
const providerConsents = await existingUser.getProviderConsents();
for (const consent of providerConsents) {
console.log('Provider consent:', consent);
// For each consent, get associated bank accounts
const bankAccounts = await consent.getBankAccounts();
for (const account of bankAccounts) {
console.log('Bank account:', account);
// Fetch transactions for each bank account
const transactions = await account.getTransactions();
for (const transaction of transactions) {
console.log('Transaction:', transaction);
}
}
}
```
### Advanced Usage
The library offers advanced features like handling provider consents, refreshing data, and managing users. For instance, you can delete a user as follows:
```typescript
await existingUser.delete();
console.log('User deleted successfully.');
```
To explore more about the library, including handling errors, refreshing tokens, and more nuanced data retrieval, consult the official API documentation provided by Tink.com and refer to the TypeScript definitions in this package.
Remember to secure your credentials and tokens appropriately and follow Tink's guidelines for data handling and user privacy.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -1,64 +0,0 @@
import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
import * as qenv from '@push.rocks/qenv';
const testQenv = new qenv.Qenv('./', './.nogit/');
import * as tink from '../ts/index.js';
let tinkTestAccount: tink.TinkAccount;
tap.test('should create a valid tink account', async () => {
tinkTestAccount = new tink.TinkAccount(
await testQenv.getEnvVarOnDemand('TINK_CLIENT_ID'),
await testQenv.getEnvVarOnDemand('TINK_CLIENT_SECRET')
);
expect(tinkTestAccount).toBeInstanceOf(tink.TinkAccount);
});
tap.test('should report tink as healthy', async () => {
await expectAsync(tinkTestAccount.getTinkHealthyBoolean()).toBeTrue();
});
tap.test('should create a tink user', async (toolsArg) => {
await tinkTestAccount.createTinkUser('user_1234_abc');
})
tap.test('should create a valid request', async (toolsArg) => {
const tinkuser: tink.TinkUser = await tinkTestAccount.getTinkUser('user_1234_abc');
console.log(tinkuser);
console.log(await tinkuser.getTinkLinkForMarket()); // defaults to 'DE';
console.log(await tinkuser.getProviderConsents());
});
tap.test('allow tink link to be used', async (toolsArg) => {
await toolsArg.delayFor(30000);
});
tap.test('get provider consents', async () => {
const tinkuser: tink.TinkUser = await tinkTestAccount.getTinkUser('user_1234_abc');
const providerConsents = await tinkuser.getProviderConsents();
console.log(providerConsents);
});
tap.test('get bankaccounts', async (toolsArg) => {
const tinkuser: tink.TinkUser = await tinkTestAccount.getTinkUser('user_1234_abc');
const bankAccounts = await tinkuser.getAllBankAccounts();
console.log(bankAccounts.map(bankAccountArg => bankAccountArg.getNormalizedData()));
for (const bankAccount of bankAccounts) {
const transactions = await bankAccount.getTransactions();
for (const transaction of transactions) {
console.log(`=======================`)
console.log(JSON.stringify(transaction.getNormalizedData()));
}
await toolsArg.delayFor(10000);
}
});
tap.test('should delete existing users', async () => {
expect(tinkTestAccount).toBeInstanceOf(tink.TinkAccount);
const tinkUser = new tink.TinkUser(tinkTestAccount, null, 'user_1234_abc');
await tinkUser.delete();
});
tap.start();

8
test/test.ts Normal file
View File

@ -0,0 +1,8 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as tink from '../ts/index';
tap.test('first test', async () => {
console.log(tink.standardExport);
});
tap.start();

View File

@ -1,8 +0,0 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@apiclient.xyz/tink',
version: '3.1.13',
description: 'an unofficial api abstraction for tink.com'
}

View File

@ -1 +0,0 @@
export * from './tinkmath.js';

View File

@ -1,22 +0,0 @@
export interface ITinkScaledAmount {
value: {
unscaledValue: string;
scale: string;
};
currencyCode: string;
}
/**
* returns a normalized amount
* @param scaledArg
* @returns
*/
export const getNormalizedAmount = (scaledArg?: ITinkScaledAmount) => {
if (!scaledArg) {
return null;
}
return {
value: parseInt(scaledArg.value.unscaledValue) * Math.pow(10, -(parseInt(scaledArg.value.scale))),
currency: 'EUR'
};
};

View File

@ -1,3 +1,3 @@
export * from './tink.classes.tinkaccount.js'; import * as plugins from './tink.plugins';
export * from './tink.classes.tinkuser.js';
export * from './tink.classes.tinkproviderconsent.js'; export let standardExport = 'Hi there! :) This is an exported string';

View File

@ -1,128 +0,0 @@
import { BankTransaction } from './tink.classes.banktransaction.js';
import { TinkUser } from './tink.classes.tinkuser.js';
import * as plugins from './tink.plugins.js';
import * as tinkHelpers from './helpers/index.js';
export interface ITinkBankAccountData {
balances: {
booked: {
amount: {
currencyCode: string;
value: {
scale: string;
unscaledValue: string;
};
};
};
available: {
amount: {
currencyCode: string;
value: {
scale: string;
unscaledValue: string;
};
};
};
};
customerSegment: string;
dates: {
lastRefreshed: string;
};
financialInstitutionId: string;
id: string;
identifiers: {
iban?: {
bban: string;
iban: string;
};
pan: {
masked: string;
};
financialInstitution: { accountNumber: string; referenceNumbers: unknown };
};
name: string;
type: string;
}
export class BankAccount {
// STATIC
public static async getAccountUserAccessToken(tinkUserArg: TinkUser) {
const authorizationCode = await tinkUserArg.tinkAccountRef.getUserAuthorizationCode(
tinkUserArg.externalUserIdArg,
tinkUserArg.tinkAccountRef.clientId,
'accounts:read,balances:read,transactions:read,provider-consents:read'
);
const accessToken = await tinkUserArg.tinkAccountRef.getUserAccessToken(authorizationCode);
return accessToken;
}
public static async getBankAccountsForUser(tinkUserArg: TinkUser) {
const userAccessToken = await this.getAccountUserAccessToken(tinkUserArg);
const returnBankAccounts: BankAccount[] = [];
const getBankAccountRecursively = async (nextPageToken?: string) => {
const searchParams = new URLSearchParams();
searchParams.set('pageSize', '200');
if (nextPageToken) {
searchParams.set('pageToken', nextPageToken);
}
const response = await tinkUserArg.tinkAccountRef.request({
urlArg: `/data/v2/accounts?${searchParams.toString()}`,
accessToken: userAccessToken,
methodArg: 'GET',
payloadArg: null,
});
for (const account of response.accounts) {
returnBankAccounts.push(new BankAccount(tinkUserArg, account));
}
if (response.nextPageToken.length > 0) {
await getBankAccountRecursively(response.nextPageToken);
}
};
await getBankAccountRecursively();
return returnBankAccounts;
}
// INSTANCE
tinkUserRef: TinkUser;
data: ITinkBankAccountData;
constructor(tinkUserRefArg: TinkUser, dataArg: ITinkBankAccountData) {
this.tinkUserRef = tinkUserRefArg;
this.data = dataArg;
}
/**
* updates the account and tries to get the latest state from bunq
*/
public async update() {
const bankAccounts = await BankAccount.getBankAccountsForUser(this.tinkUserRef);
const matchingAccount = bankAccounts.find(
(bankAccountArg) => bankAccountArg.data.id === this.data.id
);
if (matchingAccount) {
this.data = matchingAccount.data;
}
}
/**
* gets normalized data
*/
public getNormalizedData() {
return {
id: this.data.id,
name: this.data.name,
accountNumber: this.data.identifiers?.financialInstitution?.accountNumber || null,
iban: this.data.identifiers.iban?.iban || null,
bookedValue: tinkHelpers.getNormalizedAmount(this.data.balances.booked?.amount),
availableValue: tinkHelpers.getNormalizedAmount(this.data.balances.available?.amount),
};
}
/**
* gets the transactions for the bank account
*/
public async getTransactions() {
const transactions = await BankTransaction.getBankTransactions(this);
return transactions;
}
}

View File

@ -1,117 +0,0 @@
import { BankAccount } from './tink.classes.bankaccount.js';
import * as plugins from './tink.plugins.js';
import * as tinkHelpers from './helpers/index.js';
export interface ITinkBankTransactiondata {
id: string;
accountId:string;
amount: {
currencyCode: string;
value: {
scale: string;
unscaledValue: string;
};
};
categories: {
pfm: {
id: string;
name: string;
};
};
dates: {
booked: string;
value: string;
};
descriptions: {
display: string;
original: string;
};
identifiers: {
providerTransactionId: string;
};
merchantInformation: {
merchantCategoryCode: 'string';
merchantName: 'string';
};
providerMutability: string;
reference: string;
status: string;
types: {
financialInstitutionTypeCode: string;
type: string;
};
}
export class BankTransaction {
// STATIC
public static async getTransactionAccessToken(bankAccountArg: BankAccount) {
const authorizationCode =
await bankAccountArg.tinkUserRef.tinkAccountRef.getUserAuthorizationCode(
bankAccountArg.tinkUserRef.externalUserIdArg,
bankAccountArg.tinkUserRef.tinkAccountRef.clientId,
'accounts:read,balances:read,transactions:read,provider-consents:read'
);
const accessToken = await bankAccountArg.tinkUserRef.tinkAccountRef.getUserAccessToken(
authorizationCode
);
return accessToken;
}
public static async getBankTransactions(bankAccountArg: BankAccount) {
const accessToken = await this.getTransactionAccessToken(bankAccountArg);
const pageSize = 100;
const returnTransactions: BankTransaction[] = [];
const getTransactionsRecursively = async (nextPageToken?: string) => {
const searchParams = new URLSearchParams();
searchParams.set('accountIdIn', bankAccountArg.data.id);
searchParams.set('pageSize', '200');
if (nextPageToken) {
searchParams.set('pageToken', nextPageToken)
}
const response = await bankAccountArg.tinkUserRef.tinkAccountRef.request({
urlArg: `/data/v2/transactions?${searchParams.toString()}`,
accessToken: accessToken,
methodArg: 'GET',
payloadArg: null,
});
for (const transaction of response.transactions) {
returnTransactions.push(new BankTransaction(bankAccountArg, transaction));
}
if (response.nextPageToken.length > 0) {
await getTransactionsRecursively(response.nextPageToken);
}
};
await getTransactionsRecursively();
return returnTransactions;
}
// INSTANCE
bankAccountRef: BankAccount;
data: ITinkBankTransactiondata;
constructor(bankAccountRefArg: BankAccount, dataArg: ITinkBankTransactiondata) {
this.bankAccountRef = bankAccountRefArg;
this.data = dataArg;
}
/**
* gets normalized data
*/
public getNormalizedData() {
return {
id: this.data.id,
date: new Date(this.data.dates.booked).getTime(),
amount: tinkHelpers.getNormalizedAmount(this.data.amount),
name: this.data.descriptions.display,
description: this.data.descriptions.original,
originAccountId: this.data.accountId,
justForLooks: {
originalScaledAmount: this.data.amount,
dateIso: new Date(this.data.dates.booked).toISOString()
}
}
}
}

View File

@ -1,178 +0,0 @@
import * as plugins from './tink.plugins.js';
import { TinkUser } from './tink.classes.tinkuser.js';
export class TinkAccount {
public clientId: string;
private _clientSecret: string;
private _apiBaseUrl: string = 'https://api.tink.com';
constructor(clientIdArg: string, clientSecretArg: string) {
this.clientId = clientIdArg;
this._clientSecret = clientSecretArg;
}
public async getTinkHealthyBoolean(): Promise<boolean> {
const response = await plugins.smartrequest.request(
'https://api.tink.com/api/v1/monitoring/healthy',
{
keepAlive: false,
}
);
return response.body === 'ok';
}
public async getClientAccessTokenForScope(scopeArg: string): Promise<string> {
// lets get an accessToken for the request
const response = await plugins.smartrequest.postFormDataUrlEncoded(
`${this._apiBaseUrl}/api/v1/oauth/token`,
{
keepAlive: false,
},
[
{
key: 'client_id',
content: this.clientId,
},
{
key: 'client_secret',
content: this._clientSecret,
},
{
key: 'grant_type',
content: 'client_credentials',
},
{
key: 'scope',
content: scopeArg,
},
]
);
if (response.statusCode !== 200) {
console.log(response.statusCode);
console.log(response.body);
throw new Error('there was an error aquiring an access token.');
}
const clientAccessToken = response.body.access_token;
return clientAccessToken;
}
public async getUserAuthorizationCode(
externalUserIdArg: string,
actorCLientIdArg: string,
scopeArg: string
) {
const accessToken = await this.getClientAccessTokenForScope('authorization:grant');
const response = await plugins.smartrequest.postFormDataUrlEncoded(
`${this._apiBaseUrl}/api/v1/oauth/authorization-grant/delegate`,
{
keepAlive: false,
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
[
{
key: 'response_type',
content: 'code',
},
{
key: 'actor_client_id',
content: actorCLientIdArg,
},
{
key: 'external_user_id',
content: externalUserIdArg,
},
{
key: 'id_hint',
content: 'Hello there',
},
{
key: 'scope',
content: scopeArg,
},
]
);
if (response.statusCode !== 200) {
console.log(response.body);
throw new Error('there was an error aquiring an access token.');
}
const userAuthorizationCode = response.body.code;
return userAuthorizationCode;
}
public async getUserAccessToken(authorizationCode: string): Promise<string> {
const accessToken = await this.getClientAccessTokenForScope('authorization:grant');
const response = await plugins.smartrequest.postFormDataUrlEncoded(
`${this._apiBaseUrl}/api/v1/oauth/token`,
{
keepAlive: false,
},
[
{
key: 'code',
content: authorizationCode,
},
{
key: 'client_id',
content: this.clientId,
},
{
key: 'client_secret',
content: this._clientSecret,
},
{
key: 'grant_type',
content: 'authorization_code',
},
]
);
if (response.statusCode !== 200) {
console.log(response.body);
throw new Error('there was an error aquiring an access token.');
}
const userAccessToken = response.body.access_token;
return userAccessToken;
}
// the request method for tink respecting platform specific stuff
// e.g. certain headers if needed
public async request(optionsArg: {
urlArg: string;
methodArg: 'POST' | 'GET';
accessToken: string;
payloadArg: any;
}) {
// check health
if (!(await this.getTinkHealthyBoolean())) {
throw new Error('TINK is not healthy right now. Please try again later.');
} else {
console.log('tink is healthy, continuing...');
}
const response = await plugins.smartrequest.request(`${this._apiBaseUrl}${optionsArg.urlArg}`, {
keepAlive: false,
headers: {
Authorization: `Bearer ${optionsArg.accessToken}`,
'Content-Type': 'application/json',
},
method: optionsArg.methodArg,
requestBody: JSON.stringify(optionsArg.payloadArg),
});
console.log(response.statusCode);
return response.body;
}
public async getTinkUser(externalUserIdArg: string) {
const tinkuser = await TinkUser.getTinkUser(this, externalUserIdArg);
return tinkuser;
}
public async createTinkUser(externalUserIdArg: string) {
const tinkuser = await TinkUser.createNewTinkUser(this, externalUserIdArg);
return tinkuser;
}
}

View File

@ -1,87 +0,0 @@
import * as plugins from './tink.plugins.js';
export interface IProviderData {
credentialsId: string;
providerName: string;
status: string;
sessionExpiryDate: number;
accountIds: string[];
statusUpdated: number;
}
import { TinkUser } from './tink.classes.tinkuser.js';
/**
* a provider consent maps to tinks bank consents
*/
export class TinkProviderConsent {
public static async getProviderUserAccessToken(tinkUserRefArg: TinkUser) {
const authorizationCode = await tinkUserRefArg.tinkAccountRef.getUserAuthorizationCode(
tinkUserRefArg.externalUserIdArg,
tinkUserRefArg.tinkAccountRef.clientId,
'accounts:read,balances:read,transactions:read,provider-consents:read'
);
const accessToken = await tinkUserRefArg.tinkAccountRef.getUserAccessToken(authorizationCode);
return accessToken;
}
// STATIC
public static async getProviderConsentsForUser(tinkUserRefArg: TinkUser) {
const returnProviderConsents: TinkProviderConsent[] = [];
const accessToken = await this.getProviderUserAccessToken(tinkUserRefArg);
const responseData = await tinkUserRefArg.tinkAccountRef.request({
urlArg: '/api/v1/provider-consents',
accessToken,
methodArg: 'GET',
payloadArg: null,
});
// console.log(responseData); // no nextPageToken here?
if (responseData.providerConsents) {
for (const providerConsentData of responseData.providerConsents) {
returnProviderConsents.push(new TinkProviderConsent(tinkUserRefArg, providerConsentData));
}
}
return returnProviderConsents;
}
// INSTANCE
tinkUserRef: TinkUser;
data: IProviderData;
constructor(tinkUserRefArg: TinkUser, dataArg: IProviderData) {
this.tinkUserRef;
this.data = dataArg;
}
/**
* refresh the bank account data from origin
*/
public async refresh() {
const userAccessToken = await TinkProviderConsent.getProviderUserAccessToken(this.tinkUserRef);
const response = await this.tinkUserRef.tinkAccountRef.request({
accessToken: userAccessToken,
methodArg: 'POST',
urlArg: `https://api.tink.com/api/v1/credentials/${this.data.credentialsId}/refresh`,
payloadArg: null
});
// polling as per documentation for status 'UPDATED';
let pollingRounds = 0;
let status = null;
while(status !== 'UPDATED' && pollingRounds < 10) {
await plugins.smartdelay.delayFor(2000);
await this.update();
status = this.data.status;
pollingRounds++;
}
// think about how to handle errors here
}
public async update() {
const providerConsents = await TinkProviderConsent.getProviderConsentsForUser(this.tinkUserRef);
for (const providerConsent of providerConsents) {
if (providerConsent.data.credentialsId === this.data.credentialsId) {
this.data = providerConsent.data;
}
}
}
}

View File

@ -1,166 +0,0 @@
import * as plugins from './tink.plugins.js';
import { TinkAccount } from './tink.classes.tinkaccount.js';
import { TinkProviderConsent } from './tink.classes.tinkproviderconsent.js';
import { BankAccount } from './tink.classes.bankaccount.js';
export class TinkUser {
// STATIC
public static async createNewTinkUser(tinkAccountArg: TinkAccount, externalUserIdArg: string) {
const accessToken = await tinkAccountArg.getClientAccessTokenForScope('user:create');
const responseData: {
external_user_id: string;
user_id: string;
} = await tinkAccountArg.request({
urlArg: '/api/v1/user/create',
accessToken,
methodArg: 'POST',
payloadArg: {
external_user_id: externalUserIdArg,
market: 'DE',
locale: 'en_US',
},
});
const newTinkUser = await TinkUser.getTinkUser(tinkAccountArg, externalUserIdArg);
return newTinkUser;
}
public static async getTinkUser(tinkAccountArg: TinkAccount, externalUserIdArg: string) {
const authorizationCode = await tinkAccountArg.getUserAuthorizationCode(
externalUserIdArg,
tinkAccountArg.clientId,
'user:read'
);
const accessToken = await tinkAccountArg.getUserAccessToken(authorizationCode);
const responseData: {
appId: string;
created: string;
externalUserId: string;
flags: string[];
id: string;
nationalId: string;
profile: {
// cashbackEnabled: boolean; // deprecated
currency: string;
locale: string;
market: string;
notificationSettings: {
balance: boolean;
budget: boolean;
doubleCharge: boolean;
einvoices: boolean;
fraud: boolean;
income: boolean;
largeExpense: boolean;
leftToSpend: boolean;
loanUpdate: boolean;
summaryMonthly: boolean;
summaryWeekly: boolean;
transaction: boolean;
unusualAccount: boolean;
unusualCategory: boolean;
};
periodAdjustedDay: 25;
periodMode: 'MONTHLY_ADJUSTED' | 'MONTHLY';
timeZone: string;
};
// username: string; // not relevant
} = await tinkAccountArg.request({
urlArg: '/api/v1/user',
accessToken,
methodArg: 'GET',
payloadArg: null,
});
const newTinkUser = new TinkUser(tinkAccountArg, responseData.id, responseData.externalUserId);
return newTinkUser;
}
// INSTANCE
public tinkAccountRef: TinkAccount;
public tinkUserId: string;
public externalUserIdArg: string;
constructor(tinkAccountrefArg: TinkAccount, tinkUserIdArg: string, externalUserIdArg: string) {
this.tinkAccountRef = tinkAccountrefArg;
this.tinkUserId = tinkUserIdArg;
this.externalUserIdArg = externalUserIdArg;
}
/**
* deletes the user
*/
public async delete() {
const authorizationCode = await this.tinkAccountRef.getUserAuthorizationCode(
this.externalUserIdArg,
this.tinkAccountRef.clientId,
'user:delete'
);
const accessToken = await this.tinkAccountRef.getUserAccessToken(authorizationCode);
const response = await this.tinkAccountRef.request({
methodArg: 'POST',
accessToken,
payloadArg: {},
urlArg: '/api/v1/user/delete',
});
console.log(`successfully deleted user with externalId ${this.externalUserIdArg}`);
}
/**
* gets a tink link that can be used by a user to connect accounts
* @returns
*/
public async getTinkLinkForMarket(linkOptionsArg: {
countryId: string;
redirectUrl: string;
/**
* an optional state that is transported through to the callback
*/
customState: string;
testProviderBool?: boolean;
} = {
countryId: 'NL',
redirectUrl: 'https://console.tink.com/callback',
customState: "exampleState",
testProviderBool: true
}): Promise<string> {
if (typeof linkOptionsArg.testProviderBool !== 'boolean') {
linkOptionsArg.testProviderBool = false;
}
const authorizationCode = await this.tinkAccountRef.getUserAuthorizationCode(
this.externalUserIdArg,
'df05e4b379934cd09963197cc855bfe9', // this is a hardcoded app id for tink link, as recommended by tink.com
'authorization:read,authorization:grant,credentials:refresh,credentials:read,credentials:write,providers:read,user:read'
);
const tinkUrlOptions: {[key: string]: string} = {}
tinkUrlOptions['client_id'] = this.tinkAccountRef.clientId;
tinkUrlOptions['redirect_uri']= linkOptionsArg.redirectUrl;
tinkUrlOptions['authorization_code'] = authorizationCode;
tinkUrlOptions['market'] = linkOptionsArg.countryId;
if (linkOptionsArg.testProviderBool) {
tinkUrlOptions['test'] = 'true';
}
if (linkOptionsArg.customState) {
tinkUrlOptions['state'] = linkOptionsArg.customState;
}
const url = plugins.smarturl.Smarturl.createFromUrl('https://link.tink.com/1.0/business-transactions/connect-accounts', {
searchParams: tinkUrlOptions
});
const tinkLinkUrl = url.toString();
return tinkLinkUrl;
}
public async getProviderConsents(): Promise<TinkProviderConsent[]> {
const providerConsents: TinkProviderConsent[] =
await TinkProviderConsent.getProviderConsentsForUser(this);
return providerConsents;
}
/**
* gets all accounts
*/
public async getAllBankAccounts() {
const bankAccounts = await BankAccount.getBankAccountsForUser(this);
return bankAccounts;
}
}

View File

@ -1,7 +1,2 @@
// @pushrocks scope const removeme = {};
import * as smartdelay from '@push.rocks/smartdelay'; export { removeme };
import * as smartrequest from '@push.rocks/smartrequest';
import * as smartpromise from '@push.rocks/smartpromise';
import * as smarturl from '@push.rocks/smarturl';
export { smartdelay, smartrequest, smartpromise, smarturl };

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

17
tslint.json Normal file
View File

@ -0,0 +1,17 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}