Error 400 when sending request to ESocial (C #)

3

I'm getting 400 error response to executing the SOAP request on eSocial servers. The error occurs in this command:

using (HttpWebResponse resposta = request.GetResponse() as HttpWebResponse)
  • I installed the certificate chains.
  • I installed the chains by putting all the certificates in the Local Machine Root repository
  • I installed the chains by placing only the Brazilian Root Certification Authority v5 in the Root repository and the rest in the broker repository.
  • I installed the certificate (valid, not expired and with correct password) from my client in the Personal repository (On the local Machine and the Current User).

It means that I can access the webservices addresses through the browser and the padlock turns green.

This is my code:

/// <summary>
/// Cria um webrequest SOAP para [Url]
/// </summary>
/// <returns></returns>
[HttpPost]
private static string enviarRequisicao()
{
    try
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        string web_service_teste =    "https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";                
        string xml_soap = @"C:\esocial\Templates\Esocial-S1000.xml";
        string url = web_service_teste;
        string response = "";
        Stream post = null;
        X509Certificate2 cert = new X509Certificate2(@"C:\esocial\certificado.pfx", "****");
        // build request objects to pass the data/xml to the server
        byte[] buffer = Encoding.ASCII.GetBytes(xml_soap);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = "POST";
        request.ContentType = "text/xml;charset=utf-8";                
        //request.Accept = "text/xml";
        request.ContentLength = buffer.Length;
        request.ClientCertificates.Add(cert);

        using (post = request.GetRequestStream())
        {
            // post data and close connection
            post.Write(buffer, 0, buffer.Length);
            post.Close();
        }

        using (HttpWebResponse resposta = request.GetResponse() as HttpWebResponse)
        {
            using (var stream = resposta.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    var result = reader.ReadToEnd();
                    // Do something with result
                    return result;
                }
            }
        }
    }
    catch (WebException ex)
    {                
        throw ex;                
    }
}

This is XML:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Body>
        <eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v02_04_02">
            <envioLoteEventos grupo="1">
            <ideEmpregador>
                <tpInsc>1</tpInsc>
                <nrInsc>78294442</nrInsc>
            </ideEmpregador>
            <ideTransmissor>
                <tpInsc>1</tpInsc>
                <nrInsc>00254265000116</nrInsc>
            </ideTransmissor>
            <eventos>
                <evento Id="ID1333733250000002017122110411700002">
                    <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtTabRubrica/v02_04_02">
                        <evtInfoEmpregador Id="ID1027327500001832016021911320900001">
                        <ideEvento>
                            <tpAmb>2</tpAmb>
                            <procEmi>1</procEmi>
                            <verProc>1.0</verProc>
                        </ideEvento>
                        <ideEmpregador>
                            <tpInsc>1</tpInsc>
                            <nrInsc>78294442</nrInsc>
                        </ideEmpregador>
                        <infoEmpregador>
                            <inclusao>
                                <idePeriodo>
                                    <iniValid>2017-10</iniValid>
                                </idePeriodo>
                                <infoCadastro>
                                    <nmRazao>LIGA ARTE MOVEIS LTDA EPP</nmRazao>
                                    <classTrib>99</classTrib>
                                    <natJurid>399-</natJurid>
                                    <indCoop>0</indCoop>
                                    <indConstr>0</indConstr>
                                    <indDesFolha>0</indDesFolha>
                                    <indOptRegEletron>1</indOptRegEletron>
                                    <indEntEd>N</indEntEd>
                                    <indEtt>N</indEtt>
                                    <contato>
                                    <nmCtt>Cristiano dos Santos Lagame</nmCtt>
                                    <cpfCtt>08550234737</cpfCtt>
                                    <foneFixo>2122740494</foneFixo>
                                    </contato>
                                    <softwareHouse>
                                    <cnpjSoftHouse>00254265000116</cnpjSoftHouse>
                                    <nmRazao>LIGA ARTE MOVEIS LTDA EPP</nmRazao>
                                    <nmCont>Cristiano dos Santos Lagame</nmCont>
                                    <telefone>21993623199</telefone>
                                    <email>[email protected]</email>
                                    </softwareHouse>
                                    <infoComplementares>
                                    <situacaoPJ>
                                        <indSitPJ>0</indSitPJ>
                                    </situacaoPJ>
                                    <situacaoPF>
                                        <indSitPF>0</indSitPF>
                                    </situacaoPF>
                                    </infoComplementares>
                                </infoCadastro>
                            </inclusao>
                        </infoEmpregador>
                        </evtInfoEmpregador>
                        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
                        <SignedInfo>
                            <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                            <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
                            <Reference URI="">
                                <Transforms>
                                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                                    <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                                </Transforms>
                                <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                                <DigestValue>...</DigestValue>
                            </Reference>
                        </SignedInfo>
                        <SignatureValue>...</SignatureValue>
                        <KeyInfo>
                            <X509Data>
                                <X509Certificate>TqIsONfPFt6L9tVM3CElBZeynQ1AlzzyZhpNX9YUTgiALPhv4eCxF/I0djghAj56FYBJMeWA4uwyGLA9L6VWMO1ksnuAsBHTWNd4/CI2IflwhlbCujgP91rBZOZJnr0YCQM9El92dUhVB0zBkFLvP14lDbyRIivF76ZlG3EeCCp8eCPi2QFoVY8N9tUpBNDSJPqkXSxgxvxPXQqfRsmwqoeVvd8sFKEmO4a5crmPbyExYOrrjoQoFhhgiagmS3O8rtjXBsWV9pKx435/mOMmU3/hGrWlIJfx4FQ7loqQZh/NVHRTXguMqua2m3QzSkVfw5oreZxbGUh9i0uZ0Dpocg==</X509Certificate>
                            </X509Data>
                        </KeyInfo>
                        </Signature>
                    </eSocial>
                </evento>
            </eventos>
            </envioLoteEventos>
        </eSocial>
    </soap:Body>
</soap:Envelope>

Detail, I got the error 403, but I resolved through of this post .

Update: The XML was incorrect, I discovered here which was the correct formatting. I found it important to mention here that I changed the code to this one below with the instructions of @Pedro Gaspar:

private static string enviarRequisicao()
{
    try
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        //string web_service_teste = "https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";
        //              string web_service_producao = "https://webservices.envio.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";

        string urlXML = @"C:\esocial\Templates\Esocial-S1000.xml";

        X509Certificate2 x509Cert = new X509Certificate2(@"C:\esocial\certificado.pfx", "12345678");

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        XDocument loteEventosXDoc = XDocument.Load(urlXML);

        var urlServicoEnvio = @"https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";
        var address = new EndpointAddress(urlServicoEnvio);
        var binding = new BasicHttpsBinding();  //Disponível desde .NET Framework 4.5
                                                // ou:
                                                //var binding = new BasicHttpBinding(BasicHttpsSecurityMode.Transport);
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

        binding.MaxReceivedMessageSize = 768000;

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
                                SecurityProtocolType.Tls11 |
                                SecurityProtocolType.Tls12;

        var wsClient = new PortalMadeirol.Web.ServiceEsocial.ServicoEnviarLoteEventosClient(binding, address);

        // Variável 'x509Cert' é do tipo X509Certificate2.

        wsClient.ClientCredentials.ClientCertificate.Certificate = x509Cert;

        var retornoEnvioXElement = wsClient.EnviarLoteEventos(loteEventosXDoc.Root);
        wsClient.Close();
    }
    catch (WebException ex)
    {
        throw ex;
    }
}
    
asked by anonymous 10.09.2018 / 15:04

1 answer

2

Cristiano, while suggesting in the comments that you create a reference to the eSocial service through the service's WSDL, and use the generated class that inherits System.ServiceModel.ClientBase , so that .NET does all the SOAP communication work for you, instead of having to do everything at hand (suggestion including that you accepted and already made it work) out of curiosity, and to try to answer your original question, I tried to make your original code work by accessing eSocial "on hand "through HttpWebRequest .

I had to do some XML fixes, as you mentioned in some namespaces, but I also had to include the EnviarLoteEventos group at the beginning of the body of the message, so the XML was like this (I also changed your personal data ):

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <EnviarLoteEventos xmlnm="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
         <eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
            <envioLoteEventos grupo="1">
               <ideEmpregador>
                  <tpInsc>1</tpInsc>
                  <nrInsc>87654321</nrInsc>
               </ideEmpregador>
               <ideTransmissor>
                  <tpInsc>1</tpInsc>
                  <nrInsc>12345678901234</nrInsc>
               </ideTransmissor>
               <eventos>
                  <evento Id="ID1876543210000002017122110411700002">
                     <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_04_02">
                        <evtInfoEmpregador Id="ID1876543210001832016021911320900001">
                           <ideEvento>
                              <tpAmb>2</tpAmb>
                              <procEmi>1</procEmi>
                              <verProc>1.0</verProc>
                           </ideEvento>
                           <ideEmpregador>
                              <tpInsc>1</tpInsc>
                              <nrInsc>78294442</nrInsc>
                           </ideEmpregador>
                           <infoEmpregador>
                              <inclusao>
                                 <idePeriodo>
                                    <iniValid>2017-01</iniValid>
                                 </idePeriodo>
                                 <infoCadastro>
                                    <nmRazao>RAZÃO EMPREGADOR</nmRazao>
                                    <classTrib>99</classTrib>
                                    <natJurid>2062</natJurid>
                                    <indCoop>0</indCoop>
                                    <indConstr>0</indConstr>
                                    <indDesFolha>0</indDesFolha>
                                    <indOptRegEletron>1</indOptRegEletron>
                                    <indEntEd>N</indEntEd>
                                    <indEtt>N</indEtt>
                                    <contato>
                                       <nmCtt>Nome Contato</nmCtt>
                                       <cpfCtt>12345678901</cpfCtt>
                                       <foneFixo>2112345678</foneFixo>
                                    </contato>
                                    <softwareHouse>
                                       <cnpjSoftHouse>12345678901234</cnpjSoftHouse>
                                       <nmRazao>RAZÃO SOFTWAREHOUSE</nmRazao>
                                       <nmCont>Nome Contato</nmCont>
                                       <telefone>21123456789</telefone>
                                       <email>[email protected]</email>
                                    </softwareHouse>
                                    <infoComplementares>
                                       <situacaoPJ>
                                          <indSitPJ>0</indSitPJ>
                                       </situacaoPJ>
                                    </infoComplementares>
                                 </infoCadastro>
                              </inclusao>
                           </infoEmpregador>
                        </evtInfoEmpregador>
                        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
                           <SignedInfo>
                              <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                              <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
                              <Reference URI="">
                                 <Transforms>
                                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                                    <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                                 </Transforms>
                                 <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                                 <DigestValue>...</DigestValue>
                              </Reference>
                           </SignedInfo>
                           <SignatureValue>...</SignatureValue>
                           <KeyInfo>
                              <X509Data>
                                 <X509Certificate>...</X509Certificate>
                              </X509Data>
                           </KeyInfo>
                        </Signature>
                     </eSocial>
                  </evento>
               </eventos>
            </envioLoteEventos>
         </eSocial>
      </EnviarLoteEventos>
   </soap:Body>
</soap:Envelope>

In the code I changed the way I read the XML:

//byte[] buffer = Encoding.ASCII.GetBytes(xml_soap);
XDocument soapEnvelopeXml = XDocument.Load(xml_soap);

//[...]

   //post.Write(buffer, 0, buffer.Length);
   soapEnvelopeXml.Save(post);

Then the error went from 400 to 500 ).

Thanks to this answer here, from SO EN : link , I improved the treatment of error to know exactly what error was happening, that's where I got the XML.

It was also essential to inform SOAPAction in the request header, because that is what indicates which service method should be called.

So your changed code looked like this:

private static string enviarRequisicao()
{
   try
   {
      string web_service_teste = "https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";
      string xml_soap = @"C:\esocial\Templates\Esocial-S1000.xml";
      string url = web_service_teste;
      X509Certificate2 cert = new X509Certificate2(@"C:\esocial\certificado.pfx", "****");

      //byte[] buffer = Encoding.ASCII.GetBytes(xml_soap);
      XDocument soapEnvelopeXml = XDocument.Load(xml_soap);

      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

      request.Method = "POST";
      request.Headers.Add("SOAPAction", "http://www.esocial.gov.br/servicos/empregador/lote/eventos/envio/v1_1_0/ServicoEnviarLoteEventos/EnviarLoteEventos");
      request.ContentType = "text/xml;charset=utf-8";
      //request.Accept = "text/xml";
      //request.ContentLength = buffer.Length;
      request.ClientCertificates.Add(cert);

      using (Stream post = request.GetRequestStream())
      {
         // post data and close connection
         //post.Write(buffer, 0, buffer.Length);
         soapEnvelopeXml.Save(post);
         //post.Close();
      }

      using (HttpWebResponse resposta = request.GetResponse() as HttpWebResponse)
      {
         using (var stream = resposta.GetResponseStream())
         {
            using (var reader = new StreamReader(stream))
            {
               var result = reader.ReadToEnd();
               return result;
            }
         }
      }
   }
   catch (WebException webex)
   {
      WebResponse errResp = webex.Response;
      using (Stream respStream = errResp.GetResponseStream())
      {
         StreamReader reader = new StreamReader(respStream);
         string text = reader.ReadToEnd();
         return text;
      }
   }
}

The SOAPAction I discovered by looking at the service's WSDL, at:

  

link

That way it worked for me.

    
13.09.2018 / 18:40