Problem consuming Datasus webservice in PHP

Asked

Viewed 1,897 times

1

Follows the code:

            <?php   
            $client = new SoapClient('https://servicoshm.saude.gov.br/cadsus/CadsusService/v5r0?wsdl');
                                $function = "Pesquisar";
                                $arguments = array("Pesquisar" => 
                                                array(
                                                    "CNESUsuario" => array("CNES" =>"6963447", "Usuario"=>"LEONARDO", "Senha"=>"?"),
                                                    "FiltroPesquisa" => array("CPF"=> array("numeroCPF"=>"66105234368"), "tipoPesquisa"=>"IDENTICA"),
                                                    "higienizar" => "0"
                                                )
                                            );
                                $result = $client->__soapCall($function,$arguments);
                                print($result); 

            ?>

I’m getting the following error:

                Fatal error: Uncaught SoapFault exception: [env:Receiver ] nested fault: XML parse failed: libxml error: : level: 3, code: 5, file: none, line: 1, str1: "", str2: "", str3: "", int1: 0, int2: 37, message: Extra content at the end of the document in *...\cadsus.php:12 Stack trace: #0 *...\cadsus.php(12): SoapClient->__soapCall('Pesquisar', Array) #1 {main} thrown in *...\cadsus.php on line 12

Some solution?

  • "message: Extra content at the end of the Document", what was the XML generated?

  • So, I can’t parse, even using a parse_str it returns an error. Using an example in Soapui it returns right. I can’t seem to print the XML on the page.

  • Any progress in this integration with the cadsus webservice? I was also able to perform all the tests in SOAPUI, both for Homologation and production, but I can’t get ahead in PHP.

3 answers

1

Follow solution to consume this webservice in php.

class WsseAuthHeader extends SoapHeader {

 private $wss_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';

 function __construct($user, $pass, $ns = null) {
     if ($ns) {
         $this->wss_ns = $ns;
     }
     $auth = new stdClass();
     $auth->Username = new SoapVar($user, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wss_ns); 
     $auth->Password = new SoapVar($pass, XSD_STRING, NULL, $this->wss_ns, NULL, $this->wss_ns);

     $username_token = new stdClass();
     $username_token->UsernameToken = new SoapVar($auth, SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'UsernameToken', $this->wss_ns); 

     $security_sv = new SoapVar(
         new SoapVar($username_token, SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'UsernameToken', $this->wss_ns),
         SOAP_ENC_OBJECT, NULL, $this->wss_ns, 'Security', $this->wss_ns);
     parent::__construct($this->wss_ns, 'Security', $security_sv, true);
 }
}
function consulta_CNS_Base_Nacional($cns){

     $UserName = "<<usuário>>";
     $Password = '<<senha>>';

     $wsse_header = new WsseAuthHeader($UserName, $Password );

     $opts = array( 
         'ssl' => array(
             'verify_peer' => false,
             'verify_peer_name' => false,
             'allow_self_signed' => true
         )
     ); 
     $context = stream_context_create($opts); 

     $options = array( 
                 'trace'           => 1, 
                 'stream_context' => $context
                  );
     try
     {
     $client = new SoapClient('https://servicoshm.saude.gov.br/cadsus/CadsusService/v5r0?wsdl', $options); 

         $client->__setSoapHeaders(array($wsse_header));

         $dataSus = new stdClass;        
         $dataSus = new stdClass;
         $dataSus->CNESUsuario = new stdClass;
         $dataSus->CNESUsuario->CNES = "6963447";
         $dataSus->CNESUsuario->Usuario = "LEONARDO";

         $dataSus->CNS = new stdClass;
         $dataSus->CNS->numeroCNS = $cns;

         $method = 'consultar';

         $result = $client->__soapCall($method, array($dataSus));

         /*
             echo $result->UsuarioSUS->NomeCompleto->Nome;
             echo '</br>';
             echo $result->UsuarioSUS->Mae->Nome;
             echo '</br>';
             echo $result->UsuarioSUS->Pai->Nome;
             echo '</br>';
             echo $result->UsuarioSUS->Sexo->codigoSexo;
             echo '</br>';    
             echo $result->UsuarioSUS->dataNascimento;
             echo '</br>';
             echo $result->UsuarioSUS->RacaCor->codigoRacaCor;
             echo '</br>';
             echo $result->UsuarioSUS->Enderecos->Endereco->Municipio->codigoMunicipio;
             echo '</br>';
             echo $result->UsuarioSUS->EtniaIndigena->codigoEtniaIndigena;
             echo '</br>';
             echo $result->UsuarioSUS->TipoSanguineo;
             echo '</br>';
             echo $result->UsuarioSUS->DadosNacionalidade->PaisNascimento->codigoPais;
             echo '</br>';
             echo $result->UsuarioSUS->MunicipioNascimento->codigoMunicipio;
             echo '</br>';
             echo $result->UsuarioSUS->MunicipioNascimento->UF->codigoUF;
             echo '</br>';
             echo $result->UsuarioSUS->MunicipioNascimento->UF->siglaUF;
             echo '</br>';    
             echo $result->UsuarioSUS->Documentos->Identidade->numeroIdentidade;
             echo '</br>';
             echo $result->UsuarioSUS->Enderecos->Endereco->TipoLogradouro->codigoTipoLogradouro;
             echo '</br>';
             echo $result->UsuarioSUS->Enderecos->Endereco->TipoLogradouro->descricaoTipoLogradouro;
             echo '</br>';    
             echo $result->UsuarioSUS->Enderecos->Endereco->nomeLogradouro;
             echo '</br>';    
             echo $result->UsuarioSUS->Enderecos->Endereco->numero;
             echo '</br>';    
             echo $result->UsuarioSUS->Enderecos->Endereco->complemento;
             echo '</br>';    
             echo $result->UsuarioSUS->Enderecos->Endereco->Bairro->descricaoBairro;
             echo '</br>';    
             echo $result->UsuarioSUS->Enderecos->Endereco->CEP->numeroCEP;
             echo '</br>';    
             echo $result->UsuarioSUS->Enderecos->Endereco->Municipio->codigoMunicipio;
             echo '</br>';    
             echo $result->UsuarioSUS->Enderecos->Endereco->Municipio->UF->codigoUF;
             echo '</br>';
             echo $result->UsuarioSUS->Enderecos->Endereco->Municipio->UF->siglaUF;
             echo '</br>';
             echo $result->UsuarioSUS->Telefones->Telefone->DDD;
             echo '</br>';
             echo $result->UsuarioSUS->Telefones->Telefone->numeroTelefone;
             echo '</br>';
             echo $result->UsuarioSUS->Emails->Email[0]->descricaoEmail;
             echo '</br>';

             print_r($result);
             */
         }
         catch(Exception $e) 
         { 
             echo $e->getMessage(); 
         }

1


I had this error because I was missing the header with the authentication, to solve includes manually with soapVar. follows code example that works for me.

<?php
try {
    $wsdlUrl = 'https://servicoshm.saude.gov.br/cadsus/CadsusService/v5r0?wsdl';
    $wsUser = 'CADSUS.CNS.PDQ.PUBLICO';
    $passWs = 'kUXNmiiii#RDdlOELdoe00966';
    $soapClientOptions = array(
	'trace' => 1,
	'cache_wsdl' => WSDL_CACHE_NONE
    );
    $client = new SoapClient($wsdlUrl, $soapClientOptions);
    $xmlheader = '
<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" 
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:UsernameToken wsu:Id="UsernameToken-F6C95C679D248B6E3F143032021465917">
        <wsse:Username>' . $wsUser . '</wsse:Username>
        <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $passWs . '</wsse:Password>
    </wsse:UsernameToken>
</wsse:Security>
';
    $header = new SoapHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', new \SoapVar($xmlheader, XSD_ANYXML), false);
    $client->__setSoapHeaders($header);

    $requestPesquisar = new stdClass();
    $requestPesquisar->CNESUsuario = new stdClass();
    $requestPesquisar->CNESUsuario->CNES = '6963447';
    $requestPesquisar->CNESUsuario->Usuario = 'LEONARDO';
    $requestPesquisar->CNESUsuario->Senha = '?';
    $requestPesquisar->FiltroPesquisa = new stdClass();
    $requestPesquisar->FiltroPesquisa->nomeCompleto = new stdClass();
    $requestPesquisar->FiltroPesquisa->nomeCompleto->Nome = 'SERGIO ARAUJO CORREIA LIMA';
    $requestPesquisar->FiltroPesquisa->tipoPesquisa = 'IDENTICA';
    $requestPesquisar->higienizar = '0';
    $result = $client->pesquisar($requestPesquisar);
    if ($result) {
	echo '<pre>', print_r($result), '</pre>';
    } else {
	echo '<h2>Request:</h2>';
	echo '<pre>', print_r($client->__getLastRequest()), '</pre>';
	echo '<h2>Header:</h2>';
	echo '<pre>', print_r($client->__getLastRequestHeaders()), '</pre>';
	echo '<h2>Response:</h2>';
	echo '<pre>', print_r($client->__getLastResponse()), '</pre>';
    }
} catch (Exception $e) {
    echo '<pre>', print_r($e), '<pre>';
}
?>

now I am with another problem that webservice does not return complete patient data, ex: does not return the address, municipality of residence etc...

in PDQ/PIX version is more complete but could not run with PHP.

I hope it helps.

hug!

  • Hello Andre! Thank you so much for your return! This problem you are facing is due to the credentials provided for testing. In order to be able to return all the complete data, you must make the processes for approval in order to obtain the complete credentials of access to the web service.

  • Hey there, Mosquito! I used the credentials of a municipality client of mine, which already used another system integrated to the bus and had the disappointment of not returning the complete data, so I used the example of PIX/PDQ integration in soapUi and returned the complete data. But I have no idea how to use this PIX/PDQ in PHP

0

unfortunately I have no privileges to comment, I tried some things here to try to help you, but it seems to me that the problem is in the xml of web service response. I rewrote the code a little different than yours, and I always got the same result.

The Xml library is complaining that the xml document of the reply has more than one root and Xml semantically speaking can only have one root.

Bad

<?xml version="1.0"?>
<status>success</status>
<format>xml</format>

Good

<?xml version="1.0"?>
<response>
  <status>success</status>
  <format>xml</format>
</response>

The reply xml should be as follows in PHP

<soap:Fault>
         <soap:Code>
            <env:Value xmlns:env="http://www.w3.org/2003/05/soap-envelope">env:Sender</env:Value>
         </soap:Code>
         <soap:Reason>
            <soap:Text xml:lang="pt-BR">Uma ou mais regras negociais foram violadas, verifique a lista de erros.</soap:Text>
         </soap:Reason>
         <soap:Detail>
            <msf:MSFalha xmlns:msf="http://servicos.saude.gov.br/wsdl/mensageria/falha/v5r0/msfalha">
               <msf:Mensagem xmlns:men="http://servicos.saude.gov.br/wsdl/mensageria/falha/v5r0/mensagem">
                  <men:codigo>OSB_SEM_AUTENTICACAO</men:codigo>
                  <men:descricao>As credenciais informadas não são válidas</men:descricao>
               </msf:Mensagem>
            </msf:MSFalha>
         </soap:Detail>
      </soap:Fault>

This xml has code, Reason, Detail which all indicates as root

if you take this xml, which SOAPUI presents as a response and put in an XML validator, you will notice that it is wrong, you can use this link, from w3school for this, I am not an XML expert, this is just the result of a search and debug

Down with the humour I wrote in case you’re curious

<?php

//318707

$pesquisar = new stdClass();
$pesquisar->CNESUsuario = new stdClass();
$pesquisar->CNESUsuario->CNES = "6963447";
$pesquisar->CNESUsuario->Usuario = "LEONARDO";
$pesquisar->CNESUsuario->Senha = "";
$pesquisar->FiltroPesquisa = new stdClass();
$pesquisar->FiltroPesquisa->CPF = new stdClass();
$pesquisar->FiltroPesquisa->CPF->numeroCPF = "66105234368";
$pesquisar->FiltroPesquisa->tipoPesquisa = "IDENTICA";
$pesquisar->higienizar = false;


$ver = "v5r0";

$url = "https://servicoshm.saude.gov.br/cadsus/CadsusService/$ver?wsdl";

// Opções de configurações do cliente WSDL
$options = [
    'soap_version' => SOAP_1_1, // SOAP_1_2
    'encoding' => 'UTF-8',
];

$soap = new SoapClient($url, $options);

$result  = $soap->Pesquisar($pesquisar);
print $result;

I took a look at the documentation of this web service and noticed that there is a video about how to implement this solution in java and Soapui is made in java,.

  • Thank you so much for the clarification Jeferson! I got to read the whole manual and saw these examples in Java. Anyway I’ll keep trying here haha :D Any advance I’ll post here to anyone who has the same problem.

Browser other questions tagged

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