Simple National Optional Consultation (by CNPJ)

Asked

Viewed 5,579 times

8

I’m trying to implement a query of Simples Nacional, the operation is similar to the consultation by CNPJ of the recipe.

Details I’ve understood so far:

  1. After loading the page, runs a ajax (filing cabinet captcha2.js) which returns 3 items in format JSON {Token, Dados, ContentType}. The Token is stored in a cookie which would probably serve to validate the image after Ubmit. Dados is the Base64 of the image. ContentType the type of the image.
  2. It generates the cnpj input by concatenating a number that is also stored in another Hidden input (id: ctl00_ContentPlaceHolderConteudo_HiddenField1).
  3. There are other inputs (__VIEWSTATE, __EVENTVALIDATION, __EVENTARGUMENT, __EVENTTARGET) that store values, the last two, usually empty...

I am capturing the initial data and setting the headers in the second request to recover the data, however, the problem is that it always gives error (Invalid anti-toba characters. Try again.).

Follow the codes I have so far (may be messy or with unnecessary lines, are just tests yet, still need to clear the code later):

Consultacnpjsimplesnacional.php:

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);

    }

}

query cnpj_simple.php

/**
 * @var yii\web\View $this
 */
$this->title = 'Consulta CNPJ Simples Nacional';
try {
    $params = \app\common\components\consulta\ConsultaCnpjSimplesNacional::getParams();
} catch (Exception $e) {
    return Json::encode(['error' => 'error', 'mensagem' => $e->getMessage()]);
}
$form = ActiveForm::begin([
        'id' => 'form-consulta-cnpj',
        'enableClientScript' => false,
        'action' => Url::to(['consulta/processa-cnpj-simples'], true),
        'method' => 'POST'
    ]
);
?>
<img id="image_captcha" class="img-thumbnail" src="<?= $params['captchaBase64'] ?>"/><br/><br/>
<input type="hidden" id="cookie" name="cookie" value="<?= $params['cookie'] ?>">
<input type="hidden" id="viewState" name="viewState" value="<?= $params['viewState'] ?>">
<input type="hidden" id="eventValidation" name="eventValidation" value="<?= $params['eventValidation'] ?>">
<input type="hidden" id="hiddenField1" name="hiddenField1" value="<?= $params['hiddenField1'] ?>">
<input type="hidden" id="hddServidorCaptcha" name="hddServidorCaptcha" value="<?= $params['hddServidorCaptcha'] ?>">
<input type="text" name="input_captcha" id="input_captcha" placeholder="Digite o código da imagem">
<input type="text" name="cnpj" id="cnpj" placeholder="Digite o CNPJ" value="00175318000103">
<input type="submit" value="Enviar">
<?php ActiveForm::end();?>

Consulta controller.php

/**
* Processa a requisição de consulta por CNPJ;
*/
public function actionProcessaCnpjSimples()
{
    try {
        $post = Yii::$app->request->post();
        if (!isset($post['cnpj']) ||
            !isset($post['input_captcha']) ||
            !isset($post['cookie']) ||
            !isset($post['viewState']) ||
            !isset($post['eventValidation']) ||
            !isset($post['hiddenField1']) ||
            !isset($post['hddServidorCaptcha'])
        )
            throw new Exception('Informe todos os campos!', 99);

        $formatter = new Formatter();
        $cnpj = $formatter->customOnlyNumberFormat($post['cnpj']);
        $return['code'] = 0;
        $return['message'] = Yii::t('app', 'Dados encontrados!');
        $resultado = ConsultaCnpjSimplesNacional::consulta(
            $cnpj,
            $post['input_captcha'],
            $post['cookie'],
            $post['viewState'],
            $post['eventValidation'],
            $post['hiddenField1'],
            $post['hddServidorCaptcha']
        );
        //$return = array_merge($return, $resultado);
    } catch (\Exception $e) {
        $return = ['code' => $e->getCode(), 'message' => $e->getMessage()];
    }
    echo '<pre>';
    print_r($return);
    echo '</pre>';
}

Note that, the current structure is mounted in the framework Yii2 (I did not find it necessary to include her as a tag), but she can be easily "disassembled" to implement anywhere else, whereas the "heart" is the class Consultacnpjsimplesnacional.

Someone has already had to implement a query for Simple National, or could indicate some way of why not validate the images (captcha) ?

Link to the PHP Simple Html DOM Parser used in class to "defragment" html and take the values of fields.

  • 3

    Caracteres anti-robô inválidos. Tente novamente. It should be noted that the mechanism anti-toban is doing a good job. Just sins by encouraging new attempts.

3 answers

2

When making the captcha request, you are not getting the image associated with the query.

This is because the server differentiates different queries by the cookie - something you haven’t defined. There are two ways to do this:

  1. saving the cookie to a variable in the first query, and then when you get the captcha, you set that same cookie

  2. doing so automatically, using a cookie container before making any query. This approximates the way browsers handle cookies.

    $filename = 'C:\pasta\cookie.txt';
    // deve conter o caminho absoluto para o arquivo
    
    curl_setopt($ch, CURLOPT_COOKIEJAR,  $filename);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $filename);
    

This is a basic problem that I’ve identified by looking over the code. Maybe there are others, and identifying them is difficult, because programming a Curl robot in PHP is first and foremost a reverse engineering job.

I suggest activating the verbose of Curl curl_setopt($ch, CURLOPT_VERBOSE, 1); and compare the headers and GET/POST data you send with what you see in the tab Network of Ferramentas do Desenvolvedor in Chrome when making a query manually (check Preserve log). If everything is identical, it will work.

  • Sorry, it didn’t work apparently, it may be that I set it the wrong way. I added curl_setopt($chInicial, CURLOPT_COOKIEJAR, 'cookiejar'); at the first Curl and CURLOPT_COOKIEJAR => 'cookiejar', in the options array of the second. I’ll change the answer and add that code. That’s right or I’m missing?

  • In the second Curl, use the same variable $chInicial , just use curl_setopt to define the parameters that are different in the second request. I updated the response with another parameter that can be defined and other hints.

  • Continue error :/, I will update the code...

1

It seems to me that the website of the recipe was updated, nor the captcha was more loaded and after I had adjusted it, it did not validate the post giving error invalid postback or callback validation.

I had to inform the complete link to search for the captcha image and also to find more information in the header in the cookie parameter, because besides the captcha token was being sent Arraffinity=

It follows the class of Rafael Withoeft updated, for the tests I did here everything came back to work:

class ConsultaSimplesNacional {

private static function getUserAgent() {
    $agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36';
    return isset($_SERVER['USER_AGENT']) && !empty($_SERVER['USER_AGENT']) ? $_SERVER['USER_AGENT'] : $agent;
}
/**
 * Devolve um array de parâmetros para consulta de CNPJ Simples Nacional
 * @return array
 */
public static function getParams() {
    $client = new Client();
     $param = [
        'headers' => [
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding' => 'gzip, deflate, sdch',
            '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',
            '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',
            'Cache-Control'=>'max-age=0',
            'Connection'=>'keep-alive',
            'Content-type'=>'application/x-www-form-urlencoded',
            'Host'=>'www8.receita.fazenda.gov.br',
            'Referer'=>'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx',
            'User-Agent' => self::getUserAgent()
        ]
    ];

    $response = $client->request('GET', 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx');

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

    $response = $client->request('GET', 'http://www8.receita.fazenda.gov.br/'.$urlCaptchaContainer . '/Captcha/Inicializa.ashx');
    $cookies = $response->getHeader('Set-Cookie');
    $cookies = explode(';', $cookies[0]);
    $cookie = $cookies[0];

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

public static function consulta($cnpj, $captcha, $stringCookie, $viewState, $hiddenField, $servidorCaptcha) {
    $client = new Client();
    $param = [
        'form_params' => [
            '__EVENTTARGET' => null,
            '__EVENTARGUMENT' => null,
            '__VIEWSTATE' => $viewState,
            "ctl00\$ContentPlaceHolderConteudo\$$hiddenField" => $cnpj,
            'ctl00$ContentPlaceHolderConteudo$HiddenField1' => $hiddenField,
            'ctl00$ContentPlaceHolderConteudo$hddServidorCaptcha' => $servidorCaptcha,
            'ctl00$ContentPlaceHolderConteudo$txtTexto_captcha_serpro_gov_br' => $captcha,
            'ctl00$ContentPlaceHolderConteudo$btnConfirmar' => 'Consultar'
        ],
        'headers' => [
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding' => 'gzip, deflate, sdch',
            '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,
            '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' => self::getUserAgent()
        ],
        'timeout' => 20, // Response timeout
        'connect_timeout' => 20, // Connection timeout
    ];
    $response = $client->request('POST', 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx', $param);

    $html = str_get_html($response->getBody());
    $erros = $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblErroCaptcha');
    if (is_object($erros)) {
        $mensagemErro = 'Ocorreu algum erro, tente novamente mais tarde';
        switch (utf8_decode($erros->plaintext)) {
            case 'Caracteres anti-robô inválidos. Tente novamente.':
                $mensagemErro = 'Erro ao consultar. Verifique se digitou corretamente o captcha.';
                break;
            case 'O CNPJ informado deve conter 14 dígitos.':
                $mensagemErro = 'Erro ao consultar. CNPJ deve conter 14 dígitos.';
                break;
            case 'O CNPJ digitado é inválido.':
                $mensagemErro = 'Erro ao consultar. CNPJ inválido.';
                break;
        }
        throw new \Exception($mensagemErro, 99);
    }

    return [
        'cnpj' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblCNPJ')->plaintext)),
        'nome_empresarial' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblNomeEmpresa')->plaintext)),
        'situacao_simples_nacional' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSituacaoSimples')->plaintext)),
        'situacao_simei' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSituacaoMei')->plaintext)),
        'opcoes_pelo_simples_nacional_periodos_anteriores' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblPeriodoAnterior > b > font')->plaintext)),
        'opcoes_pelo_simei_periodos_anteriores' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSIMEIPeriodosAnteriores > b > font')->plaintext)),
        'agendamentos_simples_nacional' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblAgendamentosOpcaoSinac > b > font')->plaintext)),
        'eventos_futuros_simples_nacional' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblEventosFuturos > b > font')->plaintext)),
        'eventos_futuros_simei' => trim(utf8_decode($html->getElementById('ctl00_ContentPlaceHolderConteudo_lblEventosFuturosSimei > b > font')->plaintext))
    ];
}

}

  • Good afternoon, really, there were changes on the site of the simple national... I thank your contribution :). Internally, here in the company, we had already corrected this situation, but we do not make available on the internet the updated solution.... Any doubt I’m at your disposal.

  • They removed the __EVENTVALIDATION field from the site, I had to update the class again because it is no longer in HTML gave error.

0


I changed the code and now I use the Guzzle to make the requisitions and it worked.

Follow the updated code of the class Consultacnpjsimplesnacional.php

class ConsultaCnpjSimplesNacional
{

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

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';

        $html = str_get_html($resposta->getBody());
        $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();

        $resposta = $requisicao->get($urlCaptchaContainer . '/Captcha/Inicializa.ashx');

        $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)
    {
        $requisicao = new Client();
        $param = [
            'body' => [
                '__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'
            ],
            'headers' => [
                '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,
                '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/42.0.2311.152 Safari/537.36'
            ],
            'timeout' => 20, // Response timeout
            'connect_timeout' => 20, // Connection timeout
        ];
        $resposta = $requisicao->post('http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx', $param);

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'simple_html_dom.php';

        $html = str_get_html($resposta->getBody());
        $erros = $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblErroCaptcha');
        if (is_object($erros)) {
            $mensagemErro = 'Ocorreu algum erro, tente novamente mais tarde';
            switch (trim($erros->plaintext)) {
                case 'Caracteres anti-robô inválidos. Tente novamente.':
                    $mensagemErro = 'Erro ao consultar. Verifique se digitou corretamente o captcha.';
                    break;
                case 'O CNPJ informado deve conter 14 dígitos.':
                    $mensagemErro = 'Erro ao consultar. CNPJ deve conter 14 dígitos.';
                    break;
                case 'O CNPJ digitado é inválido.':
                    $mensagemErro = 'Erro ao consultar. CNPJ inválido.';
                    break;
            }
            throw new \Exception($mensagemErro, 99);
        }

        return [
            'cnpj' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblCNPJ')->plaintext,
            'nome_empresarial' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblNomeEmpresa')->plaintext,
            'situacao_simples_nacional' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSituacaoSimples')->plaintext,
            'situacao_simei' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSituacaoMei')->plaintext,
            'opcoes_pelo_simples_nacional_periodos_anteriores' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblPeriodoAnterior > b > font')->plaintext,
            'opcoes_pelo_simei_periodos_anteriores' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSIMEIPeriodosAnteriores > b > font')->plaintext,
            'agendamentos_simples_nacional' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblAgendamentosOpcaoSinac > b > font')->plaintext,
            'eventos_futuros_simples_nacional' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblEventosFuturos > b > font')->plaintext,
            'eventos_futuros_simei' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblEventosFuturosSimei > b > font')->plaintext
        ];
    }

}

Browser other questions tagged

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