Log into the NFe portal with cURL and PHP


I've done a lot of research on this and so far I haven't been able to do anything concrete. Is this possible?

I want to make a form with the access key field and the captcha code to be filled in. soon this data will be sent to the nfe portal and will return the nfe information to me.

This causes the session expired error.


untitled document


    function recebe_imagem($url, $arquivo, $cookief = "", $cookiej = "") {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        /* if(!empty($cookief)) { 
          curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
          if(!empty($cookiej)) {
          curl_setopt($ch, CURLOPT_COOKIESESSION, "cookie.txt");
          } */
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($ch, CURLOPT_COOKIESESSION, "cookie.txt");
        curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0)");

        //curl_setopt($ch, , 
        $data = curl_exec($ch);
        //curl_close ($ch); 
        $fp = fopen($arquivo, 'w');
        fwrite($fp, $data);
        return $arquivo;
    $img = recebe_imagem("http://www.nfe.fazenda.gov.br/scripts/srf/intercepta/captcha.aspx?opt=image ", "receita.gif", "", "receita.txt");
    <img src="receita.gif" /> 
    <form method="POST" action="consulta.php"> 
        <input name='letras' maxlength='4' size='8' /> 
        <br /> 
        codigo acesso 
        <input name='cnpj' maxlength='44' size='60' /> 
        <input type="submit" /> 


    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Documento sem título</title> 
    $cnpj = $_POST['cnpj'];
    $letras = $_POST['letras'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "ContentPlaceHolder1$txtChaveAcessoCompleta=$cnpj&ContentPlaceHolder1$txtCaptcha=$letras&ContentPlaceHolder1$btnConsultar=Continuar");
    curl_setopt($ch, CURLOPT_REFERER, "http://www.nfe.fazenda.gov.br/portal/consulta.aspx?tipoConsulta=completa&tipoConteudo=XbSeqxE8pl8= ");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_URL, "http://www.nfe.fazenda.gov.br/portal/consultaCompleta.aspx?tipoConteudo=XbSeqxE8pl8= ");
    $output = curl_exec($ch);
    echo utf8_encode($output);

Is there any script to run this better?


If the session is timing out then there are probably more parameters to be passed to:


Use some debugger to check which parameters the request requests. Based on them, send them.

I can't test here because I don't have any valid NF-e number.

Scroll to Top