-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathfigo.py
1466 lines (1163 loc) · 56.7 KB
/
figo.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
import base64
import json
import logging
import re
import sys
import urllib
import os
from dotenv import load_dotenv
load_dotenv()
from datetime import datetime
from datetime import timedelta
from requests.exceptions import SSLError
from requests import Session
from time import sleep
# from figo.credentials import CREDENTIALS
from figo.models import Account
from figo.models import AccountBalance
from figo.models import BankContact
from figo.models import Challenge
from figo.models import LoginSettings
from figo.models import Notification
from figo.models import Payment
from figo.models import PaymentProposal
from figo.models import Security
from figo.models import Service
from figo.models import StandingOrder
from figo.models import TaskState
from figo.models import TaskToken
from figo.models import Transaction
from figo.models import User
from figo.models import WebhookNotification
from figo.models import Sync
from figo.version import __version__
if sys.version_info[0] > 2:
import urllib.parse as urllib
else:
import urllib
logger = logging.getLogger(__name__)
API_ENDPOINT = os.getenv("API_ENDPOINT")
ERROR_MESSAGES = {
400: {
'message': "bad request",
'description': "Bad request",
'code': 90000,
},
401: {
'message': "unauthorized",
'description': "Missing, invalid or expired access token.",
'code': 90000,
},
403: {
'message': "forbidden",
'description': "Insufficient permission.",
'code': 90000,
},
404: {
'message': "not_found",
'description': "Not found.",
'code': 90000,
},
405: {
'message': "method_not_allowed",
'description': "Unexpected request method.",
'code': 90000,
},
503: {
'message': "service_unavailable",
'description': "Exceeded rate limit.",
'code': 90000,
},
}
def getAccountId(account_or_account_id):
if account_or_account_id == None:
return None
elif isinstance(account_or_account_id, Account):
return account_or_account_id.account_id
else:
return account_or_account_id
def filterKeys(object, allowed_keys):
if object == None or object == {}:
return {}
else:
keys = [key for key in object.keys() if key in allowed_keys]
return dict(zip(keys, [object[key] for key in keys]))
def filterNone(object):
return { k: v for k, v in object.items() if v is not None }
class FigoObject(object):
"""A FigoObject has the ability to communicate with the Figo API."""
def __init__(self,
api_endpoint=API_ENDPOINT,
language=None):
"""Create a FigoObject instance.
Args:
api_endpoint (str) - base URI of the server to call
language (str) - language for HTTP request header
"""
self.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': "python_figo/{0}".format(__version__),
}
self.language = language
self.api_endpoint = api_endpoint
def _request_api(self, path, data=None, method="GET"):
"""Helper method for making a REST-compliant API call.
Args:
path: path on the server to call
data: dictionary of data to send to the server in message body
method: - HTTP verb to use for the request
Returns:
the JSON-parsed result body
"""
complete_path = self.api_endpoint + path
session = Session()
session.headers.update(self.headers)
try:
response = session.request(method, complete_path, json=data)
finally:
session.close()
if 200 <= response.status_code < 300 or self._has_error(response.json()):
if response.text == '':
return {}
return response.json()
elif response.status_code in ERROR_MESSAGES:
return {'error': ERROR_MESSAGES[response.status_code]}
logger.warn("Querying the API failed when accessing '%s': %d",
complete_path,
response.status_code)
return {'error': {
'message': "internal_server_error",
'description': "We are very sorry, but something went wrong",
'code': 90000}}
def _request_with_exception(self, path, data=None, method="GET"):
response = self._request_api(path, data, method)
# the check for is_erroneous in response is here to not confuse a task/progress
# response with an error object
if self._has_error(response) and 'is_erroneous' not in response:
raise FigoException.from_dict(response)
else:
return response
def _has_error(self, response):
return 'error' in response and response["error"]
def _query_api_object(self, model, path, data=None, method="GET", collection_name=None):
"""
Helper method using _request_with_exception but encapsulating the result as an object.
"""
response = self._request_with_exception(path, data, method)
if response is None:
return None
elif collection_name is None:
return model.from_dict(self, response)
elif collection_name == "collection":
# Some collections in the API response ARE NOT embbeded in collection name. (Ex: challenges, accesses)
return [model.from_dict(self, dict_entry) for dict_entry in response]
else:
return [model.from_dict(self, dict_entry) for dict_entry in response[collection_name]]
@property
def language(self):
return self.headers.get('Accept-Language')
@language.setter
def language(self, lang):
if lang:
self.headers['Accept-Language'] = lang
elif self.headers.get('Accept-Language'):
del self.headers['Accept-Language']
class FigoException(Exception):
"""Base class for all exceptions transported via the figo connect API.
They consist of a code-like `error` and a human readable `error_description`.
"""
def __init__(self, error, error_description, code=None):
"""Create a Exception with a error code and error description."""
super(FigoException, self).__init__()
# XXX(dennis.lutter): not needed internally but left here for backwards compatibility
self.error = error
self.error_description = error_description
self.code = code
def __str__(self):
"""String representation of the FigoException."""
return "FigoException: {} ({})".format(self.error_description, self.error)
@classmethod
def from_dict(cls, dictionary):
"""
Helper function creating an exception instance from the dictionary returned by the server.
"""
return cls(dictionary['error'].get('message'),
dictionary['error'].get('description'),
dictionary['error'].get('code'))
class FigoPinException(FigoException):
"""
This exception is thrown if the wrong pin was submitted to a task. It contains information about
current state of the task.
"""
def __init__(self, country, credentials, bank_code, iban, save_pin,
error="Wrong PIN",
error_description="You've entered a wrong PIN, please provide a new one.",
code=None):
"""Initialiase an Exception for a wrong PIN which contains information about the task."""
super(FigoPinException, self).__init__(error, error_description, code)
self.country = country
self.credentials = credentials
self.bank_code = bank_code
self.iban = iban
self.save_pin = save_pin
def __str__(self):
"""String representation of the FigoPinException."""
return "FigoPinException: {}({})".format(self.error_description, self.error)
class FigoConnection(FigoObject):
"""Representing a not user-bound connection to the figo connect API.
Its main purpose is to let user login via the OAuth2 API.
"""
def __init__(self, client_id, client_secret, redirect_uri,
api_endpoint=API_ENDPOINT,
language=None):
"""
Create a FigoConnection instance.
Args:
client_id (str) - the OAuth Client ID as provided by your figo developer contact
client_secret (str) - the OAuth Client Secret as provided by your figo developer contact
redirect_uri (str) - the URI the users gets redirected to after the login is finished
or if they press `cancel`
api_endpoint (str) - base URI of the server to call
language (str) - language for HTTP request header
"""
super(FigoConnection, self).__init__(api_endpoint=api_endpoint, language=language)
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
basic_auth = "{0}:{1}".format(self.client_id, self.client_secret).encode("ascii")
basic_auth_encoded = base64.b64encode(basic_auth).decode("utf-8")
self.headers.update({'Authorization': "Basic {0}".format(basic_auth_encoded)})
def _query_api(self, path, data=None):
"""Helper method for making a OAuth2-compliant API call.
Args:
path: path on the server to call
data: dictionary of data to send to the server in message body
Returns:
the JSON-parsed result body
"""
return self._request_api(path=path, data=data)
def login_url(self, scope, state):
"""The URL a user should open in his/her web browser to start the login process.
When the process is completed, the user is redirected to the URL provided to
the constructor and passes on an authentication code. This code can be converted into
an access token for data access.
Args:
scope: Scope of data access to ask the user for, e.g. `accounts=ro`
state: String passed on through the complete login process and to the redirect
target at the end. It should be used to validate the authenticity of the
call to the redirect URL
Returns:
the URL of the first page of the login process
"""
return (self.api_endpoint +
"/auth/code?" +
urllib.urlencode(
{'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'scope': scope, 'state': state}
))
def convert_authentication_code(self, authentication_code):
"""
Convert the authentication code received as result of the login process into an
access token usable for data access.
Args:
authentication_code: the code received as part of the call to the redirect
URL at the end of the logon process
Returns:
Dictionary with the following keys:
- `access_token` - the access token for data access. You can pass it into
`FigoConnection.open_session` to get a FigoSession and access the user's data
- `refresh_token` - if the scope contained the `offline` flag, also a
refresh token is generated. It can be used to generate new access tokens,
when the first one has expired.
- `expires` - absolute time the access token expires
"""
if authentication_code[0] != "O":
raise Exception("Invalid authentication code")
response = self._request_api(
"/auth/token",
data={'code': authentication_code,
'redirect_uri': self.redirect_uri,
'grant_type': 'authorization_code'},
method="POST")
if 'error' in response:
raise FigoException.from_dict(response)
return {'access_token': response['access_token'],
'refresh_token': response['refresh_token'] if 'refresh_token' in response else None,
'expires': datetime.now() + timedelta(seconds=response['expires_in'])}
def credential_login(self, username, password, scope=None):
"""
Return a Token dictionary which tokens are used for further API actions.
Args:
username (str): Figo username
password (str): Figo password
scope (str): Space delimited set of requested permissions.
Example: "accounts=ro balance=ro transactions=ro offline"
Returns:
Dictionary which contains an access token and a refresh token.
"""
data = filterNone({"grant_type": "password",
"username": username,
"password": password,
"scope": scope})
response = self._request_api("/auth/token", data, method="POST")
if 'error' in response:
raise FigoException.from_dict(response)
return {
'access_token': response['access_token'],
'refresh_token': response['refresh_token'] if 'refresh_token' in response else None,
'expires': datetime.now() + timedelta(seconds=response['expires_in']),
'scope': response['scope'],
}
def convert_refresh_token(self, refresh_token):
"""Convert a refresh token (granted for offline access and returned by
`convert_authentication_code`) into an access token usable for data access.
Args:
refresh_token: refresh token returned by `convert_authentication_code`
Returns:
Dictionary with the following keys:
- `access_token` - the access token for data access. You can pass it into
`FigoConnection.open_session` to get a FigoSession and access the users data
- `expires` - absolute time the access token expires
"""
if refresh_token[0] != "R":
raise Exception("Invalid refresh token")
data = {
'refresh_token': refresh_token, 'redirect_uri': self.redirect_uri,
'grant_type': 'refresh_token'}
response = self._request_api("/auth/token", data=data, method="POST")
if 'error' in response:
raise FigoException.from_dict(response)
return {'access_token': response['access_token'],
'expires': datetime.now() + timedelta(seconds=response['expires_in'])}
def revoke_token(self, token):
"""Revoke a granted access or refresh token and thereby invalidate it.
Note: this action has immediate effect, i.e. you will not be able use that
token anymore after this call.
Args:
token: access or refresh token to be revoked
"""
response = self._request_api("/auth/revoke?" + urllib.urlencode({'token': token}))
if 'error' in response:
raise FigoException.from_dict(response)
def add_user(self, name, email, password, language='de'):
"""Create a new figo Account.
Args:
name: First and last name
email: Email address; It must obey the figo username & password policy
password: New figo Account password; It must obey the figo username & password policy
language: Two-letter code of preferred language
Returns:
Auto-generated recovery password.
"""
response = self._request_api(
path="/auth/user",
data={'full_name': name,
'email': email,
'password': password,
'language': language},
method="POST")
if response is None:
return None
elif 'error' in response:
raise FigoException.from_dict(response)
else:
return response
def add_user_and_login(self, name, email, password, language='de'):
"""
Create a new figo account and get a session token for the new account.
Args:
name: First and last name
email: Email address; It must obey the figo username & password policy
password: New figo Account password; It must obey the figo username & password policy
language: Two-letter code of preferred language
send_newsletter: This flag indicates whether the user has agreed to be contacted by
email
Returns:
Token dictionary for further API access
"""
self.add_user(name, email, password, language)
return self.credential_login(email, password)
def get_version(self):
"""
Returns the version of the API.
"""
return self._request_api(path="/version", method='GET')
def get_catalog(self, q=None, country_code=None):
"""Return a dict with lists of supported banks and payment services, with client auth.
Returns:
dict {'banks': [BankContact], 'services': [Service]}:
dict with lists of supported banks and payment services
"""
options = filterNone({ "country": country_code, "q": q })
catalog = self._query_api("/catalog?" + urllib.urlencode(options))
for k, v in catalog.items():
if k == 'banks':
catalog[k] = [BankContact.from_dict(self, bank) for bank in v]
elif k == 'services':
catalog[k] = [Service.from_dict(self, service) for service in v]
return catalog
class FigoSession(FigoObject):
"""
Represents a user-bound connection to the figo connect API and allows access to the users data.
"""
def __init__(self, access_token, sync_poll_retry=20,
api_endpoint=API_ENDPOINT,
language=None,
):
"""Create a FigoSession instance.
Args:
access_token (str) - the access token to bind this session to a user
sync_poll_retry (int) - maximum number of synchronization poll retries
api_endpoint (str) - base URI of the server to call
language (str) - language for HTTP request header
"""
super(FigoSession, self).__init__(api_endpoint=api_endpoint,language=language)
self.access_token = access_token
self.headers.update({'Authorization': "Bearer {0}".format(self.access_token)})
self.sync_poll_retry = sync_poll_retry
@property
def accounts(self):
"""
An array of `Account` objects, one for each account the user has granted the app access.
"""
return self._query_api_object(Account, "/rest/accounts", collection_name="accounts")
def get_account(self, account_or_account_id, cents=None):
"""
Args:
account_or_account_id: account to be queried or its ID
cents (bool): If true amounts will be shown in cents, Optional, default: False
Returns:
Account: An account accessible from Token
"""
options = { "cents": cents } if cents else {}
return self._query_api_object(Account, path="/rest/accounts/{0}".format(getAccountId(account_or_account_id)), method='GET')
def get_accounts(self):
"""
Args:
None
Returns:
List of Accounts accessible from Token
"""
return self._query_api_object(Account, path="/rest/accounts", method='GET', collection_name="accounts")
def modify_account(self, account):
"""Modify an account.
Args:
account: the modified account to be saved
Returns:
Account object for the updated account returned by server
"""
return self._query_api_object(Account, "/rest/accounts/%s" % account.account_id,
account.dump(), "PUT")
def remove_account(self, account_or_account_id):
"""Remove an account.
Args:
account_or_account_id: account to be removed or its ID
"""
path = "/rest/accounts/{0}".format(getAccountId(account_or_account_id))
self._request_with_exception(path, method="DELETE")
def add_sync(self, access_id, disable_notifications, redirect_uri, state, credentials, save_secrets):
"""
Args:
access_id (str): figo ID of the provider access, Required
disable_notifications (bool): This flag indicates whether notifications should be sent to your
application, Optional, default: False
redirect_uri (str): The URI to which the end user is redirected in OAuth cases, Optional
state (str): Arbitrary string to maintain state between this request and the callback
credentials (obj): Credentials used for authentication with the financial service provider.
save_secrets (bool): Indicates whether the confidential parts of the credentials should be saved, default: False
Returns:
Object: synchronization operation.
"""
data = filterNone({ "disable_notifications": disable_notifications, "redirect_uri": redirect_uri,
"state": state, "credentials": credentials, "save_secrets": save_secrets})
return self._query_api_object(Sync, "/rest/accesses/{0}/syncs".format(access_id), data=data, method='POST')
def get_synchronization_status(self, access_id, sync_id):
"""
Args:
access_id (str): figo ID of the provider access, Required
sync_id (str): figo ID of the synchronization operation, Required
Returns:
Object: synchronization operation.
"""
return self._query_api_object(Sync, "/rest/accesses/{0}/syncs/{1}".format(access_id, sync_id), method='GET')
def get_synchronization_challenges(self, access_id, sync_id):
"""
Args:
access_id (str): figo ID of the provider access, Required
sync_id (str): figo ID of the synchronization operation, Required
Returns:
Object: List of challenges associated with synchronization operation.
"""
return self._query_api_object(Challenge, "/rest/accesses/{0}/syncs/{1}/challenges".format(access_id, sync_id), method='GET', collection_name="collection")
def get_synchronization_challenge(self, access_id, sync_id, challenge_id):
"""
Args:
access_id (str): figo ID of the provider access, Required
sync_id (str): figo ID of the synchronization operation, Required
challenge_id (str): figo ID of the challenge, Required
Returns:
Object: Challenge associated with synchronization operation.
"""
return self._query_api_object(Challenge, "/rest/accesses/{0}/syncs/{1}/challenges/{2}".format(access_id, sync_id, challenge_id), method='GET')
def solve_synchronization_challenge(self, access_id, sync_id, challenge_id, data):
"""
Args:
access_id (str): figo ID of the provider access, Required
sync_id (str): figo ID of the synchronization operation, Required
challenge_id (str): figo ID of the challenge, Required
Returns:
{}
"""
return self._request_api(path="/rest/accesses/{0}/syncs/{1}/challenges/{2}/response"
.format(access_id, sync_id, challenge_id), data=data, method='POST')
def get_account_balance(self, account_or_account_id):
"""Get balance and account limits.
Args:
account_or_account_id: account to be queried or its ID
Returns:
AccountBalance object for the respective account
"""
if isinstance(account_or_account_id, Account):
account_or_account_id = account_or_account_id.account_id
query = "/rest/accounts/{0}/balance".format(account_or_account_id)
return self._query_api_object(AccountBalance, query)
def modify_account_balance(self, account_or_account_id, account_balance):
"""Modify balance or account limits.
Args:
account_or_account_id: account to be modified or its ID
account_balance: modified AccountBalance object to be saved
Returns:
AccountBalance object for the updated account as returned by the server
"""
if isinstance(account_or_account_id, Account):
account_or_account_id = account_or_account_id.account_id
query = "/rest/accounts/{0}/balance".format(account_or_account_id)
return self._query_api_object(AccountBalance, query, account_balance.dump(), "PUT")
def get_catalog(self, country_code=None):
"""Return a dict with lists of supported banks and payment services.
Returns:
dict {'banks': [Service], 'services': [Service]}:
dict with lists of supported banks and payment services
"""
options = filterNone({ "country": country_code })
catalog = self._request_with_exception("/rest/catalog?" + urllib.urlencode(options))
for k, v in catalog.items():
catalog[k] = [Service.from_dict(self, service) for service in v]
return catalog
def add_access(self, access_method_id, credentials, consent):
"""Add provider access
Args:
access_method_id (str): figo ID of the provider access method. [required]
credentials (Crendentials object): Credentials used for authentication with the financial service provider.
consent (Consent object): Configuration of the PSD2 consents. Is ignored for non-PSD2 accesses.
Returns:
Access object added
"""
data = { "access_method_id": access_method_id, "credentials" : credentials, "consent": consent }
return self._request_api(path="/rest/accesses", data=data, method="POST")
def get_accesses(self):
"""List all connected provider accesses of user.
Returns:
Array of Access objects
"""
return self._request_with_exception("/rest/accesses")
def get_access(self, access_id):
"""Retrieve the details of a specific provider access identified by its ID.
Args:
access_id (str): figo ID of the provider access. [required]
Returns:
Access object matching the access_id
"""
return self._request_with_exception("/rest/accesses/{0}".format(access_id), method="GET")
def remove_pin(self, access_id):
"""Remove a PIN from the API backend that has been previously stored for automatic synchronization or ease of use.
Args:
access_id (str): figo ID of the provider access. [required]
Returns:
Access object for which the PIN was removed
"""
return self._request_api(
path="/rest/accesses/%s/remove_pin" % access_id,
method="POST"
)
def get_supported_payment_services(self, country_code):
"""Return a list of supported credit cards and other payment services.
Args:
country_code (str): country code of the requested payment services
Returns:
[Service]: list of supported credit cards and other payment services
"""
services = self._request_with_exception("/rest/catalog/services/%s" % country_code)[
"services"]
return [Service.from_dict(self, service) for service in services]
def get_supported_banks(self, country_code):
"""Return a list of supported banks.
Args:
country_code (str): country code of the requested banks
Retursn:
[Service]: list of supported banks
"""
banks = self._request_with_exception("/rest/catalog/banks/%s" % country_code)[
"banks"]
return [Service.from_dict(self, bank) for bank in banks]
def get_login_settings(self, country_code, item_id):
"""Return the login settings of a bank.
Args:
country_code (str): country code of the requested bank
item_id (str): bank code or fake bank code of the requested bank
Returns:
LoginSettings: Object that contains information which are needed for
logging in to the bank
"""
return self._query_api_object(LoginSettings,
"/rest/catalog/banks/%s/%s" % (country_code, item_id))
def get_service_login_settings(self, country_code, item_id):
"""Return the login settings of a payment service.
Args:
country_code (str): country code of the requested payment service
item_id (str): bank code or fake bank code of the requested payment service
Returns:
LoginSettings: Object that contains information which are needed for
logging in to the payment service.
"""
return self._query_api_object(LoginSettings,
"/rest/catalog/services/%s/%s" % (country_code, item_id))
def get_standing_orders(self, account_or_account_id=None, accounts=None, count=None, offset=None, cents=None):
"""Get an array of `StandingOrder` objects, one for each standing order of the user on
the specified account.
Args:
account_or_account_id: account to be queried or its ID, Optional
Accounts: Comma separated list of account IDs, Optional
Count: Limit the number of returned items, Optional
Offset: Skip this number of transactions in the response, Optional
Cents: If true amounts will be shown in cents, Optional, default: False
Returns:
List of standing order objects
"""
options = filterNone({ "accounts": accounts, "count": count, "offset": offset, "cents": cents })
account_id = getAccountId(account_or_account_id)
if account_id:
query = "/rest/accounts/{0}/standing_orders?{1}".format(account_id, urllib.urlencode(options))
else:
query = "/rest/standing_orders?{0}".format(urllib.urlencode(options))
return self._query_api_object(StandingOrder, query, collection_name="standing_orders")
@property
def notifications(self):
"""An array of `Notification` objects, one for each registered notification."""
return self._query_api_object(Notification, "/rest/notifications",
collection_name="notifications")
def get_notification(self, notification_id):
"""Retrieve a specific notification.
Args:
notification_id: ID of the notification to be retrieved
Returns:
Notification object for the respective notification
"""
return self._query_api_object(Notification, "/rest/notifications/" + str(notification_id))
def add_notification(self, notification):
"""Create a new notification.
Args:
notification: new notification to be created. It should have no notification_id set
Returns:
Notification object for the newly created notification
"""
return self._query_api_object(Notification, "/rest/notifications", notification.dump(),
"POST")
def modify_notification(self, notification):
"""Modify a notification.
Args:
notification: modified notification object to be saved
Returns:
Notification object for the modified notification
"""
return self._query_api_object(Notification,
"/rest/notifications/" + notification.notification_id,
notification.dump(), "PUT")
def remove_notification(self, notification_or_notification_id):
"""Remove a notification.
Args:
notification_or_notification_id: notification to be removed or its ID
"""
if isinstance(notification_or_notification_id, Notification):
notification_or_notification_id = notification_or_notification_id.notification_id
query = "/rest/notifications/{0}".format(notification_or_notification_id)
self._request_with_exception(query, method="DELETE")
@property
def payments(self):
"""Get an array of `Payment` objects, one for each payment of the user over all accounts.
Returns:
List of Payment objects
"""
return self._query_api_object(Payment, "/rest/payments", collection_name="payments")
def get_payments(self, account_or_account_id, accounts, count, offset, cents):
"""Get an array of `Payment` objects, one for each payment of the user on
the specified account.
Args:
account_or_account_id: account to be queried or its ID
Accounts: Comma separated list of account IDs.
Count: Limit the number of returned items, Optional
Offset: Skip this number of transactions in the response, Optional
Cents: If true amounts will be shown in cents, Optional, default: False
Returns:
List of Payment objects
"""
options = filterNone({ "accounts": accounts, "count": count, "offset": offset, "cents": cents })
account_id = getAccountId(account_or_account_id)
if account_id:
query = "/rest/accounts/{0}/payments?{1}".format(account_id, urllib.urlencode(options))
else:
query = "/rest/payments?{0}".format(urllib.urlencode(options))
return self._query_api_object(Payment, query, collection_name="payments")
def get_payment(self, account_or_account_id, payment_id, cents):
"""Get a single `Payment` object.
Args:
account_or_account_id: account to be queried or its ID
payment_id: ID of the payment to be retrieved
Cents (bool): If true amounts will be shown in cents, Optional, default: False
Returns:
Payment object
"""
options = { "cents": cents } if cents else {}
query = "/rest/accounts/{0}/payments/{1}?{2}".format(getAccountId(account_or_account_id), payment_id, urllib.urlencode(options))
return self._query_api_object(Payment, query)
def add_payment(self, payment):
"""Create a new payment.
Args:
payment: payment to be created. It should not have its payment_id set.
Returns:
Payment object of the newly created payment as returned by the server
"""
return self._query_api_object(Payment, "/rest/accounts/{0}/payments".format(payment.account_id), payment.dump(), "POST")
def modify_payment(self, payment):
"""Modify a payment.
Args:
payment: modified payment object to be modified
Returns:
Payment object for the updated payment
"""
return self._query_api_object(Payment, "/rest/accounts/%s/payments/%s" % (
payment.account_id, payment.payment_id), payment.dump(), "PUT")
def remove_payment(self, payment):
"""Remove a payment.
Args:
payment: payment to be removed
"""
self._request_with_exception(
"/rest/accounts/%s/payments/%s" % (payment.account_id, payment.payment_id),
method="DELETE")
def submit_payment(self, payment, tan_scheme_id, state, redirect_uri=None):
"""Submit payment to bank server.
Args:
payment: payment to be submitted, Required
tan_scheme_id: TAN scheme ID of user-selected TAN scheme, Required
state: Any kind of string that will be forwarded in the callback response message, Required
redirect_uri: At the end of the submission process a response will
be sent to this callback URL, Optional
Returns:
the URL to be opened by the user for the TAN process
"""
params = {'tan_scheme_id': tan_scheme_id, 'state': state}
if redirect_uri is not None:
params['redirect_uri'] = redirect_uri
response = self._request_with_exception(
"/rest/accounts/%s/payments/%s/init" % (payment.account_id, payment.payment_id),
params, "POST")
def get_payment_status(self, payment_id, init_id):
"""Get initiation status for payment initiated to bank server.
Args:
payment: payment to be retrieved the status for, Required
init_id: initiation id, Required
Returns:
the initiation status of the payment
"""
response = self._request_with_exception(
"/rest/accounts/%s/payments/%s/init/%s" % (payment.account_id, payment.payment_id, init_id), None, "GET")
def get_payment_challenges(self, account_or_account_id, payment_id, init_id):
"""List payment challenges
Args:
account_or_account_id: account to be queried or its ID, Required
payment: payment to be retrieved the status for, Required
init_id: initiation id, Required
Returns:
List of challenges for the required payment
"""
account_id = getAccountId(account_or_account_id)
return self._query_api_object(Challenge, "/rest/accounts/{0}/payments/{1}/init/{2}/challenges".format(account_id, payment_id, init_id), "GET")
def get_payment_challenge(self, account_or_account_id, payment_id, init_id, challenge_id):
"""Get payment challenge
Args:
account_or_account_id: account to be queried or its ID, Required
payment: payment to be retrieved the status for, Required