Social submission problems: Invalid event subscription

Asked

Viewed 733 times

1

Using RobRichards, I am trying to get a positive response in sending the XML, but always accuses the message:

"Invalid event signature. Suggested Actions: Check if there was event change after signing. Check the validity of signing."

I have tried several ways both of signing and sending, but without success.

My PHP script:

<?php
    use RobRichards\XMLSecLibs\XMLSecurityDSig;
    use RobRichards\XMLSecLibs\XMLSecurityKey;

    $repository = getcwd().DIRECTORY_SEPARATOR;
    require $repository.'src\XMLSecurityKey.php';
    require $repository.'src\XMLSecurityDSig.php';
    require $repository.'src\XMLSecEnc.php';
    require $repository.'src\Utils/XPath.php';
    $array['xsd'] = 'evtInfoEmpregador';
    $array['pem'] = $repository.'ARQUIVO.pem';
    $array['pass'] = 'PASSWORD';
    $array['xml'] = 'S1000.xml';
    $array['xml-assinado'] = 'S1000-assinado.xml';

    function connWsEsocial($array){
        $options = array(
            'ssl' => array(
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true,
                'capture_peer_cert' => true
            ),
            'http' => array('timeout' => 5) //seconds
        );
        $stream = stream_context_create($options);
        $paramsSoap = array(
            'encoding'           => 'UTF-8',
            'local_cert'         => $array['pem'],
            'passphrase'         => $array['pass'],
            'cache_wsdl'         => WSDL_CACHE_NONE,
            'exceptions'         => true,
            'trace'              => true,
            "use"                => SOAP_ENCODED,
            "style"              => SOAP_RPC,
            'stream_context'     => $stream,
            'soap_version'       => SOAP_1_1,
            'connection_timeout' => 25 //seconds
        );
        try{
            $connSoap = new SoapClient($array['wsdl'], $paramsSoap);
            return $connSoap;
        } catch(SoapFault $fault){
            trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
            exit;
        }
    }

    function sendXmlEsocial($xml, $connSoap, $type){
        $headers = array();
        $headers[] = new SoapHeader('http://www.w3.org/2001/XMLSchema-instance','xsi');
        $headers[] = new SoapHeader('http://www.w3.org/2001/XMLSchema','xsd');
        $headers[] = new SoapHeader('http://www.w3.org/2003/05/soap-envelope','soap');
        $connSoap->__setSoapHeaders($headers);
        switch($type){
            case 'envio':
                $sXml = '<EnviarLoteEventos xmlns="http://www.esocial.gov.br/servicos/empregador/lote/eventos/envio/v1_1_0"><loteEventos>'.$xml.'</loteEventos></EnviarLoteEventos>';
                $paramSoapCall = new SoapVar($sXml, XSD_ANYXML);
                $response = $connSoap->EnviarLoteEventos($paramSoapCall);
                $objXml = simplexml_load_string($response->EnviarLoteEventosResult->any);
                print '<textarea style="height:300px; width:70%;">'; print_r($objXml); print '</textarea><br>';
                return $objXml->retornoEnvioLoteEventos->dadosRecepcaoLote->protocoloEnvio;
            break;

            case 'consulta':
                $paramSoapCall = new SoapVar($xml, XSD_ANYXML);
                $response = $connSoap->ConsultarLoteEventos($paramSoapCall);
                $objXml = simplexml_load_string($response->ConsultarLoteEventosResult->any);
                print '<textarea style="height:300px; width:70%;">'; print_r($objXml); print '</textarea><br>';
            break;
        }
    }

    $doc = new DOMDocument();
    $doc->load($array['xml']);
    $objDSig = new XMLSecurityDSig();
    $objDSig->setCanonicalMethod(XMLSecurityDSig::C14N);
    $objDSig->addReference($doc, XMLSecurityDSig::SHA256, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'));
    $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type'=>'private'));
    $objKey->passphrase = $array['pass'];
    $objKey->loadKey($array['pem'], TRUE);
    $objDSig->sign($objKey);
    $objDSig->add509Cert(file_get_contents($array['pem']));
    $objDSig->appendSignature($doc->documentElement);
    $doc->save($array['xml-assinado'], LIBXML_NOEMPTYTAG | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    /*$xml = str_replace('<?xml version="1.0"?>', '', file_get_contents($array['xml-assinado']));*/
    $xml = file_get_contents($array['xml-assinado']);
    print '<textarea style="height:300px; width:70%;">'.$xml.'</textarea><br>';

    $array['wsdl'] = 'https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc?singleWsdl'; //HOMOLOGAÇÃO
    $connSoap = connWsEsocial($array);
    $xmlLote = '<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1"><envioLoteEventos grupo="1"><ideEmpregador><tpInsc>1</tpInsc><nrInsc>CNPJ</nrInsc></ideEmpregador><ideTransmissor><tpInsc>1</tpInsc><nrInsc>CNPJ</nrInsc></ideTransmissor><eventos><evento Id="ID1">'.$xml.'</evento></eventos></envioLoteEventos></eSocial>';
    $protocolo = sendXmlEsocial($xmlLote, $connSoap, 'envio');

    $array['wsdl'] = 'https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/consultarloteeventos/WsConsultarLoteEventos.svc?singleWsdl'; //HOMOLOGAÇÃO
    $connSoap = connWsEsocial($array);
    $cXml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.esocial.gov.br/schema/lote/eventos/envio/consulta/retornoProcessamento/v1_1_0"><soapenv:Header/><soapenv:Body><v1:ConsultarLoteEventos><v1:consulta><eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/consulta/retornoProcessamento/v1_0_0"><consultaLoteEventos><protocoloEnvio>'.$protocolo.'</protocoloEnvio></consultaLoteEventos></eSocial></v1:consulta></v1:ConsultarLoteEventos></soapenv:Body></soapenv:Envelope>';
    sendXmlEsocial($cXml, $connSoap, 'consulta');
?>

EDITION

Follows XML:

<eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_05_00">
  <evtInfoEmpregador Id="ID1071163060000002019030716513500000">
    <ideEvento>
      <tpAmb>2</tpAmb>
      <procEmi>1</procEmi>
      <verProc>V020500</verProc>
    </ideEvento>
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306</nrInsc>
    </ideEmpregador>
    <infoEmpregador>
      <inclusao>
        <idePeriodo>
          <iniValid>2019-03</iniValid>
        </idePeriodo>
        <infoCadastro>
          <nmRazao>RAZAO SOCIAL</nmRazao>
          <classTrib></classTrib>
          <natJurid></natJurid>
          <indCoop>0</indCoop>
          <indConstr>0</indConstr>
          <indDesFolha>0</indDesFolha>
          <indOptRegEletron>0</indOptRegEletron>
          <indEntEd>N</indEntEd>
          <indEtt>N</indEtt>
          <contato>
            <nmCtt>NOME CONTADOR</nmCtt>
            <cpfCtt>23665896588</cpfCtt>
            <foneFixo>1123652365</foneFixo>
            <email>[email protected]</email>
          </contato>
          <softwareHouse>
            <cnpjSoftHouse>2345345243523535</cnpjSoftHouse>
            <nmRazao>SOFTWARE HOUSE LTDA</nmRazao>
            <nmCont>NOME COMPLETO</nmCont>
            <telefone>1123652365</telefone>
            <email>[email protected]</email>
          </softwareHouse>
          <infoComplementares>
            <situacaoPJ>
              <indSitPJ>0</indSitPJ>
            </situacaoPJ>
          </infoComplementares>
        </infoCadastro>
      </inclusao>
    </infoEmpregador>
  </evtInfoEmpregador>
</eSocial>

And the XML Batch is this:

<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
  <envioLoteEventos grupo="1">
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306</nrInsc>
    </ideEmpregador>
    <ideTransmissor>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306000156</nrInsc>
    </ideTransmissor>
    <eventos>
      <evento Id="ID1071163060000002019030716513500000">XML ASSINADO</evento>
    </eventos>
  </envioLoteEventos>
</eSocial>

This is the signed XML:

<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
  <envioLoteEventos grupo="1">
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306</nrInsc>
    </ideEmpregador>
    <ideTransmissor>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306000157</nrInsc>
    </ideTransmissor>
    <eventos>
      <evento Id="ID1071163060000002019030716513500000">
        <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_05_00">
          <evtInfoEmpregador Id="ID1071163060000002019030716513500000">
            <ideEvento>
              <tpAmb>2</tpAmb>
              <procEmi>1</procEmi>
              <verProc>v02_05_00</verProc>
            </ideEvento>
            <ideEmpregador>
              <tpInsc>1</tpInsc>
              <nrInsc>07116306</nrInsc>
            </ideEmpregador>
            <infoEmpregador>
              <inclusao>
                <idePeriodo>
                  <iniValid>2019-03</iniValid>
                </idePeriodo>
                <infoCadastro>
                  <nmRazao>RAZAO SOCIAL</nmRazao>
                  <classTrib>01</classTrib>
                  <natJurid>2062</natJurid>
                  <indCoop>0</indCoop>
                  <indConstr>0</indConstr>
                  <indDesFolha>0</indDesFolha>
                  <indOptRegEletron>0</indOptRegEletron>
                  <indEntEd>N</indEntEd>
                  <indEtt>N</indEtt>
                  <contato>
                    <nmCtt>NOME COMPLETO</nmCtt>
                    <cpfCtt>12345678999</cpfCtt>
                    <foneFixo>1134684850</foneFixo>
                    <email>[email protected]</email>
                  </contato>
                  <softwareHouse>
                    <cnpjSoftHouse>01234567890000</cnpjSoftHouse>
                    <nmRazao>softwareHouse LTDA</nmRazao>
                    <nmCont>NOME COMPLETO</nmCont>
                    <telefone>1123652365</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>HZxjQxHchEUvK6A1CH+3OOUsgze5Czdw+1.....</DigestValue>
              </Reference>
            </SignedInfo>
            <SignatureValue>ihjBzQZ9Q4DXQNxR8UZR/fKSCEnQDOVyW+WD4ztGZztNoR8s9oySx+6CV1B+SSSIXvMQWHIzr.....</SignatureValue>
            <KeyInfo>
              <X509Data>
                <X509Certificate>MIIH/jCCBeagAw.....
  </envioLoteEventos>
</eSocial>
  • Please post the XML you are using to sign and send ($array['xml'] = 'S1000.xml';), and also post the code snippet where you replace the placheholders CNPJ and ID1, in the variable $xmlLote used in function sendXmlEsocial().

  • Pedro Gaspar, I just posted the two of you already with the amounts due.

  • I edited your question and put the Xmls there. Delete the answer you posted here later, please. Can you also put the XML of the event after signing? Is this event ID you’re holding in your hand at some point or is the information already filled in before the signing? You make any changes to the XML of the signed event after signing?

  • I apologize for the ignorance. I am young and I am learning to move here. I do not change the XML no and as I have good database to store the information of the sending clients, I select in the database, mount the XML and then use the function for signature. After the mounted XML, before signing, I no longer move it. The ID I mount according to the E-social specifications. As it asks for a date, I mount it right away, before mounting the XML and adding it. Then with XML ready, send to sign. I will post an XML with the signature.

  • Tranquil Leonardo, no need to apologize. Not to be annoying, but, It was missing a piece in this last XML (signed) you posted... Put the full XML, please, so we can better analyze the problem!

2 answers

2


I analyzed your code and the Xmls and everything seems to be right, but then I realized that the problem seems to be on this line here:

   $doc->save($array['xml-assinado'],
              LIBXML_NOEMPTYTAG | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

First, when consulting the method documentation DOMDocument::save, I checked that this method only accepts the option LIBXML_NOEMPTYTAG, then the two other options (LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD) They’re just sitting there.

But what seems to be causing the problem in fact is the option LIBXML_NOEMPTYTAG, which, according to the documentation, expands empty tags:

LIBXML_NOEMPTYTAG
Expand Empty tags (e. g. <br/> to <br></br>)

In eSocial event XML there are no empty tags, but in the signature there are tags <CanonicalizationMethod />, <SignatureMethod />, <Transform /> and <DigestMethod />, then, the signed document is being changed, when this option is used.

See that in the basic library use example Xmlseclibs Rob Richards' method DOMDocument::save is used without any option:

   // Save the signed XML
   $doc->save('./path/to/signed.xml');

Then change this line I mentioned to:

   $doc->save($array['xml-assinado']);

that the problem must be solved.

  • Really the problem was solved with the replacement of this line. I want to thank everyone for their help. Project in operation.

  • @Leonardodelgado, good that it worked! But, the best way to thank for an answer is to mark it as accepted by clicking on the visa sign ( ). But do this only if any answer has answered your original question. When you reach 15 reputation points you can also vote in favour of an answer or question. See: Someone answered me and Why vote?.

  • Done! Grateful for everyone’s attention and collaboration!

-2

I had the same problem Signing of invalid event, I adopted this item from Pedro Gaspar’s reply

$doc->save($xml_assinado,LIBXML_NOEMPTYTAG | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

And I also put the FALSE item in this section to remove the prefixes "ds:" signed XML

$objDSig = new XMLSecurityDSig(FALSE);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.