/** * Metodo para realizar a consulta * * @throws Exception * @param string $cep CEP * @return array Endereço */ public static function consulta($cep) { if (strlen($cep) < 8) { throw new Exception('O cep informado não parece ser válido'); } $client = new Client(); $crawler = $client->request('POST', 'http://www.buscacep.correios.com.br/servicos/dnec/consultaLogradouroAction.do', array('relaxation' => Utils::unmask($cep), 'Metodo' => 'listaLogradouro', 'TipoConsulta' => 'relaxation', 'StartRow' => '1', 'EndRow' => '10')); $tr = $crawler->filter(".ctrlcontent > div:nth-child(7) > table:nth-child(1) > tr:nth-child(1)"); $retorno = array('logradouro' => $tr->filter("td:nth-child(1)")->html(), 'bairro' => $tr->filter("td:nth-child(2)")->html(), 'cidade' => $tr->filter("td:nth-child(3)")->html(), 'uf' => $tr->filter("td:nth-child(4)")->html(), 'cep' => Utils::unmask($tr->filter("td:nth-child(5)")->html())); $aux = explode(" - ", $retorno['logradouro']); $retorno['logradouro'] = count($aux) == 2 ? $aux[0] : $retorno['logradouro']; return array_map('htmlentities', array_map('trim', $retorno)); }
/** * Metodo para realizar a consulta * * @param string $cnpj CNPJ * @param string $ie IE - Não Testado * @param string $paramBot ParamBot parametro enviado para validação do captcha * @param string $captcha CAPTCHA * @param string $stringCookie COOKIE * @throws Exception * @return array Dados da empresa */ public static function consulta($cnpj, $ie, $paramBot, $captcha, $stringCookie) { $arrayCookie = explode(';', $stringCookie); if (!Utils::isCnpj($cnpj)) { throw new Exception('O CNPJ informado não é válido.'); } $client = new Client(); #$client->getClient()->setDefaultOption('timeout', 120); $client->getClient()->setDefaultOption('config/curl/' . CURLOPT_TIMEOUT, 0); $client->getClient()->setDefaultOption('config/curl/' . CURLOPT_TIMEOUT_MS, 0); $client->getClient()->setDefaultOption('config/curl/' . CURLOPT_CONNECTTIMEOUT, 0); $client->getClient()->setDefaultOption('config/curl/' . CURLOPT_RETURNTRANSFER, true); $client->setHeader('Host', 'pfeserv1.fazenda.sp.gov.br'); $client->setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0'); $client->setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8'); $client->setHeader('Accept-Language', 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3'); $client->setHeader('Accept-Encoding', 'gzip, deflate'); $client->setHeader('Referer', 'http://www.sintegra.gov.br/new_bv.html'); $client->setHeader('Cookie', $arrayCookie[0]); $client->setHeader('Connection', 'keep-alive'); $servico = strlen($cnpj) > 0 ? 'cnpj' : 'ie'; $consultaPor = strlen($cnpj) > 0 ? 'Consulta por CNPJ' : 'Consulta por IE'; $param = array('hidFlag' => '0', 'cnpj' => Utils::unmask($cnpj), 'ie' => Utils::unmask($ie), 'paramBot' => $paramBot, 'Key' => $captcha, 'servico' => $servico, 'botao' => $consultaPor); $crawler = $client->request('POST', 'http://pfeserv1.fazenda.sp.gov.br/sintegrapfe/sintegra', $param); $imageError = 'O valor da imagem esta incorreto ou expirou. Verifique novamente a imagem e digite exatamente os 5 caracteres exibidos.'; $checkError = $crawler->filter('body > center')->eq(1)->count(); if ($checkError && $imageError == trim($crawler->filter('body > center')->eq(1)->text())) { throw new Exception($imageError, 99); } $center_ = $crawler->filter('body > center'); if (count($center_) == 0) { throw new Exception('Serviço indisponível!. Tente novamente.', 99); } //self::saveFile($client); $html = self::parseContent($client->getResponse()->__toString()); $crawler = new \Symfony\Component\DomCrawler\Crawler($html); $data = self::parseSelectors($crawler); return $data; }
/** * Metodo para realizar a consulta * * @param string $cpf CPF * @param string $captcha CAPTCHA * @param string $stringCookie COOKIE * @throws Exception * @return array Dados da pessoa */ public static function consulta($cpf, $captcha, $stringCookie) { try { $arrayCookie = explode(';', $stringCookie); if (!Utils::isCpf($cpf)) { throw new Exception(); } $client = new Client(); $client->setHeader('Host', 'www.receita.fazenda.gov.br'); $client->setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0'); $client->setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'); $client->setHeader('Accept-Language', 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3'); $client->setHeader('Accept-Encoding', 'gzip, deflate'); $client->setHeader('Referer', 'http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/ConsultaPublica.asp'); $client->setHeader('Cookie', $arrayCookie[0]); $client->setHeader('Connection', 'keep-alive'); $param = array('txtCPF' => Utils::unmask($cpf), 'txtTexto_captcha_serpro_gov_br' => $captcha, 'Enviar' => 'Consultar'); $crawler = $client->request('POST', 'http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/ConsultaPublicaExibir.asp', $param); $clConteudoDados = $crawler->filter('span.clConteudoDados'); return array('cpf' => Utils::unmask($cpf), 'nome' => trim(str_replace('Nome da Pessoa Física: ', '', $clConteudoDados->eq(1)->html())), 'situacao_cadastral' => str_replace('Situação Cadastral: ', '', $clConteudoDados->eq(2)->html()), 'digito_verificador' => str_replace('Digito Verificador: ', '', $clConteudoDados->eq(3)->html())); } catch (Exception $e) { throw new Exception('Aconteceu um erro ao fazer a consulta. Envie os dados novamente.'); } }
public function gerarLinha() { $reader = new AnnotationReader(); $reflectionClass = new ReflectionClass($this); $registro = $reader->getClassAnnotation($reflectionClass, 'JansenFelipe\\SintegraPHP\\Annotations\\Registro'); $linha = $registro->tipo; foreach ($reflectionClass->getProperties() as $property) { $campo = $reader->getPropertyAnnotation($property, 'JansenFelipe\\SintegraPHP\\Annotations\\Campo'); $property->setAccessible(true); if (!is_array($property->getValue($this))) { $valor = substr($property->getValue($this), 0, $campo->tamanho); } else { $valor = $property->getValue($this); } if (!is_array($valor)) { if ($campo->tipo == 'string') { $valor = str_pad($valor, $campo->tamanho, ' ', $campo->pad_type); } if ($campo->tipo == 'numeric') { $valor = str_pad(Utils::unmask($valor), $campo->tamanho, '0', $campo->pad_type); } } else { $valorPT = ""; // exit; foreach ($valor as $key => $value) { // print_r($value); $k = str_pad(Utils::unmask($key), 2, '0', $campo->pad_type); $v = str_pad(Utils::unmask($value['valor']), 8, '0', $campo->pad_type); $valorPT .= $k . $v; } $valor = $valorPT; } $linha .= $valor; } return $linha; }
<?php require 'vendor/autoload.php'; use JansenFelipe\CnpjGratis\CnpjGratis; use JansenFelipe\Utils\Utils; use JansenFelipe\Utils\Mask; try { if (!isset($_POST['cnpj']) || !isset($_POST['captcha']) || !isset($_POST['cookie'])) { throw new Exception('Informe todos os campos', 99); } $return = CnpjGratis::consulta($_POST['cnpj'], $_POST['captcha'], $_POST['cookie']); $return['cep'] = Utils::mask($return['cep'], Mask::CEP); $return['code'] = 0; } catch (Exception $e) { $return = array('code' => $e->getCode(), 'message' => $e->getMessage()); } header('Content-Type: application/json'); echo json_encode($return);
/** * Metodo para realizar a consulta * * @param string $cnpj CNPJ * @param string $captcha CAPTCHA * @param string $stringCookie COOKIE * @throws Exception * @return array Dados da empresa */ public static function consulta($cnpj, $captcha, $stringCookie) { $result = array(); $arrayCookie = explode(';', $stringCookie); if (!Utils::isCnpj($cnpj)) { throw new Exception('O CNPJ informado não é válido'); } $client = new Client(); $client->setHeader('Host', 'www.receita.fazenda.gov.br'); $client->setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0'); $client->setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8'); $client->setHeader('Accept-Language', 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3'); $client->setHeader('Accept-Encoding', 'gzip, deflate'); $client->setHeader('Referer', 'http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/valida.asp'); $client->setHeader('Cookie', $arrayCookie[0]); $client->setHeader('Connection', 'keep-alive'); $param = array('origem' => 'comprovante', 'cnpj' => Utils::unmask($cnpj), 'txtTexto_captcha_serpro_gov_br' => $captcha, 'submit1' => 'Consultar', 'search_type' => 'cnpj'); $crawler = $client->request('POST', 'http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/valida.asp', $param); if ($crawler->filter('body > table:nth-child(3) > tr:nth-child(2) > td > b > font')->count() > 0) { throw new Exception('Erro ao consultar. O CNPJ informado não existe no cadastro.', 99); } $td = $crawler->filter('body > table:nth-child(3) > tr > td'); foreach ($td->filter('td') as $td) { $td = new Crawler($td); if ($td->filter('font:nth-child(1)')->count() > 0) { $key = trim(preg_replace('/\\s+/', ' ', $td->filter('font:nth-child(1)')->html())); switch ($key) { case 'NOME EMPRESARIAL': $key = 'razao_social'; break; case 'TÍTULO DO ESTABELECIMENTO (NOME DE FANTASIA)': $key = 'nome_fantasia'; break; case 'CÓDIGO E DESCRIÇÃO DA ATIVIDADE ECONÔMICA PRINCIPAL': $key = 'cnae_principal'; break; case 'CÓDIGO E DESCRIÇÃO DAS ATIVIDADES ECONÔMICAS SECUNDÁRIAS': $key = 'cnaes_secundario'; break; case 'CÓDIGO E DESCRIÇÃO DA NATUREZA JURÍDICA': $key = 'natureza_juridica'; break; case 'LOGRADOURO': $key = 'logradouro'; break; case 'NÚMERO': $key = 'numero'; break; case 'COMPLEMENTO': $key = 'complemento'; break; case 'CEP': $key = 'cep'; break; case 'BAIRRO/DISTRITO': $key = 'bairro'; break; case 'MUNICÍPIO': $key = 'cidade'; break; case 'UF': $key = 'uf'; break; case 'SITUAÇÃO CADASTRAL': $key = 'situacao_cadastral'; break; case 'DATA DA SITUAÇÃO CADASTRAL': $key = 'situacao_cadastral_data'; break; case 'MOTIVO DE SITUAÇÃO CADASTRAL': $key = 'motivo_situacao_cadastral'; break; case 'SITUAÇÃO ESPECIAL': $key = 'situacao_especial'; break; case 'DATA DA SITUAÇÃO ESPECIAL': $key = 'situacao_especial_data'; break; case 'TELEFONE': $key = 'telefone'; break; case 'ENDEREÇO ELETRÔNICO': $key = 'email'; break; case 'ENTE FEDERATIVO RESPONSÁVEL (EFR)': $key = 'ente_federativo_responsavel'; break; default: $key = null; break; } if (!is_null($key)) { $bs = $td->filter('font > b'); foreach ($bs as $b) { $b = new Crawler($b); $str = trim(preg_replace('/\\s+/', ' ', $b->html())); $attach = htmlspecialchars_decode($str); if ($bs->count() == 1) { $result[$key] = $attach; } else { $result[$key][] = $attach; } } } } } return $result; }
public function testCpfFalso() { $this->assertFalse(Utils::isCpf(FakerBR::cpf(false))); }
public function testUnmoeda() { $this->assertEquals(2000, Utils::unmoeda('R$ 2.000,00')); $this->assertEquals(3500.22, Utils::unmoeda('US$ 3.500,22', 'US$')); }