Coder Social home page Coder Social logo

skrilladeville / plaid-node Goto Github PK

View Code? Open in Web Editor NEW

This project forked from plaid/plaid-node

1.0 1.0 0.0 955 KB

Node bindings for Plaid

Home Page: https://plaid.com/docs

License: MIT License

JavaScript 98.44% Makefile 1.30% Mathematica 0.26%

plaid-node's Introduction

plaid-node Circle CI npm version

A node.js client library for the Plaid API.

Table of Contents

Install

$ npm install plaid

Versioning

You can specify the Plaid API version you wish to use when initializing plaid-node. Releases prior to 2.6.x do not support versioning.

const plaidClient = new plaid.Client(
  process.env.PLAID_CLIENT_ID,
  process.env.PLAID_SECRET,
  process.env.PUBLIC_KEY,
  plaid.environments.sandbox,
  {version: '2018-05-22'}
);

For information about what has changed between versions and how to update your integration, head to the API upgrade guide.

Getting started

The module supports all Plaid API endpoints. For complete information about the API, head to the docs.

All endpoints require a valid client_id, secret, and public_key to access and are accessible from a valid instance of a Plaid Client:

const plaid = require('plaid');

const plaidClient = new plaid.Client(client_id, secret, public_key, plaid_env, {version: '2018-05-22'});

The plaid_env parameter dictates which Plaid API environment you will access. Values are:

The options parameter is optional and allows for clients to override the default options used to make requests. e.g.

const patientClient = new plaid.Client(client_id, secret, public_key, plaid_env, {
  timeout: 10 * 60 * 1000, // 30 minutes
  agent: 'Patient Agent'
});

See here for a complete list of options. The default timeout for requests is 10 minutes.

Methods

Once an instance of the client has been created you use the following methods:

const plaid = require('plaid');

// Initialize client
const plaidClient = new plaid.Client(client_id, secret, public_key, plaid_env, {version: '2018-05-22'});

// createPublicToken(String, Function)
plaidClient.createPublicToken(access_token, cb);
// exchangePublicToken(String, Function)
plaidClient.exchangePublicToken(public_token, cb);
// createProcessorToken(String, String, String, Function)
plaidClient.createProcessorToken(access_token, account_id, processor, cb);

// invalidateAccessToken(String, Function)
plaidClient.invalidateAccessToken(access_token, cb);
// updateAccessTokenVersion(String, Function)
plaidClient.updateAccessTokenVersion(legacy_access_token, cb);
// removeItem(String, Function)
plaidClient.removeItem(access_token, cb);
// getItem(String, Function)
plaidClient.getItem(access_token, cb);
// importItem([String], Object, Object?, Function))
plaidClient.importItem(products, user_auth, options, cb)
// updateItemWebhook(String, String, Function)
plaidClient.updateItemWebhook(access_token, webhook, cb);

// getAccounts(String, Object?, Function)
plaidClient.getAccounts(access_token, options, cb);
// getBalance(String, Object?, Function)
plaidClient.getBalance(access_token, options, cb);
// getAuth(String, Object?, Function)
plaidClient.getAuth(access_token, options, cb);
// getIdentity(String, Function)
plaidClient.getIdentity(access_token, cb);
// getIncome(String, Function)
plaidClient.getIncome(access_token, cb);
// getCreditDetails(String, Function)
plaidClient.getCreditDetails(access_token, cb);
// getLiabilities(String, Function)
plaidClient.getLiabilities(access_token, cb);

// getDepositSwitch(String, Object?, Function)
plaidClient.getDepositSwitch(deposit_switch_id, options, cb)
// createDepositSwitch(String, String, Object?, Function)
plaidClient.createDepositSwitch(target_account_id, target_access_token, options, cb);
// createDepositSwitchToken(String, Function)
plaidClient.createDepositSwitchToken(deposit_switch_id, options, cb)

// getHoldings(String, Function)
plaidClient.getHoldings(access_token, cb);
// getInvestmentTransactions(String, Date(YYYY-MM-DD), Date(YYYY-MM-DD),
// Object?, Function)
plaidClient.getInvestmentTransactions(access_token, start_date, end_date, options, cb);

// getTransactions(String, Date(YYYY-MM-DD), Date(YYYY-MM-DD), Object?, Function)
plaidClient.getTransactions(access_token, start_date, end_date, options, cb);

// getAllTransactions(String, Date(YYYY-MM-DD), Date(YYYY-MM-DD), Object?, Function)
plaidClient.getAllTransactions(access_token, start_date, end_date, options, cb);

// refreshTransactions(String)
plaidClient.refreshTransactions(access_token);

// createStripeToken(String, String, Function)
plaidClient.createStripeToken(access_token, account_id, cb);

// getInstitutions(Number, Number, Object?, Function);
plaidClient.getInstitutions(count, offset, options, cb);
// getInstitutionsById(String, Object?, Function)
plaidClient.getInstitutionById(institution_id, options, cb);
// searchInstitutionsByName(String, [String], Object?, Function)
plaidClient.searchInstitutionsByName(query, products, options, cb);

// getCategories(Function)
plaidClient.getCategories(cb);

// getWebhookVerificationKey(String, Function)
plaidClient.getWebhookVerificationKey(key_id, cb);

// resetLogin(String, Function)
// Sandbox-only endpoint to trigger an `ITEM_LOGIN_REQUIRED` error
plaidClient.resetLogin(access_token, cb);
// Sandbox-only endpoint to trigger a webhook for an Item
plaidClient.sandboxItemFireWebhook(access_token, webhook_code, cb);
// Sandbox-only endpoint to create a `public_token`. Useful for writing integration tests without running Link.
plaidClient.sandboxPublicTokenCreate(institution_id, initial_products, options, cb);

All parameters except options are required. If the options parameter is omitted, the last argument to the function will be interpreted as the callback.

Callbacks

All requests have callbacks of the following form:

function callback(err, response) {
  // err can be a network error or a Plaid API error (i.e. invalid credentials)
}

Error Handling

The err argument passed to either callback style can either be an instance of Error or a Plaid API error object. An Error object is only passed back in the case of a HTTP connection error. The following code distinguishes between a Plaid error and a standard Error instance:

function callback(err, response) {
  if (err != null) {
    if (err instanceof plaid.PlaidError) {
      // This is a Plaid error
      console.log(err.error_code + ': ' + err.error_message);
    } else {
      // This is a connection error, an Error object
      console.log(err.toString());
    }
  }
}

Examples

Exchange a public_token from Plaid Link for a Plaid access_token and then retrieve account data:

plaidClient.exchangePublicToken(public_token, function(err, res) {
  const access_token = res.access_token;

  plaidClient.getAccounts(access_token, function(err, res) {
    console.log(res.accounts);
  });
});

Retrieve transactions for a transactions user for the last thirty days:

const now = moment();
const today = now.format('YYYY-MM-DD');
const thirtyDaysAgo = now.subtract(30, 'days').format('YYYY-MM-DD');

plaidClient.getTransactions(access_token, thirtyDaysAgo, today, (err, res) => {
  console.log(`You have ${res.transactions.length} transactions from the last thirty days.`);
});

Get accounts for a particular Item:

plaidClient.getAccounts(access_token, {
  account_ids: ['123456790']
}, (err, res) => {
  console.log(res.accounts);
});

// The library also juggles arguments, when options is omitted

plaidClient.getAccounts(access_token, (err, res) => {
  console.log(res.accounts);
});

Promise Support

Every method returns a promise, so you don't have to use the callbacks.

API methods that return either a success or an error can be used with the usual then/else paradigm, e.g.

plaidPromise.then(successResponse => {
  // ...
}).catch(err => {
  // ...
});

For example:

'use strict';

const bodyParser = require('body-parser');
const express = require('express');
const plaid = require('plaid');

const plaidClient = new plaid.Client(
  process.env.PLAID_CLIENT_ID,
  process.env.PLAID_SECRET,
  process.env.PUBLIC_KEY,
  plaid.environments.sandbox,
  {version: '2018-05-22'}
);

const app = express();
const port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.post('/plaid_exchange', (req, res) => {
  var public_token = req.body.public_token;

  return plaidClient.exchangePublicToken(public_token)
  .then(res => res.access_token)
  .then(accessToken => plaidClient.getAccounts(accessToken))
  .then(res => console.log(res.accounts))
  .catch(err => {
    // Indicates a network or runtime error.
    if (!(err instanceof plaid.PlaidError)) {
      res.sendStatus(500);
      return;
    }

    // Indicates plaid API error
    console.log('/exchange token returned an error', {
      error_type: err.error_type,
      error_code: res.statusCode,
      error_message: err.error_message,
      display_message: err.display_message,
      request_id: err.request_id,
      status_code: err.status_code,
    });

    // Inspect error_type to handle the error in your application
    switch(err.error_type) {
        case 'INVALID_REQUEST':
          // ...
          break;
        case 'INVALID_INPUT':
          // ...
          break;
        case 'RATE_LIMIT_EXCEEDED':
          // ...
          break;
        case 'API_ERROR':
          // ...
          break;
        case 'ITEM_ERROR':
          // ...
          break;
        default:
          // fallthrough
    }

    res.sendStatus(500);
  });
});

app.listen(port, () => {
  console.log(`Listening on port ${ port }`);
});

Support

Open an issue!

Contributing

Click here!

License

MIT

plaid-node's People

Contributors

davidchambers avatar michaelckelly avatar whockey avatar ntindall avatar pbernasconi avatar dsfish avatar notthefakestephen avatar evanlimanto avatar jdudek avatar jeffzwang avatar nathankot avatar philmod avatar rayraycano avatar skylarmb avatar sjlu avatar dependabot[bot] avatar mateo-quovo avatar otherchen avatar bjyoungblood avatar benperez avatar chris--young avatar ethanmick avatar esetnik avatar ggriffin avatar jacobreynolds avatar jdx avatar jsatk avatar jabas06 avatar luke-guild avatar mathisonian avatar

Stargazers

 avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.