def setUp(self):
     self.comercial = Comercial(
         numero=1006993069,
         chave=
         '25fbb99741c739dd84d7b06ec78c9bac718838630f30b112d033ce2e621b34f3')
     self.cartao = Cartao(numero=4012001037141112,
                          validade=201805,
                          indicador=1,
                          codigo_seguranca=123,
                          nome_portador='Fulano Silva')
     self.pedido = Pedido(
         numero='1234',
         valor=10000,
         moeda=986,
         data_hora=datetime.now().isoformat(),
     )
     self.pagamento = Pagamento(bandeira='visa', produto='1', parcelas=1)
     self.request = CieloRequest(sandbox=True)
 def setUp(self):
     self.comercial = Comercial(
         numero=1006993069, chave="25fbb99741c739dd84d7b06ec78c9bac718838630f30b112d033ce2e621b34f3"
     )
     self.cartao = Cartao(
         numero=4012001037141112, validade=201805, indicador=1, codigo_seguranca=123, nome_portador="Fulano Silva"
     )
     self.pedido = Pedido(numero="1234", valor=10000, moeda=986, data_hora=datetime.now().isoformat())
     self.pagamento = Pagamento(bandeira="visa", produto="1", parcelas=1)
     self.request = CieloRequest(sandbox=True)
class TestCieloRequest(TestCase):
    def setUp(self):
        self.comercial = Comercial(
            numero=1006993069,
            chave=
            '25fbb99741c739dd84d7b06ec78c9bac718838630f30b112d033ce2e621b34f3')
        self.cartao = Cartao(numero=4012001037141112,
                             validade=201805,
                             indicador=1,
                             codigo_seguranca=123,
                             nome_portador='Fulano Silva')
        self.pedido = Pedido(
            numero='1234',
            valor=10000,
            moeda=986,
            data_hora=datetime.now().isoformat(),
        )
        self.pagamento = Pagamento(bandeira='visa', produto='1', parcelas=1)
        self.request = CieloRequest(sandbox=True)

    def test_render_template(self):
        with pytest.raises(TemplateNotFound) as excinfo:
            self.request.render_template('notfound.xml', id=str(uuid.uuid4()))
        assert 'notfound.xml' in str(excinfo.value)

    @mock.patch('requests.post', autorizar_mocked_response)
    def test_autorizar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.autorizar('transacao')
        assert 'transacao precisa ser do tipo Transacao.' in str(excinfo.value)

        transacao = Transacao(comercial=self.comercial,
                              cartao=self.cartao,
                              pedido=self.pedido,
                              pagamento=self.pagamento,
                              autorizar=3,
                              capturar=True)
        transacao = self.request.autorizar(transacao=transacao)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertEqual(transacao.tid, '1006993069484E8B1001')
        self.assertEqual(transacao.pan,
                         'IqVz7P9zaIgTYdU41HaW/OB/d7Idwttqwb2vaTt8MT0=')

    @mock.patch('requests.post', erro_mocked_response)
    def test_autorizar_com_erro(self):
        transacao = Transacao(comercial=self.comercial,
                              cartao=self.cartao,
                              pedido=self.pedido,
                              pagamento=self.pagamento,
                              autorizar=3,
                              capturar=True)
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.autorizar(transacao)
        assert '000 - Mensagem' in str(excinfo.value)

    @mock.patch('requests.post', capturar_mocked_response)
    def test_capturar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid=1, comercial=self.comercial)
        assert 'tid precisa ser do tipo string.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid='tid', comercial=1)
        assert 'comercial precisa ser do tipo Comercial.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid='tid',
                                  comercial=self.comercial,
                                  valor='10000')
        assert 'valor precisa ser do tipo inteiro.' in str(excinfo.value)

        transacao = self.request.capturar(tid='10069930694849051001',
                                          comercial=self.comercial)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertTrue(isinstance(transacao.captura, Captura))

    @mock.patch('requests.post', erro_mocked_response)
    def test_capturar_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.capturar(tid='10069930694849051001',
                                  comercial=self.comercial)
        assert '000 - Mensagem' in str(excinfo.value)

    @mock.patch('requests.post', token_mocked_response)
    def test_gerar_token(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.gerar_token(comercial=1, cartao=self.cartao)
        assert 'comercial precisa ser do tipo Comercial.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.gerar_token(comercial=self.comercial, cartao=1)
        assert 'cartao precisa ser do tipo Cartao.' in str(excinfo.value)

        token = self.request.gerar_token(comercial=self.comercial,
                                         cartao=self.cartao)
        self.assertTrue(isinstance(token, Token))

    @mock.patch('requests.post', erro_mocked_response)
    def test_gerar_token_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.gerar_token(comercial=self.comercial,
                                     cartao=self.cartao)
        assert '000 - Mensagem' in str(excinfo.value)

    @mock.patch('requests.post', cancelar_mocked_response)
    def test_cancelar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid=1, comercial=self.comercial)
        assert 'tid precisa ser do tipo string.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid='tid', comercial=1)
        assert 'comercial precisa ser do tipo Comercial.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid='tid',
                                  comercial=self.comercial,
                                  valor='10000')
        assert 'valor precisa ser do tipo inteiro.' in str(excinfo.value)

        transacao = self.request.cancelar(tid='1006993069484E8B1001',
                                          comercial=self.comercial)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertTrue(isinstance(transacao.cancelamento, Cancelamento))

    @mock.patch('requests.post', erro_mocked_response)
    def test_cancelar_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.cancelar(tid='1006993069484E8B1001',
                                  comercial=self.comercial)
        assert '000 - Mensagem' in str(excinfo.value)
示例#4
0
 def _get_cielo_request(self):
     return CieloRequest(sandbox=self.shop.cielo_config.sandbox)
class TestCieloRequest(TestCase):

    def setUp(self):
        self.comercial = Comercial(
            numero=1006993069,
            chave='25fbb99741c739dd84d7b06ec78c9bac718838630f30b112d033ce2e621b34f3'
        )
        self.cartao = Cartao(
            numero=4012001037141112, validade=201805, indicador=1,
            codigo_seguranca=123, nome_portador='Fulano Silva'
        )
        self.pedido = Pedido(
            numero='1234', valor=10000, moeda=986,
            data_hora=datetime.now().isoformat(),
        )
        self.pagamento = Pagamento(bandeira='visa', produto='1', parcelas=1)
        self.request = CieloRequest(sandbox=True)

    def test_render_template(self):
        with pytest.raises(TemplateNotFound) as excinfo:
            self.request.render_template('notfound.xml', id=str(uuid.uuid4()))
        assert 'notfound.xml' in str(excinfo.value)

    @mock.patch('requests.Session.post', autorizar_mocked_response)
    def test_autorizar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.autorizar('transacao')
        assert 'transacao precisa ser do tipo Transacao.' in str(excinfo.value)

        transacao = Transacao(
            comercial=self.comercial, cartao=self.cartao, pedido=self.pedido,
            pagamento=self.pagamento, autorizar=3, capturar=True
        )
        transacao = self.request.autorizar(transacao=transacao)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertEqual(transacao.tid, '1006993069484E8B1001')
        self.assertEqual(
            transacao.pan, 'IqVz7P9zaIgTYdU41HaW/OB/d7Idwttqwb2vaTt8MT0='
        )

    @mock.patch('requests.Session.post', erro_mocked_response)
    def test_autorizar_com_erro(self):
        transacao = Transacao(
            comercial=self.comercial, cartao=self.cartao, pedido=self.pedido,
            pagamento=self.pagamento, autorizar=3, capturar=True
        )
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.autorizar(transacao)
        assert '000 - Mensagem' in str(excinfo.value)

    @mock.patch('requests.Session.post', autorizar_com_rejeicao_mocked_response)
    def test_autorizar_com_rejeicao(self):
        self.pedido = Pedido(
            numero='1234', valor=553482920, moeda=986,
            data_hora=datetime.now().isoformat(),
        )
        transacao = Transacao(
            comercial=self.comercial, cartao=self.cartao, pedido=self.pedido,
            pagamento=self.pagamento, autorizar=3, capturar=True
        )
        transacao = self.request.autorizar(transacao=transacao)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertEqual(transacao.tid, '100699306900050E36EA')
        self.assertEqual(
            transacao.pan, 'IqVz7P9zaIgTYdU41HaW/OB/d7Idwttqwb2vaTt8MT0='
        )
        self.assertEqual(
            transacao.autorizacao.mensagem, 'Autorizacao negada'
        )

    @mock.patch('requests.Session.post', capturar_mocked_response)
    def test_capturar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid=1, comercial=self.comercial)
        assert 'tid precisa ser do tipo string.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid='tid', comercial=1)
        assert 'comercial precisa ser do tipo Comercial.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(
                tid='tid', comercial=self.comercial, valor='10000'
            )
        assert 'valor precisa ser do tipo inteiro.' in str(excinfo.value)

        transacao = self.request.capturar(
            tid='10069930694849051001', comercial=self.comercial
        )
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertTrue(isinstance(transacao.captura, Captura))

    @mock.patch('requests.Session.post', erro_mocked_response)
    def test_capturar_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.capturar(
                tid='10069930694849051001', comercial=self.comercial
            )
        assert '000 - Mensagem' in str(excinfo.value)

    @mock.patch('requests.Session.post', token_mocked_response)
    def test_gerar_token(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.gerar_token(comercial=1, cartao=self.cartao)
        assert 'comercial precisa ser do tipo Comercial.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.gerar_token(comercial=self.comercial, cartao=1)
        assert 'cartao precisa ser do tipo Cartao.' in str(excinfo.value)

        token = self.request.gerar_token(
            comercial=self.comercial, cartao=self.cartao
        )
        self.assertTrue(isinstance(token, Token))

    @mock.patch('requests.Session.post', erro_mocked_response)
    def test_gerar_token_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.gerar_token(
                comercial=self.comercial, cartao=self.cartao
            )
        assert '000 - Mensagem' in str(excinfo.value)

    @mock.patch('requests.Session.post', cancelar_mocked_response)
    def test_cancelar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid=1, comercial=self.comercial)
        assert 'tid precisa ser do tipo string.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid='tid', comercial=1)
        assert 'comercial precisa ser do tipo Comercial.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(
                tid='tid', comercial=self.comercial, valor='10000'
            )
        assert 'valor precisa ser do tipo inteiro.' in str(excinfo.value)

        transacao = self.request.cancelar(
            tid='1006993069484E8B1001', comercial=self.comercial
        )
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertTrue(isinstance(transacao.cancelamento, Cancelamento))

    @mock.patch('requests.Session.post', erro_mocked_response)
    def test_cancelar_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.cancelar(
                tid='1006993069484E8B1001', comercial=self.comercial
            )
        assert '000 - Mensagem' in str(excinfo.value)

    @mock.patch('requests.Session.post', consultar_mocked_response)
    def test_consultar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.consultar(tid=1, comercial=self.comercial)
        assert 'tid precisa ser do tipo string.' in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.consultar(tid='tid', comercial=1)
        assert 'comercial precisa ser do tipo Comercial.' in str(excinfo.value)

        transacao = self.request.consultar(
            tid='10069930690005C1B5EA', comercial=self.comercial
        )
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertEqual(transacao.tid, '10069930690005C1B5EA')

    @mock.patch('requests.Session.post', erro_mocked_response)
    def test_consultar_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.consultar(
                tid='1006993069484E8B1001', comercial=self.comercial
            )
        assert '000 - Mensagem' in str(excinfo.value)
class TestCieloRequest(TestCase):
    def setUp(self):
        self.comercial = Comercial(
            numero=1006993069, chave="25fbb99741c739dd84d7b06ec78c9bac718838630f30b112d033ce2e621b34f3"
        )
        self.cartao = Cartao(
            numero=4012001037141112, validade=201805, indicador=1, codigo_seguranca=123, nome_portador="Fulano Silva"
        )
        self.pedido = Pedido(numero="1234", valor=10000, moeda=986, data_hora=datetime.now().isoformat())
        self.pagamento = Pagamento(bandeira="visa", produto="1", parcelas=1)
        self.request = CieloRequest(sandbox=True)

    def test_render_template(self):
        with pytest.raises(TemplateNotFound) as excinfo:
            self.request.render_template("notfound.xml", id=str(uuid.uuid4()))
        assert "notfound.xml" in str(excinfo.value)

    @mock.patch("requests.post", autorizar_mocked_response)
    def test_autorizar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.autorizar("transacao")
        assert "transacao precisa ser do tipo Transacao." in str(excinfo.value)

        transacao = Transacao(
            comercial=self.comercial,
            cartao=self.cartao,
            pedido=self.pedido,
            pagamento=self.pagamento,
            autorizar=3,
            capturar=True,
        )
        transacao = self.request.autorizar(transacao=transacao)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertEqual(transacao.tid, "1006993069484E8B1001")
        self.assertEqual(transacao.pan, "IqVz7P9zaIgTYdU41HaW/OB/d7Idwttqwb2vaTt8MT0=")

    @mock.patch("requests.post", erro_mocked_response)
    def test_autorizar_com_erro(self):
        transacao = Transacao(
            comercial=self.comercial,
            cartao=self.cartao,
            pedido=self.pedido,
            pagamento=self.pagamento,
            autorizar=3,
            capturar=True,
        )
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.autorizar(transacao)
        assert "000 - Mensagem" in str(excinfo.value)

    @mock.patch("requests.post", capturar_mocked_response)
    def test_capturar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid=1, comercial=self.comercial)
        assert "tid precisa ser do tipo string." in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid="tid", comercial=1)
        assert "comercial precisa ser do tipo Comercial." in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.capturar(tid="tid", comercial=self.comercial, valor="10000")
        assert "valor precisa ser do tipo inteiro." in str(excinfo.value)

        transacao = self.request.capturar(tid="10069930694849051001", comercial=self.comercial)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertTrue(isinstance(transacao.captura, Captura))

    @mock.patch("requests.post", erro_mocked_response)
    def test_capturar_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.capturar(tid="10069930694849051001", comercial=self.comercial)
        assert "000 - Mensagem" in str(excinfo.value)

    @mock.patch("requests.post", token_mocked_response)
    def test_gerar_token(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.gerar_token(comercial=1, cartao=self.cartao)
        assert "comercial precisa ser do tipo Comercial." in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.gerar_token(comercial=self.comercial, cartao=1)
        assert "cartao precisa ser do tipo Cartao." in str(excinfo.value)

        token = self.request.gerar_token(comercial=self.comercial, cartao=self.cartao)
        self.assertTrue(isinstance(token, Token))

    @mock.patch("requests.post", erro_mocked_response)
    def test_gerar_token_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.gerar_token(comercial=self.comercial, cartao=self.cartao)
        assert "000 - Mensagem" in str(excinfo.value)

    @mock.patch("requests.post", cancelar_mocked_response)
    def test_cancelar(self):
        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid=1, comercial=self.comercial)
        assert "tid precisa ser do tipo string." in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid="tid", comercial=1)
        assert "comercial precisa ser do tipo Comercial." in str(excinfo.value)

        with pytest.raises(TypeError) as excinfo:
            self.request.cancelar(tid="tid", comercial=self.comercial, valor="10000")
        assert "valor precisa ser do tipo inteiro." in str(excinfo.value)

        transacao = self.request.cancelar(tid="1006993069484E8B1001", comercial=self.comercial)
        self.assertTrue(isinstance(transacao, Transacao))
        self.assertTrue(isinstance(transacao.cancelamento, Cancelamento))

    @mock.patch("requests.post", erro_mocked_response)
    def test_cancelar_com_erro(self):
        with pytest.raises(CieloRequestError) as excinfo:
            self.request.cancelar(tid="1006993069484E8B1001", comercial=self.comercial)
        assert "000 - Mensagem" in str(excinfo.value)
示例#7
0
    def form_valid(self, form):
        # verifica se existe alguma transação pendente na sessão
        # se sim, cancela a autorização antiga para fazer uma nova
        if self.request.cielo.transaction:
            try:
                self.request.cielo.transaction.safe_cancel(self.request.cielo.transaction.total_value)
            except:
                logger.exception(_("Failed to cancel old Cielo transaction"))

        # populate the basket with all the checkout stuff
        _configure_basket(self.request)
        order_total = self.request.basket.taxful_total_price.value
        service = self.request.basket.payment_method.choice_identifier

        cc_info = form.cleaned_data
        transaction_total = order_total
        interest_amount = Decimal()
        installments = safe_int(cc_info['installments'])

        cielo_config = self.request.shop.cielo_config

        produto = CieloProduct.Credit

        if service == CIELO_SERVICE_CREDIT:
            if installments > 1:
                installment_choices = InstallmentContext(order_total, cielo_config).get_intallments_choices()

                # verifica se o número da parcela existe nas opções
                if installments <= len(installment_choices):
                    produto = CieloProduct.InstallmentCredit

                    # obtém o valor da transação de acordo com a parcela escolhida
                    transaction_total = installment_choices[installments-1][2]
                    interest_amount = installment_choices[installments-1][3]
                else:
                    installments = 1

        else:
            # debito
            produto = CieloProduct.Debit
            installments = 1

        cielo_order = CieloOrderTransaction.objects.create()

        comercial = Comercial(numero=safe_int(cielo_config.ec_num), chave=cielo_config.ec_key)

        cartao = Cartao(numero=safe_int(cc_info['cc_number']),
                        validade=safe_int("{0}{1}".format(cc_info['cc_valid_year'], cc_info['cc_valid_month'])),
                        indicador=1,  # sempre sera necessario o digito verificador
                        codigo_seguranca=safe_int(cc_info['cc_security_code']),
                        nome_portador=cc_info['cc_holder'])

        pedido = Pedido(numero="{0}".format(cielo_order.pk),
                        valor=decimal_to_int_cents(transaction_total),
                        moeda=986,  # Fixo
                        data_hora=now().isoformat())

        pagamento = Pagamento(bandeira=cc_info['cc_brand'],
                              produto=produto,
                              parcelas=installments)

        return_url = self.request.build_absolute_uri(
            reverse("shuup:cielo_transaction_return", kwargs={"cielo_order_pk": cielo_order.id})
        )

        transacao = Transacao(comercial=comercial,
                              cartao=cartao,
                              pedido=pedido,
                              pagamento=pagamento,
                              autorizar=cielo_config.authorization_mode,
                              capturar=cielo_config.auto_capture,
                              url_retorno=return_url)

        cielo_request = CieloRequest(sandbox=cielo_config.sandbox)

        # base response data
        response_data = {"success": False}
        cielo_transaction = None

        try:
            response_transaction = cielo_request.autorizar(transacao=transacao)

            cielo_transaction = CieloTransaction.objects.create(shop=self.request.shop,
                                                                order_transaction=cielo_order,
                                                                tid=response_transaction.tid,
                                                                status=response_transaction.status,
                                                                total_value=transaction_total,
                                                                cc_holder=cc_info['cc_holder'],
                                                                cc_brand=cc_info['cc_brand'],
                                                                cc_product=produto,
                                                                installments=installments,
                                                                interest_value=interest_amount)

            # se existe uma URL para autenticacao, vamos redirecionar primeiro
            if response_transaction.url_autenticacao:
                response_data["success"] = True
                response_data["redirect_url"] = response_transaction.url_autenticacao

            # transação autorizada, vamos para a página de retorno para
            # efetivar
            elif response_transaction.autorizacao:

                if response_transaction.autorizacao.lr in CIELO_AUTHORIZED_STATUSES:
                    response_data["success"] = True
                    response_data["redirect_url"] = return_url

                else:
                    response_data["success"] = False
                    error = _p("Transaction not authorized: {0}").format(
                        CieloAuthorizationCode.get(
                            response_transaction.autorizacao.lr, {}
                        ).get('msg', CIELO_UKNOWN_ERROR_MSG)
                    )
                    response_data["error"] = error

            else:
                response_data["success"] = False
                response_data["error"] = _p("Transaction not authorized: {0}").format(CIELO_UKNOWN_ERROR_MSG)

        except CieloRequestError:
            response_data["success"] = False
            response_data["error"] = _p("Internal error")
            logger.exception(_("Cielo transaction error."))

        else:
            self.request.cielo.set_order_transaction(cielo_order)
            self.request.cielo.set_transaction(cielo_transaction)
            self.request.cielo.commit()

        return self.render_to_response(response_data)
示例#8
0
    def form_valid(self, form):
        # verifica se existe alguma transação pendente na sessão
        # se sim, cancela a autorização antiga para fazer uma nova
        if self.request.cielo.transaction:
            try:
                self.request.cielo.transaction.safe_cancel(
                    self.request.cielo.transaction.total_value)
            except:
                logger.exception(_("Failed to cancel old Cielo transaction"))

        # populate the basket with all the checkout stuff
        _configure_basket(self.request)
        order_total = self.request.basket.taxful_total_price.value
        service = self.request.basket.payment_method.choice_identifier

        cc_info = form.cleaned_data
        transaction_total = order_total
        interest_amount = Decimal()
        installments = safe_int(cc_info['installments'])

        cielo_config = self.request.shop.cielo_config

        produto = CieloProduct.Credit

        if service == CIELO_SERVICE_CREDIT:
            if installments > 1:
                installment_choices = InstallmentContext(
                    order_total, cielo_config).get_intallments_choices()

                # verifica se o número da parcela existe nas opções
                if installments <= len(installment_choices):
                    produto = CieloProduct.InstallmentCredit

                    # obtém o valor da transação de acordo com a parcela escolhida
                    transaction_total = installment_choices[installments -
                                                            1][2]
                    interest_amount = installment_choices[installments - 1][3]
                else:
                    installments = 1

        else:
            # debito
            produto = CieloProduct.Debit
            installments = 1

        cielo_order = CieloOrderTransaction.objects.create()

        comercial = Comercial(numero=safe_int(cielo_config.ec_num),
                              chave=cielo_config.ec_key)

        cartao = Cartao(
            numero=safe_int(cc_info['cc_number']),
            validade=safe_int("{0}{1}".format(cc_info['cc_valid_year'],
                                              cc_info['cc_valid_month'])),
            indicador=1,  # sempre sera necessario o digito verificador
            codigo_seguranca=safe_int(cc_info['cc_security_code']),
            nome_portador=cc_info['cc_holder'])

        pedido = Pedido(
            numero="{0}".format(cielo_order.pk),
            valor=decimal_to_int_cents(transaction_total),
            moeda=986,  # Fixo
            data_hora=now().isoformat())

        pagamento = Pagamento(bandeira=cc_info['cc_brand'],
                              produto=produto,
                              parcelas=installments)

        return_url = self.request.build_absolute_uri(
            reverse("shuup:cielo_transaction_return",
                    kwargs={"cielo_order_pk": cielo_order.id}))

        transacao = Transacao(comercial=comercial,
                              cartao=cartao,
                              pedido=pedido,
                              pagamento=pagamento,
                              autorizar=cielo_config.authorization_mode,
                              capturar=cielo_config.auto_capture,
                              url_retorno=return_url)

        cielo_request = CieloRequest(sandbox=cielo_config.sandbox)

        # base response data
        response_data = {"success": False}
        cielo_transaction = None

        try:
            response_transaction = cielo_request.autorizar(transacao=transacao)

            cielo_transaction = CieloTransaction.objects.create(
                shop=self.request.shop,
                order_transaction=cielo_order,
                tid=response_transaction.tid,
                status=response_transaction.status,
                total_value=transaction_total,
                cc_holder=cc_info['cc_holder'],
                cc_brand=cc_info['cc_brand'],
                cc_product=produto,
                installments=installments,
                interest_value=interest_amount)

            # se existe uma URL para autenticacao, vamos redirecionar primeiro
            if response_transaction.url_autenticacao:
                response_data["success"] = True
                response_data[
                    "redirect_url"] = response_transaction.url_autenticacao

            # transação autorizada, vamos para a página de retorno para
            # efetivar
            elif response_transaction.autorizacao:

                if response_transaction.autorizacao.lr in CIELO_AUTHORIZED_STATUSES:
                    response_data["success"] = True
                    response_data["redirect_url"] = return_url

                else:
                    response_data["success"] = False
                    error = _p("Transaction not authorized: {0}").format(
                        CieloAuthorizationCode.get(
                            response_transaction.autorizacao.lr,
                            {}).get('msg', CIELO_UKNOWN_ERROR_MSG))
                    response_data["error"] = error

            else:
                response_data["success"] = False
                response_data["error"] = _p("Transaction not authorized: {0}"
                                            ).format(CIELO_UKNOWN_ERROR_MSG)

        except CieloRequestError:
            response_data["success"] = False
            response_data["error"] = _p("Internal error")
            logger.exception(_("Cielo transaction error."))

        else:
            self.request.cielo.set_order_transaction(cielo_order)
            self.request.cielo.set_transaction(cielo_transaction)
            self.request.cielo.commit()

        return self.render_to_response(response_data)