class LibToken(object): def __init__(self): self.variable = LibVar() self.ACCOUNT = self.variable.get_var('SALES_ACCOUNT') self.PASSWORD = self.variable.get_var('SALES_PASSWORD') if self.variable.get_var('ENV') == 'dev': self.token = '.DevSalesAuth' elif self.variable.get_var('ENV') == 'swqa': self.token = '.DevSalesAuth' else: self.token = '.PaSalesAuth' self.SESSION = requests.Session() self.SESSION.headers.update({'content-type': 'application/json'}) # --------------------------------------------------------------------------- def get_sp_token(self, account=None, password=None): """Get SP token""" if account is None and password is None: account = self.ACCOUNT password = self.PASSWORD resp = LibAccountLogin().account_login_post(account, password) token = re.findall("{}=[\w\S]+".format(self.token), resp.headers['Set-Cookie'])[0] return token
class LibBase(object): def __init__(self, host='BILLING_WEB_HOST', billing_account='BILLING_ADMIN_ACCOUNT', billing_password='******'): ''' Note: - default host is `BILLING_WEB_HOST` ''' self.BuiltIn = BuiltIn() self.LibAuth = LibAuth() self.LibVar = LibVar() self.HOST = self.LibVar.get_var(host) self.BILLING_ACCOUNT = self.LibVar.get_var(billing_account) self.BILLING_PASSWORD = self.LibVar.get_var(billing_password) self.SESSION = requests.Session() self.TOKEN = None self.SESSION.headers.update({ 'content-type': 'application/json' }) self.HOST = 'http://{}'.format(self.HOST) def authHeader(self, billing_cookie): if billing_cookie == None: self.SESS = self.LibAuth.api_auth_login(self.BILLING_ACCOUNT, self.BILLING_PASSWORD) else: self.SESS = billing_cookie self.SESSION.headers.update({'cookie': self.SESS}) def request(self, method, append='', **kwargs): ''' method: e.g.: get post put delete append: e.g.: /api/engine/job-status ''' url = self.HOST + append resp = self.SESSION.request(method, url, **kwargs, timeout=(3,3)) if method == 'get': request_message = ( ''' Response message: {} CURL: \ncurl -i --request {} --url {}{} --hearder {} '''.format(resp.text, resp.request.method, self.HOST, append, resp.request.headers) ) else: request_message = ( ''' Response message: {} CURL: \ncurl -i --request {} --url {}{} --data '{}' --hearder {} '''.format(resp.text, resp.request.method, self.HOST, append, resp.request.body, resp.request.headers) ) print (request_message) return resp
class LibCrypto(object): def __init__(self, salt='SALT'): self.LibVar = LibVar() self.SALT = self.LibVar.get_var(salt) def encode_hashid(self, encode_id): if isinstance(encode_id, int) is False: encode_id = int(encode_id) hash_ids = Hashids(salt='{}'.format(self.SALT), min_length=8, alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') hash_id = hash_ids.encode(encode_id) return hash_id def decode_encodeid(self, hash_id): # if isinstance(encode_id, int) is False: # encode_id = int(encode_id) hash_ids = Hashids(salt='{}'.format(self.SALT), min_length=8, alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') encode_id = hash_ids.decode(hash_id) return encode_id[0] @staticmethod def encode_text_with_base64(text, algorithms): m = None if algorithms == 'sha256': m = hashlib.sha256() elif algorithms == 'sha512': m = hashlib.sha512() m.update(bytes(text, encoding='utf-8')) crypto_text = str(base64.b64encode(m.digest()), encoding='utf-8') return crypto_text
class LibJSONSchema: def __init__(self): self.variable = LibVar() self.schema_location = self.variable.get_var( 'PAYMENT_GATEWAY_SCHEMA_PATH') def load_json_schema(self, filename): """ Loads the given schema file """ absolute_path = '{}/{}'.format(self.schema_location, filename) with open(absolute_path) as schema_file: schemas_file = schema_file.read() return jsonref.loads(schemas_file, jsonschema=True) def verify_schema(self, schema_filename, schema_name, sample, status_code=None): """Validates the sample JSON against the given schema.""" schema = self.load_json_schema(schema_filename) if status_code is None: schema = schema[schema_name] else: schema = schema[schema_name][status_code] try: jsonschema.validate(sample, schema) except jsonschema.ValidationError as e: print(sample) raise jsonschema.ValidationError( 'Validation error for schema {}: {}'.format( schema_name, e.message))
class LibAuth(object): def __init__(self): self.LibVar = LibVar() self.HOST = self.LibVar.get_var('BILLING_WEB_HOST') self.HOST = 'http://{}'.format(self.HOST) self.SESSION = requests.Session() self.SESSION.headers.update({ 'content-type': 'application/json' }) def __request(self, method, append='', **kwargs): print("Method: {}, uri: {}{}".format(method, self.HOST, append)) return self.SESSION.request(method, self.HOST + append, **kwargs) # --------------------------------------------------------------------------- def api_auth_login(self, user_name, user_password): """ Get billing-mgmt cookie """ data = { "username": user_name, "password": user_password } resp = self.__request('post', "/api/auth/login", json=data) billing_cookie = re.findall("billingMgmt=[\w\S]+", resp.headers['Set-Cookie'])[0] return billing_cookie
class LibBase(object): def __init__(self, host='MYGOGORO_GN_HOST'): ''' usage: __dirname = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(__dirname, '../../lib')) from _init_ import _init_ self.init = _init_() Note: - default host is `MYGOGORO_GN_HOST` ''' self.BuiltIn = BuiltIn() self.LibCSRF = LibCSRF() self.LibVar = LibVar() self.HOST = self.LibVar.get_var(host) self.SESSION = requests.Session() self.TOKEN = None self.SESSION.headers.update({ 'content-type': 'application/json' }) self.HOST = 'https://{}'.format(self.HOST) def authHeader(self, gogoro_sess, csrf_token): if gogoro_sess == None and csrf_token == None: self.SESS, self.TOKEN = self.LibCSRF.CSRF_login_get() self.SESSION.headers.update({'cookie': self.SESS}) self.SESSION.headers.update({'x-xsrf-token': self.TOKEN}) else: self.SESSION.headers.update({'cookie': gogoro_sess}) self.SESSION.headers.update({'x-xsrf-token': csrf_token}) def request(self, method, append='', **kwargs): ''' method: e.g.: get post patch delete append: e.g.: /scooter **kwargs: e.g.: data={"scooter":"qa"} ''' print (self.HOST) url = self.HOST + append resp = self.SESSION.request(method, url, **kwargs, timeout=(14, 14)) if method == 'get': request_message = ( ''' Response message: {} CURL: \ncurl -i --request {} --url {}{} --hearder {} '''.format(resp.text, resp.request.method, self.HOST, append, resp.request.headers) ) else: request_message = ( ''' Response message: {} CURL: \ncurl -i --request {} --url {}{} --data '{}' --hearder {} '''.format(resp.text, resp.request.method, self.HOST, append, resp.request.body, resp.request.headers) ) print (request_message) return resp
class LibCSRF(object): def __init__(self): self.LibVar = LibVar() self.env = self.LibVar.get_var('ENV') self.HOST = self.LibVar.get_var('MYGOGORO_GN_HOST') self.HOST = 'https://{}'.format(self.HOST) self.SESSION = requests.Session() self.SESSION.headers.update({'content-type': 'application/json'}) def __request(self, method, append='', **kwargs): print("Method: {}, uri: {}{}".format(method, self.HOST, append)) return self.SESSION.request(method, self.HOST + append, **kwargs) # --------------------------------------------------------------------------- def CSRF_login_get(self): """ Get google-sess cookie and xsrf token info """ resp = self.__request('get', "/login") gogoro_sess = re.findall("{}_gogoro-sess=[\w\S]+".format(self.env), resp.headers['Set-Cookie'])[0] csrf_token = re.findall("csrf-token=[\w\S]+", resp.headers['Set-Cookie'])[0] csrf_token = csrf_token.split('=')[1].replace(';', '') return gogoro_sess, csrf_token
class SetUpUser: def __init__(self, user_type, password): if user_type == 'new_user': rf_string = String() # RF Library self.time = int(time.time()) self.company_code = 1300 self.status = 1 self.enable_e_carrier = 1 self.country_code = 'TW' self.gender = 'M' self.gogoro_guid = str(uuid.uuid4()) self.first_name = rf_string.generate_random_string(5, '[UPPER]') self.last_name = rf_string.generate_random_string(5, '[UPPER]') self.display_name = self.last_name + self.first_name self.email = 'pasw.verify-{}@yopmail.com'.format(self.time) self.mobile = '09' + rf_string.generate_random_string( 8, '[NUMBERS]') self.profile_id = 'A1' + rf_string.generate_random_string( 8, '[NUMBERS]') self.encode_password = password self.birthday = time.strftime("%Y-%m-%d") self.contact_city = '臺北市' self.contact_district = '松山區' self.contact_zipcode = '10552' self.contact_address = '長安東路二段225號C棟11樓' self.phone = self.mobile self.occupation = '1' self.invoice_city = '臺北市' self.invoice_district = '松山區' self.invoice_zipcode = '10552' self.invoice_address = '長安東路二段225號C棟11樓' else: self.variable = LibVar() self.encode_password = password self.email = self.variable.get_var('PAYMENT_GATEWAY_ACCOUNT') self.gogoro_guid = self.variable.get_var('PAYMENT_GATEWAY_GUID')
class LibAccountLogin(object): def __init__(self): self.init = LibBase() self.variable = LibVar() self._env = self.variable.get_var('ENV') if self._env != 'prod': self.init.sales_portal_cipher_get() # --------------------------------------------------------------------------- def account_login_post(self, user_id, password, session_id=None, recaptcha_response=None, two_factor_source=0, otp_code=None, remember_device=True, browser_info=None, token=None): """login sales portal Args: user_id (str): sales account password (str): sales password two_factor_source (int): flag to check use 2FA login or not, default as 0 otp_code (str): code for 2FA login remember_device (bool): flag to check next time login should use 2FA confirmation or not browser_info (str): record browser type Return: resp: Return json object Examples: | Account Login Post | PAYLOAD | """ data = { "UserID": user_id, "Password": password, "SessionId": session_id, "RecaptchaResponse": recaptcha_response, "TwoFactorSource": two_factor_source, "OtpCode": otp_code, "RememberDevice": remember_device, "BrowserInfo": browser_info } resp = self.init.request('post', '/account/login', json=data) return resp
class _init_(object): def __init__(self, protocol='PROTOCOL', host='DATAPLATFORM_HOST', port='DATAPLATFORM_PORT', basepath='GO_AUTH_BASEPATH', client_header='GO_CLIENT_HEADER', timeout='PLATFORM_API_TIMEOUT'): ''' usage: __dirname = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(__dirname, '../../lib')) from _init_ import _init_ self.init = _init_() Note: - default host is `DATAPLATFORM_HOST` and basepath is `/go-platform/v1` - if need to use other host, please follow below example: `self.init = _init_('Other_URL', '/api/v1')` ''' self.LibAppCipher = LibAppCipher() self.LibVar = LibVar() self.PROTOCOL = self.LibVar.get_var(protocol) self.PORT = self.LibVar.get_var(port) self._BASEPATH = self.LibVar.get_var(basepath) self.GO_CLIENT_HEADER = self.LibVar.get_var(client_header) self.TIMEOUT = self.LibVar.get_var(timeout) self.HOST = self.LibVar.get_var(host) self.HOST = '{}://{}:{}{}'.format(self.PROTOCOL, self.HOST, self.PORT, self._BASEPATH) self.SESSION = requests.Session() self.TOKEN = None self.SESSION.headers.update({ 'content-type': 'application/json', 'Go-client': '{}'.format(self.GO_CLIENT_HEADER) }) def auth_header(self, account): self.TOKEN = self.LibAppCipher.app_cipher_get(account) authorization = '{}'.format(self.TOKEN) self.SESSION.headers.update( {'Authorization': 'Bearer {}'.format(authorization)}) def request(self, method, append='', **kwargs): ''' method: e.g.: get post patch delete append: e.g.: /scooter **kwargs: e.g.: data={"scooter":"qa"} ''' url = self.HOST + append resp = self.SESSION.request( method, url, **kwargs, timeout=self.TIMEOUT) try: tags = BuiltIn().get_variable_value("${TEST_TAGS}") except: tags = [] pass body = json.loads(resp.request.body.decode()) body = json.dumps(body, indent=4) resp_msg = json.loads(resp.text) resp_msg = json.dumps(resp_msg, indent=4) request_msg = ( "Response message: {resp_status_code}\n" "Body: {resp_msg}\n" "CURL:\n" " curl -i --request {method} --url {url} \\\n" " --header 'Authorization: {token}' \\\n" " --header 'content-type: {content_type}' --header 'go-client: {go_client}' \\\n" " --data '{body}'" ).format( resp_status_code=resp.status_code, resp_msg=resp_msg, method=resp.request.method, url=(self.HOST + append), token=resp.request.headers['Authorization'], content_type=resp.request.headers['Content-Type'], go_client=resp.request.headers['Go-client'], body=body ) if ('code' not in resp.json().keys() or resp.json()['code'] != 0) and 'FET' not in tags: raise AssertionError( "FYI: If the API request is failed, please refer to the following information \n{}".format( request_msg) ) else: logger.write(request_msg) return resp
class LibAppCipher(object): def __init__(self): self.LibVar = LibVar() self.CIPHER_HOST = self.LibVar.get_var('CIPHER_HOST') self.PORT = self.LibVar.get_var('CIPHER_PORT') self.CIPHER_DEV = self.LibVar.get_var('CIPHER_DEV') self.CIPHER_APP = self.LibVar.get_var('CIPHER_APP') self.CIPHER_RESOURCE = self.LibVar.get_var('CIPHER_RESOURCE') self.CIPHER_PASSWORD = self.LibVar.get_var('CIPHER_PASSWORD') self.CIPHER_ACCOUNT = self.LibVar.get_var('CIPHER_GEN_ACCOUNT') self.SESSION = requests.Session() self.SESSION.headers.update({'content-type': 'application/json'}) # --------------------------------------------------------------------------- def app_cipher_get(self, account, **kwargs): """ Get cipher token Args: account(str): [email protected] (default) cipher_app(str): dev (default) cipher_resource(str): dev (default) ciphe_pwd(str): 123 (default) """ host = self.CIPHER_HOST port = self.PORT env = self.CIPHER_DEV cipher_app = kwargs.get('cipher_app', self.CIPHER_APP) cipher_resource = kwargs.get('cipher_resource', self.CIPHER_RESOURCE) password = kwargs.get('cipher_pwd', self.CIPHER_PASSWORD) if account is None: account = self.CIPHER_ACCOUNT cipher_request = (f"http://{host}:{port}/app/cipher?" f"env={env}&" f"app={cipher_app}&" f"resource={cipher_resource}&" f"username={account}&" f"password={password}") resp = self.SESSION.request('get', cipher_request) if resp.status_code == 200: logger.write(cipher_request) token = resp.text return token else: raise AssertionError("Get cipher error: \n" "status code: {}\n" "api request: {}\n".format( resp.status_code, cipher_request)) def encode_password_get(self, password): """ encode password """ resp = self.SESSION.request( 'get', "http://{}:3031/encrypt/level1?plaintext={}".format( self.CIPHER_HOST, password)) return resp
class LibPaymentActions: def __init__(self): self.variable = LibVar() self.log_host = self.variable.get_var('LOG_SERVER_HOST') self.log_account = self.variable.get_var('LOG_SERVER_ACCOUNT') self.log_password = self.variable.get_var('LOG_SERVER_PASSWORD') self.calender = self.variable.get_var('PAYMENT_GATEWAY_CALENDER') @staticmethod def get_credit_card_and_delete(user_id, wallet_id, credit_card_number): credit_card_id = None auth = LibAppCipher().app_cipher_get(account=None) response = Wallet() get_json = response.get_credit_cards(wallet_id, auth).json() for i in get_json['data']: if i['credit_card_number'] == credit_card_number: credit_card_id = i['credit_card_id'] if credit_card_id is None: raise Exception('The credit card is not activate') delete_json = response.delete_credit_cards(wallet_id, user_id, credit_card_id, auth).json() if delete_json['code'] != 0: raise Exception('Delete user_id: {} wallet_id:{} credit_card_number:{} is failure' .format(user_id, wallet_id, credit_card_number)) def get_logs(self, log_text): ssh = LibSSHCommand(self.log_host, self.log_account, self.log_password) logs = ssh.exec_command('cd services/;docker-compose logs --tail=10') if log_text in logs: return True else: return False def get_working_day(self, days, date_format): """ Get working day depends on the calender """ holiday = {} with open(self.calender, 'r') as file: data = json.loads(file.read()) for i in data['result']['records']: holiday[i['date']] = i['isHoliday'] count = 1 while True: working_date = (date.today() - timedelta(days=count)).strftime('%Y/%-m/%-d') if working_date in holiday and holiday[working_date] == '否' or working_date not in holiday: days -= 1 if days == 0: break count += 1 working_date = datetime.strptime(working_date, '%Y/%m/%d').strftime(date_format) return working_date @staticmethod def get_timestamp_interval(days): if isinstance(days, str): days = int(days) today = date.today() calculate_days = today + timedelta(days=days) from_time = datetime.combine(calculate_days, time.min).strftime('%s') to_time = datetime.combine(calculate_days, time.max).strftime('%s') return {'from_time': from_time, 'to_time': to_time} @staticmethod def replace_ach_file(source_file, target_file, **kwargs): with open(source_file, 'r', newline='') as file: file_data = file.read() for key, value in kwargs.items(): file_data = file_data.replace(key, value) with open(source_file, 'w', newline='') as file: file.write(file_data) os.rename(source_file, target_file) # args should put the account_num, bank_barcode1, r_code @staticmethod def replace_ach_p01_file(source_file, target_file, *args: list): with open(source_file, 'r', newline='') as file: lines = file.readlines() with open(source_file, 'w', newline='') as file: for line_index in range(len(lines)): if line_index == 0: first_line_r1 = re.search(r'^BOFACHP01(\d{14})81200129990250', lines[0]).group(1) lines[line_index] = lines[line_index].replace(lines[line_index], 'BOFACHR01' + first_line_r1 + '99902508120012' + ' ' * 123 + '\r\n') file.write(lines[line_index]) elif line_index == len(lines) - 1: last_line_r = re.search(r'^EOFACHP01(\d{8})81200129990250(\d{8})(\d{16})', lines[len(lines) - 1]) last_line_r1 = last_line_r.group(1) last_line_r2 = last_line_r.group(2) last_line_r3 = last_line_r.group(3) lines[line_index] = lines[line_index].replace(lines[line_index], 'EOFACHR01' + last_line_r1 + '99902508120012' + last_line_r2 + last_line_r3 + ' ' * 105) file.write(lines[line_index]) else: for element in args: if len(element) != 3: raise Exception('The input data is invalid!') account_num = element[0] bank_barcode1 = element[1] r_code = element[2] middle_line_r = re.search( r'^NSD(\d{9})8120012(\d{14})(812\d{4})(\d{14})(0000000060)00B54387162\s{2}' + account_num + '\s{6}0{14}\s' + bank_barcode1, lines[line_index]) middle_line_r1 = middle_line_r.group(1) middle_line_r2 = middle_line_r.group(2) middle_line_r3 = middle_line_r.group(3) middle_line_r4 = middle_line_r.group(4) middle_line_r5 = middle_line_r.group(5) lines[line_index] = lines[line_index].replace(lines[line_index], 'RSD' + middle_line_r1 + middle_line_r3 + middle_line_r4 + '8120012' + middle_line_r2 + middle_line_r5 + r_code + 'B54387162 ' + account_num + ' ' * 6 + '0' * 14 + ' ' + bank_barcode1 + ' ' * 36 + '\r\n') file.write(lines[line_index]) os.rename(source_file, target_file) @staticmethod def filter_get_card_page_info(card_number, expired_date, auth_url): """ card number: 3565580700005806 will split to card_no1 ~ card_no4 expired date: 4112 will split to expired_year and expired_month binding card will get the auth_url and will split to trans_id """ bank_info = {} card_no1, card_no2, card_no3, card_no4 = card_number[0:4], card_number[4:8], card_number[8:12], card_number[ 12:16] expired_year, expired_month = re.search('([0-9][0-9])([0-9][0-9])', expired_date).group(1, 2) trans_id = re.search('(.*)?id=(.*)', auth_url).group(2) bank_info.update({'card_no1': card_no1, 'card_no2': card_no2, 'card_no3': card_no3, 'card_no4': card_no4, 'expired_year': expired_year, 'expired_month': expired_month, 'trans_id': trans_id}) return bank_info
class Base: def __init__(self): self.variable = LibVar() self.pg_url = self.variable.get_var('PAYMENT_GATEWAY_URL') self.bind_card_url = self.variable.get_var('EXTERNAL_BANK_URL') self.tspg_url = None self.scheduler_url = self.variable.get_var('BILLING_SCHEDULER_URL') self.timeout = self.variable.get_var('API_TIMEOUT') self.headers = { 'Content-Type': 'application/json' } def pg_post(self, end_point, data, auth=None): api_request = None try: if auth is not None: self.headers.update({'Authorization': 'bearer {}'.format(auth)}) host = self.pg_url + end_point payload = json.dumps(data) api_request = requests.post(host, headers=self.headers, data=payload, timeout=self.timeout) logger.info('{} status_code is {}, payload is {}, auth is {} and the response json is {}'.format( end_point, api_request.status_code, data, auth, api_request.json())) api_request.close() except JSONDecodeError: logger.info('{} status_code is {}, payload is {}, auth is {} and the response text is {}'.format( end_point, api_request.status_code, data, auth, api_request.text)) except ReadTimeout: logger.info('HTTPSConnectionPool Read Timeout, payload is {}, auth is {}'.format( data, auth)) except Exception as ex: logger.exception(ex) return api_request def pg_request(self, method, end_point, data, auth=None): api_request = None try: if auth is not None: self.headers.update({'Authorization': 'bearer {}'.format(auth)}) host = self.pg_url + end_point payload = json.dumps(data) api_request = requests.request(method, host, headers=self.headers, data=payload, timeout=self.timeout) logger.info('{} status_code is {}, payload is {}, auth is {} and the response json is {}'.format( end_point, api_request.status_code, data, auth, api_request.json())) api_request.close() except JSONDecodeError: logger.info('{} status_code is {}, payload is {}, auth is {} and the response text is {}'.format( end_point, api_request.status_code, data, auth, api_request.text)) except ReadTimeout: logger.info('HTTPSConnectionPool Read Timeout, payload is {}, auth is {}'.format( data, auth)) except Exception as ex: logger.exception(ex) return api_request def scheduler_request(self, method, end_point, auth, data=None): api_request = None try: if auth is not None: self.headers.update({ 'Authorization': 'bearer {}'.format(auth), 'Go-Client': self.variable.get_var('GO_CLIENT_HEADER') }) host = self.scheduler_url + end_point if data is None: api_request = requests.request(method, host, headers=self.headers, timeout=self.timeout) else: payload = json.dumps(data) api_request = requests.request(method, host, headers=self.headers, data=payload, timeout=self.timeout) logger.info('{} status_code is {}, payload is {}, auth is {} and the response json is {}'.format( end_point, api_request.status_code, data, auth, api_request.json())) api_request.close() except JSONDecodeError: logger.info('{} status_code is {}, payload is {}, auth is {} and the response text is {}'.format( end_point, api_request.status_code, data, auth, api_request.text)) except ReadTimeout: logger.info('HTTPSConnectionPool Read Timeout, auth is {}'.format(auth)) except Exception as ex: logger.exception(ex) return api_request def external_request(self, method, end_point, data=None): api_request = None try: if data is None: api_request = requests.request(method, self.tspg_url) else: host = self.bind_card_url + end_point if self.headers['Content-Type'] == 'application/json': payload = json.dumps(data) else: payload = data api_request = requests.request(method, host, headers=self.headers, data=payload) logger.info('{} status_code is {}, payload is {} and the response text is {}'.format( end_point, api_request.status_code, data, api_request.text)) api_request.close() except Exception as ex: logger.exception(ex) return api_request def multiprocess_pg_post(self, count, end_point, data, auth=None): pool = multiprocessing.Pool(processes=count) result = [] for i in range(count): result.append(pool.apply_async(self.pg_post, args=(end_point, data[i], auth))) pool.close() pool.join() return result
class LibBase(object): def __init__(self, protocol='https', host='SALES_PORTAL_API_URL', basepath='/api', timeout='API_TIMEOUT'): self.variable = LibVar() self.HOST = self.variable.get_var(host) self.HOST = '{}://{}{}'.format(protocol, self.HOST, basepath) self.GO_CLIENT_HEADER = 'sales_portal' self.timeout = self.variable.get_var(timeout) self.SESSION = requests.Session() self.CIPHER_HOST = self.variable.get_var('CIPHER_HOST') self.PORT = self.variable.get_var('CIPHER_PORT') self.CIPHER_DEV = self.variable.get_var('CIPHER_DEV') self.CIPHER_APP = 'sales_portal' self.CIPHER_RESOURCE = 'sales_portal' self.CIPHER_ACCOUNT = self.variable.get_var('SALES_ACCOUNT') self.CIPHER_PASSWORD = self.variable.get_var('SALES_PASSWORD') self.SESSION.headers.update({ 'content-type': 'application/json; charset=utf-8', 'Go-client': '{}'.format(self.GO_CLIENT_HEADER) }) self.token = None # --------------------------------------------------------------------------- def auth(self, token, hash_id=None): if 'Authorization' not in self.SESSION.headers: cipher = self.sales_portal_cipher_get() self.SESSION.headers.update( {'Authorization': 'Bearer {}'.format(cipher)}) if hash_id: token += hash_id self.SESSION.headers.update({'cookie': token}) def dict_to_json_string(self, data): """ Transfer payload from dict to json """ return str(data).replace("\'", "\"").replace("None", "\"\"") def sales_portal_cipher_get(self): """ Get cipher token """ host = self.CIPHER_HOST port = self.PORT env = self.CIPHER_DEV cipher_app = self.CIPHER_APP cipher_resource = self.CIPHER_RESOURCE account = self.CIPHER_ACCOUNT password = self.CIPHER_PASSWORD cipher_request = (f"http://{host}:{port}/app/cipher?" f"env={env}&" f"app={cipher_app}&" f"resource={cipher_resource}&" f"username={account}&" f"password={password}") if self.token is None: resp = self.SESSION.request('get', cipher_request) self.token = resp if resp.status_code == 200: logger.write(cipher_request) token = resp.text return token else: raise AssertionError("Get cipher error: \n" "status code: {}\n" "api request: {}\n".format( resp.status_code, cipher_request)) return resp.text else: return self.token def request(self, method, append='', **kwargs): ''' method: e.g.: get post put append: e.g.: /account/login **kwargs: e.g.: data={"Result":1,"Message":"","MessageCode":"","Data": ...} ''' url = self.HOST + append resp = self.SESSION.request(method, url, **kwargs, timeout=(30, 30)) if method == 'get': request_message = (''' Response message: {} CURL: \ncurl -i --request {} --url {}{} --hearder {} '''.format(resp.text, resp.request.method, self.HOST, append, resp.request.headers)) else: request_message = (''' Response message: {} CURL: \ncurl -i --request {} --url {}{} --data '{}' --hearder {} '''.format(resp.text, resp.request.method, self.HOST, append, resp.request.body, resp.request.headers)) print(request_message) return resp
class LibLocalStorage: def __init__(self): self.variable = LibVar() self.info_yaml = self.variable.get_var('PAYMENT_GATEWAY_LOCAL_STORAGE') def open_yaml(self): with open(self.info_yaml) as file: contents = yaml.safe_load(file) return contents @staticmethod def get_user_info(account_type, key): """ Get the value from key in the user_info.yml """ contents = LibLocalStorage().open_yaml() account_type = account_type.lower() value = contents[account_type][key] return value def update_user_info(self, account_type, response_json, status_code): """ Update the value from key in the user_info.yml """ contents = LibLocalStorage().open_yaml() account_type = account_type.lower() url = response_json['resultData']['prepayId'] if status_code == 200 and 'O2OgwApi' in url: contents[account_type]['card_auth_url'] = url elif status_code == 200 and 'tspgapi' in url: contents[account_type]['3d_verification_url'] = url with open(self.info_yaml, 'w') as file: yaml.dump(contents, file, default_flow_style=False) def update_es_bill_info(self, **kwargs): """ Update the ES bill info in the user_info.yml """ contents = LibLocalStorage().open_yaml() for input_key, input_value in kwargs.items(): for yaml_key in contents['pg_es_bill_info']: if input_key == yaml_key: contents['pg_es_bill_info'][yaml_key] = input_value with open(self.info_yaml, 'w') as file: yaml.dump(contents, file, default_flow_style=False) @staticmethod def get_es_bill_info(): es_bill_dict = {} contents = LibLocalStorage().open_yaml() for yaml_key in contents['pg_es_bill_info']: es_bill_dict[yaml_key] = contents['pg_es_bill_info'][yaml_key] return es_bill_dict @staticmethod def write_multiple_es_bill_info(**kwargs): with open('es_bill.log', 'a') as file: for input_key, input_value in kwargs.items(): file.write(str(input_key) + ':' + str(input_value) + '\n') file.write('----------------------------------------------\n') file.close()