forked from plaid/quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·426 lines (390 loc) · 13.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
'use strict';
var util = require('util');
var envvar = require('envvar');
var express = require('express');
var bodyParser = require('body-parser');
var moment = require('moment');
var plaid = require('plaid');
var APP_PORT = envvar.number('APP_PORT', 8000);
var PLAID_CLIENT_ID = envvar.string('PLAID_CLIENT_ID');
var PLAID_SECRET = envvar.string('PLAID_SECRET');
var PLAID_PUBLIC_KEY = envvar.string('PLAID_PUBLIC_KEY');
var PLAID_ENV = envvar.string('PLAID_ENV', 'sandbox');
// PLAID_PRODUCTS is a comma-separated list of products to use when initializing
// Link. Note that this list must contain 'assets' in order for the app to be
// able to create and retrieve asset reports.
var PLAID_PRODUCTS = envvar.string('PLAID_PRODUCTS', 'transactions');
// PLAID_PRODUCTS is a comma-separated list of countries for which users
// will be able to select institutions from.
var PLAID_COUNTRY_CODES = envvar.string('PLAID_COUNTRY_CODES', 'US,CA,GB,FR,ES,IE,NL');
// Parameters used for the OAuth redirect Link flow.
//
// Set PLAID_OAUTH_REDIRECT_URI to 'http://localhost:8000/oauth-response.html'
// The OAuth redirect flow requires an endpoint on the developer's website
// that the bank website should redirect to. You will need to whitelist
// this redirect URI for your client ID through the Plaid developer dashboard
// at https://dashboard.plaid.com/team/api.
var PLAID_OAUTH_REDIRECT_URI = envvar.string('PLAID_OAUTH_REDIRECT_URI', '');
// Set PLAID_OAUTH_NONCE to a unique identifier such as a UUID for each Link
// session. The nonce will be used to re-open Link upon completion of the OAuth
// redirect. The nonce must be at least 16 characters long.
var PLAID_OAUTH_NONCE = envvar.string('PLAID_OAUTH_NONCE', '');
// We store the access_token in memory - in production, store it in a secure
// persistent data store
var ACCESS_TOKEN = null;
var PUBLIC_TOKEN = null;
var ITEM_ID = null;
// The payment_token is only relevant for the UK Payment Initiation product.
// We store the payment_token in memory - in production, store it in a secure
// persistent data store
var PAYMENT_TOKEN = null;
var PAYMENT_ID = null;
// Initialize the Plaid client
// Find your API keys in the Dashboard (https://dashboard.plaid.com/account/keys)
var client = new plaid.Client(
PLAID_CLIENT_ID,
PLAID_SECRET,
PLAID_PUBLIC_KEY,
plaid.environments[PLAID_ENV],
{version: '2019-05-29', clientApp: 'Plaid Quickstart'}
);
var app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.get('/', function(request, response, next) {
response.render('index.ejs', {
PLAID_PUBLIC_KEY: PLAID_PUBLIC_KEY,
PLAID_ENV: PLAID_ENV,
PLAID_PRODUCTS: PLAID_PRODUCTS,
PLAID_COUNTRY_CODES: PLAID_COUNTRY_CODES,
PLAID_OAUTH_REDIRECT_URI: PLAID_OAUTH_REDIRECT_URI,
PLAID_OAUTH_NONCE: PLAID_OAUTH_NONCE,
ITEM_ID: ITEM_ID,
ACCESS_TOKEN: ACCESS_TOKEN,
});
});
// This is an endpoint defined for the OAuth flow to redirect to.
app.get('/oauth-response.html', function(request, response, next) {
response.render('oauth-response.ejs', {
PLAID_PUBLIC_KEY: PLAID_PUBLIC_KEY,
PLAID_ENV: PLAID_ENV,
PLAID_PRODUCTS: PLAID_PRODUCTS,
PLAID_COUNTRY_CODES: PLAID_COUNTRY_CODES,
PLAID_OAUTH_NONCE: PLAID_OAUTH_NONCE,
});
});
// Exchange token flow - exchange a Link public_token for
// an API access_token
// https://plaid.com/docs/#exchange-token-flow
app.post('/get_access_token', function(request, response, next) {
PUBLIC_TOKEN = request.body.public_token;
client.exchangePublicToken(PUBLIC_TOKEN, function(error, tokenResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
ACCESS_TOKEN = tokenResponse.access_token;
ITEM_ID = tokenResponse.item_id;
prettyPrintResponse(tokenResponse);
response.json({
access_token: ACCESS_TOKEN,
item_id: ITEM_ID,
error: null,
});
});
});
// Retrieve Transactions for an Item
// https://plaid.com/docs/#transactions
app.get('/transactions', function(request, response, next) {
// Pull transactions for the Item for the last 30 days
var startDate = moment().subtract(30, 'days').format('YYYY-MM-DD');
var endDate = moment().format('YYYY-MM-DD');
client.getTransactions(ACCESS_TOKEN, startDate, endDate, {
count: 250,
offset: 0,
}, function(error, transactionsResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error
});
} else {
prettyPrintResponse(transactionsResponse);
response.json({error: null, transactions: transactionsResponse});
}
});
});
// Retrieve Identity for an Item
// https://plaid.com/docs/#identity
app.get('/identity', function(request, response, next) {
client.getIdentity(ACCESS_TOKEN, function(error, identityResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(identityResponse);
response.json({error: null, identity: identityResponse});
});
});
// Retrieve real-time Balances for each of an Item's accounts
// https://plaid.com/docs/#balance
app.get('/balance', function(request, response, next) {
client.getBalance(ACCESS_TOKEN, function(error, balanceResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(balanceResponse);
response.json({error: null, balance: balanceResponse});
});
});
// Retrieve an Item's accounts
// https://plaid.com/docs/#accounts
app.get('/accounts', function(request, response, next) {
client.getAccounts(ACCESS_TOKEN, function(error, accountsResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(accountsResponse);
response.json({error: null, accounts: accountsResponse});
});
});
// Retrieve ACH or ETF Auth data for an Item's accounts
// https://plaid.com/docs/#auth
app.get('/auth', function(request, response, next) {
client.getAuth(ACCESS_TOKEN, function(error, authResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(authResponse);
response.json({error: null, auth: authResponse});
});
});
// Retrieve Holdings for an Item
// https://plaid.com/docs/#investments
app.get('/holdings', function(request, response, next) {
client.getHoldings(ACCESS_TOKEN, function(error, holdingsResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(holdingsResponse);
response.json({error: null, holdings: holdingsResponse});
});
});
// Retrieve Investment Transactions for an Item
// https://plaid.com/docs/#investments
app.get('/investment_transactions', function(request, response, next) {
var startDate = moment().subtract(30, 'days').format('YYYY-MM-DD');
var endDate = moment().format('YYYY-MM-DD');
client.getInvestmentTransactions(ACCESS_TOKEN, startDate, endDate, function(error, investmentTransactionsResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(investmentTransactionsResponse);
response.json({error: null, investment_transactions: investmentTransactionsResponse});
});
});
// Create and then retrieve an Asset Report for one or more Items. Note that an
// Asset Report can contain up to 100 items, but for simplicity we're only
// including one Item here.
// https://plaid.com/docs/#assets
app.get('/assets', function(request, response, next) {
// You can specify up to two years of transaction history for an Asset
// Report.
var daysRequested = 10;
// The `options` object allows you to specify a webhook for Asset Report
// generation, as well as information that you want included in the Asset
// Report. All fields are optional.
var options = {
client_report_id: 'Custom Report ID #123',
// webhook: 'https://your-domain.tld/plaid-webhook',
user: {
client_user_id: 'Custom User ID #456',
first_name: 'Alice',
middle_name: 'Bobcat',
last_name: 'Cranberry',
ssn: '123-45-6789',
phone_number: '555-123-4567',
email: '[email protected]',
},
};
client.createAssetReport(
[ACCESS_TOKEN],
daysRequested,
options,
function(error, assetReportCreateResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(assetReportCreateResponse);
var assetReportToken = assetReportCreateResponse.asset_report_token;
respondWithAssetReport(20, assetReportToken, client, response);
});
});
// This functionality is only relevant for the UK Payment Initiation product.
// Retrieve Payment for a specified Payment ID
app.get('/payment_get', function(request, response, next) {
client.getPayment(PAYMENT_ID, function(error, paymentGetResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error,
});
}
prettyPrintResponse(paymentGetResponse);
response.json({error: null, payment: paymentGetResponse});
});
});
// Retrieve information about an Item
// https://plaid.com/docs/#retrieve-item
app.get('/item', function(request, response, next) {
// Pull the Item - this includes information about available products,
// billed products, webhook information, and more.
client.getItem(ACCESS_TOKEN, function(error, itemResponse) {
if (error != null) {
prettyPrintResponse(error);
return response.json({
error: error
});
}
// Also pull information about the institution
client.getInstitutionById(itemResponse.item.institution_id, function(err, instRes) {
if (err != null) {
var msg = 'Unable to pull institution information from the Plaid API.';
console.log(msg + '\n' + JSON.stringify(error));
return response.json({
error: msg
});
} else {
prettyPrintResponse(itemResponse);
response.json({
item: itemResponse.item,
institution: instRes.institution,
});
}
});
});
});
var server = app.listen(APP_PORT, function() {
console.log('plaid-quickstart server listening on port ' + APP_PORT);
});
var prettyPrintResponse = response => {
console.log(util.inspect(response, {colors: true, depth: 4}));
};
// This is a helper function to poll for the completion of an Asset Report and
// then send it in the response to the client. Alternatively, you can provide a
// webhook in the `options` object in your `/asset_report/create` request to be
// notified when the Asset Report is finished being generated.
var respondWithAssetReport = (
numRetriesRemaining,
assetReportToken,
client,
response
) => {
if (numRetriesRemaining == 0) {
return response.json({
error: 'Timed out when polling for Asset Report',
});
}
var includeInsights = false;
client.getAssetReport(
assetReportToken,
includeInsights,
function(error, assetReportGetResponse) {
if (error != null) {
prettyPrintResponse(error);
if (error.error_code == 'PRODUCT_NOT_READY') {
setTimeout(
() => respondWithAssetReport(
--numRetriesRemaining, assetReportToken, client, response),
1000
);
return
}
return response.json({
error: error,
});
}
client.getAssetReportPdf(
assetReportToken,
function(error, assetReportGetPdfResponse) {
if (error != null) {
return response.json({
error: error,
});
}
response.json({
error: null,
json: assetReportGetResponse.report,
pdf: assetReportGetPdfResponse.buffer.toString('base64'),
})
}
);
}
);
};
app.post('/set_access_token', function(request, response, next) {
ACCESS_TOKEN = request.body.access_token;
client.getItem(ACCESS_TOKEN, function(error, itemResponse) {
response.json({
item_id: itemResponse.item.item_id,
error: false,
});
});
});
// This functionality is only relevant for the UK Payment Initiation product.
// Sets the payment token in memory on the server side. We generate a new
// payment token so that the developer is not required to supply one.
// This makes the quickstart easier to use.
app.post('/set_payment_token', function(request, response, next) {
client.createPaymentRecipient(
'Harry Potter',
'GB33BUKB20201555555555',
{street: ['4 Privet Drive'], city: 'Little Whinging', postal_code: '11111', country: 'GB'},
).then(function(createPaymentRecipientResponse) {
let recipientId = createPaymentRecipientResponse.recipient_id;
return client.createPayment(
recipientId,
'payment_ref',
{currency: 'GBP', value: 12.34},
).then(function(createPaymentResponse) {
let paymentId = createPaymentResponse.payment_id;
return client.createPaymentToken(
paymentId,
).then(function(createPaymentTokenResponse) {
let paymentToken = createPaymentTokenResponse.payment_token;
PAYMENT_TOKEN = paymentToken;
PAYMENT_ID = paymentId;
return response.json({error: null, paymentToken: paymentToken});
})
})
}).catch(function(error) {
prettyPrintResponse(error);
return response.json({ error: error });
});
});