Search code examples
phpxmlweb-servicescurlfsockopen

PHP - XML not parsed


I'm tryng to send an request to Cielo's webservice, but if i send with curl, fsockopen or other, it doesn't work, and if I post an form, it work perfectly...

PHP with XML:

<?php
$xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
$xml .= '<requisicao-transacao id="' . md5(date("YmdHisu")) . '" versao="1.1.0">';
$xml .= '<dados-ec><numero>1001734898</numero><chave>e84827130b9837473681c2787007da5914d6359947015a5cdb2b8843db0fa832</chave>';
$xml .= '</dados-ec>';
$xml .= '<dados-pedido>';
$xml .= '<numero>234</numero>';
$xml .= '<valor>1500</valor>';
$xml .= '<moeda>986</moeda>';
$xml .= '<data-hora>' . date("Y-m-d") . "T" . date("H:i:s") . '</data-hora>';
$xml .= '<descricao>234 - teste: 1 x $15.00</descricao>';
$xml .= '<idioma>PT</idioma>';
$xml .= '</dados-pedido>';
$xml .= '<forma-pagamento>';
$xml .= '<bandeira>visa</bandeira>';
$xml .= '<produto>1</produto>';
$xml .= '<parcelas>1</parcelas>';
$xml .= '</forma-pagamento>';
$xml .= '<url-retorno><![CDATA[' . 'http://localhost/cielo/index.php?option=com_events_booking&controller=booking&task=payment_notify&payment_method=cielo&Itemid=1' . ']]></url-retorno>';
$xml .= '<autorizar>3</autorizar>';
$xml .= '<capturar>true</capturar>';
$xml .= '</requisicao-transacao>';

$endereco = 'ssl://qasecommerce.cielo.com.br';

$resultado = '';
$fp = fsockopen($endereco, 443, $errno, $errstr, 60);

if (!$fp) {
    exit($errno . ' - ' . $errstr);
} else {
    $http = "POST /servicos/ecommwsec.do HTTP/1.1\r\n";
    $http .= "Host: " . $_SERVER['HTTP_HOST'] . "\r\n";
    $http .= "User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . "\r\n";
    $http .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $http .= "Content-length: " . strlen('mensagem='.$xml) . "\r\n";
    $http .= "Connection: close\r\n\r\n";
    $http .= 'mensagem='.$xml . "\r\n\r\n";

    fwrite($fp, $http);

    while (!feof($fp)) {
        $resultado .= fgets($fp, 4096);
    }
    fclose($fp);

    echo $resultado;
}

If I post the same XML with the follow HTML It work perfectly:

<form action="https://qasecommerce.cielo.com.br/servicos/ecommwsec.do" method="post">
<textarea name="mensagem" cols="120" rows="10"/></textarea>
<input type="submit" value="Teste"/>
</form>

I've lost hours trying to solve, but can not find the problem.


Solution

  • You're sending it as x-www-form-urlencoded data, but you aren't urlencoding it.

    Change

    $http .= 'mensagem='.$xml . "\r\n\r\n";
    

    To

    $http .= 'mensagem='.rawurlencode($xml); // The extra newlines aren't needed.
    

    Make sure to also update your Content-Length.