Skip to content

šŸ”„ Atualização de versĆ£o #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.Python
env/
venv/
build/
develop-eggs/
dist/
Expand Down
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ python:
- "3.7"
- "3.9"
- "3.11"
- "3.12"
- "pypy"
install:
- pip install -r requirements-dev.txt
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ $ pip install efipay
```
## Tested with
```
python 3.11
python 3.12
```
## Basic usage

Expand Down
214 changes: 117 additions & 97 deletions efipay/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,41 @@

from __future__ import unicode_literals
from six import iteritems

import json
import re
import requests
import inspect
import base64
import os
from functools import partial

from .constants import Constants
from .exceptions import MissingParametersError
from .exceptions import UnauthorizedError
from .exceptions import EndpointError
from .exceptions import CertificateError
from .version import *
from .exceptions import (
MissingParametersError,
UnauthorizedError,
EndpointError,
CertificateError
)
from .version import VERSION

from functools import partial

class Endpoints(object):

def __init__(self, options):
super(Endpoints, self).__init__()
self.token = None
self.options = options

def __getattr__(self, name):

self.endpoints = {}
self.cert = False

# seletor de ambiente (sandbox ou produção)
self.urls = {
'production': 'https://api.efipay.com.br/v1',
'sandbox': 'https://api.efipay.com.br/v1'
}
use_sandbox = options.get('sandbox', False)
self.base_url = self.urls['sandbox'] if use_sandbox else self.urls['production']

def __getattr__(self, name):
apis = Constants.APIS
api_names = ['PIX', 'OPEN-FINANCE', 'PAYMENTS', 'OPENING-ACCOUNTS', 'STATEMENT']

Expand All @@ -36,141 +45,152 @@ def __getattr__(self, name):
self.endpoints = apis[api_name]['ENDPOINTS']
self.urls = apis[api_name]['URL']
self.cert = True
break

if name in Constants.APIS['CHARGES']['ENDPOINTS']:
self.endpoints = Constants.APIS['CHARGES']['ENDPOINTS']
self.urls = Constants.APIS['CHARGES']['URL']
self.set_base_url()
return partial(self.request, self.endpoints[name])

if name in apis['CHARGES']['ENDPOINTS']:
self.endpoints = apis['CHARGES']['ENDPOINTS']
self.urls = apis['CHARGES']['URL']
self.cert = False

self.get_url()
return partial( self.request, self.endpoints[name])

self.set_base_url()
return partial(self.request, self.endpoints[name])

def request(self, settings, **kwargs):
raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, name))

def set_base_url(self):
use_sandbox = self.options.get('sandbox', False)
self.base_url = self.urls['sandbox'] if use_sandbox else self.urls['production']

if(self.base_url == ""):
return EndpointError(404)
def request(self, settings, **kwargs):
if not self.base_url:
raise EndpointError(404)

oauth = self.authenticate()

if(oauth == 200):
params = {} if 'params' not in kwargs else kwargs['params']
body = {} if 'body' not in kwargs else kwargs['body']
headers = {} if 'headers' not in kwargs else kwargs['headers']
if oauth == 200:
params = kwargs.get('params', {})
body = kwargs.get('body', {})
headers = kwargs.get('headers', {})

response = self.send(settings, params, body, headers)

try:
response.json()
return response.json()
except:
if(response and response.text != ''):
msg = '{\'code\': ' + str(response.status_code) + ', \'content\': \'' + response.text + '\'}'
return msg
else:
return '{\'code\': ' + str(response.status_code) + '}'
elif(oauth == 404):
return CertificateError(404)
except Exception:
if response is not None and response.text:
return {
'code': response.status_code,
'content': response.text
}
return {'code': response.status_code}

elif oauth == 404:
raise CertificateError(404)
else:
return UnauthorizedError(oauth)

raise UnauthorizedError(oauth)

def send(self, settings, params, body, headersComplement):
def send(self, settings, params, body, headers_complement):
url = self.build_url(settings['route'], params)

if(self.cert):
headers = {
'Authorization': 'Bearer {token}'.format(token=self.token['access_token']),
'Content-Type': 'application/json',
'api-sdk': 'efi-python-{v}'.format(v=VERSION)
}

for (key,value) in headersComplement.items():
headers[key] = value

if 'partner_token' in self.options:
headers['partner-token'] = self.options['partner_token']
cert=self.options['certificate']
return requests.request(settings['method'],url, headers=headers, data=json.dumps(body), cert=cert)
headers = {
'Authorization': 'Bearer {0}'.format(self.token['access_token']),
'api-sdk': 'efi-python-{0}'.format(VERSION),
'Content-Type': 'application/json'
}

headers.update(headers_complement)

if 'partner_token' in self.options:
headers['partner-token'] = self.options['partner_token']

if self.cert:
cert = self.options.get('certificate')
return requests.request(
settings['method'],
url,
headers=headers,
data=json.dumps(body),
cert=cert
)
else:
headers = {
'accept': 'application/json',
'api-sdk': 'efi-python-{v}'.format(v=VERSION),
'Authorization': 'Bearer {token}'.format(token=self.token['access_token'])
}
if 'partner_token' in self.options:
headers['partner-token'] = self.options['partner_token']
return requests.request(settings['method'], url, json=body, headers=headers)
return requests.request(
settings['method'],
url,
headers=headers,
json=body
)

def authenticate(self):
url = self.build_url(self.endpoints['authorize']['route'], {})

if(self.cert):
auth = base64.b64encode((f"{self.options['client_id']}:{self.options['client_secret']}").encode()).decode()
payload = "{\r\n \"grant_type\": \"client_credentials\"\r\n}"
url = self.build_url(self.endpoints['authorize']['route'], {})

if self.cert:
auth_string = '{0}:{1}'.format(
self.options['client_id'],
self.options['client_secret']
)
auth = base64.b64encode(auth_string.encode('utf-8')).decode('utf-8')
payload = json.dumps({"grant_type": "client_credentials"})

headers = {
'Authorization': f"Basic {auth}",
'Authorization': 'Basic {0}'.format(auth),
'Content-Type': 'application/json'
}

if 'partner_token' in self.options:
headers['partner-token'] = self.options['partner_token']
cert=self.options['certificate']
if(os.path.exists(cert)):

cert = self.options.get('certificate')
if cert and os.path.exists(cert):
response = requests.post(url, headers=headers, data=payload, cert=cert)
else:
return 404
else:
headers = {
'accept': 'application/json',
'api-sdk': 'efi-python-{v}'.format(v=VERSION)
'api-sdk': 'efi-python-{0}'.format(VERSION)
}

if 'partner_token' in self.options:
headers['partner-token'] = self.options['partner_token']
auth = (self.options['client_id'], self.options['client_secret'])
auth_body = {'grant_type': 'client_credentials'}
response = requests.post(url, headers=headers, auth=auth, json=auth_body)

auth = (
self.options['client_id'],
self.options['client_secret']
)
auth_body = {'grant_type': 'client_credentials'}

response = requests.post(
url, headers=headers, auth=auth, json=auth_body
)

if response.status_code == 200:
json = response.json()
self.token = json
self.token = response.json()

return response.status_code


def get_url(self):
self.base_url = self.urls['sandbox']
if 'sandbox' in self.options:
self.base_url = self.urls['sandbox'] if self.options[
'sandbox'] else self.urls['production']

def build_url(self, route, params):
params = {} if params is None else params
params = params or {}
route = self.remove_placeholders(route, params)
return self.complete_url(route, params)

def remove_placeholders(self, route, params):
regex = r'\:(\w+)'
match = re.findall(regex, route)
if match:
for attr in match:
regex = r':(\w+)'
matches = re.findall(regex, route)
if matches:
for attr in matches:
if attr not in params:
raise MissingParametersError(attr)
route = route.replace(':' + attr, str(params[attr]))
del params[attr]

return route

def query_string(self, params):
mapped = []
for (p, value) in iteritems(params):
mapped.append('{attr}={value}'.format(attr=p, value=value))
return '&'.join(mapped)
return '&'.join(
'{0}={1}'.format(p, v) for p, v in iteritems(params)
)

def complete_url(self, route, params):
qs = self.query_string(params)

if len(qs) == 0:
return '{base}{route}'.format(base=self.base_url, route=route)

return '{base}{route}?{qs}'.format(base=self.base_url, route=route, qs=qs)
if qs:
return '{0}{1}?{2}'.format(self.base_url, route, qs)
return '{0}{1}'.format(self.base_url, route)
2 changes: 1 addition & 1 deletion efipay/version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# encoding: utf-8

VERSION = '1.0.3'
VERSION = '1.0.4'
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
# encoding: utf-8

import os
import sys
from efipay import EfiPay
from ....credentials import credentials

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(project_root)

from credentials import credentials

efi = EfiPay(credentials.CREDENTIALS)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
# encoding: utf-8

import os
import sys
from efipay import EfiPay
from ....credentials import credentials

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(project_root)

from credentials import credentials

efi = EfiPay(credentials.CREDENTIALS)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
# encoding: utf-8

import os
import sys
from efipay import EfiPay
from ....credentials import credentials

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(project_root)

from credentials import credentials

efi = EfiPay(credentials.CREDENTIALS)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
# encoding: utf-8

import os
import sys
from efipay import EfiPay
from ....credentials import credentials

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(project_root)

from credentials import credentials

efi = EfiPay(credentials.CREDENTIALS)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
# encoding: utf-8

import os
import sys
from efipay import EfiPay
from ....credentials import credentials

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(project_root)

from credentials import credentials

efi = EfiPay(credentials.CREDENTIALS)

Expand Down
Loading