UNPKG

@mft/moneyhub-api-client

Version:
1,677 lines (1,302 loc) 73.8 kB
# Moneyhub API Client ## Introduction This is an Node.JS client for the [Moneyhub API](https://docs.moneyhubenterprise.com/docs). It currently supports the following features: - Getting the list of supported banks - Registering users - Deleting users - Generating authorisation urls for new and existing users - Getting access tokens and refresh tokens from an authorisation code - Refreshing access tokens - Deleting user connections - Getting access tokens with client credentials - CRUD actions for accounts - CRUD actions for transactions - Generate authorisation url for payments - Add Payees - Get Payees and payments - Add Pay links - Get Pay links - Get categories - CRUD actions on projects - CRUD actions on transaction attachments - CRUD actions on transaction splits - Get a tax return for a subset of transactions - Get the regular transactions on an account - Get beneficiaries - CAAS (Categorisation as a Service) API for advanced transaction enrichment and categorisation Currently this library supports `client_secret_basic`, `client_secret_jwt` and `private_key_jwt` authentication. ## Upgrading from 3.x The breaking changes when upgrading are outlined below: - Normalisation of all methods to use object destructuring to pass parameters. Please refer to the docs of each method when migrating to this version - Delete methods only return the status code when successful - All methods to retrieve data return the body response as json, on previous versions some methods were returning the full response from the got library. - When our API response code is not 2xx an HTTP error is thrown. Includes a response property with more information. - Removal of all the methods with the suffix `WithToken`. To migrate to this version you can use the method with the same name but without the suffix. e.g `getUserConnectionsWithToken()` => `getUserConnections()` For the full list of changes please refer to the [changelog](CHANGELOG.md) ## Upgrading from 4.x The major upgrade from version 4.x is that the library now caters for TypeScript. To allow for this, the factory method that creates the client instance is now a named export rather than a default export. ```js // v4.x const Moneyhub = require("@mft/moneyhub-api-client") // v5.x const {Moneyhub} = require("@mft/moneyhub-api-client") ``` ## Changelog [Learn about the latest improvements and breaking changes](CHANGELOG.md). ## Prerequisites To use this API client you will need: - A `client_id`, `client_secret` and `redirect_uri` of a registered API client - The url of the Moneyhub identity service for the environment you are connecting to (https://identity.moneyhub.co.uk) - The url for the API gateway for the environment that you are connecting to (https://api.moneyhub.co.uk/v2.0) ## To install `npm install @mft/moneyhub-api-client` ## Creating JWKS If you need to generate JWKS (JSON Web Key Set) for authentication with `private_key_jwt`, you can use the provided script: ```bash npm run create-jwks -- --key-alg RS256 --key-size 2048 --key-use sig --alg RS256 ``` ### Options - `--key-alg`: The key algorithm (default: uses the value from `--alg`) - `--key-size`: The key size in bits (default: 2048) - `--key-use`: The key usage, typically `sig` for signing (default: sig) - `--alg`: The signing algorithm, e.g., `RS256`, `RS384`, `RS512` (default: RS256) This will generate both public and private JWKS. The public keys should be added to your API client configuration in the Moneyhub Admin portal, and the private keys should be used as the `keys` value when configuring the Moneyhub API client. ## Usage This module exposes a single factory function that accepts the following configuration: ```javascript const {Moneyhub} = require("@mft/moneyhub-api-client") const moneyhub = await Moneyhub({ resourceServerUrl: "https://api.moneyhub.co.uk/v3", identityServiceUrl: "https://identity.moneyhub.co.uk", options: { // optional timeout: 60000, // request timeout in milliseconds retry: { limit: 3, // maximum number of retries methods: ["GET", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE"], // HTTP methods to retry statusCodes: [408, 413, 429, 500, 502, 503, 504, 521, 522, 524], // status codes to retry on maxRetryAfter: 5000 // maximum time to wait between retries in milliseconds }, } client: { client_id: "your client id", client_secret: "your client secret", token_endpoint_auth_method: "client_secret_basic", id_token_signed_response_alg: "RS256", request_object_signing_alg: "none", redirect_uri: "https://your-redirect-uri", response_type: "code", keys: [ /* your jwks */ ], /* optionally use Mutual TLS certificates */ mTLS: { tls_client_certificate_bound_access_tokens: true, cert: readFileSync(path.join(__dirname, "../certs/cert.pem")), key: readFileSync(path.join(__dirname, "../certs/key.pem")), } }, }) ``` ## Options When making calls to our methods that require authentication, you can provide an extra argument at the end of these methods. This argument must be an object with these optional keys: ```js { token: "full.access.token" // if specified will be added to authorisation header of request headers: { Authorization: "Bearer full.access.token" // can be used to specify authorisation header or additional headers }, version: "v3" // Forces an specific API version when calling the method } ``` Example usages ```javascript const accounts = await moneyhub.getAccounts({ userId: "user-id", params: {}, }, {}); const accounts = await moneyhub.getAccounts({ params: {}, }, { token: "full.access.token" }); const accounts = await moneyhub.getAccounts({ params: {}, }, { headers: { Authorization: "Bearer full.access.token" } }); const accounts = await moneyhub.getAccountsList({ params: {}, }, { version: "v2" }); ``` At least one of the following parameters needs to be passed in to any api call that requires user authentication: - **userId**: Automatically requests a token for this userId with the correct scopes - **token**: The token will be added as bearer authorization header - **Authorization header**: The full authorisation header can be passed in ## Using the client behind a gateway The client keeps the original resource URLs in config (`resourceServerUrl`, `identityServiceUrl`, `caasResourceServerUrl`, `osipResourceServerUrl`, `accountConnectUrl`). You can optionally set a **gateway URL** for each resource (`gatewayResourceServerUrl`, `gatewayIdentityServiceUrl`, `gatewayCaasResourceServerUrl`, `gatewayOsipResourceServerUrl`, `gatewayAccountConnectUrl`). **Only when a gateway URL is set** for a resource does the client use that URL for requests to that resource and rewrite responses to it. If you only route one resource through a gateway, set only that resource’s gateway URL; the others stay on the original URLs and no rewriting occurs for them. Example: ```javascript const moneyhub = await Moneyhub({ resourceServerUrl: "https://api.moneyhub.co.uk/v3", identityServiceUrl: "https://identity.moneyhub.co.uk", gatewayResourceServerUrl: "https://my-gateway.example.com/moneyhub/v3", gatewayIdentityServiceUrl: "https://my-gateway.example.com/moneyhub/identity", options: { openIdConfigCacheTtlMs: 3600000, // optional; default 1 hour }, client: { /* ... */ }, }) ``` Behaviour: - **Identity**: When `gatewayIdentityServiceUrl` is set, the client fetches the OpenID discovery document from that URL and rewrites endpoint URLs in the document to use it, so that authorization, token exchange, and JWKS requests go through the gateway. When it is not set, discovery is fetched from `identityServiceUrl` and no rewriting is applied. - **Resource server**: When `gatewayResourceServerUrl` (or `gatewayCaasResourceServerUrl` or `gatewayOsipResourceServerUrl`) is set, the client uses that URL for requests to that API and rewrites link URLs in responses (e.g. `links.self`, `links.next`, `links.prev`) to that base. When no gateway URL is set for that resource, the client uses the original URL and does not rewrite response links. **Verifying behaviour**: Run the unit tests for the rewrite logic with `npx mocha --require ts-node/register "src/__tests__/discovery.ts"`; run the integration tests for gateway rewriting with `npm run test -- -g "Gateway URL rewriting"` (or run the full test suite as described in [Running Tests](#running-tests)); in production, check your gateway access logs to confirm identity and API requests hit the gateway, or inspect `getOpenIdConfig()` and any `response.links` to see gateway URLs. ### Security considerations The following points are intended for security review (e.g. by banks or regulated entities). - **Rewrite target is always a configured gateway URL** URLs are rewritten only to the gateway base URLs you supply (`gatewayIdentityServiceUrl`, `gatewayResourceServerUrl`, etc.). The client never uses a URL from a response or discovery document as the *target* of the rewrite. An attacker who could influence response content cannot cause the client to send traffic to an arbitrary or malicious host. - **TLS and certificates** The client validates TLS only to the configured base (the gateway). The gateway is responsible for TLS to the upstream identity and API services. No new certificate or trust store requirements are introduced by the library. - **OIDC issuer claim and discovery `issuer`** ID tokens from the identity provider carry an `iss` (issuer) claim. Many OIDC clients validate that the token’s `iss` matches the Issuer’s `issuer` from discovery. When using a gateway, the implementation may leave the discovery `issuer` field unchanged so that token validation continues to expect the IdP’s canonical `iss`; or the identity service behind the gateway may be configured to issue tokens with `iss` equal to the gateway URL. See the release notes or implementation docs for the chosen behaviour so you can align with your IdP and validation policies. - **Response body integrity** The client modifies response bodies (e.g. `links`) for resource server responses. If you sign or checksum the *full* response body elsewhere, rewriting URL fields would invalidate that. Treat the client as the consumer of the API for integrity purposes, or apply signing after the client (e.g. at the gateway) so the signed payload is the rewritten one. - **Secrets** Client credentials, keys, and tokens are used as in the standard flow. No new storage, logging, or transmission of secrets is introduced by the gateway rewrite logic. ### Governance considerations - **Change control and risk** The gateway feature alters outbound request behaviour (discovery used for the Issuer) and response bodies (resource server links). Release notes and CHANGELOG describe the change. Summary: enables gateway-only routing; no new external dependency; rewrite targets are config-only; considerations include issuer claim alignment and response body integrity as above. - **Audit and assurance** To demonstrate that traffic to Moneyhub goes through your approved gateway, set the relevant gateway URLs and use the verification steps above (tests, gateway logs, inspection of `getOpenIdConfig()` and `response.links`). Internal or external audit can rely on config plus these verification steps. - **Third-party and supply chain** The client uses `@isaacs/ttlcache` for OIDC discovery caching. Rewrite targets are never taken from responses or discovery documents. - **Regulatory and outsourcing** Use of a gateway is your architectural choice; this feature makes it possible for the client to honour that choice. Regulatory implications (e.g. outsourcing, record-keeping) remain with your use of the gateway and the Moneyhub service, not with the library change itself. ## API Once the api client has been initialised it provides a simple promise based interface with the following methods: ### Auth API The options below can be set on the following URL generating methods: - `getAuthorizeUrl` - `getAuthorizeUrlForCreatedUser` - `getReauthAuthorizeUrlForCreatedUser` - `getRefreshAuthorizeUrlForCreatedUser` The `expirationDateTime` and `transactionFromDateTime` options can be set according to the [AIS Consents documentation](https://docs.moneyhubenterprise.com/docs/ais-consents) Set `enableAsync` to true if you wish to make an AIS connection that won't wait for accounts and transactions to be fetched. **Note:** all methods generate an authorise URL using the Pushed Authorisation Request (PAR) method, see [here](https://docs.moneyhubenterprise.com/docs/pushed-authorisation-requests-par) for more details. #### `getAuthorizeUrl` This method returns an authorize url for your API client. You can redirect a user to this url, after which they will be redirected back to your `redirect_uri`. [Financial institutions](https://docs.moneyhubenterprise.com/docs/bank-connections) [Scopes](https://docs.moneyhubenterprise.com/docs/scopes) [Claims](https://docs.moneyhubenterprise.com/docs/claims) ```javascript const url = await moneyhub.getAuthorizeUrl({ scope: "openid bank-id-scope other-data-scopes", state: " your state value", // optional nonce: "your nonce value", //optional claims: claimsObject, // optional permissions: ["ReadBeneficiariesDetail"], // optional - set of extra permissions to set for auth URL permissionsAction: "replace" // optional - replace default consent permissions. Defaults to "add" expirationDateTime: "2022-09-01T00:00:00.000Z", // optional transactionFromDateTime: "2020-09-01T00:00:00.000Z", // optional, enableAsync: false, // optional }); // Default claims if none are provided const defaultClaims = { id_token: { sub: { essential: true, }, "mh:con_id": { essential: true, }, }, }; ``` #### `getAuthorizeUrlForCreatedUser` This is a helper function that returns an authorize url for a specific user to connect to a specific bank. This function uses the following scope with the value of the bankId provided `id:${bankId} openid`. [Financial institutions](https://docs.moneyhubenterprise.com/docs/bank-connections) [Scopes](https://docs.moneyhubenterprise.com/docs/scopes) [Claims](https://docs.moneyhubenterprise.com/docs/claims) ```javascript const url = await moneyhub.getAuthorizeUrlForCreatedUser({ bankId: "bank id to connect to", userId: "user id returned from the registerUser call", state: "your state value", // optional nonce: "your nonce value", // optional claims: claimsObject, // optional permissions: ["ReadBeneficiariesDetail"], // optional - set of extra permissions to set for auth URL permissionsAction: "replace" // optional - replace default consent permissions. Defaults to "add" enableAsync: false, // optional }); // Scope used with the bankId provided const scope = `id:${bankId} openid`; // Default claims if none are provided const defaultClaims = { id_token: { sub: { essential: true, value: userId, // userId provided }, "mh:con_id": { essential: true, }, }, }; ``` #### `getReauthAuthorizeUrlForCreatedUser` This is a helper function that returns an authorize url for a specific user to re authorize an existing connection. This function uses the scope `openid reauth`. ```javascript const url = await moneyhub.getReauthAuthorizeUrlForCreatedUser({ userId: "the user id", connectionId: "connection Id to re authorize", state: "your state value", // optional nonce: "your nonce value", // optional claims: claimsObject, // optional enableAsync: false, // optional }); // Default claims if none are provided const defaultClaims = { id_token: { sub: { essential: true, value: userId, // userId provided }, "mh:con_id": { essential: true, value: connectionId, // connectionId provided }, }, }; ``` #### `getReconsentAuthorizeUrlForCreatedUser` This is a helper function that returns a url for a specific user to reconsent an existing connection. This function uses the scope `openid reconsent`. The `expiresAt` date cannot be set to more than 90 days in the future. If `expiresAt` is not provided it will default to a date 90 days in the future. **Please note - this method should only be used for connections that have `tppConsent` set as `true`**. ```javascript const url = await moneyhub.getReconsentAuthorizeUrlForCreatedUser({ userId: "user id", connectionId: "connection ID to reconsent", state: "your state value", // optional nonce: "your nonce value", // optional claims: claimsObject // optional expiresAt: "ISO date-time string for new expiry of the connection" // optional - defaults to 90 days in future }); // Default claims if none are provided const defaultClaims = { id_token: { sub: { essential: true, value: userId, // userId provided }, "mh:con_id": { essential: true, value: connectionId, // connectionId provided }, "mh:consent": { value: { expirationDateTime: expiresAt, // expiresAt provided. If not provided defaults to a date 90 days in the future }, }, }, }; ``` #### `getRefreshAuthorizeUrlForCreatedUser` #### `getAuthorizeUrlLegacy` This method returns an authorize url for your API client using the legacy method (where a request object is generated and passed in as the `request` query parameter). You can redirect a user to this url, after which they will be redirected back to your `redirect_uri`. It has the same method signature as `getAuthorizeUrl` ```javascript const url = await moneyhub.getAuthorizeUrlLegacy({ scope: "openid bank-id-scope other-data-scopes", state: " your state value", // optional nonce: "your nonce value", //optional claims: claimsObject, // optional permissions: ["ReadBeneficiariesDetail"], // optional - set of extra permissions to set for auth URL permissionsAction: "replace" // optional - replace default consent permissions. Defaults to "add" expirationDateTime: "2022-09-01T00:00:00.000Z", // optional transactionFromDateTime: "2020-09-01T00:00:00.000Z", // optional, enableAsync: false, // optional }); ``` This is a helper function that returns an authorize url for a specific user to refresh an existing connection. This function uses the scope `openid refresh`. (Only relevant for legacy connections) ```javascript const url = await moneyhub.getRefreshAuthorizeUrlForCreatedUser({ userId: "the user id", connectionId: "connection Id to re refresh", state: "your state value", // optional nonce: "your nonce value", // optional claims: claimsObject, // optional enableAsync: false, // optional }); // Default claims if none are provided const defaultClaims = { id_token: { sub: { essential: true, value: userId, // userId provided }, "mh:con_id": { essential: true, value: connectionId, // connectionId provided }, }, }; ``` #### `exchangeCodeForTokensLegacy` This is a legacy method to get tokens for a user. After a user has successfully authorised they will be redirected to your redirect_uri with an authorization code. You can use this to retrieve access, refresh and id tokens for the user. ```javascript const tokens = await moneyhub.exchangeCodeForTokensLegacy({ code: "the authorization code", nonce: "your nonce value", // optional state: "your state value", // optional id_token: "your id token", // optional }); ``` #### `exchangeCodeForTokens` After a user has successfully authorised they will be redirected to your redirect_uri with an authorization code. You can use this method to retrieve access, refresh and id tokens for the user. The signature for this method changed in v3. The previous function is available at 'exchangeCodeForTokensLegacy' This method requires an object with two properties: - `paramsFromCallback` : an object with all the params received at your redirect uri - `localParams` : an object with params that you have in the local session for the user. ```javascript const tokens = await moneyhub.exchangeCodeForTokens({ paramsFromCallback: { "code": "the auth code", "id_token": "the id_token", // when code id_token response type is used "state": "state", }, localParams: { "state": "state", // this must be from the local session not the redirect uri "nonce": "nonce", // this must be from the local session "sub": "the user id", // optional, but without this param, requests where there are missing cookies will fail "max_age", // optional, not normally required "response_type" // recommended to enhance securirty "code_verifier" // required if PKCE is used } }) ``` #### `getClientCredentialTokens` Use this to get a client credentials access token. ```javascript const tokens = await moneyhub.getClientCredentialTokens({ scope: "the-required-scope", sub: "the user id", // optional }); ``` #### `refreshTokens` Use this to get a new access token using a refresh token ```javascript const tokens = await moneyhub.refreshTokens({ refreshToken: "refresh-token", }); ``` ### Auth Request URI #### `requestObject` Creates a request object ```javascript const tokens = await moneyhub.requestObject({ scope: "the-required-scope", state: "state", nonce: "nonce", claims: claimsObject, }); ``` #### `getRequestUri` Use this to create a request uri from a request object ```javascript const requestUri = await moneyhub.getRequestUri(requestObject); ``` #### `getAuthorizeUrlFromRequestUri` Use this to retrieve an authorization url from a request uri ```javascript const url = await moneyhub.getAuthorizeUrlFromRequestUri({ requestUri: "request-uri", }); ``` ### Auth Requests #### `createAuthRequest` Creates a connection auth request ```javascript const tokens = await moneyhub.createAuthRequest({ redirectUri: "redirect-uri", userId: "user-id", scope: "openid 1ffe704d39629a929c8e293880fb449a", // replace bank id with the bank you want to connect to categorisationType: "personal", // optional - defaults to personal permissions: ["ReadBeneficiariesDetail"], // optional - set of extra permissions to set for auth request permissionsAction: "replace" // optional - replace default consent permissions. Defaults to "add" }); ``` Creates a reauth auth request ```javascript const tokens = await moneyhub.createAuthRequest({ redirectUri: "redirect-uri", userId: "user-id", connectionId: "connection-id", scope: "openid reauth", }); ``` Creates a refresh auth request ```javascript const tokens = await moneyhub.createAuthRequest({ redirectUri: "redirect-uri", userId: "user-id", connectionId: "connection-id", scope: "openid refresh", }); ``` Creates a payment auth request ```javascript const tokens = await moneyhub.createAuthRequest({ redirectUri: "redirect-uri", userId: "user-id", connectionId: "connection-id", scope: "openid payment", payment: { payeeId: "payee-id", amount: 200, payeeRef: "Payee ref", payerRef: "Payer ref", }, }); ``` Creates a reverse payment auth request ```javascript const tokens = await moneyhub.createAuthRequest({ redirectUri: "redirect-uri", userId: "user-id", connectionId: "connection-id", scope: "openid reverse_payment", reversePayment: { paymentId: "payment-id", }, }); ``` #### `completeAuthRequest` Completes an auth request successfully ```javascript const tokens = await moneyhub.completeAuthRequest({ id: "auth-request-id", authParams: { code: "code" state: "state", "id_token": "idToken", } }) ``` Completes an auth request with an error ```javascript const tokens = await moneyhub.completeAuthRequest({ id: "auth-request-id", authParams: { error: "error-code", error_description: "error description", }, }); ``` #### `getAllAuthRequests` Retrieves auth requests ```javascript const tokens = await moneyhub.getAllAuthRequests({ limit: 10, // optional offset: 0, // optional }); ``` #### `getAuthRequest` Retrieve a single auth request ```javascript const tokens = await moneyhub.getAuthRequest({ id: "auth-request-id", }); ``` ### User Management #### `registerUser` Helper method that gets the correct client credentials access token and then registers a user. ```javascript const user = await moneyhub.registerUser({ clientUserId: "your user id", // optional }); ``` #### `getUsers` Returns all the users registered for your api-client ```javascript const users = await moneyhub.getUsers({ limit, offset, isDemo, }); ``` #### `getUser` Get a single user by their id ```javascript const user = await moneyhub.getUser({ userId: "user-id", }); ``` #### `deleteUser` Helper method that gets the correct client credentials access token and then deletes a user. ```javascript const user = await moneyhub.deleteUser({ userId: "user-id", }); ``` ### User Connections #### `getUserConnections` Helper method that gets the correct client credentials access token and then gets all user connections. ```javascript const user = await moneyhub.getUserConnections({ userId: "user-id", }, options); ``` #### `syncUserConnection` Sync an existing user connection. This process will fetch the latest balances and transactions of the accounts attached to the connection. This method only returns the status of the syncing. ```javascript const tokens = await moneyhub.syncUserConnection({ userId, connectionId, customerIpAddress, // optional customerLastLoggedTime, // optional enableAsync, // optional }, options); ``` #### `deleteUserConnection` Helper method that gets the correct client credentials access token and then deletes a user connection. ```javascript const user = await moneyhub.deleteUserConnection({ userId: "user-id", connectionId: "connection-id", }, options); ``` #### `getConnectionSyncs` Retrieve the syncs for a given connection ID. ```javascript const syncs = await moneyhub.getConnectionSyncs({ userId: "user-id", connectionId: "connection-id", params: { limit: 10, offset: 0, }, }, options); ``` #### `getUserSyncs` Retrieve the syncs for a given connection ID. ```javascript const syncs = await moneyhub.getUserSyncs({ userId: "user-id", params: { limit: 10, offset: 0, }, }, options); ``` #### `getSync` Retrieve the syncs for the given sync ID. ```javascript const syncs = await moneyhub.getSync({ userId: "user-id", syncId: "sync-id", }, options); ``` #### `updateUserConnection` Helper method that updates a connection. Requires scope `user:update`. Currently only the consent can be updated by updating the `expiresAt` field. This field should be a valid date-time ISO string and not be more than 90 days away. This method can only be used by those clients that have bypassed consent (the `Enforce user consent` option in the Admin Portal). If successful returns a 204. ```javascript const user = await moneyhub.updateUserConnection({ userId: "user-id", connectionId: "connection-id", expiresAt: "2022-06-26T09:43:16.318+00:00" }, options) ``` ### SCIM User Management Registers a SCIM user. ```javascript const user = await moneyhub.registerSCIMUser({ externalId: "your user id", name: { givenName: "Andrea", familyName: "Hedley" }, emails: [{ value: "andrea.hedley@moneyhub.com" }] }); ``` Fetch a SCIM user. ```javascript const user = await moneyhub.getSCIMUser({ userId: "userId" }); ``` ### Data API #### `getAccounts` Get all accounts for a user. This function uses the scope `accounts:read`. ```javascript const queryParams = { limit: 10, offset: 5 , showTransacionData: false, showPerformanceScore: true}; const accounts = await moneyhub.getAccounts({ userId: "userId", params: queryParams, }, options); ``` #### `getAccountsWithDetails` Get all accounts for a user including extra details (sort code, account number, account holder name). This function uses the scopes `accounts:read accounts_details:read`. ```javascript const queryParams = { limit: 10, offset: 5 }; const accounts = await moneyhub.getAccountsWithDetails({ userId: "userId", params: queryParams, }, options); ``` #### `getAccountsList` Similar to getAccounts method, however this method does not return `transactionData` and `performanceScore` by default meaning data can be retrieved more quickly. These fields can still be returned on from this method by using `showTransacionData` and `showPerformanceScore` query params. This function uses the scope `accounts:read`. ```javascript const queryParams = { limit: 10, offset: 5 , showTransacionData: false, showPerformanceScore: true}; const accounts = await moneyhub.getAccounts({ userId: "userId", params: queryParams, }, options); ``` #### `getAccountsListWithDetails` Similar to getAccountsWithDetails method, however this method does not return `transactionData` and `performanceScore` by default meaning data can be retrieved more quickly. These fields can still be returned on from this method by using `showTransacionData` and `showPerformanceScore` query params. This function uses the scopes `accounts:read accounts_details:read`. ```javascript const queryParams = { limit: 10, offset: 5 }; const accounts = await moneyhub.getAccountsWithDetails({ userId: "userId", params: queryParams, }, options); ``` #### `getAccount` Get a single account for a user by the accountId. This function uses the scope `accounts:read`. ```javascript const account = await moneyhub.getAccount({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountWithDetails` Get a single account for a user by the accountId including extra details (sort code, account number, account holder name). This function uses the scope `accounts:read accounts_details:read`. ```javascript const account = await moneyhub.getAccountWithDetails({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountBalances` Get account balances for a user. This function uses the scope `accounts:read`. ```javascript const account = await moneyhub.getAccountBalances({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountHoldings` Get account holdings for a user. This function uses the scope `accounts:read`. ```javascript const account = await moneyhub.getAccountHoldings({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountHoldingsWithMatches` Get account holdings with ISIN codes matchers for a user. This function uses the scope `accounts:read`. ```javascript const account = await moneyhub.getAccountHoldingsWithMatches({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountHolding` Get a single holding from a user's account. This function uses the scope `accounts:read`. ```javascript const account = await moneyhub.getAccountHolding({ userId: "userId", accountId: "accountId", holdingId: "holdingId", }, options); ``` #### `getAccountCounterparties` Get account counterparties for a user. This function uses the scope `accounts:read transactions:read`. ```javascript const account = await moneyhub.getAccountCounterparties({ userId: "userId", accountId: "accountId", params: { counterpartiesVersion: "v3", }, }, options); ``` #### `getAccountRecurringTransactions` Get account recurring transactions for a user. This function uses the scope `accounts:read transactions:read`. ```javascript const account = await moneyhub.getAccountRecurringTransactions({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountStandingOrders` Get the standing orders for an account. This function uses the scope `standing_orders:read` and a connection with `ReadStandingOrdersBasic` permission. ```javascript const standingOrders = await moneyhub.getAccountStandingOrders({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountStandingOrdersWithDetail` Get the standing orders with detail (payee information) for an account. This function uses the scope `standing_orders_detail:read` and a connection with `ReadStandingOrdersDetail` permission. ```javascript const standingOrders = await moneyhub.getAccountStandingOrdersWithDetail({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountStatements` Get the statements for an account. This function uses the scope `statements_basic:read` and a connection with `ReadStatementsBasic` permission. ```javascript const statements = await moneyhub.getAccountStatements({ userId: "userId", accountId: "accountId", }, options); ``` #### `getAccountStatementsWithDetail` Get the statements with detail for an account. This function uses the scope `statements_detail:read` and a connection with `ReadStatementsDetail` permission. ```javascript const statements = await moneyhub.getAccountStatementsWithDetail({ userId: "userId", accountId: "accountId", }, options); ``` #### `createAccount` Create a manual account for a user. This function uses the scopes `accounts:read accounts:write:all` ```javascript const account = await moneyhub.createAccount({ userId: "userId", account: { accountName: "Account name", providerName: "Provider name", type: "cash:current", accountType: "personal", balance: { date: "2018-08-12", amount: { value: 300023, }, }, }, }, options); ``` #### `deleteAccount` Delete a manual account for a user. This function uses the scope `accounts:write:all` ```javascript const result = await moneyhub.deleteAccount({ userId: "userId", accountId: "accountId", }, options); ``` #### `addAccountBalance` Add a balance to a manual account. This function uses the scope `accounts:read accounts:write:all` ```javascript const result = await moneyhub.addAccountBalance({ userId: "userId", accountId: "accountId", balance: { amount: { value: 123 }, date: "2022-01-01", } }, options); ``` #### `updateAccount` Update manual account. This function uses the scope `accounts:read accounts:write:all` ```javascript const result = await moneyhub.updateAccount({ userId: "userId", accountId: "accountId", account: { accountName: "accountName", providerName: "providerName" details: {} } }, options); ``` #### `getTransactions` Get all transactions for a user that have been enhanced with our data-enrichment engine. This function uses the scope `transactions:read:all`.. ```javascript const queryParams = { limit: 10, offset: 5 }; const transactions = await moneyhub.getTransactions({ userId: "userId", params: queryParams, }, options); ``` #### `getTransaction` Get a transaction by ID for a user that has been enhanced with our data-enrichment engine. This function uses the scope `transactions:read:all`.. ```javascript const transactions = await moneyhub.getTransaction({ userId: "userId", transactionId: "transactionId", }, options); ``` #### `getUnenrichedTransactions` Get all unenriched transactions for a user. This function uses the scope `transactions_unenriched:read:all`.. ```javascript const queryParams = { limit: 10, offset: 5 }; const transactions = await moneyhub.getUnenrichedTransactions({ userId: "userId", params: queryParams, }, options); ``` #### `getUnenrichedTransaction` Get an unenriched transaction by ID for a user. This function uses the scope `transactions_unenriched:read:all`.. ```javascript const transactions = await moneyhub.getUnenrichedTransaction({ userId: "userId", transactionId: "transactionId", }, options); ``` #### `updateTransaction` Update a transaction by ID for a user. This function uses the scopes `transactions:read:all transactions:write:all`.. ```javascript const transactions = await moneyhub.updateTransaction({ userId: "userId", transactionId: "transactionId", transaction: { amount: { value: 10, }, }, }, options); ``` #### `addTransaction` Add a transaction for a user. Please note, transaction must belong to an account that is transaction-able. This function uses the scopes `transactions:read:all transactions:write:all`.. ```javascript const transactions = await moneyhub.addTransaction({ userId: "userId", transaction: { amount: { value: 10, }, }, }, options); ``` #### `addTransactions` Add up to 50 transactions for a user. Please note, transaction must belong to an account that is transaction-able. This function uses the scopes `transactions:read:all transactions:write:all`. ```javascript const transactions = await moneyhub.addTransactions({ userId: "userId", transactions: [ { amount: { value: 10, }, }, { amount: { value: 25, }, }, ], params: { categorise: true, // optional - enable categorisatio for transactions }, }, options); ``` #### `deleteTransaction` Delete a transaction for a user. This function uses the scopes `transactions:write:all`.. ```javascript const result = await moneyhub.deleteTransaction({ userId: "userId", id: "transactionId", }, options); ``` #### `getBeneficiaries` Get all beneficiaries for a user. This function uses the scope `beneficiaries:read` ```javascript const queryParams = { limit: 10, offset: 5 }; const beneficiaries = await moneyhub.getBeneficiaries({ userId: "userId", params: queryParams, }, options); ``` #### `getBeneficiariesWithDetail` Get all beneficiaries for a user, including beneficiary detail. This function uses the scope `beneficiaries_detail:read` ```javascript const queryParams = { limit: 10, offset: 5 }; const beneficiaries = await moneyhub.getBeneficiariesWithDetail({ userId: "userId", params: queryParams, }, options); ``` #### `getBeneficiary` Get a beneficiary for a user. This function uses the scope `beneficiaries:read` ```javascript const beneficiary = await moneyhub.getBeneficiary({ userId: "userId", id: "beneficiaryId", }, options); ``` #### `getBeneficiaryWithDetail` Get a beneficiary for a user, including beneficiary detail. This function uses the scope `beneficiaries_detail:read` ```javascript const beneficiary = await moneyhub.getBeneficiaryWithDetail({ userId: "userId", id: "beneficiaryId", }, options); ``` #### `addFileToTransaction` Add an attachment to a transaction. This call requires an access token with a scope that allows it to read and write transactions. The third parameter must be a stream, and the size of the file being uploaded can be of max size 10MB. ```javascript const file = await money.addFileToTransaction({ userId: "userId", transactionId: "transactionId", fileName: "file-name", fileData: fs.createReadStream("path/to/file.png"), }, options); ``` #### `getTransactionFiles` Get all attachments associated with a transaction. This call requires an access token with a scope that allows it to read transactions. ```javascript const files = await money.getTransactionFiles({ userId: "userId", transactionId: "transactionId", }, options); ``` #### `getTransactionFile` Get an attachment associated with a transaction. This call requires an access token with a scope that allows it to read transactions. ```javascript const files = await money.getTransactionFile({ userId: "userId", transactionId: "transactionId", fileId: "fileId", }, options); ``` #### `deleteTransactionFile` Delete an attachment associated with a transaction. This call requires an access token with a scope that allows it to read and write transactions. ```javascript await money.deleteTransactionFile({ userId: "userId", transactionId: "transactionId", fileId: "fileId", }, options); ``` #### `splitTransaction` Split up a transaction into different categories and/or projects. ```javascript const splits = await moneyhub.splitTransaction({ userId: "userId", transactionId: "transactionId", splits: [ { categoryId: "std:5a7ff1f3-cd2c-4676-a368-caf09f2ca35a", description: "Split 1", amount: -6000, }, { categoryId: "std:eac238ec-3899-49ff-8cce-e3b9f4b1aede", description: "Split 2", amount: -4000, }, ], }, options); ``` #### `getTransactionSplits` Get a transactions splits. ```javascript const splits = await moneyhub.getTransactionSplits({ userId: "userId", transactionId: "transactionId", }, options); ``` #### `patchTransactionSplit` Update a transaction's split's description, categoryId or projectId. ```javascript const splits = await moneyhub.patchTransactionSplit({ userId: "userId", transactionId: "transactionId", split: { description: "New description", }, }, options); ``` #### `deleteTransactionSplits` Delete a transaction's splits and merge them back together. ```javascript const splits = await moneyhub.deleteTransactionSplits({ userId: "userId", transactionId: "transactionId", }, options); ``` #### `getOsipAccounts` Get all accounts for a user. This function uses the scope `osip:read`. ```javascript const queryParams = { limit: 10, offset: 5 }; const accounts = await moneyhub.getOsipAccounts({ userId: "userId", params: queryParams, }); ``` #### `getOsipAccount` Get an account for a user. This function uses the scope `osip:read`. ```javascript const queryParams = { limit: 10, offset: 5 }; const accounts = await moneyhub.getOsipAccounts({ userId: "userId", accountId: "accountId", params: queryParams, }); ``` #### `getOsipAccountHoldings` Get account holdings for an account. This function uses the scope `osip:read`. ```javascript const queryParams = { limit: 10, offset: 5 }; const accounts = await moneyhub.getOsipAccounts({ userId: "userId", accountId: "accountId", params: queryParams, }); ``` #### `getOsipAccountTransactions` Get account transactions. This function uses the scope `osip:read`. ```javascript const queryParams = { limit: 10, offset: 5 }; const accounts = await moneyhub.getOsipAccounts({ userId: "userId", accountId: "accountId", params: queryParams, }); ``` #### `getGlobalCounterparties` Get global counterparties. ```javascript const accounts = await moneyhub.getGlobalCounterparties(); ``` #### `categoriseTransactions` Returns categories for a given list of transactions. This function uses the scope `categorisation`. ```javascript const data = await moneyhub.categoriseTransactions({ accountId: "b72f2a5d-c43f-4db1-8143-6f6682ac132c", accountType: "cash", transactions: [ { id: "b72f2a5d-c43f-4db1-8143-6f6682ac132c", description: "Amazon", amount: { value: -3000, }, date: "2025-05-02T15:50:19.603Z", proprietaryTransactionCode: "DEBIT", merchantCategoryCode: "OT42" }, ], }) ``` #### `getCategories` Get all categories for a user. This function uses the scope `categories:read`. ```javascript const categories = await moneyhub.getCategories({ userId: "userId", params: { type: "personal", // optional personal|business }, }, options); ``` #### `getCategory` Get a single category for a user. This function uses the scope `categories:read`. ```javascript const category = await moneyhub.getCategory({ userId: "userId", categoryId: "categoryId", }, options); ``` #### `getCategoryGroups` Get all category groups for a user. This function uses the scope `categories:read`. ```javascript const categoryGroups = await moneyhub.getCategoryGroups({ userId: "userId", params: { type: "personal", // optional personal|business }, }, options); ``` #### `getStandardCategories` Get standard categories. ```javascript const categories = await moneyhub.getStandardCategories({ params: { type: "personal", // optional personal|business|all }, }, options); ``` #### `getStandardCategoryGroups` Get standard categories. ```javascript const categoryGroups = await moneyhub.getStandardCategoryGroups({ params: { type: "personal", // optional personal|business|all }, }, options); ``` #### `createCustomCategory` Create a custom category. This function uses the scopes `categories:read categories:write`. ```javascript const category = await moneyhub.createCustomCategory({ userId: "userId", category: { group: "group:1" name: "custom-category", }, }, options) ``` ### Spending analysis #### `getSpendingAnalysis` This method returns the spending analysis for the given dates. This function uses the scope `spending_analysis:read` ```javascript const projects = await moneyhub.getSpendingAnalysis({ userId: "userId", dates: [ { name: "currentMonth", from: "2018-10-01", to: "2018-10-31", }, { name: "previousMonth", from: "2018-09-01", to: "2018-09-30", }, ], accountIds: ["ac9bd177-d01e-449c-9f29-d3656d2edc2e"], // optional categoryIds: ["std:338d2636-7f88-491d-8129-255c98da1eb8"], // optional }, options); ``` ### Projects #### `getProjects` This method returns a list of projects. This function uses the scope `projects:read` ```javascript const projects = await moneyhub.getProjects({ userId: "userId", params: { limit: "limit", // optional offset: "offset", // optional }, // optional }, options); ``` #### `getProject` Get a single project for a user by the projectId. This function uses the scope `projects:read`. ```javascript const project = await moneyhub.getProject({ userId: "userId", projectId: "projectId", }, options); ``` #### `addProject` Create a new project for a user. This function uses the scope `projects.write`. This will return the new project. ```javascript const project = await moneyhub.addProject({ userId: "userId", project: { name: "Project Name", accountIds: "id1,id2", // comma-separated list of account IDs type: "PropertyProject", }, }, options); ``` #### `updateProject` Update a project for a user. This function uses the scope `projects.write`. This will return the newly updated project. ```javascript const project = await moneyhub.updateProject({ userId: "userId", projectId: "projectId", project: { name: "Updated Project Name", accountIds: "id1,id2", // comma-separated list of account IDs type: "PropertyProject", archived: false, }, }, options); ``` #### `deleteProject` Delete a project for a user given a project ID. This function uses the scope `projects.delete`. ```javascript const result = await moneyhub.deleteProject({ userId: "userId", projectId: "projectId", }); ``` ### Tax Return #### `getTaxReturn` Get a tax return object for a subset of transactions. This makes use of the `enhancedCategories` on transactions. This functions uses the scope `tax:read` ```javascript const result = await moneyhub.getTaxReturn({ userId: "userId", params: { startDate: "2020-01-01", endDate: "2020-02-01", accountId: "accountId", projectId: "projectId", }, }, options); ``` ### Payments #### `getPaymentAuthorizeUrl` This is a helper function that returns an authorize url to authorize a payment to the payee with the bank selected. This function uses the following scope with the value of the bankId provided `payment openid id:${bankId}`. It also requires the authentication to be `client_secret_jwt` or `private_key_jwt`. ```javascript const url = await moneyhub.getPaymentAuthorizeUrl({ bankId: "Bank id to authorise payment from", // required payeeId: "Id of payee", // required or payee payee: "Details of payee to create", // required or payeeId payeeType: "Payee type [api-payee|mh-user-account]", // optional - defaults to api-payee payerType: "Payer type [mh-user-account | api-payer]", // required only if payerId or payer is used payerId: "Id of payer", // required only if payerType is defined as mh-user-account payer: "Details of payer to use", // required if using api-payer for payerType amount: "Amount in pence to authorize payment", payeeRef: "Payee reference", payerRef: "Payer reference", payerName: "Payer Name", // optional payerEmail: "Payer Email", // optional state: "your state value", nonce: "your nonce value", // optional context: "Payment context [Other,BillPayment,PartyToParty]", // optional - defaults to PartyToParty userId: "Moneyhub API User ID you wish to attach to the payment", // optional claims: claimsObject, // optional }); // Scope used with the bankId provided const scope = `payment openid id:${bankId}`; // Default claims if none are provided const defaultClaims = { id_token: { "mh:con_id": { essential: true, }, "mh:payment": { essential: true, value: { amount, payeeRef, payerRef, payeeId, payeeType, payerId, payerType, payerName, payerEmail, }, }, }, }; ``` #### `getReversePaymentAuthorizeUrl` This is a helper function that returns an authorize url to authorize a reverse payment for a payment that is reversible. This function uses the following scope with the value of the bankId provided `reverse_payment openid id:${bankId}`. It also requires the authentication to be `client_secret_jwt` or `private_key_jwt`. ```javascript const url = await moneyhub.getReversePaymentAuthorizeUrl({ bankId: "Bank id to authorise payment from", paymentId: "Id of payment to reverse", state: "your state value", amount: "reverse payment amount" // optional nonce: "your nonce value", // optional claims: claimsObject, // optional payerType: "Payer type [mh-user-account | api-payer]", // required only if payerId or payer is used payerId: "payer id that will make the payment", // required if using mh-user-account for payerType payer: "Details of payer to use", // required if using api-payer for payerType }) // Scope used with the bankId provided const scope = `reverse_payment openid id:${bankId}` /