Beispiel #1
0
 def _post(self, url, xml):
     certificadoA1 = CertificadoA1(self.certificado)
     chave, cert = certificadoA1.separar_arquivo(self.certificado_senha,
                                                 caminho=True)
     chave_cert = (cert, chave)
     # Abre a conexão HTTPS
     try:
         xml_declaration = '<?xml version="1.0" encoding="UTF-8"?>'
         # limpa xml com caracteres bugados para infNFeSupl em NFC-e
         xml = re.sub(
             '<qrCode>(.*?)</qrCode>', lambda x: x.group(0).replace(
                 '&lt;', '<').replace('&gt;', '>').replace('amp;', ''),
             etree.tostring(xml, encoding='unicode').replace('\n', ''))
         xml = xml_declaration + xml
         # debug dev 4.00
         print(xml)
         print(url)
         # Faz o request com o servidor
         result = requests.post(url,
                                xml,
                                headers=self._post_header(),
                                cert=chave_cert,
                                verify=False)
         result.encoding = 'utf-8'
         return result
     except requests.exceptions.RequestException as e:
         raise e
     finally:
         certificadoA1.excluir()
    def test_excluir_arquivos_temporarios(self):
        self.a1 = CertificadoA1(self.certificado_correto)
        self.a1.separar_arquivo(senha=self.senha_correto,
                                caminho=self.certificado_correto)
        self.a1.excluir()

        self.assertTrue(len(self.a1.arquivos_temp) == 0)
 def test_exception_certificado_senha_errada(self):
     with self.assertRaises(Exception) as context:
         self.a1 = CertificadoA1(self.certificado_correto)
         self.a1.separar_arquivo(senha=self.senha_incorreto,
                                 caminho=self.certificado_correto)
     self.assertEqual(
         str(context.exception),
         "Falha ao carregar certificado digital A1. Verifique a senha do certificado."
     )
 def test_exception_certificado_filenotfounderror(self):
     with self.assertRaises(Exception) as context:
         self.a1 = CertificadoA1(self.certificado_incorreto)
         self.a1.separar_arquivo(senha=self.senha_incorreto,
                                 caminho=self.certificado_incorreto)
     self.assertEqual(
         str(context.exception),
         "Falha ao abrir arquivo do certificado digital A1. Verifique local e permissoes do arquivo."
     )
    def test_assinatura_com_caminho(self):
        self.a1 = CertificadoA1(self.certificado_correto)
        cert = self.a1.separar_arquivo(senha=self.senha_correto,
                                       caminho=self.certificado_correto)

        self.assertTrue(cert[0].startswith('/tmp/'))
        self.assertTrue(cert[1].startswith('/tmp/'))

        self.a1.excluir()
    def test_assinatura_sem_caminho(self):
        self.a1 = CertificadoA1(self.certificado_correto)
        cert = self.a1.separar_arquivo(senha=self.senha_correto, caminho=None)

        texto_inicial_esperado = '-----BEGIN PRIVATE KEY-----'
        texto_inicial_gerado = cert[0].decode('utf-8')

        self.assertTrue(
            texto_inicial_gerado.startswith(texto_inicial_esperado))

        self.a1.excluir()
Beispiel #7
0
    def _post_https(self, url, xml, metodo):
        """ Comunicação wsdl (https) utilizando certificado do usuário """
        # cabecalho
        cabecalho = self._cabecalho()
        # comunicacao wsdl
        try:
            from suds.client import Client
            from pynfe.utils.https_nfse import HttpAuthenticated

            certificadoA1 = CertificadoA1(self.certificado)
            chave, cert = certificadoA1.separar_arquivo(self.certificado_senha,
                                                        caminho=True)

            cliente = Client(url,
                             transport=HttpAuthenticated(key=chave,
                                                         cert=cert,
                                                         endereco=url))

            # gerar nfse
            if metodo == 'gerar':
                return cliente.service.GerarNfse(cabecalho, xml)
            elif metodo == 'enviar_lote':
                return cliente.service.RecepcionarLoteRpsV3(cabecalho, xml)
            elif metodo == 'consulta':
                return cliente.service.ConsultarNfseV3(cabecalho, xml)
            elif metodo == 'consulta_lote':
                return cliente.service.ConsultarLoteRpsV3(cabecalho, xml)
            elif metodo == 'consulta_situacao_lote':
                return cliente.service.ConsultarSituacaoLoteRpsV3(
                    cabecalho, xml)
            elif metodo == 'consultaRps':
                return cliente.service.ConsultarNfsePorRpsV3(cabecalho, xml)
            elif metodo == 'consultaFaixa':
                return cliente.service.ConsultarNfseFaixa(cabecalho, xml)
            elif metodo == 'cancelar':
                # versão 2
                return cliente.service.CancelarNfse(xml)
                # versão 3
                #return cliente.service.CancelarNfseV3(cabecalho, xml)
            # TODO outros metodos
            else:
                raise Exception('Método não implementado no autorizador.')
        except Exception as e:
            raise e
Beispiel #8
0
    def _post(self, url, xml):
        certificadoA1 = CertificadoA1(self.certificado)
        chave, cert = certificadoA1.separar_arquivo(self.certificado_senha,
                                                    caminho=True)
        chave_cert = (cert, chave)
        # Abre a conexão HTTPS
        try:
            xml_declaration = '<?xml version="1.0" encoding="utf-8"?>'
            xml = etree.tostring(xml, encoding='unicode',
                                 pretty_print=False).replace('\n', '')
            xml = xml_declaration + xml

            # Faz o request com o servidor
            result = requests.post(url,
                                   xml,
                                   headers=self._post_header(),
                                   cert=chave_cert,
                                   verify=False)
            result.encoding = 'utf-8'
            return result
        except requests.exceptions.ConnectionError as e:
            raise e
        finally:
            certificadoA1.excluir()
Beispiel #9
0
    def _post(self, url, xml):
        certificado_a1 = CertificadoA1(self.certificado)
        chave, cert = certificado_a1.separar_arquivo(self.certificado_senha,
                                                     caminho=True)
        chave_cert = (cert, chave)
        # Abre a conexão HTTPS
        try:
            xml_declaration = '<?xml version="1.0" encoding="UTF-8"?>'

            # limpa xml com caracteres bugados para infMDFeSupl em NFC-e
            xml = re.sub(
                '<qrCodMDFe>(.*?)</qrCodMDFe>', lambda x: x.group(0).replace(
                    '&lt;', '<').replace('&gt;', '>').replace('amp;', ''),
                etree.tostring(xml, encoding='unicode').replace('\n', ''))
            xml = xml_declaration + xml
            xml = xml.encode(
                'utf8')  # necessário para o evento "CONSULTAR NÃO ENCERRADOS"

            print(xml)
            print('-' * 20)

            # Faz o request com o servidor
            result = requests.post(url,
                                   xml,
                                   headers=self._post_header(),
                                   cert=chave_cert,
                                   verify=False,
                                   timeout=50)
            result.encoding = 'utf-8'
            return result
        except requests.exceptions.Timeout as e:
            raise e
        except requests.exceptions.RequestException as e:
            raise e
        finally:
            certificado_a1.excluir()
Beispiel #10
0
f = open("mylog.xml", "w")
a = str(etree.tostring(xml))
f.write(a)
f.close()
#a1 = AssinaturaA1(certificado, "1234")
#xml = a1.assinar(xml)
res = post(xml, url)
f = open("file.txt", "w")
a = str(res.content)
f.write(a)
f.close()
print(a)
'''

#'''
certificado_a1 = CertificadoA1(certificado)
chave, cert = certificado_a1.separar_arquivo(senha, caminho=True)
chave_cert = (cert, chave)
f = open("xmlfuncional.xml", "r")
a1 = AssinaturaA1(certificado, senha)
xml = etree.XML(f.read())
xml = a1.assinar(xml)
print(etree.tostring(xml))
#a1 = AssinaturaA1(certificado, "1234")
#xml = a1.assinar(xml)
#print(etree.tostring(xml))
res = mdfe.post(xml, url, chave_cert)
f = open("file.txt", "w")
a = str(res.content)
f.write(a)
f.close()