-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfiGoConnection.go
506 lines (408 loc) · 14.5 KB
/
fiGoConnection.go
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
package fiGo
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"github.com/Jeffail/gabs"
)
const (
defaultBaseURL = "https://api.figo.me"
authUserURL = "/auth/user"
authTokenURL = "/auth/token"
restAccountsURL = "/rest/accounts"
restUserURL = "/rest/user"
restTransactionsURL = "/rest/transactions"
restStandingOrdersURL = "/rest/standing_orders"
restSyncURL = "/rest/sync"
taskProgressURL = "/task/progress"
catalog = "/catalog"
)
var (
// ErrUserAlreadyExists - code 30002
ErrUserAlreadyExists = errors.New("user already exists")
// ErrHTTPUnauthorized - code 90000
ErrHTTPUnauthorized = errors.New("invalid authorization")
)
// IConnection represent an interface for connections.
// This provides to use fakeConnection and a real-figoConnection
type IConnection interface {
// Set another host
SetHost(host string)
// http://docs.figo.io/#create-new-figo-user
// Ask user for new name, email and password
CreateUser(name string, email string, password string) ([]byte, error)
// http://docs.figo.io/#credential-login
// Login with email (aka username) and password
CredentialLogin(username string, password string) ([]byte, error)
// http://docs.figo.io/#delete-current-user
// Remove user with an accessToken. You get the token after successfully login
DeleteUser(accessToken string) ([]byte, error)
// http://docs.figo.io/#setup-new-bank-account
// Add a BankAccount to figo-Account
// -> you get accessToken from the login-response
// -> country is something like "de" (for germany)
SetupNewBankAccount(accessToken string, bankCode string, country string, credentials []string, savePin bool) ([]byte, error)
// http://docs.figo.io/#retrieve-all-bank-accounts
// Retrieves all bankAccounts for an user
RetrieveAllBankAccounts(accessToken string, cents bool) ([]byte, error)
// http://docs.figo.io/#delete-bank-account
// Removes a bankAccount from figo-account
RemoveBankAccount(accessToken string, bankAccountID string) ([]byte, error)
// http://docs.figo.io/#poll-task-state
// request a task
// -> you need a taskToken. You will get this from SetupNewBankAccount or when triggering a manuel sync
RequestForTask(accessToken string, taskToken string) ([]byte, error)
// http://docs.figo.io/#poll-task-state
// request a task
// -> you need a taskToken. You will get this from SetupNewBankAccount or when triggering a manual sync
RequestForTaskWithPinChallenge(accessToken string, taskToken string, pin string, savePin bool) ([]byte, error)
// http://docs.figo.io/#retrieve-transactions-of-one-or-all-account
// Retrieves all Transactions
RetrieveTransactionsOfAllAccounts(accessToken string, options ...TransactionOption) ([]byte, error)
// Retrieves all Transactions of a single account
RetrieveTransactionsSingleAccount(accessToken, accountid string, options ...TransactionOption) ([]byte, error)
// http://docs.figo.io/#retrieve-a-transaction
// Retrieves a specific Transaction
RetrieveSpecificTransaction(accessToken string, transactionID string) ([]byte, error)
// http://docs.figo.io/#tag/Catalog
// Read individual Catalog Entry
ReadIndividualCatalogEntry(accessToken string, catalogCategory string, countryCode string, serviceID string) ([]byte, error)
// http://docs.figo.io/#standing-orders-api-calls-read-standing-orders
// Read standing orders
ReadStandingOrder(accessToken string, options ...TransactionOption) ([]byte, error)
}
// Connection represent a connection to figo
type Connection struct {
AuthString string
Host string
}
// NewFigoConnection creates a new connection.
// -> You need a clientID and a clientSecret. (You will get this from figo.io)
func NewFigoConnection(clientID string, clientSecret string) *Connection {
authInfo := clientID + ":" + clientSecret
authString := "Basic " + base64.URLEncoding.EncodeToString([]byte(authInfo))
return &Connection{AuthString: authString, Host: defaultBaseURL}
}
// SetHost sets a new host
func (connection *Connection) SetHost(host string) {
connection.Host = host
}
// CreateUser creates a new user.
// Ask User for name, email and a password
func (connection *Connection) CreateUser(name string, email string, password string) ([]byte, error) {
// build url
url := connection.Host + authUserURL
// build jsonBody
requestBody := map[string]string{
"name": name,
"email": email,
"password": password}
jsonBody, err := json.Marshal(requestBody)
// build request
request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, connection.AuthString)
}
// CredentialLogin create a login.
// -> First you have to create a user (CreateUser)
func (connection *Connection) CredentialLogin(username string, password string) ([]byte, error) {
// build url
url := connection.Host + authTokenURL
// build jsonBody
requestBody := map[string]string{
"grant_type": "password",
"username": username,
"password": password}
jsonBody, err := json.Marshal(requestBody)
// build request
request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, connection.AuthString)
}
// SetupNewBankAccount add a new bankAccount to an existing figo-Account
func (connection *Connection) SetupNewBankAccount(accessToken string, bankCode string, country string, credentials []string, savePin bool) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restAccountsURL
// build jsonBody
requestBody := map[string]interface{}{
"bank_code": bankCode,
"country": country,
"credentials": credentials,
"save_pin": savePin,
}
jsonBody, err := json.Marshal(requestBody)
// build request
request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, accessToken)
}
// RemoveBankAccount removes a bank account
func (connection *Connection) RemoveBankAccount(accessToken string, bankAccountID string) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restAccountsURL + "/" + bankAccountID
// build request
request, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, accessToken)
}
// DeleteUser deletes an existing user
func (connection *Connection) DeleteUser(accessToken string) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restUserURL
// build request
request, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, accessToken)
}
// RequestForTask starts a new task or polls it to synchronize real bankAccount and figoAccount
func (connection *Connection) RequestForTask(accessToken, taskToken string) ([]byte, error) {
return connection.RequestForTaskWithPinChallenge(accessToken, taskToken, "", false)
}
// RequestForTaskWithPinChallenge can be use to respond to a pin challenge that might occur when syncing
func (connection *Connection) RequestForTaskWithPinChallenge(accessToken, taskToken, pin string, savePin bool) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + taskProgressURL + "?id=" + taskToken
body := map[string]interface{}{"continue": false}
if pin != "" {
body["pin"] = pin
if savePin {
body["save_pin"] = true
}
}
payload, err := json.Marshal(body)
if err != nil {
return nil, err
}
// build request
request, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, accessToken)
}
// SyncTask represents a synchronization task
type SyncTask struct {
State string `json:"state"`
RedirectURI string `json:"redirect_uri,omitempty"`
DisableNotifications bool `json:"disable_notifications,omitempty"`
IfNotSyncedSince int `json:"if_not_synced_since,omitempty"`
AutoContinue bool `json:"auto_continue,omitempty"`
AccountIds []string `json:"account_ids,omitempty"`
SyncTasks []string `json:"sync_tasks,omitempty"`
}
// CreateSynchronizationTask creates a new task to synchronize
func (connection *Connection) CreateSynchronizationTask(accessToken string, syncTask SyncTask) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restSyncURL
marshaledSyncTask, err := json.Marshal(&syncTask)
if err != nil {
return nil, err
}
// build request
request, err := http.NewRequest("POST", url, bytes.NewBuffer(marshaledSyncTask))
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, accessToken)
}
// TransactionOption are options for transaction-calls
type TransactionOption struct {
Key TransactionOptionKey
Value string
}
// TransactionOptionKey are the type for allowed keys
type TransactionOptionKey string
var (
// Cent if true, the amount of the transactions will be shown in cents.
Cent TransactionOptionKey = "cents"
)
// RetrieveTransactionsOfAllAccounts with accessToken from login-session
func (connection *Connection) RetrieveTransactionsOfAllAccounts(accessToken string, options ...TransactionOption) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restTransactionsURL
// build request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// if there are options, apply these
if len(options) > 0 {
q := request.URL.Query()
for _, option := range options {
q.Add(string(option.Key), option.Value)
}
request.URL.RawQuery = q.Encode()
}
return buildRequestAndCheckResponse(request, accessToken)
}
// ReadStandingOrder all standing orders
func (connection *Connection) ReadStandingOrder(accessToken string, options ...TransactionOption) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restStandingOrdersURL
// build request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// if there are options, apply these
if len(options) > 0 {
q := request.URL.Query()
for _, option := range options {
q.Add(string(option.Key), option.Value)
}
request.URL.RawQuery = q.Encode()
}
return buildRequestAndCheckResponse(request, accessToken)
}
func (connection *Connection) RetrieveTransactionsSingleAccount(accessToken, accountid string, options ...TransactionOption) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restAccountsURL + "/" + accountid + "/transactions"
// build request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// if there are options, apply these
if len(options) > 0 {
q := request.URL.Query()
for _, option := range options {
q.Add(string(option.Key), option.Value)
}
request.URL.RawQuery = q.Encode()
}
return buildRequestAndCheckResponse(request, accessToken)
}
// RetrieveSpecificTransaction with accessToken from login-session
func (connection *Connection) RetrieveSpecificTransaction(accessToken string, transactionID string) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restTransactionsURL + "/" + transactionID
// build request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, accessToken)
}
// RetrieveAllBankAccounts retrieves specific bankAccounts for an user
func (connection *Connection) RetrieveSpecificBankAccounts(accessToken, accountID string, cents bool) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restAccountsURL + "/" + accountID
// build request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// add cents query param
if cents {
q := request.URL.Query()
q.Add("cents", "true")
request.URL.RawQuery = q.Encode()
}
return buildRequestAndCheckResponse(request, accessToken)
}
// RetrieveAllBankAccounts retrieves all bankAccounts for an user
func (connection *Connection) RetrieveAllBankAccounts(accessToken string, cents bool) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + restAccountsURL
// build request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// add cents query param
if cents {
q := request.URL.Query()
q.Add("cents", "true")
request.URL.RawQuery = q.Encode()
}
return buildRequestAndCheckResponse(request, accessToken)
}
// ReadIndividualCatalogEntry gets all infos for a specific catalog entry.
// catalogCategory is "banks" or "services"
// countryCode is "de" or "at"
// serviceID is something like BLZ
func (connection *Connection) ReadIndividualCatalogEntry(accessToken string, catalogCategory string, countryCode string, serviceID string) ([]byte, error) {
// build accessToken
accessToken = "Bearer " + accessToken
// build url
url := connection.Host + catalog + "/" + catalogCategory + "/" + serviceID
// build request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return buildRequestAndCheckResponse(request, accessToken)
}
func buildRequestAndCheckResponse(request *http.Request, authString string) ([]byte, error) {
// set headers
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", authString)
// setup client
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
// get response
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
// check response for errors
if string(body) != "" {
jsonParsed, err := gabs.ParseJSON(body)
if err != nil {
return nil, err
}
value, ok := jsonParsed.Path("error.code").Data().(float64)
if ok {
if value == 30002 {
return body, ErrUserAlreadyExists
} else if value == 90000 {
return body, ErrHTTPUnauthorized
} else {
msg, ok := jsonParsed.Path("error.description").Data().(string)
if ok {
return body, errors.New(msg)
}
}
}
}
return body, nil
}