Skip to main content
Pergunta protegida por user28595
tags editadas
Link
Oralista de Sistemas
  • 23,7mil
  • 7
  • 66
  • 126
título editado
Fonte Link
Rafael Withoeft
  • 2,3mil
  • 15
  • 31

Consulta Simples Nacional Optantes (por CNPJ)

Estou tentando implementar uma consulta do Simples Nacional, o funcionamento é parecido com o "oficial"a consulta por CNPJ da receita.

Consulta Simples Nacional CNPJ

Estou tentando implementar uma consulta do Simples Nacional, o funcionamento é parecido com o "oficial" da receita.

Consulta Simples Nacional Optantes (por CNPJ)

Estou tentando implementar uma consulta do Simples Nacional, o funcionamento é parecido com a consulta por CNPJ da receita.

adicionou 1253 caracteres ao conteúdo
Fonte Link
Rafael Withoeft
  • 2,3mil
  • 15
  • 31
class ConsultaCnpjSimplesNacional  
{

    /**
     * Devolve um array de parâmetros para consulta de CNPJ Simples Nacional
     * @return array
     */
    public static function getParams()
    {
        $urlRoot$ckfile = 'http:/tempnam("/www8.receita.fazenda.gov.br';
        $urlAplicacao =tmp", 'SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx';"CURLCOOKIE");

//        ini_set('xdebug.var_display_max_depth', 5);
//        ini_set('xdebug.var_display_max_children', 256);
//        ini_set('xdebug.var_display_max_data', 10000000000000);

        $urlConsulta = 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx';
        $chInicial = curl_init("$urlRoot/$urlAplicacao");
        curl_setopt($chInicial, CURLOPT_URL, $urlConsulta);
        curl_setopt($chInicial, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($chInicial, CURLOPT_VERBOSE, 1);
        curl_setopt($chInicial, CURLOPT_HEADER, 1);
        curl_setopt($chInicial, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($chInicial, CURLOPT_COOKIEJAR, 'cookiejar'$ckfile);
        curl_setopt($chInicial, CURLOPT_COOKIEFILE, $ckfile);
        curl_setopt($chInicial, CURLOPT_TIMEOUT, 20000);
        curl_setopt($chInicial, CURLOPT_CONNECTTIMEOUT, 20000);
        $response = curl_exec($chInicial);
        curl_close($chInicial);

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';

        $html = str_get_html($response);
        $inputViewStateValue = $html->getElementById('__VIEWSTATE')->value;
        $inputEventValidationValue = $html->getElementById('__EVENTVALIDATION')->value;
        $inputHiddenField1Value = $html->getElementById('ctl00_ContentPlaceHolderConteudo_HiddenField1')->value;
        $inputHddServidorCaptchaValue = $html->getElementById('hddServidorCaptcha')->value;
        $urlCaptchaContainer = $html->getElementById('captcha-container')->{'data-url'};
        //Essa informação é definida no javascript da página
        $urlPathImg = '/Captcha/Inicializa.ashx';
        $html->clear();
        unset($html);
        
        //Vamos requisitar a imagem (normalmente executado por ajax no cliente)
        $urlCaptchaContainer .= $urlPathImg;

        $chImagem//Essa =url curl_init($urlCaptchaContainer);
informada, é definida no javascript captcha2.js
   $options = [
   //$chInicial = curl_init($urlCaptchaContainer . '/Captcha/Inicializa.ashx');
     CURLOPT_COOKIEJAR => 'cookiejar',
 curl_setopt($chInicial, CURLOPT_URL, $urlCaptchaContainer. '/Captcha/Inicializa.ashx');
        CURLOPT_HTTPHEADERcurl_setopt($chInicial, =>CURLOPT_RETURNTRANSFER, [1);
        curl_setopt($chInicial, CURLOPT_VERBOSE, 1);
      'Content-type' => 'application/x-www-form-urlencoded'
 curl_setopt($chInicial, CURLOPT_HEADER, 1);
        curl_setopt($chInicial, ]CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($chInicial, CURLOPT_COOKIEJAR, $ckfile);
  CURLOPT_RETURNTRANSFER => TRUE    curl_setopt($chInicial,
  CURLOPT_COOKIEFILE, $ckfile);
        curl_setopt($chInicial, CURLOPT_HTTPHEADER, CURLOPT_FOLLOWLOCATION['Content-type' => 1,'application/x-www-form-urlencoded']);
        ];$response = curl_exec($chInicial);
        curl_setopt_array$header_size = curl_getinfo($chImagem$chInicial, $optionsCURLINFO_HEADER_SIZE);
        $response = curl_execsubstr($chImagem$response, $header_size);
        curl_close($chImagem$chInicial);
        $jsonResponse = json_decode($response);

        $browser = new Browser();
        if ($browser->getBrowser() == Browser::BROWSER_IE /*&& $browser->getVersion() <= 8*/) {
            $randomName = utf8_encode(\Yii::$app->security->generateRandomString());
            $pasta = Url::to("@webroot/assets/temp_images_ie/$randomName.png");
            $imgReturn = Url::to("@web/assets/temp_images_ie/$randomName.png");
            file_put_contents("$pasta", $jsonResponse->Dados);
        } else {
            $imgReturn = 'data:image/png;base64,' . $jsonResponse->Dados;
        }

        return [
            'cookie' => 'captcha_token=' . $jsonResponse->Token,
            'viewState' => $inputViewStateValue,
            'eventValidation' => $inputEventValidationValue,
            'hiddenField1' => $inputHiddenField1Value,
            'hddServidorCaptcha' => $inputHddServidorCaptchaValue,
            'captchaBase64' => $imgReturn
        ];
    }

    public static function consulta($cnpj, $captcha, $stringCookie, $viewState, $eventValidation, $hiddenField, $servidorCaptcha)
    {
        $result = [];
        $ch = curl_init('http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx');
        $ckfile = tempnam("/tmp", "CURLCOOKIE");

        $options = [
            CURLOPT_COOKIEJAR => 'cookiejar',
            CURLOPT_HTTPHEADER => [
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding' => 'gzip, deflate',
                'Accept-Language' => 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',
                'Connection' => 'keep-alive',
                'Content-type' => 'application/x-www-form-urlencoded',
                'Cookie' => $stringCookie,
                'DNT' => 1,
                'Host' => 'www8.receita.fazenda.gov.br',
                'Origin' => 'http://www8.receita.fazenda.gov.br',
                'Referer' => 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx',
                'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'
            ],
            CURLOPT_COOKIEJAR => $ckfile,
            CURLOPT_COOKIEFILE => $ckfile,
            CURLOPT_POST => TRUE,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_POSTFIELDS => [
                '__EVENTTARGET' => ''null,
                '__EVENTARGUMENT' => ''null,
                '__VIEWSTATE' => $viewState,
                '__EVENTVALIDATION' => $eventValidation,
                "ctl00\$ContentPlaceHolderConteudo\$$hiddenField" => $cnpj,
                'ctl00$ContentPlaceHolderConteudo$HiddenField1' => $hiddenField,
                'ctl00$ContentPlaceHolderConteudo$hddServidorCaptcha' => $servidorCaptcha,
                'ctl00$ContentPlaceHolderConteudo$txtTexto_captcha_serpro_gov_br' => $captcha,
                'ctl00$ContentPlaceHolderConteudo$btnConfirmar' => 'Consultar'
            ],
            CURLOPT_TIMEOUT => 20000,
            CURLOPT_CONNECTTIMEOUT => 20000
        ];
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);
        curl_close($ch);

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';
        echo $response;exit();

        echo $response;
        exit();

        $html = str_get_html($response);
 
    }

}
class ConsultaCnpjSimplesNacional {

    /**
     * Devolve um array de parâmetros para consulta de CNPJ Simples Nacional
     * @return array
     */
    public static function getParams()
    {
        $urlRoot = 'http://www8.receita.fazenda.gov.br';
        $urlAplicacao = 'SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx';

        $chInicial = curl_init("$urlRoot/$urlAplicacao");
        curl_setopt($chInicial, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($chInicial, CURLOPT_HEADER, 1);
        curl_setopt($chInicial, CURLOPT_COOKIEJAR, 'cookiejar');
        curl_setopt($chInicial, CURLOPT_TIMEOUT, 20000);
        curl_setopt($chInicial, CURLOPT_CONNECTTIMEOUT, 20000);
        $response = curl_exec($chInicial);
        curl_close($chInicial);

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';

        $html = str_get_html($response);
        $inputViewStateValue = $html->getElementById('__VIEWSTATE')->value;
        $inputEventValidationValue = $html->getElementById('__EVENTVALIDATION')->value;
        $inputHiddenField1Value = $html->getElementById('ctl00_ContentPlaceHolderConteudo_HiddenField1')->value;
        $inputHddServidorCaptchaValue = $html->getElementById('hddServidorCaptcha')->value;
        $urlCaptchaContainer = $html->getElementById('captcha-container')->{'data-url'};
        //Essa informação é definida no javascript da página
        $urlPathImg = '/Captcha/Inicializa.ashx';
        $html->clear();
        unset($html);
        
        //Vamos requisitar a imagem (normalmente executado por ajax no cliente)
        $urlCaptchaContainer .= $urlPathImg;

        $chImagem = curl_init($urlCaptchaContainer);
        $options = [
            CURLOPT_COOKIEJAR => 'cookiejar',
            CURLOPT_HTTPHEADER => [
                'Content-type' => 'application/x-www-form-urlencoded'
            ],
            CURLOPT_RETURNTRANSFER => TRUE,
             CURLOPT_FOLLOWLOCATION => 1,
        ];
        curl_setopt_array($chImagem, $options);
        $response = curl_exec($chImagem);
        curl_close($chImagem);
        $jsonResponse = json_decode($response);

        $imgReturn = 'data:image/png;base64,' . $jsonResponse->Dados;
        return [
            'cookie' => 'captcha_token='.$jsonResponse->Token,
            'viewState' => $inputViewStateValue,
            'eventValidation' => $inputEventValidationValue,
            'hiddenField1' => $inputHiddenField1Value,
            'hddServidorCaptcha' => $inputHddServidorCaptchaValue,
            'captchaBase64' => $imgReturn
        ];
    }

    public static function consulta($cnpj, $captcha, $stringCookie, $viewState, $eventValidation, $hiddenField, $servidorCaptcha)
    {
        $result = [];
        $ch = curl_init('http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx');

        $options = [
            CURLOPT_COOKIEJAR => 'cookiejar',
            CURLOPT_HTTPHEADER => [
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding' => 'gzip, deflate',
                'Accept-Language' => 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',
                'Connection' => 'keep-alive',
                'Content-type' => 'application/x-www-form-urlencoded',
                'Cookie' => $stringCookie,
                'DNT' => 1,
                'Host' => 'www8.receita.fazenda.gov.br',
                'Origin' => 'http://www8.receita.fazenda.gov.br',
                'Referer' => 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx',
                'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'
            ],
            CURLOPT_POST => TRUE,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_POSTFIELDS => [
                '__EVENTTARGET' => '',
                '__EVENTARGUMENT' => '',
                '__VIEWSTATE' => $viewState,
                '__EVENTVALIDATION' => $eventValidation,
                "ctl00\$ContentPlaceHolderConteudo\$$hiddenField" => $cnpj,
                'ctl00$ContentPlaceHolderConteudo$HiddenField1' => $hiddenField,
                'ctl00$ContentPlaceHolderConteudo$hddServidorCaptcha' => $servidorCaptcha,
                'ctl00$ContentPlaceHolderConteudo$txtTexto_captcha_serpro_gov_br' => $captcha,
                'ctl00$ContentPlaceHolderConteudo$btnConfirmar' => 'Consultar'
            ],
            CURLOPT_TIMEOUT => 20000,
            CURLOPT_CONNECTTIMEOUT => 20000
        ];
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);
        curl_close($ch);

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';
        echo $response;exit();

        $html = str_get_html($response);
    }

}
class ConsultaCnpjSimplesNacional 
{

    /**
     * Devolve um array de parâmetros para consulta de CNPJ Simples Nacional
     * @return array
     */
    public static function getParams()
    {
        $ckfile = tempnam("/tmp", "CURLCOOKIE");

//        ini_set('xdebug.var_display_max_depth', 5);
//        ini_set('xdebug.var_display_max_children', 256);
//        ini_set('xdebug.var_display_max_data', 10000000000000);

        $urlConsulta = 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx';
        $chInicial = curl_init();
        curl_setopt($chInicial, CURLOPT_URL, $urlConsulta);
        curl_setopt($chInicial, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($chInicial, CURLOPT_VERBOSE, 1);
        curl_setopt($chInicial, CURLOPT_HEADER, 1);
        curl_setopt($chInicial, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($chInicial, CURLOPT_COOKIEJAR, $ckfile);
        curl_setopt($chInicial, CURLOPT_COOKIEFILE, $ckfile);
        curl_setopt($chInicial, CURLOPT_TIMEOUT, 20000);
        curl_setopt($chInicial, CURLOPT_CONNECTTIMEOUT, 20000);
        $response = curl_exec($chInicial);

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';

        $html = str_get_html($response);
        $inputViewStateValue = $html->getElementById('__VIEWSTATE')->value;
        $inputEventValidationValue = $html->getElementById('__EVENTVALIDATION')->value;
        $inputHiddenField1Value = $html->getElementById('ctl00_ContentPlaceHolderConteudo_HiddenField1')->value;
        $inputHddServidorCaptchaValue = $html->getElementById('hddServidorCaptcha')->value;
        $urlCaptchaContainer = $html->getElementById('captcha-container')->{'data-url'};
        $html->clear();
        unset($html);

        //Essa url informada, é definida no javascript captcha2.js
        //$chInicial = curl_init($urlCaptchaContainer . '/Captcha/Inicializa.ashx');
        curl_setopt($chInicial, CURLOPT_URL, $urlCaptchaContainer. '/Captcha/Inicializa.ashx');
        curl_setopt($chInicial, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($chInicial, CURLOPT_VERBOSE, 1);
        curl_setopt($chInicial, CURLOPT_HEADER, 1);
        curl_setopt($chInicial, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($chInicial, CURLOPT_COOKIEJAR, $ckfile);
        curl_setopt($chInicial, CURLOPT_COOKIEFILE, $ckfile);
        curl_setopt($chInicial, CURLOPT_HTTPHEADER, ['Content-type' => 'application/x-www-form-urlencoded']);
        $response = curl_exec($chInicial);
        $header_size = curl_getinfo($chInicial, CURLINFO_HEADER_SIZE);
        $response = substr($response, $header_size);
        curl_close($chInicial);
        $jsonResponse = json_decode($response);

        $browser = new Browser();
        if ($browser->getBrowser() == Browser::BROWSER_IE /*&& $browser->getVersion() <= 8*/) {
            $randomName = utf8_encode(\Yii::$app->security->generateRandomString());
            $pasta = Url::to("@webroot/assets/temp_images_ie/$randomName.png");
            $imgReturn = Url::to("@web/assets/temp_images_ie/$randomName.png");
            file_put_contents("$pasta", $jsonResponse->Dados);
        } else {
            $imgReturn = 'data:image/png;base64,' . $jsonResponse->Dados;
        }

        return [
            'cookie' => 'captcha_token=' . $jsonResponse->Token,
            'viewState' => $inputViewStateValue,
            'eventValidation' => $inputEventValidationValue,
            'hiddenField1' => $inputHiddenField1Value,
            'hddServidorCaptcha' => $inputHddServidorCaptchaValue,
            'captchaBase64' => $imgReturn
        ];
    }

    public static function consulta($cnpj, $captcha, $stringCookie, $viewState, $eventValidation, $hiddenField, $servidorCaptcha)
    {
        $result = [];
        $ch = curl_init('http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx');
        $ckfile = tempnam("/tmp", "CURLCOOKIE");

        $options = [
            CURLOPT_HTTPHEADER => [
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding' => 'gzip, deflate',
                'Accept-Language' => 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',
                'Connection' => 'keep-alive',
                'Content-type' => 'application/x-www-form-urlencoded',
                'Cookie' => $stringCookie,
                'DNT' => 1,
                'Host' => 'www8.receita.fazenda.gov.br',
                'Origin' => 'http://www8.receita.fazenda.gov.br',
                'Referer' => 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx',
                'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'
            ],
            CURLOPT_COOKIEJAR => $ckfile,
            CURLOPT_COOKIEFILE => $ckfile,
            CURLOPT_POST => TRUE,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_POSTFIELDS => [
                '__EVENTTARGET' => null,
                '__EVENTARGUMENT' => null,
                '__VIEWSTATE' => $viewState,
                '__EVENTVALIDATION' => $eventValidation,
                "ctl00\$ContentPlaceHolderConteudo\$$hiddenField" => $cnpj,
                'ctl00$ContentPlaceHolderConteudo$HiddenField1' => $hiddenField,
                'ctl00$ContentPlaceHolderConteudo$hddServidorCaptcha' => $servidorCaptcha,
                'ctl00$ContentPlaceHolderConteudo$txtTexto_captcha_serpro_gov_br' => $captcha,
                'ctl00$ContentPlaceHolderConteudo$btnConfirmar' => 'Consultar'
            ],
            CURLOPT_TIMEOUT => 20000,
            CURLOPT_CONNECTTIMEOUT => 20000
        ];
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);
        curl_close($ch);

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';

        echo $response;
        exit();

        $html = str_get_html($response);
 
    }

}
Adicionado código para cookies.
Fonte Link
Rafael Withoeft
  • 2,3mil
  • 15
  • 31
Carregando
Adicionado tag web-crawler, que é o tema principal da pergunta
Link
Carregando
Fonte Link
Rafael Withoeft
  • 2,3mil
  • 15
  • 31
Carregando