Capture SOAP Header with PHP

Asked

Viewed 883 times

2

Good Afternoon

I am consuming a WSDL of a Webservice where after login and after each request as XML returned below me is presented the following tags in the head of Soap

<Sequencia> 1 </ Sequencia>
<SessionId> 4b4uc2536530-941f-44e6-ab95-8ee7179fb016 </ SessionId>
 

As a security rule I must save these and in the next request use the data for the next save request, in this new request will be generated new session and sequence and I must save them for another request and so on.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Header>
        <Sessao xmlns="http://dominio.com.br">
            <Sequencia>1</Sequencia>
            <SessionId>4b4uc2536530-941f-44e6-ab95-8ee7179fb016</SessionId>
            <Versao>
                <Id>1</Id>
                <SituacaoCache>Inalterado</SituacaoCache>
                <VersaoAtual>0</VersaoAtual>
                <ReleaseAtual>0</ReleaseAtual>
                <ProximaAtualizacao>0001-01-01T00:00:00</ProximaAtualizacao>
                <Minutos>0</Minutos>
                <VersaoDisponivel>
                    <VersaoRota>0</VersaoRota>
                    <VersaoBanco>0</VersaoBanco>
                    <ReleaseBanco>0</ReleaseBanco>
                    <Compilacao>0</Compilacao>
                </VersaoDisponivel>
                <QuantidadeReleases>0</QuantidadeReleases>
            </Versao>
        </Sessao>
    </soap:Header>
    <soap:Body>
        <LogOnResponse xmlns="http://dominio.com.br">
            <LogOnResult>
                <Excecoes />
                <DatabaseCount>0</DatabaseCount>
                <Retorno>
                    <Id>18659</Id>
                    <Nome>NOME</Nome>
                    <Email>[email protected]</Email>
                    <Endereco />
                    <Bairro />
                    <Cidade />
                    <Estado />
                    <Pais />
                    <Cep />
                    <LogOn>login</LogOn>
                    <DataNascimento>1984-09-17T00:00:00</DataNascimento>
                    <RG />
                    <Cpf>000.000.000-00</Cpf>
                    <Telefone />
                    <Celular />
                    <Configuracoes />
                    <Ativo>true</Ativo>
                    <Tema>Azul</Tema>
                    <Perfil>
                        <Id>12</Id>
                        <Nome>Sites Externos</Nome>
                        <Descricao />
                        <NiveisAcesso>
                            <CLPerfilNivelAcesso>
                                <Id>11</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <NivelAcesso>
                                    <Id>1</Id>
                                    <Nome>Usuário</Nome>
                                    <Codigo>1</Codigo>
                                    <Descricao />
                                </NivelAcesso>
                            </CLPerfilNivelAcesso>
                        </NiveisAcesso>
                        <Modulos>
                            <CLPerfilModulo>
                                <Id>19</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <Modulo>
                                    <Id>9</Id>
                                    <Nome>Portais</Nome>
                                    <Codigo>256</Codigo>
                                    <Descricao />
                                </Modulo>
                            </CLPerfilModulo>
                            <CLPerfilModulo>
                                <Id>20</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <Modulo>
                                    <Id>2</Id>
                                    <Nome>Processos</Nome>
                                    <Codigo>2</Codigo>
                                    <Descricao />
                                </Modulo>
                            </CLPerfilModulo>
                        </Modulos>
                        <Atividades />
                    </Perfil>
                    <Skype />
                    <EmpresaAtual>
                        <Id>0</Id>
                        <SituacaoCache>Inalterado</SituacaoCache>
                        <Nome />
                        <RazaoSocial />
                        <Cnpj />
                        <Endereco />
                        <Bairro />
                        <Cidade />
                        <Estado />
                        <Pais />
                        <Cep />
                        <SistemaWooba>
                            <Id>0</Id>
                            <SituacaoCache>Inalterado</SituacaoCache>
                            <Codigo />
                            <Nome />
                            <Wooba>0</Wooba>
                            <Observacoes />
                            <TemBilhetes>true</TemBilhetes>
                            <PermiteBilheteSemLocalizador>false</PermiteBilheteSemLocalizador>
                            <Campos />
                        </SistemaWooba>
                        <SistemaSisav>
                            <Id>0</Id>
                            <SituacaoCache>Inalterado</SituacaoCache>
                            <Codigo />
                            <Nome />
                            <Wooba>0</Wooba>
                            <Observacoes />
                            <TemBilhetes>true</TemBilhetes>
                            <PermiteBilheteSemLocalizador>false</PermiteBilheteSemLocalizador>
                            <Campos />
                        </SistemaSisav>
                        <Arquivo>
                            <Nome />
                            <Extensao />
                            <Hash />
                            <Conteudo />
                        </Arquivo>
                    </EmpresaAtual>
                    <DeveAlterarSenha>false</DeveAlterarSenha>
                    <SenhaNuncaExpira>false</SenhaNuncaExpira>
                    <DataAlteracaoSenha>2015-11-10T14:53:45.647</DataAlteracaoSenha>
                    <DataAlteracaoEmail>0001-01-01T00:00:00</DataAlteracaoEmail>
                    <DataAlteracaoCelular>0001-01-01T00:00:00</DataAlteracaoCelular>
                    <Perguntas>0</Perguntas>
                    <UsaBloqueioIP>false</UsaBloqueioIP>
                    <JornadaTrabalho>
                        <Id>0</Id>
                        <Nome />
                        <Prioridade>0</Prioridade>
                    </JornadaTrabalho>
                    <Sexo>Masculino</Sexo>
                    <TokenSSO />
                    <Arquivo>
                        <Nome />
                        <Extensao />
                        <Hash />
                        <Conteudo />
                    </Arquivo>
                </Retorno>
            </LogOnResult>
        </LogOnResponse>
    </soap:Body>
</soap:Envelope>
<pre>

in tests the PHP code below when running presents me the following message XML does not exist

$UrlWSLogin = new SoapClient('https://ws.dominio.com.br/integrador/integrador.asmx?WSDL', array('trace' => 1));
//print_r($UrlWS->__getFunctions());

$MetodoLoginWS = 'LogOn';

$DadosLoginWs = array(
    "Sequencia" => "0",
    "SessionId" => "0",
    "prUsuario" => "login",
    "prSenha" => "senha",
);

$ResultadoWS = $UrlWSLogin->$MetodoLoginWS($DadosLoginWs);

//$RespostaWS = '<pre>'.print_r($ResultadoWS,true).'</pre>';

if (isset($ResultadoWS)) {
    //echo '<pre>'. print_r($UrlWSLogin->__getLastResponse());'</pre>';
    
    $XMLws = $UrlWSLogin->__getLastResponse(); // usando __getLastResponse tenho acesso ao header do soap

    if (!$xml = simplexml_load_string("$XMLws")) {
        echo 'XML não existe';
    } else {
        echo $xml->Sessao->SessionId;
    }
    
    echo "Falha ao capturar xml do ws";
}

It would have some treatment so that I can convert the tags of the object in variables so being able to work easier with them as to save the data of the tags in variables?

  • You just want to get the nodes Sequencia and SessionId ?

  • Yes that’s just what I need

  • No one? I’ve seen that the bug is harder to tame than I thought.

  • I was going to, but I saw in your code something like this: // usando __getLastResponse tenho acesso ao header do soap. So this seems contradictory and confusing, since you want the header but at the same time say you get it.

  • See the answer below.

1 answer

0

Well, come on...
The truth is that you should not need any parser, Reader XML to parse the XML data returned by the web service query via SOAP.
Soapclient itself should be able to do this without extra parsing of the XML tree.

All examples below are based on the XML of the author’s response question.

This should be more or less like this:

$client = new SoapClient('arquivo WSDL');
$response = $client->LogOn($DadosLoginWs);
print $response->Header->Sessao->Sequencia;
// ...

As far as I know the above code should serve very well. However, if you still want to parse XML, here’s how you should proceed:

Domdocument / Domdocument::Domxpath()

# Registre corretamente o domínio namespace
$namespaceDomain = 'http://dominio.com.br';
# Isso na verdade é somente XML em string
$xmldata = file_get_contents('http://localhost/soap.xml');

$dom = DOMDocument::loadXML($xmldata);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('sessao', $namespaceDomain);
#retorna DOMNode (servirá de contexto)
$sessao = $xpath->query('//soap:Header/sessao:Sessao')->item(0); 
$sessaoSeq = $xpath->query('sessao:Sequencia', $sessao)->item(0)->nodeValue;
$sessaoId  = $xpath->query('sessao:SessionId', $sessao)->item(0)->nodeValue;

Simplexmlelement / Simplexmlelement::xpath()

$reader = new SimpleXMLElement($xmldata);
$reader->registerXPathNamespace('sessao', $namespaceDomain);
$sessao = $reader->xpath('//soap:Header/sessao:Sessao');
$sessaoSeq = $sessao[0]->Sequencia;
$sessaoId  = $sessao[0]->SessionId;

As you can see, it is necessary to register the namespace before analyzing the nodes in the XML tree, otherwise it will not work! That’s because, in your case, the knot Sessao has a namespace, so to access your descendants you need to inform the prefix namespace. The namespace prefix can be any name.


Useful links:

Browser other questions tagged

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