-
Notifications
You must be signed in to change notification settings - Fork 43
/
PlaidClient.cs
378 lines (328 loc) · 16.1 KB
/
PlaidClient.cs
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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Acklann.Plaid
{
/// <summary>
/// Provides methods for sending request to and receiving data from Plaid banking API.
/// </summary>
public class PlaidClient
{
/// <summary>
/// Initializes a new instance of the <see cref="PlaidClient"/> class.
/// </summary>
public PlaidClient() : this(null, null, null, Plaid.Environment.Production)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PlaidClient"/> class.
/// </summary>
/// <param name="environment">The environment.</param>
public PlaidClient(Plaid.Environment environment) : this(null, null, null, environment)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PlaidClient"/> class.
/// </summary>
/// <param name="clientId">The client identifier.</param>
/// <param name="secret">The secret.</param>
/// <param name="accessToken">The access token.</param>
/// <param name="environment">The environment.</param>
/// <param name="apiVersion">The Plaid API version.</param>
public PlaidClient(string clientId,
string secret,
string accessToken,
Plaid.Environment environment = Plaid.Environment.Production,
string apiVersion = "2019-05-29")
{
_secret = secret;
_clientId = clientId;
_accessToken = accessToken;
_environment = environment;
_apiVersion = apiVersion;
}
/* Item Management */
/// <summary>
/// Retrieves information about the status of an <see cref="Entity.Item"/>. Endpoint '/item/get'.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.GetItemResponse>.</returns>
public Task<Management.GetItemResponse> FetchItemAsync(Management.GetItemRequest request)
{
return PostAsync<Management.GetItemResponse>("item/get", request);
}
/// <summary>
/// Delete an <see cref="Entity.Item"/>. Once deleted, the access_token associated with the <see cref="Entity.Item"/> is no longer valid and cannot be used to access any data that was associated with the <see cref="Entity.Item"/>.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.DeleteItemResponse>.</returns>
public Task<Management.DeleteItemResponse> DeleteItemAsync(Management.DeleteItemRequest request)
{
return PostAsync<Management.DeleteItemResponse>("item/delete", request);
}
/// <summary>
/// Updates the webhook associated with an <see cref="Entity.Item"/>. This request triggers a WEBHOOK_UPDATE_ACKNOWLEDGED webhook.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.UpdateWebhookResponse>.</returns>
public Task<Management.UpdateWebhookResponse> UpdateWebhookAsync(Management.UpdateWebhookRequest request)
{
return PostAsync<Management.UpdateWebhookResponse>("item/webhook/update", request);
}
/// <summary>
/// Exchanges a Link public_token for an API access_token.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.ExchangeTokenResponse>.</returns>
public Task<Management.CreatePublicTokenResponse> CreatePublicTokenAsync(Management.CreatePublicTokenRequest request)
{
return PostAsync<Management.CreatePublicTokenResponse>("item/public_token/create", request);
}
/// <summary>
/// Creates a Link link_token.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public Task<Management.CreateLinkTokenResponse> CreateLinkToken(Management.CreateLinkTokenRequest request)
{
return PostAsync<Management.CreateLinkTokenResponse>("link/token/create", request);
}
/// <summary>
/// Exchanges a Link public_token for an API access_token.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.ExchangeTokenResponse>.</returns>
public Task<Management.ExchangeTokenResponse> ExchangeTokenAsync(Management.ExchangeTokenRequest request)
{
return PostAsync<Management.ExchangeTokenResponse>("item/public_token/exchange", request);
}
/// <summary>
/// Rotates the access_token associated with an <see cref="Entity.Item"/>. The endpoint returns a new access_token and immediately invalidates the previous access_token.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.RotateAccessTokenResponse>.</returns>
public Task<Management.RotateAccessTokenResponse> RotateAccessTokenAsync(Management.RotateAccessTokenRequest request)
{
return PostAsync<Management.RotateAccessTokenResponse>("item/access_token/invalidate", request);
}
/// <summary>
/// Updates an access_token from the legacy version of Plaid’s API, you can use method to generate an access_token for the Item that works with the current API.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.UpdateAccessTokenVersionResponse>.</returns>
public Task<Management.UpdateAccessTokenVersionResponse> UpdateAccessTokenVersion(Management.UpdateAccessTokenVersionRequest request)
{
return PostAsync<Management.UpdateAccessTokenVersionResponse>("item/access_token/update_version", request);
}
/* Institutions */
/// <summary>
/// Retrieves the details on all financial institutions currently supported by Plaid.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Institution.SearchResponse>.</returns>
public Task<Institution.SearchResponse> FetchAllInstitutionsAsync(Institution.SearchAllRequest request)
{
return PostAsync<Institution.SearchResponse>("institutions/get", request);
}
/// <summary>
/// Retrieves the institutions that match the query parameters.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Institution.SearchResponse>.</returns>
public Task<Institution.SearchResponse> FetchInstitutionsAsync(Institution.SearchRequest request)
{
return PostAsync<Institution.SearchResponse>("institutions/search", request);
}
/// <summary>
/// Retrieves the institutions that match the id.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Institution.SearchByIdResponse>.</returns>
public Task<Institution.SearchByIdResponse> FetchInstitutionByIdAsync(Institution.SearchByIdRequest request)
{
return PostAsync<Institution.SearchByIdResponse>("institutions/get_by_id", request);
}
/* Income */
/// <summary>
/// Retrieves information pertaining to a <see cref="Entity.Item"/>’s income. In addition to the annual income, detailed information will be provided for each contributing income stream (or job).
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Income.GetIncomeResponse>.</returns>
public Task<Income.GetIncomeResponse> FetchUserIncomeAsync(Income.GetIncomeRequest request)
{
return PostAsync<Income.GetIncomeResponse>("income/get", request);
}
/* Investments */
/// <summary>
/// Retrieves information pertaining to a <see cref="Entity.Item"/>'s investment holdings.
/// </summary>
public Task<Investments.GetInvestmentHoldingsResponse> FetchInvestmentHoldingsAsync(Investments.GetInvestmentHoldingsRequest request)
{
return PostAsync<Investments.GetInvestmentHoldingsResponse>("investments/holdings/get", request);
}
/// <summary>
/// Retrieves information pertaining to a <see cref="Entity.Item"/>'s investment transactions.
/// </summary>
public Task<Investments.GetInvestmentTransactionsResponse> FetchInvestmentTransactionsAsync(Investments.GetInvestmentTransactionsRequest request)
{
return PostAsync<Investments.GetInvestmentTransactionsResponse>("investments/transactions/get", request);
}
/* Auth */
/// <summary>
/// Retrieves the bank account and routing numbers associated with an <see cref="Entity.Item"/>’s checking and savings accounts, along with high-level account data and balances.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Auth.GetAccountInfoResponse>.</returns>
public Task<Auth.GetAccountInfoResponse> FetchAccountInfoAsync(Auth.GetAccountInfoRequest request)
{
return PostAsync<Auth.GetAccountInfoResponse>("auth/get", request);
}
/* Balance */
/// <summary>
/// Retrieve high-level information about all accounts associated with an <see cref="Entity.Item"/>.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Balance.GetAccountResponse>.</returns>
public Task<Balance.GetAccountResponse> FetchAccountAsync(Balance.GetAccountRequest request)
{
return PostAsync<Balance.GetAccountResponse>("accounts/get", request);
}
/// <summary>
/// Retrieves the real-time balance for each of an <see cref="Entity.Item"/>’s accounts.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Balance.GetBalanceResponse>.</returns>
public Task<Balance.GetBalanceResponse> FetchAccountBalanceAsync(Balance.GetBalanceRequest request)
{
return PostAsync<Balance.GetBalanceResponse>("accounts/balance/get", request);
}
/* Categories */
/// <summary>
/// Retrieves detailed information on categories returned by Plaid.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Category.GetCategoriesResponse>.</returns>
public Task<Category.GetCategoriesResponse> FetchCategoriesAsync(Category.GetCategoriesRequest request)
{
return PostAsync<Category.GetCategoriesResponse>("categories/get", request);
}
/* Identity */
/// <summary>
/// Retrieves various account holder information on file with the financial institution, including names, emails, phone numbers, and addresses.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Identity.GetUserIdentityResponse>.</returns>
public Task<Identity.GetUserIdentityResponse> FetchUserIdentityAsync(Identity.GetUserIdentityRequest request)
{
return PostAsync<Identity.GetUserIdentityResponse>("identity/get", request);
}
/* Transactions */
/// <summary>
/// Retrieves user-authorized transaction data for credit and depository-type <see cref="Entity.Account"/>.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Transactions.GetTransactionsResponse>.</returns>
public Task<Transactions.GetTransactionsResponse> FetchTransactionsAsync(Transactions.GetTransactionsRequest request)
{
return PostAsync<Transactions.GetTransactionsResponse>("transactions/get", request);
}
/* Stripe */
/// <summary>
/// Exchanges a Link access_token for an Stripe API stripe_bank_account_token.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task<Management.StripeTokenResponse>.</returns>
public Task<Management.StripeTokenResponse> FetchStripeTokenAsync(Management.StripeTokenRequest request)
{
return PostAsync<Management.StripeTokenResponse>("processor/stripe/bank_account_token/create", request);
}
/* ***** */
internal string GetEndpoint(string path)
{
string subDomain = "";
switch (_environment)
{
default:
case Environment.Production:
subDomain = "production.";
break;
case Environment.Development:
subDomain = "development.";
break;
case Environment.Sandbox:
subDomain = "sandbox.";
break;
}
return new UriBuilder()
{
Scheme = Uri.UriSchemeHttps,
Host = $"{subDomain}plaid.com",
Path = path.Trim(' ', '/', '\\')
}.Uri.AbsoluteUri;
}
internal async Task<TResponse> PostAsync<TResponse>(string path, SerializableContent request) where TResponse : ResponseBase
{
EnsureCredentials(request);
using (var http = new HttpClient())
{
string url = GetEndpoint(path);
string json = request.ToJson();
Log(json, $"POST: '{url}'");
HttpContent body = Body(json);
body.Headers.Add("Plaid-Version", this._apiVersion);
using (HttpResponseMessage response = await http.PostAsync(url, Body(json)))
{
json = await response.Content.ReadAsStringAsync();
Log(json, $"RESPONSE ({response.StatusCode})");
TResponse result = JsonConvert.DeserializeObject<TResponse>(json);
result.StatusCode = response.StatusCode;
if (response.IsSuccessStatusCode == false)
{
var error = JObject.Parse(json);
result.Exception = new Exceptions.PlaidException(error["error_message"].Value<string>())
{
HelpLink = "https://plaid.com/docs/api/#errors-overview",
DisplayMessage = error["display_message"].Value<string>(),
ErrorType = error["error_type"].Value<string>(),
ErrorCode = error["error_code"].Value<string>(),
Source = url,
};
}
#if DEBUG
result.RawJsonForDebugging = json;
#endif
return result;
}
}
}
#region Private Members
private readonly Plaid.Environment _environment;
private readonly string _clientId, _secret, _accessToken, _apiVersion;
private static HttpContent Body(string json)
{
return new StringContent(json, Encoding.UTF8, "application/json");
}
private static void Log(string message, string title = "RESPONSE")
{
#if DEBUG
var line = string.Concat(System.Linq.Enumerable.Repeat('-', 100));
int n = (title.Length > line.Length) ? line.Length : (line.Length - title.Length + 2);
System.Diagnostics.Debug.WriteLine(line.Substring(0, n).Insert(5, $" {title} "));
System.Diagnostics.Debug.WriteLine(message);
#endif
}
private void EnsureCredentials(object request)
{
if (request is RequestBase req)
{
if (string.IsNullOrEmpty(req.Secret)) req.Secret = _secret;
if (string.IsNullOrEmpty(req.ClientId)) req.ClientId = _clientId;
if (string.IsNullOrEmpty(req.AccessToken)) req.AccessToken = _accessToken;
}
}
#endregion Private Members
}
}