forked from plaid/quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·299 lines (265 loc) · 11.7 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
import base64
import os
import datetime
import plaid
import json
import time
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
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')
PLAID_PUBLIC_KEY = os.getenv('PLAID_PUBLIC_KEY')
# 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')
# 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,CA,GB,FR,ES,IE,NL')
# Parameters used for the OAuth redirect Link flow.
#
# Set PLAID_OAUTH_REDIRECT_URI to 'http://localhost:5000/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.
PLAID_OAUTH_REDIRECT_URI = os.getenv('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.
PLAID_OAUTH_NONCE = os.getenv('PLAID_OAUTH_NONCE', '');
client = plaid.Client(client_id = PLAID_CLIENT_ID, secret=PLAID_SECRET,
public_key=PLAID_PUBLIC_KEY, environment=PLAID_ENV, api_version='2019-05-29')
@app.route('/')
def index():
return render_template(
'index.ejs',
plaid_public_key=PLAID_PUBLIC_KEY,
plaid_environment=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,
)
# This is an endpoint defined for the OAuth flow to redirect to.
@app.route('/oauth-response.html')
def oauth_response():
return render_template(
'oauth-response.ejs',
plaid_public_key=PLAID_PUBLIC_KEY,
plaid_environment=PLAID_ENV,
plaid_products=PLAID_PRODUCTS,
plaid_country_codes=PLAID_COUNTRY_CODES,
plaid_oauth_nonce=PLAID_OAUTH_NONCE,
)
# We store the access_token in memory - in production, store it in a secure
# persistent data store.
access_token = None
# 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.
payment_token = None
payment_id = None
# Exchange token flow - exchange a Link public_token for
# an API access_token
# https://plaid.com/docs/#exchange-token-flow
@app.route('/get_access_token', methods=['POST'])
def get_access_token():
global access_token
public_token = request.form['public_token']
try:
exchange_response = client.Item.public_token.exchange(public_token)
except plaid.errors.PlaidError as e:
return jsonify(format_error(e))
pretty_print_response(exchange_response)
access_token = exchange_response['access_token']
return jsonify(exchange_response)
# Retrieve ACH or ETF account numbers for an Item
# https://plaid.com/docs/#auth
@app.route('/auth', methods=['GET'])
def get_auth():
try:
auth_response = client.Auth.get(access_token)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
pretty_print_response(auth_response)
return jsonify({'error': None, 'auth': auth_response})
# Retrieve Transactions for an Item
# https://plaid.com/docs/#transactions
@app.route('/transactions', methods=['GET'])
def get_transactions():
# Pull transactions for the last 30 days
start_date = '{:%Y-%m-%d}'.format(datetime.datetime.now() + datetime.timedelta(-30))
end_date = '{:%Y-%m-%d}'.format(datetime.datetime.now())
try:
transactions_response = client.Transactions.get(access_token, start_date, end_date)
except plaid.errors.PlaidError as e:
return jsonify(format_error(e))
pretty_print_response(transactions_response)
return jsonify({'error': None, 'transactions': transactions_response})
# Retrieve Identity data for an Item
# https://plaid.com/docs/#identity
@app.route('/identity', methods=['GET'])
def get_identity():
try:
identity_response = client.Identity.get(access_token)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
pretty_print_response(identity_response)
return jsonify({'error': None, 'identity': identity_response})
# Retrieve real-time balance data for each of an Item's accounts
# https://plaid.com/docs/#balance
@app.route('/balance', methods=['GET'])
def get_balance():
try:
balance_response = client.Accounts.balance.get(access_token)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
pretty_print_response(balance_response)
return jsonify({'error': None, 'balance': balance_response})
# Retrieve an Item's accounts
# https://plaid.com/docs/#accounts
@app.route('/accounts', methods=['GET'])
def get_accounts():
try:
accounts_response = client.Accounts.get(access_token)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
pretty_print_response(accounts_response)
return jsonify({'error': None, 'accounts': accounts_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('/assets', methods=['GET'])
def get_assets():
try:
asset_report_create_response = client.AssetReport.create([access_token], 10)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
pretty_print_response(asset_report_create_response)
asset_report_token = asset_report_create_response['asset_report_token']
# Poll for the completion of the Asset Report.
num_retries_remaining = 20
asset_report_json = None
while num_retries_remaining > 0:
try:
asset_report_get_response = client.AssetReport.get(asset_report_token)
asset_report_json = asset_report_get_response['report']
break
except plaid.errors.PlaidError as e:
if e.code == 'PRODUCT_NOT_READY':
num_retries_remaining -= 1
time.sleep(1)
continue
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
if asset_report_json == None:
return jsonify({'error': {'display_message': 'Timed out when polling for Asset Report', 'error_code': e.code, 'error_type': e.type } })
asset_report_pdf = None
try:
asset_report_pdf = client.AssetReport.get_pdf(asset_report_token)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
return jsonify({
'error': None,
'json': asset_report_json,
'pdf': base64.b64encode(asset_report_pdf),
})
# Retrieve investment holdings data for an Item
# https://plaid.com/docs/#investments
@app.route('/holdings', methods=['GET'])
def get_holdings():
try:
holdings_response = client.Holdings.get(access_token)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
pretty_print_response(holdings_response)
return jsonify({'error': None, 'holdings': holdings_response})
# Retrieve Investment Transactions for an Item
# https://plaid.com/docs/#investments
@app.route('/investment_transactions', methods=['GET'])
def get_investment_transactions():
# Pull transactions for the last 30 days
start_date = '{:%Y-%m-%d}'.format(datetime.datetime.now() + datetime.timedelta(-30))
end_date = '{:%Y-%m-%d}'.format(datetime.datetime.now())
try:
investment_transactions_response = client.InvestmentTransactions.get(access_token,
start_date,
end_date)
except plaid.errors.PlaidError as e:
return jsonify(format_error(e))
pretty_print_response(investment_transactions_response)
return jsonify({'error': None, 'investment_transactions': investment_transactions_response})
# This functionality is only relevant for the UK Payment Initiation product.
# Retrieve Payment for a specified Payment ID
@app.route('/payment', methods=['GET'])
def payment():
global payment_id
payment_get_response = client.PaymentInitiation.get_payment(payment_id)
pretty_print_response(payment_get_response)
return jsonify({'error': None, 'payment': payment_get_response})
# Retrieve high-level information about an Item
# https://plaid.com/docs/#retrieve-item
@app.route('/item', methods=['GET'])
def item():
global access_token
item_response = client.Item.get(access_token)
institution_response = client.Institutions.get_by_id(item_response['item']['institution_id'])
pretty_print_response(item_response)
pretty_print_response(institution_response)
return jsonify({'error': None, 'item': item_response['item'], 'institution': institution_response['institution']})
@app.route('/set_access_token', methods=['POST'])
def set_access_token():
global access_token
access_token = request.form['access_token']
item = client.Item.get(access_token)
return jsonify({'error': None, 'item_id': item['item']['item_id']})
# 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.route('/set_payment_token', methods=['POST'])
def set_payment_token():
global payment_token
global payment_id
try:
create_recipient_response = client.PaymentInitiation.create_recipient(
'Harry Potter',
'GB33BUKB20201555555555',
{
'street': ['4 Privet Drive'],
'city': 'Little Whinging',
'postal_code': '11111',
'country': 'GB',
},
)
recipient_id = create_recipient_response['recipient_id']
create_payment_response = client.PaymentInitiation.create_payment(
recipient_id,
'payment_ref',
{
'currency': 'GBP',
'value': 12.34,
},
)
payment_id = create_payment_response['payment_id']
create_payment_token_response = client.PaymentInitiation.create_payment_token(payment_id)
payment_token = create_payment_token_response['payment_token']
except plaid.errors.PlaidError as e:
return jsonify({'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type } })
return jsonify({'error': None, 'payment_token': payment_token})
def pretty_print_response(response):
print(json.dumps(response, indent=2, sort_keys=True))
def format_error(e):
return {'error': {'display_message': e.display_message, 'error_code': e.code, 'error_type': e.type, 'error_message': e.message } }
if __name__ == '__main__':
app.run(port=os.getenv('PORT', 5000))