Enviando uma Nota Fiscal Eletronica

Salve GUJ, problemas com a Nota Fiscal Eletronica (ja busquei aqui no forum e já achei até alguns códigos mas ainda estou perdidaço)

Galera é o seguinte ja consegui gerar o XML e Assinar o XML (se alguem precisar de ajuda em algum desses passos é só pedir que eu ajudo), porém agora eu preciso me comunicar com o WebService para enviar/cancelar/solicitar Status/entre outros serviços.

Só que eu nem sei direito por onde começar (nunca trabalhei com SOAP/WSDL/etc), eu ja baixei os arquivos WSDL do governo e ja tenho um certificado .pfx (que eu assinei o XML), no eclipse já gerei as classes java para os arquivos WSDL. Mas e agora como me conectar no WebService por onde eu começo???

Existe algum tutorial que vcs me recomendam, algum livro, algum curso qq coisa???

se alguem puder me passar algum exemplo eu agradeço…

De cada 10 pessoas desse forum, sobre NF-e ajudei 9.
Pelo oq eu percebi vc ja passou de alguns passos. Bom pra comsumir os WebServices, vc precisa gerar as classes dos XSD. Eu e muita gente tem usado JAXB pela facilidade e de gerar as classes. Mas com as classes geradas em cima do WSDL ja da pra acessa sem problemas.
Qualquer coisa me manda um email ai agente coloca um feedback aqui no forum.

Abracos e bons codigos.

Andei fazendo alguns avanços no envio da nota , mas ainda não consegui estou recebendo um erro alguem pode me ajudar???

É o seguinte eu tinha somente o arquivo .pfx e executei o seguinte comando para gerar o arquivo .jks
keytool -genkeypair -alias www.testenfe.com -keyalg RSA -file C:\certificados\cert.pfx -keypass SENHA -storepass SENHA -keystore C:\certificado\cert.jks -validity 2000

o Arquivo gerou com sucesso, então executei o seguinte código:

public static void main(String[] args) {

		String nfeCabecMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			+ "<cabecMsg xmlns=\"http://www.portalfiscal.inf.br/nfe\" "
			+ "versao=\"1.02\">" + "<versaoDados>1.07</versaoDados>"
			+ "</cabecMsg>";

		String nfeDadosMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			+ "<consStatServ " + " versao=\"1.07\""
			+ " xmlns=\"http://www.portalfiscal.inf.br/nfe\">"
			+ "<tpAmb>2</tpAmb>" + "<cUF>42</cUF>"
			+ "<xServ>STATUS</xServ>" + "</consStatServ>";

		System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

		System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
		System.setProperty("javax.net.ssl.keyStore","C:\\certificados\\cert.pfx");
		System.setProperty("javax.net.ssl.keyStorePassword", "SENHA");

		System.setProperty("javax.net.ssl.trustStoreType", "JKS");
		System.setProperty("javax.net.ssl.trustStore", "C:\\certificados\\cert.jks");
		System.setProperty("javax.net.ssl.trustStorePassword", "SENHA");  

		NfeStatusServico service = new NfeStatusServicoLocator();
		try {
			NfeStatusServicoSoap nfeStatus = service.getNfeStatusServicoSoap();
			System.out.println(nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg));
		} catch (Throwable e1) {
			e1.printStackTrace();
		}
	}

As classes NfeStatusServico e NfeStatusServicoSoap foram geradas com o Eclipse a partir dos arquivos WSDL do governo.
Mas esse código da o seguinte erro:

AxisFault
 faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
 faultSubcode: 
 faultString: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 faultActor: 
 faultNode: 
 faultDetail: 
	{http://xml.apache.org/axis/}stackTrace:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
	at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:186)
	at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
	at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
	at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138)
	at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
	at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
	at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
	at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
	at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
	at org.apache.axis.client.Call.invoke(Call.java:2767)
	at org.apache.axis.client.Call.invoke(Call.java:2443)
	at org.apache.axis.client.Call.invoke(Call.java:2366)
	at org.apache.axis.client.Call.invoke(Call.java:1812)
	at br.com.multitecsistemas.nfe.service.NfeStatusServicoSoapStub.nfeStatusServicoNF(NfeStatusServicoSoapStub.java:110)
	at br.com.multitecsistemas.nfe.service.Teste.main(Teste.java:37)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
	at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
	at sun.security.validator.Validator.validate(Unknown Source)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
	... 23 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
	at java.security.cert.CertPathBuilder.build(Unknown Source)
	... 29 more

	{http://xml.apache.org/axis/}hostname:multitec-6c5024

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
	at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154)
	at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
	at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
	at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
	at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
	at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
	at org.apache.axis.client.Call.invoke(Call.java:2767)
	at org.apache.axis.client.Call.invoke(Call.java:2443)
	at org.apache.axis.client.Call.invoke(Call.java:2366)
	at org.apache.axis.client.Call.invoke(Call.java:1812)
	at br.com.multitecsistemas.nfe.service.NfeStatusServicoSoapStub.nfeStatusServicoNF(NfeStatusServicoSoapStub.java:110)
	at br.com.multitecsistemas.nfe.service.Teste.main(Teste.java:37)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
	at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:186)
	at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
	at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
	at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138)
	... 11 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
	at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
	at sun.security.validator.Validator.validate(Unknown Source)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
	... 23 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
	at java.security.cert.CertPathBuilder.build(Unknown Source)
	... 29 more

Alguem pode me ajudar???

Muito Obrigado

Olá.

Estou no mesmo ponto que vcs. Criei uma classe no NetBeans utilizando os WSDL. Alguém teve algum progresso, ao menos para a obtenção do Status do serviço?

Obrigado

Da uma olhada neste post:

http://www.guj.com.br/posts/list/15/52035.java

eu coloquei um passo a passo ai, e ta funcionando 100%;

Alguem sabe me explicar como faço para gerar as classes a partir do XSD com o JAXB?

Estou fazendo assim:
xjc -d …/src -p nfe.xsd atuCadEmiDFe_v1.01.xsd
xjc -d …/src -p nfe.xsd cabecMsg_v1.02.xsd

isso para cada um dos arquivos xsd que baixei da página, mas quando tento gerar por exemplo uma mensagem de cabeçalho:

		CabecMsg cabecalho = new CabecMsg();
		cabecalho.setVersaoDados("1.07");
		cabecalho.setVersao("1.02");
		
		JAXBContext jc = JAXBContext.newInstance( "nfe.xsd" );
		
		StringWriter writer = new StringWriter();
		
		Marshaller m = jc.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
		m.marshal( cabecalho, writer );

Obtenho um erro: javax.xml.bind.JAXBException: nfe.xsd.CabecMsg nor any of its super class is known to this context

Agora se eu rodar novamente o comando:
xjc -d …/src -p nfe.xsd cabecMsg_v1.02.xsd

passa a funcionar.
Alguém sabe me explicar o porque disso? e como faço para resolver esse problema?

Vale a pena conhecer o componente SpeedLabs Nfe, ele faz todo o processo de emissão de NF-e, e integra por arquivo texto e XML.
www.speedcase.com.br/lab/nfe

Obrigado!

Gerar classes Nf-e com jaxb
http://www.technopub.com.br/arquivo/6

Estou com problema com um certificado .pfx de um cliente:

Minha aplicação está funcionando perfeitamente em um cliente com o mesmo certificado .pfx (tipo A1), mes em outro cliente ao tentar acessar qualquer um dos web services dá o seguinte erro:

[b]
com.sun.xml.internal.ws.wsdl.parser.InaccessibleWSDLException: 2 counts of InaccessibleWSDLException.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(RuntimeWSDLParser.java:161)
    at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:133)
    at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:254)
    at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:217)
    at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:165)
    at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:93)
    at javax.xml.ws.Service.<init>(Service.java:56)
    at br.inf.portalfiscal.nfe.wsdl.nfestatusservico.NfeStatusServico.<init>(NfeStatusServico.java:44)
    at Main.main(Main.java:45)

[/b]

Minha classe de teste:


public class Main {

    public static void main(String... args) {
        try {
            acceptSSL();
            System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

            //System.setProperty("javax.net.ssl.trustStoreType", "JKS");
            System.setProperty("javax.net.ssl.trustStore", "c:\\homologa_SP");  // Arquivo gerado com o InstallCert

            System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
            System.setProperty("javax.net.ssl.keyStore", "c:\\arquivo_certificado.pfx");  // o arquivo com o certificado do emitente
            System.setProperty("javax.net.ssl.keyStorePassword", "senha");  // a senha do arquivo

            
           

            NfeStatusServicoNF status = new ObjectFactory().createNfeStatusServicoNF();
            
            status.setNfeCabecMsg("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><cabecMsg xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"1.02\"><versaoDados>1.07</versaoDados></cabecMsg>");
            status.setNfeDadosMsg("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><consStatServ xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"1.07\"><tpAmb>2</tpAmb><cUF>35</cUF><xServ>STATUS</xServ></consStatServ>");
            NfeStatusServico service = new NfeStatusServico(new URL("https://homologacao.nfe.fazenda.sp.gov.br/nfeweb/services/nfestatusservico.asmx "), new QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico", "NfeStatusServico"));
            NfeStatusServicoSoap soap = service.getNfeStatusServicoSoap();
            String result = soap.nfeStatusServicoNF(status.getNfeCabecMsg(), status.getNfeDadosMsg());

            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void acceptSSL() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }
    }
}

Será que falta algum cadastro? Segundo o cliente o já foram feitos todos os cadastros na Sefaz.
E com esse mesmo certificado o cliente está usando perfeitamente (em produção) o programa da receita para envio de Nfe.

Agradeço a quem puder ajudar.

Meu certificado do site da receita estava vencido, baixei outro e o erro é esse:

[b]
com.sun.xml.internal.ws.wsdl.parser.InaccessibleWSDLException: 2 counts of InaccessibleWSDLException.

java.io.IOException: Server returned HTTP response code: 403 for URL: https://homologacao.nfe.fazenda.sp.gov.br/nfeweb/services/nfestatusservico.asmx
java.io.IOException: Server returned HTTP response code: 403 for URL: https://homologacao.nfe.fazenda.sp.gov.br/nfeweb/services/nfestatusservico.asmx?wsdl

    at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(RuntimeWSDLParser.java:161)
    at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:133)
    at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:254)
    at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:217)
    at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:165)
    at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:93)
    at javax.xml.ws.Service.<init>(Service.java:56)
    at br.inf.portalfiscal.nfe.wsdl.nfestatusservico.NfeStatusServico.<init>(NfeStatusServico.java:44)
    at Main.main(Main.java:41)

[/b]

Pelo que vi nesse site http://nf-eletronica.com/blog/?page_id=93 o problema provavelmente está no certificado (.pfx), mas quando acesso o Web Service pelo browse não tenho nenhum problema.

Alguém já teve algum problema parecido?

Estou enfrentando o mesmo problema! alguém sabe como resolver?

Estou enfrentando o mesmo problema. Uso as configurações abaixo:

        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
        System.setProperty("javax.net.ssl.keyStore", "/caminho/absoluto/certificado.pfx");
        System.setProperty("javax.net.ssl.keyStorePassword", "senha");
        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
        System.setProperty("javax.net.ssl.trustStore", "/caminho/absoluto/arquivo.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "senha_do_JKS");

E quando executo recebo o erro:

Exception in thread “main” com.sun.xml.internal.ws.client.ClientTransportException: HTTP transport error: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Olá danilo.magrini,

Tente refazer seu arquivo “arquivo.jks”, esse erro costuma estar relacionado a falta de certificados para consumir o Web Services da NF-e.

[quote=rafaelbtz]Salve GUJ, problemas com a Nota Fiscal Eletronica (ja busquei aqui no forum e já achei até alguns códigos mas ainda estou perdidaço)

Galera é o seguinte ja consegui gerar o XML e Assinar o XML (se alguem precisar de ajuda em algum desses passos é só pedir que eu ajudo), porém agora eu preciso me comunicar com o WebService para enviar/cancelar/solicitar Status/entre outros serviços.

Só que eu nem sei direito por onde começar (nunca trabalhei com SOAP/WSDL/etc), eu ja baixei os arquivos WSDL do governo e ja tenho um certificado .pfx (que eu assinei o XML), no eclipse já gerei as classes java para os arquivos WSDL. Mas e agora como me conectar no WebService por onde eu começo???

Existe algum tutorial que vcs me recomendam, algum livro, algum curso qq coisa???

se alguem puder me passar algum exemplo eu agradeço…

[/quote]

Cara, estou tentando encontrar um tutorial ou algo para realizar a conexão com a receita para para envio, impressão da DANFE, validação dos dados, etc. Estou buscando algo para realizar esses procedimentos. Se você puder me ajudar e fico muito agradecido a você. Estou construindo um sistema para minha loja, em Java, o banco de dados é o MySQL, mais estou pensando em migrar para o SQL SERVER 2005 ou 2008 R2.

Desde já agradeço a sua atenção dispensada a este.

Att,

Amigos

Por favor me ajudem

Estou fazendo no JAX-WS com Weblogic e eu tentei colocar

System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");  
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());  
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");  
System.setProperty("javax.net.ssl.keyStore", "/caminho/absoluto/certificado.pfx");  
System.setProperty("javax.net.ssl.keyStorePassword", "senha");  
System.setProperty("javax.net.ssl.trustStoreType", "JKS");  
System.setProperty("javax.net.ssl.trustStore", "/caminho/absoluto/arquivo.jks");  
System.setProperty("javax.net.ssl.trustStorePassword", "senha_do_JKS");  

Ele funciona na IDE mas quando mando pro Weblogic ele dá exception conection reset.

Tem alguma outra forma de fazer isso?

Obrigado