Beispiel #1
0
    def test_base_url(self):
        endpoints = Gerencianet({})
        assert endpoints.base_url == Constants.URL['sandbox']

        endpoints = Gerencianet({'sandbox': True})
        assert endpoints.base_url == Constants.URL['sandbox']

        endpoints = Gerencianet({'sandbox': False})
        assert endpoints.base_url == Constants.URL['production']
Beispiel #2
0
def chargeCardParticular(itens):
    """Realiza o charge somente para a comanda INDIVIDUAL de cada usuário."""
    gn = Gerencianet(options)
    body = {'items': itens}
    response = gn.create_charge(body=body)
    p(response)
    return response
Beispiel #3
0
def charge(itensJSON):
    """Realiza o charge para o ingresso do evento escolhido."""
    gn = Gerencianet(options)
    body = {'items': [itensJSON]}
    response = gn.create_charge(body=body)
    print(response)
    return response
Beispiel #4
0
    def test_api_request_call_with_partner_token(self):
        responses.add(responses.POST,
                      Constants.URL['sandbox'] + '/authorize',
                      content_type='application/json',
                      status=200,
                      json=TestGerencianet.auth_success)

        responses.add(responses.POST,
                      Constants.URL['sandbox'] + '/charge',
                      content_type='application/json',
                      status=200,
                      json=TestGerencianet.charge)

        items = [{
            'name': 'item 1',
            'value': 1000
        }, {
            'name': 'item 2',
            'value': 2000
        }]

        endpoints = Gerencianet({
            'client_id': 'cid',
            'client_secret': 'csec',
            'partner_token': 'partner'
        })
        response = endpoints.create_charge(body={'items': items})

        assert response == TestGerencianet.charge
Beispiel #5
0
    def obter(self, m_contrato):
        try:
            # m_contrato_cadastro = Contrato()
            # if len(str(m_contrato.id_contrato)) > 0:
            #     m_contrato_cadastro.id_contrato = m_contrato.id_contrato

            #     retorno_contrato = m_contrato_cadastro.obter()
            #     if not retorno_contrato.estado.ok:
            #         if len(str(m_contrato.cliente.cpf)) > 0:
            #             m_cliente = Cliente()
            #             m_cliente.cpf = m_contrato_cadastro.cliente.cpf
            #             m_contrato.cliente = m_cliente
            #             retorno_contrato = m_contrato.obter_por_cliente()

            #             if not retorno_contrato.estado.ok:
            #                 return retorno_contrato

            # m_contrato_cadastro = retorno_contrato.dados

            params = {'id': m_contrato.chave_boleto_ext}

            m_gerencia_net = Gerencianet(credentials)
            d_billet = m_gerencia_net.detail_charge(params=params)

            retorno = self.tratar_retorno_gerencia_net(d_billet)
            retorno.dados = self

            return retorno

        except Exception as e:

            retorno = Retorno(False, self, 'A consulta do boleto falhou.',
                              None, None, e)
            return retorno
Beispiel #6
0
 def gerencianet(self):
     credentials = {
         'client_id': settings.GERENCIANET_CLIENT_ID,
         'client_secret': settings.GERENCIANET_CLIENT_SECRET,
         'sandbox': settings.GERENCIANET_SANDBOX
     }
     gn = Gerencianet(credentials)
     return gn
Beispiel #7
0
    def test_query_string(self):
        endpoints = Gerencianet({})

        qs = endpoints.query_string({
            'age': 78,
            'name': 'Gorbadoc',
            'lastname': 'Oldbuck'
        })
        assert all(
            x in qs
            for x in ['lastname=Oldbuck', 'age=78', 'name=Gorbadoc', '&'])
Beispiel #8
0
    def test_authenticate_success(self):
        responses.add(responses.POST,
                      Constants.URL['sandbox'] + '/authorize',
                      content_type='application/json',
                      status=200,
                      json=TestGerencianet.auth_success)

        endpoints = Gerencianet({'client_id': 'cid', 'client_secret': 'csec'})
        endpoints.authenticate()

        assert endpoints.token == TestGerencianet.auth_success
Beispiel #9
0
    def test_authenticate_failure(self):
        responses.add(responses.POST,
                      Constants.URL['sandbox'] + '/authorize',
                      content_type='application/json',
                      status=401)

        endpoints = Gerencianet({'client_id': 'cid', 'client_secret': 'csec'})

        with pytest.raises(UnauthorizedError) as raised:
            endpoints.authenticate()

        assert '401' in str(raised)
Beispiel #10
0
    def gerar(self, m_contrato):
        try:
            # m_contrato_cadastro = Contrato()
            # if len(str(m_contrato.id_contrato)) > 0:
            #     m_contrato_cadastro.id_contrato = m_contrato.id_contrato

            #     retorno_contrato = m_contrato_cadastro.obter()
            #     if not retorno_contrato.estado.ok:
            #         if len(str(m_contrato.cliente.cpf)) > 0:
            #             m_cliente = Cliente()
            #             m_cliente.cpf = m_contrato_cadastro.cliente.cpf
            #             m_contrato.cliente = m_cliente
            #             retorno_contrato = m_contrato.obter_por_cliente()

            #             if not retorno_contrato.estado.ok:
            #                 return retorno_contrato

            # m_contrato_cadastro = retorno_contrato.dados

            today = date.today()
            data_vencimento = today.strftime("%Y-%m-%d")

            params = {'id': m_contrato.chave_boleto_ext}

            body = {
                'payment': {
                    'banking_billet': {
                        'expire_at': data_vencimento,
                        'customer': {
                            'name': m_contrato.cliente.nome,
                            'email': m_contrato.cliente.email,
                            'cpf': m_contrato.cliente.cpf,
                            # 'birth': m_contrato.cliente.,
                            'phone_number': m_contrato.cliente.telefone
                        }
                    }
                }
            }
            m_gerencia_net = Gerencianet(credentials)
            d_billet = m_gerencia_net.pay_charge(params=params, body=body)

            retorno = self.tratar_retorno_gerencia_net(d_billet)
            retorno.dados = self

            return retorno

        except Exception as e:

            retorno = Retorno(False, self, 'A geração do boleto falhou.', None,
                              None, e)
            return retorno
Beispiel #11
0
    def incluir(self, d_dados_pedido):
        try:
            m_gerencia_net = Gerencianet(credentials)

            d_charge = m_gerencia_net.create_charge(body=d_dados_pedido)
            retorno = self.tratar_retorno_gerencia_net(d_charge)

            retorno.dados = self

            return retorno

        except Exception as e:

            retorno = Retorno(False, self,
                              'A inclusão de transação para boleto falhou.',
                              None, None, e)
            return retorno
Beispiel #12
0
    def gerar(self, m_contrato):
        try:
            # t = TransacaoGerenciaNet()

            # retorno = t.incluir()
            # if not retorno.estado.ok:
            #     return retorno

            today = date.today()

            data_vencimento = today.strftime("%Y-%m-%d")

            params = {'id': m_contrato.charge_id}

            body = {
                'payment': {
                    'banking_billet': {
                        'expire_at': data_vencimento,
                        'customer': {
                            'name': m_contrato.cliente.nome,
                            'email': m_contrato.cliente.email,
                            'cpf': m_contrato.cliente.cpf,
                            # 'birth': m_contrato.cliente.,
                            'phone_number': m_contrato.cliente.telefone
                        }
                    }
                }
            }
            m_gerencia_net = Gerencianet(credentials)
            d_billet = m_gerencia_net.pay_charge(params=params, body=body)

            retorno = self.tratar_retorno_gerencia_net(d_billet)

            return retorno

        except Exception as e:
            print(traceback.format_exception(None, e, e.__traceback__),
                  file=sys.stderr,
                  flush=True)

            retorno = Retorno(
                False, 'Falha de comunicação. Em breve será normalizado.')
            return retorno
Beispiel #13
0
    def incluir(self, d_dados_pedido):
        try:
            m_gerencia_net = Gerencianet(credentials)

            d_charge = m_gerencia_net.create_charge(body=d_dados_pedido)
            self.converter_de_gerencia_net(d_charge)

            retorno = Retorno(True)
            retorno.dados = self

            return retorno

        except Exception as e:
            print(traceback.format_exception(None, e, e.__traceback__),
                  file=sys.stderr,
                  flush=True)

            retorno = Retorno(
                False, 'Falha de comunicação. Em breve será normalizado.')
            return retorno
Beispiel #14
0
    def test_remove_placeholders(self):
        endpoints = Gerencianet({})
        fixed_route = endpoints.remove_placeholders(
            Constants.ENDPOINTS['detail_charge']['route'], {'id': 1})
        assert fixed_route == '/charge/1'

        fixed_route = endpoints.remove_placeholders(
            Constants.ENDPOINTS['create_charge']['route'], {})
        assert fixed_route == '/charge'

        fixed_route = endpoints.remove_placeholders(
            Constants.ENDPOINTS['update_parcel']['route'], {
                'id': 1,
                'parcel': 2
            })
        assert fixed_route == '/carnet/1/parcel/2'

        with pytest.raises(MissingParametersError) as raised:
            fixed_route = endpoints.remove_placeholders(
                Constants.ENDPOINTS['update_parcel']['route'], {'id': 1})

        assert "MissingParametersError('parcel')" in str(raised)
Beispiel #15
0
    def test_build_url(self):
        endpoints = Gerencianet({})

        #test parameter completion
        url = endpoints.build_url(
            Constants.ENDPOINTS['detail_charge']['route'], {'id': 1})
        assert url == Constants.URL['sandbox'] + '/charge/1'

        #test multiple parameter completion
        url = endpoints.build_url(
            Constants.ENDPOINTS['update_parcel']['route'], {
                'id': 1,
                'parcel': 2
            })
        assert url == Constants.URL['sandbox'] + '/carnet/1/parcel/2'

        #test querystring
        url = endpoints.build_url(
            Constants.ENDPOINTS['get_installments']['route'], {
                'brand': 'visa',
                'total': 1000
            })
        assert all(x in url for x in [
            Constants.URL['sandbox'] +
            '/installments', 'brand=visa', 'total=1000'
        ])

        #test querystring with url parameters
        url = endpoints.build_url(
            Constants.ENDPOINTS['detail_charge']['route'], {
                'id': 1,
                'status': 'new',
                'value': 1000
            })
        assert all(x in url for x in [
            Constants.URL['sandbox'] + '/charge/1', 'status=new', 'value=1000'
        ])
Beispiel #16
0
def pay(charge_id, token, billingAddr, user):
    """Realiza o pagamento para INGRESSOS e COMANDAS."""
    date = user['Birth']
    birthParsed = dateutil.parser.parse(date)
    birthFormated = birthParsed.strftime('%Y-%m-%d')

    gn = Gerencianet(options)
    params = {'id': charge_id}

    body = {
        'payment': {
            'credit_card': {
                'installments': 1,
                'payment_token': token,
                'billing_address': {
                    'street': billingAddress['Street'],
                    'number': int(billingAddress['Number']),
                    'neighborhood': billingAddress['Neighborhood'],
                    'zipcode': billingAddress['Zipcode'],
                    'city': billingAddress['City'],
                    'state': billingAddress['State']
                },
                'customer': {
                    'name': user['Name'],
                    'email': user['Email'],
                    'cpf': user['Cpf'],
                    'birth': birthFormated,
                    'phone_number': user['PhoneNumber']
                }
            }
        }
    }

    response = gn.pay_charge(params=params, body=body)
    print(response)
    return response
Beispiel #17
0
def chargeCardDivided(new_card):
    """Realiza o charge somente para a comanda DIVIDIDA do usuário que solicitou o fechamento."""
    gn = Gerencianet(options)
    ref = db.reference('itens')
    print(new_card)
    itens_new_card = new_card['itens']
    divideBy = new_card['divideBy']

    itens = []
    ## Dentro do laço abaixo eu itero cada item atualizando o valor
    # final dividindo pelo que está armazenado em divideBy:
    for itemKey, amount in itens_new_card.items():
        itemRef = ref.child(itemKey)
        item = itemRef.get()

        itName = item['name']
        itPrice = item['price']

        itemPrecoDividido = 100 * itPrice // divideBy
        # itPriceDivided = '%.2f'%(itPriceDivided)
        # itPriceDivided = '{:.2f}'.format(itPriceDivided)
        # itemPrecoDividido = str(itPriceDivided).replace('.','')
        # itemPrecoDividido = int(itPriceDivided * 100)
        dicItem = {
            'name': itName,
            'value': int(itemPrecoDividido),
            'amount': amount
        }
        itens.append(dicItem)

    print(itens)

    body = {'items': itens}
    response = gn.create_charge(body=body)
    print(response)
    return response
# encoding: utf-8

from gerencianet import Gerencianet
from credentials import CREDENTIALS

gn = Gerencianet(CREDENTIALS)

params = {'id': 1}

body = {
    'title':
    'Balancete Demonstrativo',
    'body': [{
        'header':
        'Demonstrativo de Consumo',
        'tables': [{
            'rows': [[{
                'align': 'left',
                'color': '#000000',
                'style': 'bold',
                'text': 'Exemplo de despesa',
                'colspan': 2
            }, {
                'align': 'left',
                'color': '#000000',
                'style': 'bold',
                'text': 'Total lançado',
                'colspan': 2
            }],
                     [{
                         'align': 'left',
Beispiel #19
0
#     "client_secret": "Client_Secret_*",
#     "account_identifier": "*"
#  }

credentials = {
    'client_id': client['client_id'],
    'client_secret': client['client_secret'],
    'sandbox': True
}


def adjust_number_of_whats(s, i=2):
    return s[:i] + s[i+1:]


gn = Gerencianet(credentials)
app = Flask(__name__)


# define a variavel account_identifier como global em todos os templates
@app.context_processor
def insert_account_identifier():
    return dict(account_identifier=client['account_identifier'])


@app.route('/')
def index():
    return render_template('index.html')


@app.errorhandler(404)