### Install consultar-cnpj package Source: https://docs.cnpj.ws/blog/consultar-cnpj-javascript Install the 'consultar-cnpj' package using either YARN or NPM to facilitate integration with the CNPJ.ws API. ```shell yarn add consultar-cnpj ``` ```shell npm i consultar-cnpj --save ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.cnpj.ws/blog/cnpjws To get additional information not directly available on a page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.cnpj.ws/blog/cnpjws.md?ask= ``` -------------------------------- ### Instalação do Pacote consultar-cnpj Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/consultando-consumo Instale o pacote npm 'consultar-cnpj' para facilitar a integração com JavaScript. ```shell yarn add consultar-cnpj ``` -------------------------------- ### Query Documentation with Ask Parameter Source: https://docs.cnpj.ws/modelos-de-dados/inscricoes-estaduais To get information not directly on the page, perform an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.cnpj.ws/modelos-de-dados/inscricoes-estaduais.md?ask= ``` -------------------------------- ### Consultar Documentação Dinamicamente Source: https://docs.cnpj.ws/modelos-de-dados/atividades-economicas Exemplo de como realizar uma requisição GET para consultar a documentação com um parâmetro 'ask' para fazer perguntas específicas. ```http GET https://docs.cnpj.ws/modelos-de-dados/atividades-economicas.md?ask= ``` -------------------------------- ### Querying Documentation API Source: https://docs.cnpj.ws/modelos-de-dados/mensagens-erro To get additional information not directly present on a page, you can query the documentation dynamically. Perform an HTTP GET request on the page URL with the 'ask' query parameter. ```http GET https://docs.cnpj.ws/modelos-de-dados/mensagens-erro.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.cnpj.ws/referencia-de-api/api-comercial You can dynamically query the documentation by performing an HTTP GET request to the current page URL with the `ask` query parameter. This is useful for retrieving specific information not explicitly present on the page or for clarification. ```APIDOC ## Querying This Documentation Perform an HTTP GET request on the current page URL with the `ask` query parameter: ``` GET https://docs.cnpj.ws/referencia-de-api/api-comercial.md?ask= ``` The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. ``` -------------------------------- ### Exemplo de Chamada HTTP GET para API Pública Source: https://docs.cnpj.ws/blog/consultar-cnpj-excel Este exemplo ilustra como realizar uma requisição HTTP GET para a API pública do CNPJ.ws. É importante notar que a API pública tem limitações de consulta por minuto e não requer um token para uso básico. ```HTTP GET https://public.cnpj.ws/cnpj/00000000000000 ``` -------------------------------- ### Exemplo de Consulta com Token de API Source: https://docs.cnpj.ws/blog/consultar-cnpj-excel Este exemplo mostra a estrutura de uma requisição GET para a API do CNPJ.ws quando um token é utilizado. O uso do token geralmente oferece limites de consulta maiores e maior velocidade. ```HTTP GET https://api.cnpj.ws/cnpj/00000000000000?token=SEU_TOKEN ``` -------------------------------- ### Query CNPJ Root using Node.js Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/consultando-raiz-cnpj Example of how to use the 'consultar-cnpj' package in Node.js to query CNPJ information by its root. Ensure you replace 'INFORME O SEU TOKEN DE ACESSO' with your actual API token. ```javascript const consultarCNPJ = require("consultar-cnpj"); async function getRaiz() { const token = "INFORME O SEU TOKEN DE ACESSO"; const data = await consultarCNPJ.raiz("27865757", token); console.log(data); } ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.cnpj.ws/modelos-de-dados/estados Use this endpoint to ask questions about the documentation. The response includes direct answers and relevant excerpts. ```HTTP GET https://docs.cnpj.ws/modelos-de-dados/estados.md?ask= ``` -------------------------------- ### Dependência OkHttp para Maven Source: https://docs.cnpj.ws/blog/consultar-cnpj-java Adicione esta dependência ao seu arquivo pom.xml para usar a biblioteca OkHttp em seu projeto Maven. ```xml com.squareup.okhttp3 okhttp 4.9.0 ``` -------------------------------- ### Exemplo de Consulta de CNPJ com VBA Source: https://docs.cnpj.ws/blog/consultar-cnpj-excel Este snippet demonstra como a planilha utiliza VBA para automatizar consultas de CNPJ. Ao abrir a planilha, é necessário habilitar as macros para que a funcionalidade seja ativada. ```VBA Sub ConsultarCNPJ() Dim cnpj As String Dim url As String Dim response As String Dim ws As Worksheet Dim rng As Range Set ws = ThisWorkbook.Sheets("Consultas") Set rng = ws.Range("A2") ' Assumindo que o CNPJ está na célula A2 cnpj = Replace(rng.Value, ".", ""): cnpj = Replace(cnpj, "/", ""): cnpj = Replace(cnpj, "-", ""): cnpj = Replace(cnpj, " ", "") If cnpj = "" Then MsgBox "Por favor, insira um CNPJ.", vbExclamation Exit Sub End If ' URL da API pública do CNPJ.ws (sem token) url = "https://public.cnpj.ws/cnpj/" & cnpj On Error Resume Next response = GetUrl(url) On Error GoTo 0 If response = "" Then MsgBox "Não foi possível obter os dados. Verifique o CNPJ ou sua conexão.", vbCritical Exit Sub End If ' Processar a resposta JSON e preencher a planilha Call ProcessarJson(response, ws) End Sub Function GetUrl(url As String) As String Dim http As Object Set http = CreateObject("MSXML2.ServerXMLHTTP") http.Open "GET", url, False http.Send If http.Status = 200 Then GetUrl = http.responseText Else GetUrl = "" End If End Function Sub ProcessarJson(json As String, ws As Worksheet) ' Esta é uma implementação simplificada. Uma biblioteca de parsing JSON seria ideal. ' Para simplificar, vamos extrair alguns campos básicos. ' Em um cenário real, use uma biblioteca como VBA-JSON. Dim razaoSocial As String Dim nomeFantasia As String Dim situacaoCadastral As String ' Exemplo de extração (muito simplificado e propenso a erros com JSON complexo) razaoSocial = GetValueFromJson(json, "razaoSocial") nomeFantasia = GetValueFromJson(json, "nomeFantasia") situacaoCadastral = GetValueFromJson(json, "situacaoCadastral") ' Preencher a planilha (assumindo colunas B, C, D a partir da linha 2) ws.Range("B2").Value = razaoSocial ws.Range("C2").Value = nomeFantasia ws.Range("D2").Value = situacaoCadastral ' Adicionar mais campos conforme necessário... End Sub Function GetValueFromJson(json As String, key As String) As String ' Função auxiliar MUITO SIMPLIFICADA para extrair valor de uma chave JSON. ' NÃO é robusta para JSON aninhado ou com caracteres especiais. Dim startPos As Long Dim endPos As Long Dim temp As String startPos = InStr(json, "\"" & key & "\":\"") If startPos > 0 Then startPos = startPos + Len("\"" & key & "\":\"") endPos = InStr(startPos, json, "\",\"") If endPos = 0 Then ' Último item ou sem vírgula endPos = InStr(startPos, json, "}") If endPos = 0 Then endPos = Len(json) End If temp = Mid(json, startPos, endPos - startPos) GetValueFromJson = Replace(temp, "\\", "\") ' Desfaz escape de barras Else GetValueFromJson = "" End If End Function ``` -------------------------------- ### Example CNPJ API Response Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/consultando-cnpj This JSON object represents the data returned when querying CNPJ 27865757000102. ```json { "cnpj_raiz": "27865757", "razao_social": "GLOBO COMUNICACAO E PARTICIPACOES S/A", "capital_social": "6983568523.86", "responsavel_federativo": "", "atualizado_em": "2023-11-11T03:00:00.000Z", "porte": { "id": "05", "descricao": "Demais" }, "natureza_juridica": { "id": "2054", "descricao": "Sociedade Anônima Fechada" }, "qualificacao_do_responsavel": { "id": 10, "descricao": "Diretor " }, "socios": [ { "cpf_cnpj_socio": "***048947**", "nome": "PAULO DAUDT MARINHO", "tipo": "Pessoa Física", "data_entrada": "2020-01-16", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "41 a 50 anos", "atualizado_em": "2023-10-14T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null, "pais": { "id": "1058", "iso2": "BR", "iso3": "BRA", "nome": "Brasil", "comex_id": "105" } }, { "cpf_cnpj_socio": "***834960**", "nome": "CLAUDIA FALCAO DA MOTTA", "tipo": "Pessoa Física", "data_entrada": "2020-01-16", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "51 a 60 anos", "atualizado_em": "2023-10-14T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null, "pais": { "id": "1058", "iso2": "BR", "iso3": "BRA", "nome": "Brasil", "comex_id": "105" } }, { "cpf_cnpj_socio": "***486498**", "nome": "RAYMUNDO COSTA PINTO BARROS", "tipo": "Pessoa Física", "data_entrada": "2021-03-15", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "61 a 70 anos", "atualizado_em": "2023-10-14T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null, "pais": { "id": "1058", "iso2": "BR", "iso3": "BRA", "nome": "Brasil", "comex_id": "105" } }, { "cpf_cnpj_socio": "***223047**", "nome": "ERICK DE MIRANDA BRETAS", "tipo": "Pessoa Física", "data_entrada": "2020-01-16", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "41 a 50 anos", "atualizado_em": "2023-10-14T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null, "pais": { "id": "1058", "iso2": "BR", "iso3": "BRA", "nome": "Brasil", "comex_id": "105" } }, { "cpf_cnpj_socio": "***189808**", "nome": "AMAURI SERGIO SOARES", "tipo": "Pessoa Física", "data_entrada": "2022-02-11", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "51 a 60 anos", "atualizado_em": "2023-10-14T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null, "pais": { "id": "1058", "iso2": "BR", "iso3": "BRA", "nome": "Brasil", "comex_id": "105" } } ] } ``` -------------------------------- ### Método consultarCNPJ para API CNPJ.ws Source: https://docs.cnpj.ws/blog/integracao-protheus Este método utiliza a classe FWREST para consultar a API do CNPJ.ws. Ele recebe o CNPJ como parâmetro e retorna um booleano indicando sucesso ou falha. ```javascript method consultarCNPJ(cCNPJ) class CNPJws local oRest := FWRest():New(::cURL) local cPath := '' ::cRet := '' ::oRet := nil ::lRet := .t. ::cErro:= '' cPath+= allTrim(cCNPJ) oRest:setPath(cPath) if oRest:Get(::aHeaders) if !empty(oRest:GetResult()) ::cRet:= FWNoAccent(DecodeUtf8(oRest:GetResult())) if empty(::cRet) ::cRet:= FWNoAccent(oRest:GetResult()) endif ::cRet:= strTran(::cRet,'\/','/') ::cRet:= strtran(::cRet,":null",': " "') ::cRet:= strtran(::cRet,'"self"','"_self"') ::oRet:= JsonObject():new() ::oRet:fromJson(::cRet) ::lRet := .t. ::cErro:= '' else ::oRet := nil ::cErro:= '' ::lRet := .t. endif ::consoleLog('Sucesso! ' + cPath) else ::setError(oRest,cPath) endif FreeObj(oRest) return ::lRet ``` -------------------------------- ### Classe Java para Consulta de CNPJ Source: https://docs.cnpj.ws/blog/consultar-cnpj-java Implementa a funcionalidade de consulta de CNPJ utilizando a biblioteca OkHttp. Requer a biblioteca OkHttp e o JDK instalados. ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class ConsultaCNPJ { private static final String URL_BASE = "https://publica.cnpj.ws/cnpj/"; //Caso use a API Comercial a URL é diferente, veja a doc: public static void main(String[] args) { try { String cnpj = "27865757000102"; String jsonResponse = consultaCNPJ(cnpj); System.out.println(jsonResponse); } catch (IOException e) { e.printStackTrace(); } } public static String consultaCNPJ(String cnpj) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(URL_BASE + cnpj) .get() .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } } ``` -------------------------------- ### Exemplo de Requisição HTTP para Próxima Página Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/pesquisa-de-empresas Utilize este formato para requisições subsequentes, incluindo o parâmetro 'cursor' obtido na resposta anterior. ```http GET /v2/pesquisa?razao_social=LTDA&limite=20&cursor=eyJ2Ijoi..." ``` -------------------------------- ### JavaScript CNPJ Query Example Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/consultando-cnpj Use the 'consultar-cnpj' package to query company information by CNPJ and access token. ```javascript const consultarCNPJ = require("consultar-cnpj"); async function getCNPJ() { const token = "INFORME O SEU TOKEN DE ACESSO"; const empresa = await consultarCNPJ("27865757000102", token); console.log(empresa); } ``` -------------------------------- ### Example CNPJ API Response Source: https://docs.cnpj.ws/blog/consulta-cnpj-php This is a sample JSON response structure from the CNPJ.ws API, illustrating the type of data returned for a company query. ```json { "cnpj_raiz": "27865757", "razao_social": "GLOBO COMUNICACAO E PARTICIPACOES S/A", "capital_social": "6983568523.86", "responsavel_federativo": "", "atualizado_em": "2021-10-05T03:00:00.000Z", "porte": { "id": "05", "descricao": "Demais" }, "natureza_juridica": { "id": "2054", "descricao": "Sociedade Anônima Fechada" }, "qualificacao_do_responsavel": { "id": 10, "descricao": "Diretor " }, "socios": [ { "cpf_cnpj_socio": "***486498**", "nome": "RAYMUNDO COSTA PINTO BARROS", "tipo": "Pessoa Física", "data_entrada": "2021-03-15", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "51 a 60 anos", "atualizado_em": "2021-09-11T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null }, { "cpf_cnpj_socio": "***720677**", "nome": "MANZAR GOMES FERES", "tipo": "Pessoa Física", "data_entrada": "2021-04-26", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "51 a 60 anos", "atualizado_em": "2021-09-11T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null }, { "cpf_cnpj_socio": "***617850**", "nome": "CARLOS HENRIQUE SCHRODER", "tipo": "Pessoa Física", "data_entrada": "2014-12-12", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "61 a 70 anos", "atualizado_em": "2021-07-21T06:55:45.553Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null }, { "cpf_cnpj_socio": "***632567**", "nome": "JORGE LUIZ DE BARROS NOBREGA", "tipo": "Pessoa Física", "data_entrada": "2014-12-12", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "61 a 70 anos", "atualizado_em": "2021-09-11T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null }, { "cpf_cnpj_socio": "***030727**", "nome": "MARCELO LUIS MENDES SOARES DA SILVA", "tipo": "Pessoa Física", "data_entrada": "2014-12-12", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "51 a 60 anos", "atualizado_em": "2021-09-11T03:00:00.000Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null } ] } ``` -------------------------------- ### Consultar Documentação com Parâmetro 'ask' Source: https://docs.cnpj.ws/modelos-de-dados/situacoes-cadastrais Utilize este endpoint para fazer perguntas específicas sobre a documentação. A resposta incluirá a resposta direta, trechos relevantes e fontes. ```http GET https://docs.cnpj.ws/modelos-de-dados/situacoes-cadastrais.md?ask= ``` -------------------------------- ### Consult CNPJ Source: https://docs.cnpj.ws/referencia-de-api/api-publica/consultando-cnpj Allows up to 3 queries per minute for a CNPJ using the GET method. This query is performed solely on our database. Remember to send the CNPJ without special characters. ```APIDOC ## GET https://publica.cnpj.ws/cnpj/NUMERO_DO_CNPJ_SEM_CARACTERES_ESPECIAIS ### Description Queries CNPJ information from the public API's database. ### Method GET ### Endpoint `https://publica.cnpj.ws/cnpj/{NUMERO_DO_CNPJ_SEM_CARACTERES_ESPECIAIS}` ### Parameters #### Path Parameters - **NUMERO_DO_CNPJ_SEM_CARACTERES_ESPECIAIS** (string) - Required - The CNPJ number without special characters. ### Response #### Success Response (200) - **cnpj_raiz** (string) - The root CNPJ. - **razao_social** (string) - The company's legal name. - **capital_social** (string) - The company's share capital. - **responsavel_federativo** (string) - The federative responsible party. - **atualizado_em** (string) - The date the record was last updated. - **porte** (object) - Information about the company's size. - **id** (string) - The size ID. - **descricao** (string) - The size description. - **natureza_juridica** (object) - Information about the legal nature of the company. - **id** (string) - The legal nature ID. - **descricao** (string) - The legal nature description. - **qualificacao_do_responsavel** (object) - Information about the qualification of the responsible party. - **id** (integer) - The qualification ID. - **descricao** (string) - The qualification description. - **socios** (array) - A list of company partners. - **cpf_cnpj_socio** (string) - The partner's CPF or CNPJ. - **nome** (string) - The partner's name. - **tipo** (string) - The partner's type (e.g., Pessoa Física). - **data_entrada** (string) - The date the partner entered the company. - **cpf_representante_legal** (string) - The CPF of the legal representative. - **nome_representante** (string) - The name of the legal representative. - **faixa_etaria** (string) - The partner's age range. - **atualizado_em** (string) - The date the partner's record was last updated. - **pais_id** (string) - The ID of the partner's country. - **qualificacao_socio** (object) - The partner's qualification. - **id** (integer) - The qualification ID. - **descricao** (string) - The qualification description. - **qualificacao_representante** (object) - The representative's qualification. ### Response Example ```json { "cnpj_raiz": "27865757", "razao_social": "GLOBO COMUNICACAO E PARTICIPACOES S/A", "capital_social": "6983568523.86", "responsavel_federativo": "", "atualizado_em": "2021-07-20T05:41:44.884Z", "porte": { "id": "05", "descricao": "Demais" }, "natureza_juridica": { "id": "2054", "descricao": "Sociedade Anônima Fechada" }, "qualificacao_do_responsavel": { "id": 10, "descricao": "Diretor " }, "socios": [ { "cpf_cnpj_socio": "***486498**", "nome": "RAYMUNDO COSTA PINTO BARROS", "tipo": "Pessoa Física", "data_entrada": "2021-03-15", "cpf_representante_legal": "***000000**", "nome_representante": null, "faixa_etaria": "51 a 60 anos", "atualizado_em": "2021-07-21T06:55:45.553Z", "pais_id": "1058", "qualificacao_socio": { "id": 10, "descricao": "Diretor " }, "qualificacao_representante": null } ] } ``` ``` -------------------------------- ### Requisição para Obter a Próxima Página Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/pesquisa-de-empresas Demonstra como solicitar a próxima página de resultados utilizando o parâmetro 'cursor' com o valor de 'proximo_cursor' retornado na resposta anterior. ```shell curl -X GET https://comercial.cnpj.ws/v2/pesquisa?cursor=eyJ2IjoiMDAwMDAwMDA2NzI5NjMiLCJkIjoiYXNjIiwibSI6ImV4YyJ9 -H "x_api_token: SEU_TOKEN" ``` -------------------------------- ### CNPJws Class Constructor (new method) Source: https://docs.cnpj.ws/blog/integracao-protheus Initializes the CNPJws class, setting up API endpoints, token, and logging verbosity. It supports both public and commercial API endpoints based on the presence of a CN_TOKEN. ```advpl method new(lTest) class CNPJws default lTest:= .f. ::cToken := if(lTest, '', superGetMV('CN_TOKEN',.f.,'')) ::cURL := if(empty(::cToken),'https://publica.cnpj.ws','https://comercial.cnpj.ws') ::lVerb := if(lTest, .t., superGetMV('CN_VERBO',.f.,.t.)) //Indica se ira imprimir todas as msgs no console ::cErro := '' ::cRet := '' ::oRet := nil ::lRet := .t. ::aHeaders:= {"Content-Type: application/json; charset=utf-8"} if !empty(::cToken) aAdd(::aHeaders,'x_api_token: ' + allTrim(::cToken)) endif ::consoleLog('Classe instanciada com sucesso!') return Self ``` -------------------------------- ### Pesquisa avançada de CNPJs (v2 - paginação por cursor) Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/pesquisa-de-empresas Realiza uma pesquisa avançada de CNPJs utilizando parâmetros de filtro e paginação por cursor. Retorna uma lista de empresas que correspondem aos critérios especificados. ```APIDOC ## GET /v2/pesquisa ### Description Realiza uma pesquisa avançada de CNPJs com paginação por cursor. Retorna uma lista de empresas que correspondem aos critérios especificados. ### Method GET ### Endpoint /v2/pesquisa ### Parameters #### Query Parameters - **cursor** (string) - Optional - Cursor para a próxima página (obtido em `proximo_cursor` da resposta anterior). Não enviar na primeira requisição. - **limite** (integer) - Optional - Quantidade de itens por página (1 a 100). Default: 20. - **limit** (integer) - Optional - Alias para `limite`. - **atividade_principal_id** (string) - Optional - Código CNAE da atividade principal. - **atividade_secundaria_id** (string) - Optional - Código CNAE da atividade secundária. - **atividade_id** (string) - Optional - Código CNAE (pesquisa na atividade principal e secundária). - **natureza_juridica_id** (string) - Optional - Código da Natureza Jurídica. - **razao_social** (string) - Optional - Razão Social (mín. 3 caracteres). - **nome_fantasia** (string) - Optional - Nome Fantasia. - **pais_id** (string) - Optional - Código do País do BACEN. - **estado_id** (string) - Optional - Código IBGE do estado. - **cidade_id** (string) - Optional - Código IBGE da Cidade. - **cep** (string) - Optional - CEP. - **situacao_cadastral** (string) - Optional - Situação cadastral na Receita Federal. - **data_situacao_cadastral_de** (string) - Optional - Data da Situação Cadastral (a partir de) YYYY-MM-DD. - **data_situacao_cadastral_ate** (string) - Optional - Data da Situação Cadastral (até) YYYY-MM-DD. - **porte_id** (string) - Optional - Id do porte da empresa. - **socio_nome** (string) - Optional - Nome do Sócio. - **socio_cpf_cnpj** (string) - Optional - CPF ou CNPJ do Sócio (apenas dígitos). - **data_inicio_atividade_de** (string) - Optional - Data de Início de Atividade (a partir de) YYYY-MM-DD. - **data_inicio_atividade_ate** (string) - Optional - Data de Início de Atividade (até) YYYY-MM-DD. - **token** (string) - Optional - Token de autenticação. #### Header Parameters - **x_api_token** (string) - Optional - Token de autenticação. ### Response #### Success Response (200) - **lista** (array) - Lista de CNPJs encontrados. - **proximo_cursor** (string) - Cursor para a próxima página. - **tem_proxima_pagina** (boolean) - Indica se há mais páginas de resultados. #### Error Response (400) - **erro** (string) - Mensagem de erro descrevendo o problema (e.g., Parâmetros inválidos ou cursor inválido). #### Error Response (401) - **erro** (string) - Mensagem de erro descrevendo o problema (e.g., Token de API inválido ou não fornecido). #### Error Response (403) - **erro** (string) - Mensagem de erro descrevendo o problema (e.g., Plano não permite pesquisa). ### Examples #### Primeira página `GET /v2/pesquisa?razao_social=LTDA&limite=20` #### Próxima página `GET /v2/pesquisa?razao_social=LTDA&limite=20&cursor=eyJ2Ijoi...` ``` -------------------------------- ### Lógica de Preenchimento de Inscrições Estaduais Source: https://docs.cnpj.ws/blog/gatilho-consultar-cnpj Este trecho de código itera sobre as inscrições estaduais de um estabelecimento para encontrar e definir a inscrição estadual correspondente ao estado atual. É utilizado quando o estado do estabelecimento coincide com uma de suas inscrições estaduais. ```AdvPL for nX:=1 to len(oJSON['estabelecimento']['inscricoes_estaduais']) if oJSON['estabelecimento']['estado']['id'] == oJSON['estabelecimento']['inscricoes_estaduais'][nX]['estado']['id'] oModel:SetValue('SA2MASTER','A2_INSCR', oJSON['estabelecimento']['inscricoes_estaduais'][nX]['inscricao_estadual']) EXIT endif next endif ``` -------------------------------- ### Exemplo de Requisição com Token na URL Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/consultando-consumo Demonstra como incluir o token de acesso diretamente na URL para consultar o consumo. ```http https://comercial.cnpj.ws/consumo?token=SEU_TOKEN ``` -------------------------------- ### Erro: Limite de Requisições por Minuto Excedido Source: https://docs.cnpj.ws/referencia-de-api/api-publica/limitacoes Este é o formato da resposta de erro quando o limite de 3 requisições por minuto por IP é excedido. A mensagem indica o status 429 e o tempo estimado para liberação. ```shell { "status": 429, "titulo": "Muitas requisições", "detahes": "Excedido o limite máximo de 3 consultas por minuto. Liberação ocorrerá em Thu Jun 03 2021 16:15:00 GMT-0300 (Horário Padrão de Brasília)" } ``` -------------------------------- ### Exemplo de Uso do Pacote consultar-cnpj em JavaScript Source: https://docs.cnpj.ws/referencia-de-api/api-comercial/pesquisa-de-empresas Demonstra como usar o pacote 'consultar-cnpj' para pesquisar empresas por atividade principal e estado, paginando os resultados. Certifique-se de substituir 'INFORME O SEU TOKEN DE ACESSO' pelo seu token real. ```javascript const consultarCNPJ = require("consultar-cnpj"); async function getCNPJ() { const token = "INFORME O SEU TOKEN DE ACESSO"; const page = 2; const data = await consultarCNPJ.pesquisa( { atividade_principal_id: "6203100", estado_id: 28 }, token, page ); console.log(data); } ```