Skip to content
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

add page param, disable json error handler and add function to retrive singleton boleto #6

Open
wants to merge 18 commits into
base: master
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
2 changes: 1 addition & 1 deletion .bumpversion.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[bumpversion]
current_version = 0.0.1
current_version = 0.2.0
commit = True
tag = True

Expand Down
2 changes: 1 addition & 1 deletion .cookiecutterrc
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ default_context:
test_runner: 'pytest'
travis: 'yes'
travis_osx: 'no'
version: '0.0.1'
version: '0.2.0'
website: 'https://www.kmee.com.br'
year_from: '2020'
year_to: '2020'
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ Changelog
=========

0.0.1 (2020-11-15)
0.2.0 (2022-10-08)
->API INTER V2
------------------

* First release on PyPI.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
year = '2020'
author = 'Luis Felipe Mileo'
copyright = '{0}, {1}'.format(year, author)
version = release = '0.0.1'
version = release = '0.2.0'

pygments_style = 'trac'
templates_path = ['.']
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def read(*names, **kwargs):

setup(
name='erpbrasil.bank.inter',
version='0.0.1',
version='0.2.0',
license='MIT',
description='Integração com o Banco Inter em Python',
long_description='%s\n%s' % (
Expand Down
2 changes: 1 addition & 1 deletion src/erpbrasil/bank/inter/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
__version__ = '0.1.0'
__version__ = "0.2.0"

from erpbrasil.bank.inter import *
154 changes: 87 additions & 67 deletions src/erpbrasil/bank/inter/api.py
Original file line number Diff line number Diff line change
@@ -1,137 +1,157 @@
# -*- coding: utf-8 -*-
import json

import requests

from .auth import Auth

FILTRAR_POR = [
'TODOS',
'VENCIDOSAVENCER',
'EXPIRADOS',
'PAGOS',
'TODOSBAIXADOS',
"TODOS",
"VENCIDOSAVENCER",
"EXPIRADOS",
"PAGOS",
"TODOSBAIXADOS",
]

ORDENAR_CONSULTA_POR = [
'NOSSONUMERO', # (Default)
'SEUNUMERO',
'DATAVENCIMENTO_ASC',
'DATAVENCIMENTO_DSC',
'NOMESACADO',
'VALOR_ASC',
'VALOR_DSC',
'STATUS_ASC',
'STATUS_DSC',
"NOSSONUMERO", # (Default)
"SEUNUMERO",
"DATAVENCIMENTO_ASC",
"DATAVENCIMENTO_DSC",
"NOMESACADO",
"VALOR_ASC",
"VALOR_DSC",
"STATUS_ASC",
"STATUS_DSC",
]


class ApiInter(object):
""" Implementa a Api do Inter"""
"""Implementa a Api do Inter"""

_api = 'https://apis.bancointer.com.br:8443/openbanking/v1/certificado/boletos'
# _api = 'https://apis.bancointer.com.br:8443/openbanking/v1/certificado/boletos'
_api = "https://cdpj.partners.bancointer.com.br/cobranca/v2/boletos/"

def __init__(self, cert, conta_corrente):
def __init__(self, cert, conta_corrente, clientId, clientSecret):
self._cert = cert
self.conta_corrente = conta_corrente
self.auth = Auth(
clientId,
# "50acb448-5107-4f57-81ea-54a615c5da0a",
clientSecret,
# "0a0275ff-4fcc-4f7f-a092-edcbb5bb6bd8",
)
self.auth.generate_token_boleto_write("boleto-cobranca.write", self._cert)
self.auth.generate_token_boleto_read("boleto-cobranca.read", self._cert)

def _prepare_headers(self):
def _prepare_headers(self, token):
return {
'content-type': 'application/json',
'x-inter-conta-corrente': self.conta_corrente,
"content-type": "application/json",
"x-inter-conta-corrente": self.conta_corrente,
"Authorization": "Bearer " + token,
}

def _call(self, http_request, url, params=None, data=None, **kwargs):
def _call(self, token, http_request, url, params=None, data=None, **kwargs):
debug1 = self._prepare_headers(token)
debug2 = json.dumps(data or {})
debug3 = params or {}
response = http_request(
url,
headers=self._prepare_headers(),
headers=self._prepare_headers(token),
params=params or {},
data=json.dumps(data or {}),
cert=self._cert,
verify=False,
**kwargs
verify=True,
**kwargs,
)
if response.status_code > 299:
error = response.json()
message = '%s - Código %s' % (
response.status_code,
error.get('error-code')
# error = response.json()
error = response # .json()
# message = '%s - Código %s' % (
# response.status_code,
# error.get('error-code')
# )
# raise Exception(message)
raise Exception(
[str(response.text), response.status_code, debug1, debug2, debug3]
)
raise Exception(message)
return response

def boleto_inclui(self, boleto):
""" POST
https://apis.bancointer.com.br:8443/openbanking/v1/certificado/boletos
"""POST

:param boleto:
:return:
"""
result = self._call(
requests.post,
url=self._api,
data=boleto
self.auth.token_boleto_write, requests.post, url=self._api, data=boleto
)
return result.content and result.json() or result.ok

def boleto_consulta(self, filtrar_por='TODOS', data_inicial=None, data_final=None,
ordenar_por='NOSSONUMERO'):
""" GET
https://apis.bancointer.com.br:8443/openbanking/v1/certificado/boletos?
filtrarPor=TODOS&
dataInicial=2020-01-01&
dataFinal=2020-12-01&
ordenarPor=SEUNUMERO

:param filtrar_por:
:param data_inicial:
:param data_final:
:param ordenar_por:
:return:
"""
def boleto_consulta(
self,
filtrar_por="TODOS",
data_inicial=None,
data_final=None,
ordenar_por="NOSSONUMERO",
page=0,
):
result = self._call(
self.auth.token_boleto_read,
requests.get,
url=self._api,
params=dict(
filtrarPor=filtrar_por,
dataInicial=data_inicial,
dataFinal=data_final,
ordenarPor=ordenar_por
)
ordenarPor=ordenar_por,
page=page,
),
)
return result.content and result.json() or result.ok

def boleto_recupera(self, nosso_numero):

_url = f"{self._api}{nosso_numero}"

result = self._call(
self.auth.token_boleto_read,
requests.get,
url=_url,
)

return result.content and result.json() or result.ok

def boleto_baixa(self, nosso_numero, codigo_baixa):
""" POST
https://apis.bancointer.com.br:8443/openbanking/v1/certificado/boletos/
00576501185/baixas
def boleto_baixa(self, nossoNumero, motivoCancelamento):
"""POST
https://cdpj.partners.bancointer.com.br/cobranca/v2/boletos/{nossoNumero}/cancelar


:param nosso_numero:
:return:
"""
url = '{}/{}/baixas'.format(
self._api,
nosso_numero
)
url = "{}{}/cancelar".format(self._api, nossoNumero)
result = self._call(
self.auth.token_boleto_write,
requests.post,
url=url,
data=dict(
codigoBaixa=codigo_baixa,
)
motivoCancelamento=motivoCancelamento,
),
)
return result.content and result.json() or result.ok

def boleto_pdf(self, nosso_numero):
""" GET
https://apis.bancointer.com.br:8443/openbanking/v1/certificado/boletos/
"""GET
https://cdpj.partners.bancointer.com.br/cobranca/v2/boletos/
00595764723/pdf

:param nosso_numero:
:return:
"""
url = '{}/{}/pdf'.format(
self._api,
nosso_numero
)
url = "{}{}/pdf".format(self._api, nosso_numero)
result = self._call(
self.auth.token_boleto_read,
requests.get,
url=url,
)
Expand Down
76 changes: 76 additions & 0 deletions src/erpbrasil/bank/inter/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import os
import json
import requests
import time



class Auth:
access_token = ""
token_type = ""
expires_in = ""
scope = ""
client_id = ""
client_secret = ""
scope = ""
grant_type = "client_credentials"
token_boleto_write = ""
token_boleto_read = ""

def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret

def generate_token_boleto_write(self, scope, cert):
request_body = (
"client_id={0}&client_secret={1}&scope={2}&grant_type={3}".format(
self.client_id, self.client_secret, scope, self.grant_type
)
)
if os.environ.get('INTER_TOKEN_BOLETO_WRITE_LAST_UPDATE') is None:
os.environ['INTER_TOKEN_BOLETO_WRITE_LAST_UPDATE'] = str(0)
if float(os.environ.get('INTER_TOKEN_BOLETO_WRITE_LAST_UPDATE')) + 3600 < time.time():
response = requests.post(
"https://cdpj.partners.bancointer.com.br/oauth/v2/token",
headers={"Content-Type": "application/x-www-form-urlencoded"},
data=request_body,
cert=cert,
)

if response.status_code != 200:
print("Server didn't return an 'OK' response. Content was: {!r}".format(response.content))
raise Exception(
["Server didn't return an 'OK' response. Content was: {!r}".format(response.content),
str(response.text), response.status_code]
)
self.token_boleto_write = json.loads(response.text)
else:
os.environ['INTER_TOKEN_BOLETO_WRITE'] = response.json().get("access_token")
os.environ['INTER_TOKEN_BOLETO_WRITE_LAST_UPDATE'] = str(time.time())
self.token_boleto_write = os.environ.get('INTER_TOKEN_BOLETO_WRITE')

def generate_token_boleto_read(self, scope, cert):
request_body = (
"client_id={0}&client_secret={1}&scope={2}&grant_type={3}".format(
self.client_id, self.client_secret, scope, self.grant_type
)
)
if os.environ.get('INTER_TOKEN_BOLETO_READ_LAST_UPDATE') is None:
os.environ['INTER_TOKEN_BOLETO_READ_LAST_UPDATE'] = str(0)
if float(os.environ.get('INTER_TOKEN_BOLETO_READ_LAST_UPDATE')) + 3600 < time.time():
response = requests.post(
"https://cdpj.partners.bancointer.com.br/oauth/v2/token",
headers={"Content-Type": "application/x-www-form-urlencoded"},
data=request_body,
cert=cert,
)
if response.status_code != 200:
raise Exception(
["Server didn't return an 'OK' response. Content was: {!r}".format(response.content),
str(response.text), response.status_code]
)
self.token_boleto_read = json.loads(response.text)
else:
os.environ['INTER_TOKEN_BOLETO_READ'] = response.json().get("access_token")
os.environ['INTER_TOKEN_BOLETO_READ_LAST_UPDATE'] = str(time.time())
self.token_boleto_read = os.environ.get('INTER_TOKEN_BOLETO_READ')
Loading