-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
620 lines (530 loc) · 22.4 KB
/
server.py
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# source /Users/tnappy/node_projects/quickstart/python/bin/activate
# Read env vars from .env file
from plaid.exceptions import ApiException
from plaid.model.payment_amount import PaymentAmount
from plaid.model.payment_amount_currency import PaymentAmountCurrency
from plaid.model.products import Products
from plaid.model.country_code import CountryCode
from plaid.model.recipient_bacs_nullable import RecipientBACSNullable
from plaid.model.payment_initiation_address import PaymentInitiationAddress
from plaid.model.payment_initiation_recipient_create_request import PaymentInitiationRecipientCreateRequest
from plaid.model.payment_initiation_payment_create_request import PaymentInitiationPaymentCreateRequest
from plaid.model.payment_initiation_payment_get_request import PaymentInitiationPaymentGetRequest
from plaid.model.link_token_create_request_payment_initiation import LinkTokenCreateRequestPaymentInitiation
from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
from plaid.model.link_token_create_request import LinkTokenCreateRequest
from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser
from plaid.model.asset_report_create_request import AssetReportCreateRequest
from plaid.model.asset_report_create_request_options import AssetReportCreateRequestOptions
from plaid.model.asset_report_user import AssetReportUser
from plaid.model.asset_report_get_request import AssetReportGetRequest
from plaid.model.asset_report_pdf_get_request import AssetReportPDFGetRequest
from plaid.model.auth_get_request import AuthGetRequest
from plaid.model.transactions_sync_request import TransactionsSyncRequest
from plaid.model.identity_get_request import IdentityGetRequest
from plaid.model.investments_transactions_get_request_options import InvestmentsTransactionsGetRequestOptions
from plaid.model.investments_transactions_get_request import InvestmentsTransactionsGetRequest
from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest
from plaid.model.accounts_get_request import AccountsGetRequest
from plaid.model.investments_holdings_get_request import InvestmentsHoldingsGetRequest
from plaid.model.item_get_request import ItemGetRequest
from plaid.model.institutions_get_by_id_request import InstitutionsGetByIdRequest
from plaid.model.transfer_authorization_create_request import TransferAuthorizationCreateRequest
from plaid.model.transfer_create_request import TransferCreateRequest
from plaid.model.transfer_get_request import TransferGetRequest
from plaid.model.transfer_network import TransferNetwork
from plaid.model.transfer_type import TransferType
from plaid.model.transfer_user_in_request import TransferUserInRequest
from plaid.model.ach_class import ACHClass
from plaid.model.transfer_create_idempotency_key import TransferCreateIdempotencyKey
from plaid.model.transfer_user_address_in_request import TransferUserAddressInRequest
from plaid.api import plaid_api
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
from datetime import datetime
from datetime import timedelta
import plaid
import base64
import os
import datetime
import json
import time
from dotenv import load_dotenv
from werkzeug.wrappers import response
load_dotenv()
from supergood import Client as SupergoodClient
SupergoodClient()
app = Flask(__name__)
# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
# Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('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.
PLAID_PRODUCTS = os.getenv('PLAID_PRODUCTS', 'transactions').split(',')
# PLAID_COUNTRY_CODES is a comma-separated list of countries for which users
# will be able to select institutions from.
PLAID_COUNTRY_CODES = os.getenv('PLAID_COUNTRY_CODES', 'US').split(',')
def empty_to_none(field):
value = os.getenv(field)
if value is None or len(value) == 0:
return None
return value
host = plaid.Environment.Sandbox
if PLAID_ENV == 'sandbox':
host = plaid.Environment.Sandbox
if PLAID_ENV == 'development':
host = plaid.Environment.Development
if PLAID_ENV == 'production':
host = plaid.Environment.Production
# Parameters used for the OAuth redirect Link flow.
#
# Set PLAID_REDIRECT_URI to 'http://localhost:3000/'
# The OAuth redirect flow requires an endpoint on the developer's website
# that the bank website should redirect to. You will need to configure
# this redirect URI for your client ID through the Plaid developer dashboard
# at https://dashboard.plaid.com/team/api.
PLAID_REDIRECT_URI = empty_to_none('PLAID_REDIRECT_URI')
configuration = plaid.Configuration(
host=host,
api_key={
'clientId': PLAID_CLIENT_ID,
'secret': PLAID_SECRET,
'plaidVersion': '2020-09-14'
}
)
api_client = plaid.ApiClient(configuration)
client = plaid_api.PlaidApi(api_client)
products = []
for product in PLAID_PRODUCTS:
products.append(Products(product))
# We store the access_token in memory - in production, store it in a secure
# persistent data store.
access_token = None
# The payment_id is only relevant for the UK Payment Initiation product.
# We store the payment_id in memory - in production, store it in a secure
# persistent data store.
payment_id = None
# The transfer_id is only relevant for Transfer ACH product.
# We store the transfer_id in memomory - in produciton, store it in a secure
# persistent data store
transfer_id = None
item_id = None
@app.route('/api/info', methods=['POST'])
def info():
global access_token
global item_id
return jsonify({
'item_id': item_id,
'access_token': access_token,
'products': PLAID_PRODUCTS
})
@app.route('/api/create_link_token_for_payment', methods=['POST'])
def create_link_token_for_payment():
global payment_id
try:
request = PaymentInitiationRecipientCreateRequest(
name='John Doe',
bacs=RecipientBACSNullable(account='26207729', sort_code='560029'),
address=PaymentInitiationAddress(
street=['street name 999'],
city='city',
postal_code='99999',
country='GB'
)
)
response = client.payment_initiation_recipient_create(
request)
recipient_id = response['recipient_id']
request = PaymentInitiationPaymentCreateRequest(
recipient_id=recipient_id,
reference='TestPayment',
amount=PaymentAmount(
PaymentAmountCurrency('GBP'),
value=100.00
)
)
response = client.payment_initiation_payment_create(
request
)
pretty_print_response(response.to_dict())
# We store the payment_id in memory for demo purposes - in production, store it in a secure
# persistent data store along with the Payment metadata, such as userId.
payment_id = response['payment_id']
linkRequest = LinkTokenCreateRequest(
# The 'payment_initiation' product has to be the only element in the 'products' list.
products=[Products('payment_initiation')],
client_name='Plaid Test',
# Institutions from all listed countries will be shown.
country_codes=list(map(lambda x: CountryCode(x), PLAID_COUNTRY_CODES)),
language='en',
user=LinkTokenCreateRequestUser(
# This should correspond to a unique id for the current user.
# Typically, this will be a user ID number from your application.
# Personally identifiable information, such as an email address or phone number, should not be used here.
client_user_id=str(time.time())
),
payment_initiation=LinkTokenCreateRequestPaymentInitiation(
payment_id=payment_id
)
)
if PLAID_REDIRECT_URI!=None:
linkRequest['redirect_uri']=PLAID_REDIRECT_URI
linkResponse = client.link_token_create(linkRequest)
pretty_print_response(linkResponse.to_dict())
return jsonify(linkResponse.to_dict())
except plaid.ApiException as e:
return json.loads(e.body)
@app.route('/api/create_link_token', methods=['POST'])
def create_link_token():
try:
request = LinkTokenCreateRequest(
products=products,
client_name="Plaid Quickstart",
country_codes=list(map(lambda x: CountryCode(x), PLAID_COUNTRY_CODES)),
language='en',
user=LinkTokenCreateRequestUser(
client_user_id=str(time.time())
)
)
if PLAID_REDIRECT_URI!=None:
request['redirect_uri']=PLAID_REDIRECT_URI
# create link token
response = client.link_token_create(request)
return jsonify(response.to_dict())
except plaid.ApiException as e:
return json.loads(e.body)
# Exchange token flow - exchange a Link public_token for
# an API access_token
# https://plaid.com/docs/#exchange-token-flow
@app.route('/api/set_access_token', methods=['POST'])
def get_access_token():
global access_token
global item_id
global transfer_id
public_token = request.form['public_token']
try:
exchange_request = ItemPublicTokenExchangeRequest(
public_token=public_token)
exchange_response = client.item_public_token_exchange(exchange_request)
access_token = exchange_response['access_token']
item_id = exchange_response['item_id']
if 'transfer' in PLAID_PRODUCTS:
transfer_id = authorize_and_create_transfer(access_token)
return jsonify(exchange_response.to_dict())
except plaid.ApiException as e:
return json.loads(e.body)
# Retrieve ACH or ETF account numbers for an Item
# https://plaid.com/docs/#auth
@app.route('/api/auth', methods=['GET'])
def get_auth():
try:
request = AuthGetRequest(
access_token=access_token
)
response = client.auth_get(request)
pretty_print_response(response.to_dict())
return jsonify(response.to_dict())
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Retrieve Transactions for an Item
# https://plaid.com/docs/#transactions
@app.route('/api/transactions', methods=['GET'])
def get_transactions():
# Set cursor to empty to receive all historical updates
cursor = ''
# New transaction updates since "cursor"
added = []
modified = []
removed = [] # Removed transaction ids
has_more = True
try:
# Iterate through each page of new transaction updates for item
while has_more:
request = TransactionsSyncRequest(
access_token=access_token,
cursor=cursor,
)
response = client.transactions_sync(request).to_dict()
# Add this page of results
added.extend(response['added'])
modified.extend(response['modified'])
removed.extend(response['removed'])
has_more = response['has_more']
# Update cursor to the next cursor
cursor = response['next_cursor']
pretty_print_response(response)
# Return the 8 most recent transactions
latest_transactions = sorted(added, key=lambda t: t['date'])[-8:]
return jsonify({
'latest_transactions': latest_transactions})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Retrieve Identity data for an Item
# https://plaid.com/docs/#identity
@app.route('/api/identity', methods=['GET'])
def get_identity():
try:
request = IdentityGetRequest(
access_token=access_token
)
response = client.identity_get(request)
pretty_print_response(response.to_dict())
return jsonify(
{'error': None, 'identity': response.to_dict()['accounts']})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Retrieve real-time balance data for each of an Item's accounts
# https://plaid.com/docs/#balance
@app.route('/api/balance', methods=['GET'])
def get_balance():
try:
request = AccountsBalanceGetRequest(
access_token=access_token
)
response = client.accounts_balance_get(request)
pretty_print_response(response.to_dict())
return jsonify(response.to_dict())
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Retrieve an Item's accounts
# https://plaid.com/docs/#accounts
@app.route('/api/accounts', methods=['GET'])
def get_accounts():
try:
request = AccountsGetRequest(
access_token=access_token
)
response = client.accounts_get(request)
pretty_print_response(response.to_dict())
return jsonify(response.to_dict())
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# 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.route('/api/assets', methods=['GET'])
def get_assets():
try:
request = AssetReportCreateRequest(
access_tokens=[access_token],
days_requested=60,
options=AssetReportCreateRequestOptions(
webhook='https://www.example.com',
client_report_id='123',
user=AssetReportUser(
client_user_id='789',
first_name='Jane',
middle_name='Leah',
last_name='Doe',
ssn='123-45-6789',
phone_number='(555) 123-4567',
email='[email protected]',
)
)
)
response = client.asset_report_create(request)
pretty_print_response(response.to_dict())
asset_report_token = response['asset_report_token']
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Poll for the completion of the Asset Report.
num_retries_remaining = 20
asset_report_json = None
while num_retries_remaining > 0:
try:
request = AssetReportGetRequest(
asset_report_token=asset_report_token,
)
response = client.asset_report_get(request)
asset_report_json = response['report']
break
except plaid.ApiException as e:
response = json.loads(e.body)
if response['error_code'] == 'PRODUCT_NOT_READY':
num_retries_remaining -= 1
time.sleep(1)
continue
error_response = format_error(e)
return jsonify(error_response)
if asset_report_json is None:
return jsonify({'error': {'status_code': e.status, 'display_message':
'Timed out when polling for Asset Report', 'error_code': '', 'error_type': ''}})
asset_report_pdf = None
try:
request = AssetReportPDFGetRequest(
asset_report_token=asset_report_token,
)
pdf = client.asset_report_pdf_get(request)
return jsonify({
'error': None,
'json': asset_report_json.to_dict(),
'pdf': base64.b64encode(pdf.read()).decode('utf-8'),
})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Retrieve investment holdings data for an Item
# https://plaid.com/docs/#investments
@app.route('/api/holdings', methods=['GET'])
def get_holdings():
try:
request = InvestmentsHoldingsGetRequest(access_token=access_token)
response = client.investments_holdings_get(request)
pretty_print_response(response.to_dict())
return jsonify({'error': None, 'holdings': response.to_dict()})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Retrieve Investment Transactions for an Item
# https://plaid.com/docs/#investments
@app.route('/api/investments_transactions', methods=['GET'])
def get_investments_transactions():
# Pull transactions for the last 30 days
start_date = (datetime.datetime.now() - timedelta(days=(30)))
end_date = datetime.datetime.now()
try:
options = InvestmentsTransactionsGetRequestOptions()
request = InvestmentsTransactionsGetRequest(
access_token=access_token,
start_date=start_date.date(),
end_date=end_date.date(),
options=options
)
response = client.investments_transactions_get(
request)
pretty_print_response(response.to_dict())
return jsonify(
{'error': None, 'investments_transactions': response.to_dict()})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# This functionality is only relevant for the ACH Transfer product.
# Retrieve Transfer for a specified Transfer ID
@app.route('/api/transfer', methods=['GET'])
def transfer():
global transfer_id
try:
request = TransferGetRequest(transfer_id=transfer_id)
response = client.transfer_get(request)
pretty_print_response(response.to_dict())
return jsonify({'error': None, 'transfer': response['transfer'].to_dict()})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# This functionality is only relevant for the UK Payment Initiation product.
# Retrieve Payment for a specified Payment ID
@app.route('/api/payment', methods=['GET'])
def payment():
global payment_id
try:
request = PaymentInitiationPaymentGetRequest(payment_id=payment_id)
response = client.payment_initiation_payment_get(request)
pretty_print_response(response.to_dict())
return jsonify({'error': None, 'payment': response.to_dict()})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
# Retrieve high-level information about an Item
# https://plaid.com/docs/#retrieve-item
@app.route('/api/item', methods=['GET'])
def item():
try:
request = ItemGetRequest(access_token=access_token)
response = client.item_get(request)
request = InstitutionsGetByIdRequest(
institution_id=response['item']['institution_id'],
country_codes=list(map(lambda x: CountryCode(x), PLAID_COUNTRY_CODES))
)
institution_response = client.institutions_get_by_id(request)
pretty_print_response(response.to_dict())
pretty_print_response(institution_response.to_dict())
return jsonify({'error': None, 'item': response.to_dict()[
'item'], 'institution': institution_response.to_dict()['institution']})
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
def pretty_print_response(response):
response = response
# print(json.dumps(response, indent=2, sort_keys=True, default=str))
def format_error(e):
response = json.loads(e.body)
return {'error': {'status_code': e.status, 'display_message':
response['error_message'], 'error_code': response['error_code'], 'error_type': response['error_type']}}
# This is a helper function to authorize and create a Transfer after successful
# exchange of a public_token for an access_token. The transfer_id is then used
# to obtain the data about that particular Transfer.
def authorize_and_create_transfer(access_token):
try:
# We call /accounts/get to obtain first account_id - in production,
# account_id's should be persisted in a data store and retrieved
# from there.
request = AccountsGetRequest(access_token=access_token)
response = client.accounts_get(request)
account_id = response['accounts'][0]['account_id']
request = TransferAuthorizationCreateRequest(
access_token=access_token,
account_id=account_id,
type=TransferType('credit'),
network=TransferNetwork('ach'),
amount='1.34',
ach_class=ACHClass('ppd'),
user=TransferUserInRequest(
legal_name='FirstName LastName',
email_address='[email protected]',
address=TransferUserAddressInRequest(
street='123 Main St.',
city='San Francisco',
region='CA',
postal_code='94053',
country='US'
),
),
)
response = client.transfer_authorization_create(request)
pretty_print_response(response)
authorization_id = response['authorization']['id']
request = TransferCreateRequest(
idempotency_key=TransferCreateIdempotencyKey('1223abc456xyz7890001'),
access_token=access_token,
account_id=account_id,
authorization_id=authorization_id,
type=TransferType('credit'),
network=TransferNetwork('ach'),
amount='1.34',
description='Payment',
ach_class=ACHClass('ppd'),
user=TransferUserInRequest(
legal_name='FirstName LastName',
email_address='[email protected]',
address=TransferUserAddressInRequest(
street='123 Main St.',
city='San Francisco',
region='CA',
postal_code='94053',
country='US'
),
),
)
response = client.transfer_create(request)
pretty_print_response(response)
return response['transfer']['id']
except plaid.ApiException as e:
error_response = format_error(e)
return jsonify(error_response)
if __name__ == '__main__':
app.run(port=os.getenv('PORT', 8000))