import json, os, uuid
from urllib.request import Request, urlopen
from urllib.error import HTTPError

key = os.environ['BANKGATEWAY_API_KEY']
request = Request(
    'https://api.bankgateway.vn/api/v1/lookup',
    data=json.dumps({'bankCode': 'MB', 'accountNumber': '000000000000'}).encode(),
    headers={'X-API-Key': key, 'Content-Type': 'application/json',
             'Idempotency-Key': str(uuid.uuid4())},
    method='POST',
)
try:
    with urlopen(request, timeout=30) as response:
        status, body = response.status, json.load(response)
except HTTPError as error:
    status, body = error.code, json.load(error)

if status == 200 and body.get('success'):
    print(body['data']['accountName'])
elif status == 404 and body.get('error', {}).get('code') == 'NOT_FOUND':
    print('NOT_FOUND')  # Có tính phí theo phương thức thanh toán.
else:
    raise RuntimeError(body.get('error', {}).get('code', f'HTTP_{status}'))
