Skip to content

Commit

Permalink
update module
Browse files Browse the repository at this point in the history
  • Loading branch information
Lh4cKg committed Sep 9, 2020
1 parent 259f38e commit 3b13d24
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 103 deletions.
2 changes: 1 addition & 1 deletion docs/tbc.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class MyTBCProvider(TBCProvider):
return 'xx.xx.xx.xx'

@property
def merchant_url(self) -> str:
def service_url(self) -> str:
return 'https://ecommerce.ufc.ge:18443/ecomm2/MerchantHandler'

@property
Expand Down
2 changes: 1 addition & 1 deletion geopayment/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from geopayment.providers import TBCProvider, IPayProvider

__version__ = '0.3.2'
__version__ = '0.4.0'
29 changes: 13 additions & 16 deletions geopayment/providers/bog/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from base64 import b64encode
from typing import Optional, Any, Dict

from geopayment.providers.utils import bog_request
from geopayment.providers.utils import _request, bog_params


__all__ = ['IPayProvider']
Expand Down Expand Up @@ -76,8 +76,8 @@ def get_credentials(self) -> bytes:

class IPayProvider(BaseIPayProvider):

@bog_request(verify=True, timeout=(3, 10), endpoint='oauth2/token',
method='post', api='auth')
@bog_params(endpoint='oauth2/token', api='auth')
@_request(verify=True, timeout=(3, 10), method='post')
def get_auth(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
checkout api docs: https://developer.ipay.ge/checkout
Expand All @@ -89,8 +89,8 @@ def get_auth(self, **kwargs: Optional[Any]) -> Dict[str, str]:
self.access = kwargs['result']
return self.access

@bog_request(verify=True, timeout=(3, 10), currency_code='GEL',
endpoint='checkout/orders', method='post', api='checkout')
@bog_params(currency_code='GEL', endpoint='checkout/orders', api='checkout')
@_request(verify=True, timeout=(3, 10), method='post')
def checkout(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
checkout api docs: https://developer.ipay.ge/checkout
Expand All @@ -109,8 +109,8 @@ def checkout(self, **kwargs: Optional[Any]) -> Dict[str, str]:
self.rel_approve = link[0]['href']
return result

@bog_request(verify=True, timeout=(3, 10), endpoint='checkout/refund',
method='post', api='refund')
@bog_params(endpoint='checkout/refund', api='refund')
@_request(verify=True, timeout=(3, 10), method='post')
def refund(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
Expand All @@ -120,9 +120,8 @@ def refund(self, **kwargs: Optional[Any]) -> Dict[str, str]:

return kwargs['result']

@bog_request(verify=True, timeout=(3, 10),
endpoint='checkout/orders/status/{order_id}', method='get',
api='status')
@bog_params(endpoint='checkout/orders/status/{order_id}', api='status')
@_request(verify=True, timeout=(3, 10), method='get')
def checkout_status(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
Expand All @@ -132,9 +131,8 @@ def checkout_status(self, **kwargs: Optional[Any]) -> Dict[str, str]:

return kwargs['result']

@bog_request(verify=True, timeout=(3, 10),
endpoint='checkout/orders/{order_id}', method='get',
api='details')
@bog_params(endpoint='checkout/orders/{order_id}', api='details')
@_request(verify=True, timeout=(3, 10), method='get')
def checkout_details(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
Expand All @@ -144,9 +142,8 @@ def checkout_details(self, **kwargs: Optional[Any]) -> Dict[str, str]:

return kwargs['result']

@bog_request(verify=True, timeout=(3, 10),
endpoint='checkout/payment/{order_id}', method='get',
api='payment')
@bog_params(endpoint='checkout/payment/{order_id}', api='payment')
@_request(verify=True, timeout=(3, 10), method='get')
def payment_details(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
Expand Down
24 changes: 12 additions & 12 deletions geopayment/providers/tbc/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from typing import Dict, Any, Optional, Tuple

from geopayment.providers.utils import tbc_params, tbc_request
from geopayment.providers.utils import _request, tbc_params


__all__ = ['TBCProvider']
Expand All @@ -24,8 +24,8 @@ def __init__(self) -> None:
'`client_ip` must be property, not callable'
assert callable(self.cert) is False, \
'`cert` must be property, not callable'
assert callable(self.merchant_url) is False, \
'`merchant_url` must be property, not callable'
assert callable(self.service_url) is False, \
'`service_url` must be property, not callable'

@property
def description(self) -> str:
Expand Down Expand Up @@ -58,21 +58,21 @@ def cert(self) -> Tuple[str, str]:
)

@property
def merchant_url(self) -> str:
def service_url(self) -> str:
"""
:return: merchant service url
"""
raise NotImplementedError(
'Provider needs implement `merchant_url` function'
'Provider needs implement `service_url` function'
)


class TBCProvider(BaseTBCProvider):

@tbc_params('amount', 'currency', 'client_ip_addr',
'description', command='v', language='ka', msg_type='SMS')
@tbc_request(verify=False, timeout=(3, 10))
@_request(verify=False, timeout=(3, 10), method='post')
def get_trans_id(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
command: Transaction type
Expand All @@ -97,7 +97,7 @@ def get_trans_id(self, **kwargs: Optional[Any]) -> Dict[str, str]:
return result

@tbc_params('trans_id', 'client_ip_addr', command='c')
@tbc_request(verify=False, timeout=(3, 10))
@_request(verify=False, timeout=(3, 10), method='post')
def check_trans_status(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
command: Transaction type
Expand All @@ -124,7 +124,7 @@ def check_trans_status(self, **kwargs: Optional[Any]) -> Dict[str, str]:
return kwargs['result']

@tbc_params('trans_id', 'amount', command='r')
@tbc_request(verify=False, timeout=(3, 10))
@_request(verify=False, timeout=(3, 10), method='post')
def reversal_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
command: Transaction type
Expand All @@ -146,7 +146,7 @@ def reversal_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:
return kwargs['result']

@tbc_params('trans_id', 'amount', command='k')
@tbc_request(verify=False, timeout=(3, 10))
@_request(verify=False, timeout=(3, 10), method='post')
def refund_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
command: Transaction type
Expand All @@ -170,7 +170,7 @@ def refund_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:

@tbc_params('amount', 'currency', 'client_ip_addr', 'description',
command='a', language='ka', msg_type='DMS')
@tbc_request(verify=False, timeout=(3, 10))
@_request(verify=False, timeout=(3, 10), method='post')
def pre_auth_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
command: Transaction type
Expand All @@ -195,7 +195,7 @@ def pre_auth_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:

@tbc_params('trans_id', 'amount', 'currency', 'client_ip_addr',
'description', command='t', language='ka', msg_type='DMS')
@tbc_request(verify=False, timeout=(3, 10))
@_request(verify=False, timeout=(3, 10), method='post')
def confirm_pre_auth_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
command: Transaction type
Expand All @@ -222,7 +222,7 @@ def confirm_pre_auth_trans(self, **kwargs: Optional[Any]) -> Dict[str, str]:
return kwargs['result']

@tbc_params(command='b')
@tbc_request(verify=False, timeout=(3, 10))
@_request(verify=False, timeout=(3, 10), method='post')
def end_of_business_day(self, **kwargs: Optional[Any]) -> Dict[str, str]:
"""
command: Transaction type
Expand Down
129 changes: 63 additions & 66 deletions geopayment/providers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import json
from decimal import Decimal, ROUND_UP
from functools import wraps
from typing import Dict, Any

import requests


Expand Down Expand Up @@ -82,6 +84,57 @@ def get_currency_code(code):
return ALLOW_CURRENCY_CODES[code]


def _request(**kw):
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
request_params: Dict[str, Any] = dict()
for k, v in kw.items():
if k in kwargs:
continue
kwargs[k] = v

klass = args[0]
method = kwargs['method']
request_params['url'] = kwargs.get('url', klass.service_url)
request_params['method'] = method
request_params.update(kwargs['payload'])
request_params['headers'] = kwargs.get('headers')
request_params['verify'] = kwargs['verify']
request_params['timeout'] = kwargs['timeout']
request_params['cert'] = getattr(klass, 'cert', None)
if method == 'get':
request_params['allow_redirects'] = True

try:
resp = requests.request(**request_params)
if resp.status_code == 200:
try:
result = resp.json()
except (ValueError, json.decoder.JSONDecodeError):
result = parse_response(resp.text)
except Exception:
result = resp.text
else:
try:
result = resp.json()
except (ValueError, json.decoder.JSONDecodeError):
result = {
'RESULT': resp.text,
'STATUS_CODE': resp.status_code,
}
except requests.exceptions.RequestException as e:
result = {
'RESULT': str(e)
}

return f(result=result, *args, **kwargs)

return wrapped

return wrapper


def tbc_params(*arg_params, **kwarg_params):
"""
Decorator that pops all accepted parameters from method's kwargs and puts
Expand Down Expand Up @@ -116,48 +169,14 @@ def wrapped(*a, **kw):
payload[param] = gel_to_tetri(kw[param])
else:
payload[param] = kw[param]
return f(payload=payload, *a, **kw)
return f(payload={'data': payload}, *a, **kw)

return wrapped

return wrapper


def tbc_request(**kw):

def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
for k, v in kw.items():
if k in kwargs:
continue
kwargs[k] = v
klass = args[0]
try:
resp = requests.post(
klass.merchant_url, data=kwargs['payload'],
verify=kwargs['verify'], timeout=kwargs['timeout'],
cert=klass.cert
)
if resp.status_code == 200:
result = parse_response(resp.text)
else:
result = {
'RESULT': resp.text,
'STATUS_CODE': resp.status_code,
}
except requests.exceptions.RequestException as e:
result = {
'RESULT': str(e)
}
return f(result=result, *args, **kwargs)

return wrapped

return wrapper


def bog_request(**kw):
def bog_params(**kw):
"""
:param kw:
:return:
Expand All @@ -172,7 +191,7 @@ def wrapped(*args, **kwargs):
kwargs[k] = v

klass = args[0]
data, headers, request_params = dict(), dict(), dict()
data, headers, payload = dict(), dict(), dict()
endpoint = kw['endpoint']
api = kw['api']
if api == 'auth':
Expand All @@ -184,7 +203,7 @@ def wrapped(*args, **kwargs):
data['grant_type'] = kwargs['grant_type']
else:
data['grant_type'] = 'client_credentials'
request_params.update({'data': data})
payload.update({'data': data})
elif api == 'checkout':
headers['accept'] = 'application/json'
headers['Content-Type'] = 'application/json'
Expand Down Expand Up @@ -230,7 +249,7 @@ def wrapped(*args, **kwargs):
'industry_type': 'ECOMMERCE'
}
]
request_params.update({'json': data})
payload.update({'json': data})
elif api == 'refund':
if 'order_id' not in kwargs:
raise ValueError(
Expand All @@ -246,7 +265,7 @@ def wrapped(*args, **kwargs):
}
headers['accept'] = 'application/json'
headers['Content-Type'] = 'application/x-www-form-urlencoded'
request_params.update({'data': data})
payload.update({'data': data})
elif api in ('status', 'details', 'payment'):
if 'order_id' not in kwargs:
raise ValueError(
Expand All @@ -273,34 +292,12 @@ def wrapped(*args, **kwargs):
)
headers['Authorization'] = f'Bearer {access_token}'

request_params.update({
'method': kw['method'],
kwargs = {
'url': f'{klass.service_url}{endpoint}',
'headers': headers,
'verify': kwargs['verify'],
'timeout': kwargs['timeout']
})

if kw['method'] == 'get':
request_params.setdefault('allow_redirects', True)
'headers': headers
}

try:
resp = requests.request(**request_params)
if resp.status_code == 200:
result = resp.json()
else:
try:
result = resp.json()
except (ValueError, json.decoder.JSONDecodeError):
result = {
'RESULT': resp.text,
'STATUS_CODE': resp.status_code,
}
except requests.exceptions.RequestException as e:
result = {
'RESULT': str(e)
}
return f(result=result, *args, **kwargs)
return f(payload=payload, *args, **kwargs)

return wrapped

Expand Down
Loading

0 comments on commit 3b13d24

Please sign in to comment.