├── .gitignore ├── LICENSE ├── README.md ├── aisp_example.py └── pisp_example.py /.gitignore: -------------------------------------------------------------------------------- 1 | .python-version 2 | .vscode 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | | :warning: Deprecation Notice | 2 | |-----------------------------| 3 | | This repository is deprecated and is no longer maintained. | 4 | | Please refer to the [documentation](https://enablebanking.com/docs/) for the relevant information. | 5 | | It is advised to use [Enable Banking API](https://enablebanking.com/docs/api/reference/) for Open Banking integrations | 6 | 7 | 8 | # Open Banking Python Examples 9 | 10 | This repository contains sample Python code showing how to use Open banking APIs (PSD2 AISP & PISP) using Python library 11 | of Enable Banking aggregation core. 12 | 13 | ## Quickstart 14 | 15 | In order to run the example code you need to have Python 3.6+ and enablebanking library installed. 16 | 17 | 18 | To run examples from your command line: 19 | 20 | ``` 21 | python3 aisp_example.py 22 | ``` 23 | -------------------------------------------------------------------------------- /aisp_example.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import datetime 3 | import logging 4 | import readline # imported to allow pasting long lines into `input` function 5 | import time 6 | from typing import Dict, Any 7 | import uuid 8 | 9 | import enablebanking 10 | 11 | logging.getLogger().setLevel(logging.INFO) 12 | 13 | REDIRECT_URL = "https://enablebanking.com/auth_redirect" # PUT YOUR REDIRECT URI HERE 14 | 15 | 16 | CONNECTOR_NAME = "Nordea" 17 | CONNECTOR_COUNTRY = "FI" 18 | CONNECTOR_SETTINGS = { 19 | "sandbox": True, 20 | "consentId": None, 21 | "accessToken": None, 22 | "refreshToken": None, 23 | "redirectUri": REDIRECT_URL, 24 | "country": "DK", 25 | "language": None, 26 | "clientId": "", 27 | "clientSecret": "", 28 | "signKeyPath": "/path/to/your/private.key", 29 | } 30 | 31 | 32 | def read_redirected_url(url, redirect_url): 33 | print("Please, open this page in browser: " + url) 34 | print("Login, authenticate and copy paste back the URL where you got redirected.") 35 | print(f"URL: (starts with %s): " % redirect_url) 36 | 37 | redirected_url = input() # insert your url 38 | return redirected_url 39 | 40 | 41 | async def get_connector_meta( 42 | connector_name: str, connector_country: str 43 | ) -> enablebanking.MetaApi: 44 | meta_api = enablebanking.MetaApi(enablebanking.ApiClient()) 45 | for conn in (await meta_api.get_connectors(country=connector_country)).connectors: 46 | if conn.name == connector_name: 47 | return conn 48 | raise Exception("Meta not found") 49 | 50 | 51 | async def main(): 52 | api_meta = await get_connector_meta( 53 | CONNECTOR_NAME, CONNECTOR_COUNTRY 54 | ) # get meta information for current connector 55 | 56 | api_client = enablebanking.ApiClient( 57 | CONNECTOR_NAME, connector_settings=CONNECTOR_SETTINGS 58 | ) # Create client instance. 59 | 60 | auth_api = enablebanking.AuthApi(api_client) # Create authentication interface. 61 | 62 | client_info = enablebanking.ClientInfo() 63 | connector_psu_headers = api_meta.required_psu_headers 64 | if "psuIpAddress" in connector_psu_headers: 65 | client_info.psu_ip_address = "10.10.10.10" 66 | 67 | if "psuUserAgent" in connector_psu_headers: 68 | client_info.psu_user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15" 69 | 70 | await auth_api.set_client_info(client_info=client_info) 71 | 72 | access = enablebanking.Access( 73 | valid_until=(datetime.datetime.now() + datetime.timedelta(days=89)) 74 | ) 75 | get_auth_params: Dict[str, Any] = {"state": str(uuid.uuid4())} 76 | if api_meta.auth_info[0].info.access: 77 | get_auth_params["access"] = access 78 | auth_response = await auth_api.get_auth(**get_auth_params) 79 | 80 | make_token_response = None 81 | if auth_response.url: 82 | # if url is returned, then we are doing redirect flow 83 | redirected_url = read_redirected_url(auth_response.url, REDIRECT_URL) 84 | query_params = await auth_api.parse_redirect_url(redirected_url) 85 | logging.info("Parsed query: %s", query_params) 86 | make_token_response = await auth_api.make_token( 87 | "authorization_code", # grant type, MUST be set to "authorization_code" 88 | code=query_params.code, 89 | auth_env=auth_response.env, 90 | ) 91 | else: 92 | # decoupled flow otherwise 93 | # Doing a retry to check periodically whether user has already authorized a consent 94 | sleep_time = 3 95 | for _ in range(3): 96 | try: 97 | make_token_response = await auth_api.make_token( 98 | "authorization_code", # grant type, MUST be set to "authorization_code" 99 | code="", 100 | auth_env=auth_response.env, 101 | ) 102 | except enablebanking.MakeTokenException as e: 103 | logging.debug( 104 | f"Failed to get authorization code, sleeping for {sleep_time} seconds" 105 | ) 106 | time.sleep(sleep_time) 107 | else: 108 | break 109 | 110 | logging.info("Token: %s", make_token_response) 111 | 112 | aisp_api = enablebanking.AISPApi( 113 | api_client 114 | ) # api_client has already accessToken and refreshToken applied after call to makeToken() 115 | 116 | if api_meta.modify_consents_info[0].info.before_accounts: 117 | # bank requires to create a consent explicitly before accessing list of accounts 118 | consent = await aisp_api.modify_consents(access=access) 119 | logging.debug(f"Consent: {consent}") 120 | try: 121 | # If returned consent has a redirect url, we need to redirect a PSU there 122 | consent_url = consent.links.redirect.href 123 | redirect_url = read_redirected_url(consent_url, REDIRECT_URL) 124 | logging.debug(f"Redirect url: {redirect_url}") 125 | except AttributeError: 126 | pass 127 | 128 | accounts = await aisp_api.get_accounts() 129 | logging.info("Accounts info: %s", accounts) 130 | 131 | if api_meta.modify_consents_info[0].info.accounts_required: 132 | # bank requires to create a consent with account ids specified 133 | account_ids = [ 134 | enablebanking.AccountIdentification(iban=acc.account_id.iban) 135 | for acc in accounts.accounts 136 | ] 137 | access.accounts = account_ids 138 | consent = await aisp_api.modify_consents(access=access) 139 | logging.debug(f"Consent: {consent}") 140 | try: 141 | # If returned consent has a redirect url, we need to redirect a PSU there 142 | consent_url = consent.links.redirect.href 143 | redirect_url = read_redirected_url(consent_url, REDIRECT_URL) 144 | logging.debug(f"Redirect url: {redirect_url}") 145 | except AttributeError: 146 | pass 147 | 148 | for account in accounts.accounts: 149 | transactions = await aisp_api.get_account_transactions(account.resource_id) 150 | logging.info("Transactions info: %s", transactions) 151 | 152 | balances = await aisp_api.get_account_balances(account.resource_id) 153 | logging.info("Balances info: %s", balances) 154 | 155 | 156 | if __name__ == "__main__": 157 | loop = asyncio.get_event_loop() 158 | loop.run_until_complete(main()) 159 | -------------------------------------------------------------------------------- /pisp_example.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import enablebanking 4 | 5 | logging.getLogger().setLevel(logging.INFO) 6 | 7 | REDIRECT_URL = "https://enablebanking.com" # PUT YOUR REDIRECT URI HERE 8 | 9 | 10 | def alior_settings(): 11 | return { 12 | "sandbox": True, 13 | "clientId": "client-id", # API client ID 14 | "clientSecret": "client-secret", 15 | "certPath": "cert-path", # Path or URI QWAC certificate in PEM format 16 | "keyPath": "key-path", # Path or URI to QWAC certificate private key in PEM format 17 | "signKeyPath": "sign-key-path", # Path or URI to QSeal certificate in PEM format 18 | "signPubKeySerial": "sign-pub-key-serial", # Public serial key of the QSeal certificate located in signKeyPath 19 | "signFingerprint": "sign-fingerprint", 20 | "signCertUrl": "sign-cert-url", 21 | "accessToken": None, 22 | "consentId": None, 23 | "redirectUri": REDIRECT_URL, 24 | "paymentAuthRedirectUri": REDIRECT_URL, # URI where clients are redirected to after payment authorization. 25 | "paymentAuthState": "test" # This value returned to paymentAuthRedirectUri after payment authorization. 26 | } 27 | 28 | def read_redirected_url(url, redirect_url): 29 | print("Please, open this page in browser: " + url) 30 | print("Login, authenticate and copy paste back the URL where you got redirected.") 31 | print(f"URL: (starts with %s): " % redirect_url) 32 | 33 | redirected_url = input() # insert your url 34 | return redirected_url 35 | 36 | 37 | def main(): 38 | api_client = enablebanking.ApiClient("Alior", connector_settings=alior_settings()) # Create client instance. 39 | pisp_api = enablebanking.PISPApi(api_client) 40 | 41 | payment_request_resource = enablebanking.PaymentRequestResource( 42 | payment_type_information=enablebanking.PaymentTypeInformation(service_level="SEPA", # will be resolved to "pis:EEA" 43 | local_instrument="SEPA"), # set explicitly, can also be for example SWIFT or ELIXIR 44 | credit_transfer_transaction=[ 45 | enablebanking.CreditTransferTransaction( 46 | instructed_amount=enablebanking.AmountType( 47 | amount="12.25", 48 | currency="EUR"), 49 | beneficiary=enablebanking.Beneficiary( 50 | creditor=enablebanking.PartyIdentification(name="Creditor Name", 51 | postal_address={"country": "RO", 52 | "addressLine": ["Creditor Name", 53 | "Creditor Address 1", 54 | "Creditor Address 2"]}), 55 | creditor_account=enablebanking.AccountIdentification(iban="RO56ALBP0RON421000045875"), 56 | ), 57 | remittance_information=["Some remittance information"], 58 | ), 59 | ], 60 | debtor=enablebanking.PartyIdentification(name="Debtor Name", 61 | postal_address={"country": "PL", 62 | "addressLine": ["Debtor Name", 63 | "Debtor Address 1", 64 | "Debtor Address 2"]}), 65 | debtor_account=enablebanking.AccountIdentification(iban="PL63249000050000400030900682"), 66 | ) 67 | request_creation = pisp_api.make_payment_request(payment_request_resource) 68 | logging.info("Request creation: %s", request_creation) 69 | 70 | redirected_url = read_redirected_url(request_creation.links.consent_approval.href, REDIRECT_URL) # calling helper functions for CLI interaction 71 | auth_api = enablebanking.AuthApi(api_client) # Create authentication interface. 72 | parsed_query_params = auth_api.parse_redirect_url(redirected_url) 73 | logging.info("Query params: %s", parsed_query_params) 74 | 75 | payment_request_confirmation = pisp_api.make_payment_request_confirmation( 76 | request_creation.payment_request_resource_id, 77 | confirmation=enablebanking.PaymentRequestConfirmation( 78 | psu_authentication_factor=parsed_query_params.code 79 | )) 80 | logging.info("Payment request confirmation: %s", payment_request_confirmation) 81 | 82 | 83 | if __name__ == "__main__": 84 | main() 85 | --------------------------------------------------------------------------------