From 303d9f8ccb6499cc8066943fff419c9266607a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ariano=20Fonseca=20=C3=82ngelo?= Date: Tue, 23 Apr 2024 12:48:38 +0100 Subject: [PATCH] v2.1.0 * Minor bugfixes * Improve error handling --- README.md | 43 +++++--- blockbee/BlockBee.py | 201 ++++++----------------------------- blockbee/BlockBeeCheckout.py | 67 ++---------- blockbee/BlockBeeRequests.py | 68 ++++++++++++ blockbee/__init__.py | 3 +- setup.py | 2 +- test.py | 16 +-- 7 files changed, 148 insertions(+), 252 deletions(-) create mode 100644 blockbee/BlockBeeRequests.py diff --git a/README.md b/README.md index bc182ac..d24c915 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,6 @@ For object creation, same parameters as before. You must first call ``getAddress * ``value`` is the value requested to the user in the coin to which the request was done. **Optional**, can be empty if you don't wish to add the value to the QR Code. * ``size`` Size of the QR Code image in pixels. Optional, leave empty to use the default size of 512. -* ``api_key`` is the API Key provided by BlockBee's [dashboard](https://dash.blockbee.io/). > Response is an object with `qr_code` (base64 encoded image data) and `payment_uri` (the value encoded in the QR), see https://docs.blockbee.io/#operation/qrcode for more information. @@ -132,14 +131,13 @@ For object creation, same parameters as before. You must first call ``getAddress ```python from blockbee import BlockBeeHelper -fees = BlockBeeHelper.get_estimate(coin, addresses, priority, api_key) +fees = BlockBeeHelper.get_estimate(coin, addresses, priority) ``` #### Where: * ``coin`` is the coin you wish to check, from BlockBee's supported currencies (e.g 'btc', 'eth', 'erc20_usdt', ...) * ``addresses`` The number of addresses to forward the funds to. Optional, defaults to 1. * ``priority`` Confirmation priority, (check [this](https://support.blockbee.io/article/how-the-priority-parameter-works) article to learn more about it). Optional, defaults to ``default``. -* ``api_key`` is the API Key provided by BlockBee's [dashboard](https://dash.blockbee.io/). > Response is an object with ``estimated_cost`` and ``estimated_cost_usd``, see https://docs.blockbee.io/#operation/estimate for more information. @@ -165,7 +163,7 @@ from blockbee import BlockBeeHelper bb = BlockBeeHelper(coin, own_address, callback_url, params, bb_params, api_key) -conversion = bb.get_conversion(value, from_coin, api_key) +conversion = bb.get_conversion(value, from_coin) ``` #### Where: @@ -173,7 +171,6 @@ conversion = bb.get_conversion(value, from_coin, api_key) * ``coin`` the target currency to convert to, from BlockBee's supported currencies (e.g 'btc', 'eth', 'erc20_usdt', ...) * ``value`` value to convert in `from`. * ``from_coin`` currency to convert from, FIAT or crypto. -* ``api_key`` is the API Key provided by BlockBee's [dashboard](https://dash.blockbee.io/). > Response is an object with ``value_coin`` and ``exchange_rate``, see https://docs.blockbee.io/#operation/convert for more information. @@ -192,12 +189,9 @@ conversion = bb.get_conversion(value, from_coin, api_key) ```python from blockbee import BlockBeeHelper -supportedCoins = BlockBeeHelper.get_supported_coins(api_key) +supportedCoins = BlockBeeHelper.get_supported_coins() ``` -### Where: -* ``api_key`` is the API Key provided by BlockBee's [dashboard](https://dash.blockbee.io/). - > Response is an array with all supported coins. #### Response sample: @@ -382,8 +376,8 @@ If `process` is `false`. { "status": "success", "request_ids": [ - 103227, - 103228 + "42d5245e-0a29-402a-9a7e-355e38f1d81d", + "080a546e-4045-4c73-870c-4d9ec08c9cab" ] } ``` @@ -392,6 +386,23 @@ If `process` is `true`. ```json { "status": "success", + "payout_info": { + "id": "88e5eacc-d5a5-4b8a-8133-e23136151b7c", + "status": "Pending Payment", + "from": "0x18B211A1Ba5880C7d62C250B6441C2400d588589", + "requests": { + "0xA6B78B56ee062185E405a1DDDD18cE8fcBC4395d": "0.5", + "0x18B211A1Ba5880C7d62C250B6441C2400d588589": "0.1" + }, + "total_requested": "0.6", + "total_with_fee": "0.603", + "error": "None", + "blockchain_fee": 0, + "fee": "0.003", + "coin": "bep20_usdt", + "txid": "", + "timestamp": "23/04/2024 11:13:49" + }, "queued": true } ``` @@ -424,7 +435,7 @@ create_payout = BlockBeeHelper.list_payouts(coin, status, page, api_key, payout_ "status": "success", "payouts": [ { - "id": 2460, + "id": "88e5eacc-d5a5-4b8a-8133-e23136151b7c", "status": "Done", "total_requested": "0.6", "total_with_fee": "0.606", @@ -482,7 +493,7 @@ payout = BlockBeeHelper.create_payout_by_ids(api_key, payout_ids) { "status": "success", "payout_info": { - "id": 2461, + "id": "88e5eacc-d5a5-4b8a-8133-e23136151b7c", "status": "Created", "from": "", "requests": { @@ -545,7 +556,7 @@ status = BlockBeeHelper.check_payout_status(api_key, payout_id) { "status": "success", "payout_info": { - "id": 2463, + "id": "88e5eacc-d5a5-4b8a-8133-e23136151b7c", "status": "Done", "from": "0x18B211A1Ba5880C7d62C250B6441C2400d588589", "requests": { @@ -599,6 +610,10 @@ Contact us @ https://blockbee.io/contacts/ #### 2.0.1 * Minor bugfixes +#### 2.1.0 +* Minor bugfixes +* Improve error handling + ### Breaking Changes #### 2.0.0 diff --git a/blockbee/BlockBee.py b/blockbee/BlockBee.py index e714286..927bf02 100644 --- a/blockbee/BlockBee.py +++ b/blockbee/BlockBee.py @@ -1,28 +1,27 @@ -""" -BlockBee's Python Helper -""" - -import requests -import json +from .BlockBeeRequests import BlockBeeRequests as Req from requests.models import PreparedRequest -from urllib.parse import urljoin, urlencode - class BlockBeeHelper: BLOCKBEE_URL = 'https://api.blockbee.io/' BLOCKBEE_HOST = 'api.blockbee.io' def __init__(self, coin, own_address, callback_url, parameters, bb_params, api_key): - if parameters is None: + if not parameters: parameters = {} - if bb_params is None: + if not bb_params: bb_params = {} - if api_key is None: + if not api_key: raise Exception("API Key Missing") + if not callback_url: + raise Exception("Callback URL is Missing") + + if not coin: + raise Exception('Coin is Missing') + self.coin = coin self.own_address = own_address self.callback_url = callback_url @@ -32,9 +31,6 @@ def __init__(self, coin, own_address, callback_url, parameters, bb_params, api_k self.payment_address = '' def get_address(self): - if self.coin is None: - return None - coin = self.coin if self.parameters: @@ -50,20 +46,16 @@ def get_address(self): if self.own_address is not None: params['address'] = self.own_address - _address = BlockBeeHelper.process_request_get(coin, endpoint='create', params=params) - if _address: - self.payment_address = _address['address_in'] - return _address + _address = Req.process_request_get(coin, endpoint='create', params=params) + + self.payment_address = _address['address_in'] - return None + return _address def get_logs(self): coin = self.coin callback_url = self.callback_url - if coin is None or callback_url is None: - return None - if self.parameters: req = PreparedRequest() req.prepare_url(self.callback_url, self.parameters) @@ -74,17 +66,9 @@ def get_logs(self): 'apikey': self.api_key } - _logs = BlockBeeHelper.process_request_get(coin, endpoint='logs', params=params) - - if _logs: - return _logs - - return None + return Req.process_request_get(coin, endpoint='logs', params=params) def get_qrcode(self, value='', size=300): - if self.coin is None: - return None - address = self.payment_address if not address: @@ -99,50 +83,23 @@ def get_qrcode(self, value='', size=300): if value: params['value'] = value - _qrcode = BlockBeeHelper.process_request_get(self.coin, endpoint='qrcode', params=params) - - if _qrcode: - return _qrcode - - return None - - def get_conversion(self, from_coin, value, api_key): - if api_key is None: - raise Exception("API Key Missing") + return Req.process_request_get(self.coin, endpoint='qrcode', params=params) + def get_conversion(self, from_coin, value): params = { 'from': from_coin, 'value': value, - 'apikey': api_key } - _value = BlockBeeHelper.process_request_get(self.coin, endpoint='convert', params=params) - - if _value: - return _value - - return None + return Req.process_request_get(self.coin, endpoint='convert', params=params) @staticmethod - def get_info(coin, api_key): - if api_key is None: - raise Exception("API Key Missing") - - _info = BlockBeeHelper.process_request_get(coin, endpoint='info', params={ - 'apikey': api_key - }) - - if _info: - return _info - - return None + def get_info(coin, api_key=''): + return Req.process_request_get(coin, endpoint='info') @staticmethod - def get_supported_coins(api_key): - if api_key is None: - raise Exception("API Key Missing") - - _info = BlockBeeHelper.get_info('', api_key=api_key) + def get_supported_coins(api_key=''): + _info = BlockBeeHelper.get_info(coin=None) _info.pop('fee_tiers', None) @@ -160,27 +117,15 @@ def get_supported_coins(api_key): @staticmethod def get_estimate(coin, addresses=1, priority='default', api_key=''): - if api_key is None: - raise Exception("API Key Missing") - params = { 'addresses': addresses, - 'priority': priority, - 'apikey': api_key + 'priority': priority } - _estimate = BlockBeeHelper.process_request_get(coin, endpoint='estimate', params=params) - - if _estimate: - return _estimate - - return None + return Req.process_request_get(coin, endpoint='estimate', params=params) @staticmethod def create_payout(coin, payout_requests, api_key, process=False): - if not payout_requests: - raise ValueError('No requests provided') - body = {'outputs': payout_requests} endpoint = 'payout/request/bulk' @@ -188,18 +133,10 @@ def create_payout(coin, payout_requests, api_key, process=False): if process: endpoint = endpoint + '/process' - _payout = BlockBeeHelper.process_request_post(coin, endpoint, api_key, body, True) - - if _payout.get('status') == 'success': - return _payout - - return None + return Req.process_request_post(coin, endpoint, api_key, body, True) @staticmethod - def list_payouts(coin, status = 'all', page = 1, api_key = '', payout_request=False): - if not api_key: - return None - + def list_payouts(coin, status='all', page=1, api_key='', payout_request=False): params = { 'apikey': api_key, 'status': status, @@ -211,24 +148,16 @@ def list_payouts(coin, status = 'all', page = 1, api_key = '', payout_request=Fa if payout_request: endpoint = 'payout/request/list' - _payouts = BlockBeeHelper.process_request_get(coin, endpoint, params) - - if _payouts.get('status') == 'success': - return _payouts - - return None + return Req.process_request_get(coin, endpoint, params) @staticmethod def get_payout_wallet(coin, api_key, balance=False): - wallet = BlockBeeHelper.process_request_get(coin, 'payout/address', {'apikey': api_key}) - - if wallet.get('status') != 'success': - return None + wallet = Req.process_request_get(coin, 'payout/address', {'apikey': api_key}) output = {'address': wallet.get('address')} if balance: - wallet_balance = BlockBeeHelper.process_request_get(coin, 'payout/balance', {'apikey': api_key}) + wallet_balance = Req.process_request_get(coin, 'payout/balance', {'apikey': api_key}) if wallet_balance.get('status') == 'success': output['balance'] = wallet_balance.get('balance') @@ -237,78 +166,12 @@ def get_payout_wallet(coin, api_key, balance=False): @staticmethod def create_payout_by_ids(api_key, payout_ids): - if not payout_ids: - raise ValueError('Please provide the Payout Request(s) ID(s)') - - _payout = BlockBeeHelper.process_request_post('', 'payout/create', api_key, {'request_ids': ','.join(map(str, payout_ids))}) - - if _payout.get('status') == 'success': - return _payout - - return None + return Req.process_request_post('', 'payout/create', api_key, {'request_ids': ','.join(map(str, payout_ids))}) @staticmethod def process_payout(api_key, payout_id): - if not payout_id: - return None - - _process = BlockBeeHelper.process_request_post('', 'payout/process', api_key, {'payout_id': payout_id}) - - if _process.get('status') == 'success': - return _process - - return None + return Req.process_request_post('', 'payout/process', api_key, {'payout_id': payout_id}) @staticmethod def check_payout_status(api_key, payout_id): - if not id: - raise ValueError('Please provide the Payout ID') - - _status = BlockBeeHelper.process_request_post('', 'payout/status', api_key, {'payout_id': payout_id}) - - if _status.get('status') == 'success': - return _status - - return None - - @staticmethod - def process_request_get(coin='', endpoint='', params=None): - if coin != '': - coin += '/' - - response = requests.get( - url="{base_url}{coin}{endpoint}/".format( - base_url=BlockBeeHelper.BLOCKBEE_URL, - coin=coin.replace('_', '/'), - endpoint=endpoint, - ), - params=params, - headers={'Host': BlockBeeHelper.BLOCKBEE_HOST}, - ) - - return response.json() - - @staticmethod - def process_request_post(coin='', endpoint='', apiKey='', body=None, isJson=False): - if coin: - coin_path = coin.replace('_', '/') + '/' - else: - coin_path = '' - - url = urljoin(BlockBeeHelper.BLOCKBEE_URL, f"{coin_path}{endpoint}/") - url += '?' + urlencode({'apikey': apiKey}) - - headers = { - 'Host': BlockBeeHelper.BLOCKBEE_HOST, - } - - if isJson: - headers['Content-Type'] = 'application/json' - data = json.dumps(body) - else: - headers['Content-Type'] = 'application/x-www-form-urlencoded' - data = urlencode(body) - - response = requests.post(url, headers=headers, data=data) - - return response.json() + return Req.process_request_post('', 'payout/status', api_key, {'payout_id': payout_id}) diff --git a/blockbee/BlockBeeCheckout.py b/blockbee/BlockBeeCheckout.py index 9aef0da..b75f0c4 100644 --- a/blockbee/BlockBeeCheckout.py +++ b/blockbee/BlockBeeCheckout.py @@ -1,23 +1,16 @@ -""" -BlockBee's Checkout Python Helper -""" - -import requests from requests.models import PreparedRequest +from .BlockBeeRequests import BlockBeeRequests as Req class BlockBeeCheckoutHelper: - BLOCKBEE_URL = 'https://api.blockbee.io/' - BLOCKBEE_HOST = 'api.blockbee.io' - def __init__(self, api_key, parameters=None, bb_params=None): - if parameters is None: + if not parameters: parameters = {} - if bb_params is None: + if not bb_params: bb_params = {} - if api_key is None: + if not api_key: raise Exception("API Key Missing") self.parameters = parameters @@ -25,9 +18,6 @@ def __init__(self, api_key, parameters=None, bb_params=None): self.api_key = api_key def payment_request(self, redirect_url, value): - if redirect_url is None or value is None: - return None - if self.parameters: req = PreparedRequest() req.prepare_url(redirect_url, self.parameters) @@ -39,31 +29,18 @@ def payment_request(self, redirect_url, value): 'value': value, **self.bb_params} - _request = BlockBeeCheckoutHelper.process_request('', endpoint='checkout/request', params=params) - if _request['status'] == 'success': - return _request - return None + return Req.process_request_get(None, endpoint='checkout/request', params=params) @staticmethod def payment_logs(token, api_key): - if token is None or api_key is None: - return None - params = { 'apikey': api_key, 'token': token } - _request = BlockBeeCheckoutHelper.process_request('', endpoint='checkout/logs', params=params) - - if _request['status'] == 'success': - return _request - return None + return Req.process_request_get(None, endpoint='checkout/logs', params=params) def deposit_request(self, notify_url): - if notify_url is None: - return None - if self.parameters: req = PreparedRequest() req.prepare_url(notify_url, self.parameters) @@ -74,41 +51,13 @@ def deposit_request(self, notify_url): 'apikey': self.api_key, **self.bb_params} - _request = BlockBeeCheckoutHelper.process_request('', endpoint='deposit/request', params=params) - - if _request['status'] == 'success': - return _request - return None + return Req.process_request_get(None, endpoint='deposit/request', params=params) @staticmethod def deposit_logs(token, api_key): - if token is None or api_key is None: - return None - params = { 'apikey': api_key, 'token': token } - _request = BlockBeeCheckoutHelper.process_request('', endpoint='deposit/logs', params=params) - - if _request['status'] == 'success': - return _request - return None - - @staticmethod - def process_request(coin='', endpoint='', params=None): - if coin != '': - coin += '/' - - response = requests.get( - url="{base_url}{coin}{endpoint}/".format( - base_url=BlockBeeCheckoutHelper.BLOCKBEE_URL, - coin=coin.replace('_', '/'), - endpoint=endpoint, - ), - params=params, - headers={'Host': BlockBeeCheckoutHelper.BLOCKBEE_HOST}, - ) - - return response.json() + return Req.process_request_get(None, endpoint='deposit/logs', params=params) diff --git a/blockbee/BlockBeeRequests.py b/blockbee/BlockBeeRequests.py new file mode 100644 index 0000000..d2621e1 --- /dev/null +++ b/blockbee/BlockBeeRequests.py @@ -0,0 +1,68 @@ +import requests +import json + +from urllib.parse import urljoin, urlencode +from requests.exceptions import RequestException + + +class BlockBeeAPIException(Exception): + pass + + +class BlockBeeRequests: + BLOCKBEE_URL = 'https://api.blockbee.io/' + BLOCKBEE_HOST = 'api.blockbee.io' + + @staticmethod + def process_request_get(coin=None, endpoint='', params=None): + if coin: + coin += '/' + else: + coin = '' + + response = requests.get( + url="{base_url}{coin}{endpoint}/".format( + base_url=BlockBeeRequests.BLOCKBEE_URL, + coin=coin.replace('_', '/'), + endpoint=endpoint, + ), + params=params, + headers={'Host': BlockBeeRequests.BLOCKBEE_HOST}, + ) + + response_obj = response.json() + + if response_obj.get('status') == 'error': + raise BlockBeeAPIException(response_obj['error']) + + return response_obj + + @staticmethod + def process_request_post(coin=None, endpoint='', apiKey='', body=None, isJson=False): + if coin: + coin_path = coin.replace('_', '/') + '/' + else: + coin_path = '' + + url = urljoin(BlockBeeRequests.BLOCKBEE_URL, f"{coin_path}{endpoint}/") + url += '?' + urlencode({'apikey': apiKey}) + + headers = { + 'Host': BlockBeeRequests.BLOCKBEE_HOST, + } + + if isJson: + headers['Content-Type'] = 'application/json' + data = json.dumps(body) + else: + headers['Content-Type'] = 'application/x-www-form-urlencoded' + data = urlencode(body) + + response = requests.post(url, headers=headers, data=data) + + response_obj = response.json() + + if response_obj.get('status') == 'error': + raise BlockBeeAPIException(response_obj['error']) + + return response_obj \ No newline at end of file diff --git a/blockbee/__init__.py b/blockbee/__init__.py index e5bc79b..c2227b0 100644 --- a/blockbee/__init__.py +++ b/blockbee/__init__.py @@ -1,2 +1,3 @@ from .BlockBee import BlockBeeHelper -from .BlockBeeCheckout import BlockBeeCheckoutHelper \ No newline at end of file +from .BlockBeeCheckout import BlockBeeCheckoutHelper +from .BlockBeeRequests import BlockBeeRequests \ No newline at end of file diff --git a/setup.py b/setup.py index 4ca9ef4..d071c79 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ name='python-blockbee', - version='2.0.1', + version='2.1.0', packages=find_packages(), diff --git a/test.py b/test.py index 15bd199..6b9b441 100644 --- a/test.py +++ b/test.py @@ -27,12 +27,12 @@ """ Get coin information """ -# print(BlockBeeHelper.get_info('btc', api_key=apikey)) +# print(BlockBeeHelper.get_info('btc')) """ Get all supported coins """ -# print(BlockBeeHelper.get_supported_coins(api_key=apikey)) +# print(BlockBeeHelper.get_supported_coins()) """ Get Logs @@ -47,7 +47,7 @@ """ Get Conversion """ -# print(bb.get_conversion('eur', 100, api_key=apikey)) +# print(bb.get_conversion('eur', 100)) """ Get Estimate @@ -58,7 +58,7 @@ Create Payout """ # print(BlockBeeHelper.create_payout( -# 'polygon_matic', +# 'bep20_usdt', # { # '0xA6B78B56ee062185E405a1DDDD18cE8fcBC4395d': 0.5, # '0x18B211A1Ba5880C7d62C250B6441C2400d588589': 0.1 @@ -70,7 +70,7 @@ """ List Payouts """ -# print(BlockBeeHelper.list_payouts('polygon_matic', api_key=apikey, payout_request=True)) +# print(BlockBeeHelper.list_payouts('polygon_matic', api_key=apikey, payout_request=True, page=1)) """ Get payout wallet @@ -80,17 +80,17 @@ """ Create payout by Payout Request IDs """ -# print(BlockBeeHelper.create_payout_by_ids(api_key=apikey, payout_ids=[52258, 52257])) +# print(BlockBeeHelper.create_payout_by_ids(api_key=apikey, payout_ids=['f43b771d-bb26-4dc5-b6d3-3c276d4043e0', '53af840d-b356-46ab-ad0d-f8e3de80b12a'])) """ Process Payout """ -# print(BlockBeeHelper.process_payout(api_key=apikey, payout_id=2468)) +# (BlockBeeHelper.process_payout(api_key=apikey, payout_id="05d28b9e-5a2e-4aa2-9240-16fd65fbce9c")) """ Check Payout Status """ -# print(BlockBeeHelper.check_payout_status(api_key=apikey, payout_id=2468)) +# print(BlockBeeHelper.check_payout_status(api_key=apikey, payout_id="05d28b9e-5a2e-4aa2-9240-16fd65fbce9c")) ###