Webservice de CNPJ

Asked

Viewed 3,696 times

1

I need to get some CNPJ data for my registration system, I found this webservice on interwebs.

GET - http://receitaws.com.br/v1/cnpj/[cnpj]

But I’m not able to implement in PHP code.

You could help me?

Personal excuse,

Follow my attempt to implement:

<html>
<head>
<title>CNPJ</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<!-- Adicionando JQuery -->
<script src="//code.jquery.com/jquery-2.2.2.min.js"></script>

<!-- Adicionando Javascript -->
<script type="text/javascript" >

    $(document).ready(function() {

        function limpa_formulário_cnpj() {
            // Limpa valores do formulário de cnpj.
            $("#rua").val("");
            $("#bairro").val("");
            $("#cidade").val("");
            $("#uf").val("");
            $("#nome").val("");
        }

        //Quando o campo cnpj perde o foco.
        $("#cnpj").blur(function() {

            //Nova variável "cnpj" somente com dígitos.
            var cnpj = $(this).val().replace(/\D/g, '');

            //Verifica se campo cnpj possui valor informado.
            if (cnpj != "") {

                //Expressão regular para validar o CNPJ.
                var validacnpj = /^[0-9]/;

                //Valida o formato do CNPJ.
                if(validacnpj.test(cnpj)) {

                    //Preenche os campos com "..." enquanto consulta webservice.
                    $("#logradouro").val("...")
                    $("#bairro").val("...")
                    $("#municipio").val("...")
                    $("#uf").val("...")
                    $("#nome").val("...")

                    $.getJSON("http://receitaws.com.br/v1/cnpj/"+ cnpj, function(dados) {

                        if (!("erro" in dados)) {
                            //Atualiza os campos com os valores da consulta.
                            $("#logradouro").val(dados.logradouro);
                            $("#bairro").val(dados.bairro);
                            $("#municipio").val(dados.municipio);
                            $("#uf").val(dados.uf);
                            $("#nome").val(dados.abertura);
                        } //end if.
                        else {
                            //Cnpj pesquisado não foi encontrado.
                            limpa_formulário_cnpj();
                            alert("CNPJ não encontrado.");
                        }
                    });
                } //end if.
                else {
                    //cnpj é inválido.
                    limpa_formulário_cnpj();
                    alert("Formato de CNPJ inválido.");
                }
            } //end if.
            else {
                //cnpj sem valor, limpa formulário.
                limpa_formulário_cnpj();
            }
        });
    });

</script>
</head>

<body>
<!-- Inicio do formulario -->
  <form method="get" action=".">
    <label>Cnpj:
    <input name="cnpj" type="text" id="cnpj" value="" size="10" maxlength="19" /></label><br />
    <label>Rua:
    <input name="logradouro" type="text" id="logradouro" size="60" /></label><br />
    <label>Bairro:
    <input name="bairro" type="text" id="bairro" size="40" /></label><br />
    <label>Cidade:
    <input name="municipio" type="text" id="municipio" size="40" /></label><br />
    <label>Estado:
    <input name="uf" type="text" id="uf" size="2" /></label><br />
    <label>Nome:
    <input name="nome" type="text" id="nome" size="8" /></label><br />
  </form>
</body>

</html>
  • Guys, I edited the question! I didn’t know about the "rules"...

  • 2

    It’s not by the rules, it’s improved a lot with editing. It’s more about the fact that it was becoming impractical to help you. Already with the new post, you can see that this is a CORS problem. Javascript will not be able to get the data from another domain. I would have to use PHP itself to get the data. I noticed that you used the PHP tag, but in fact you are currently using jQuery. If you’re actually using PHP on your server, it’s easier.

  • @Bacco This, I intend to put on a PHP server. But I need this communication to be "automatic"! I made this same script in Via CEP and it worked perfectly.

  • Beware of the "worked perfectly", under real conditions the thing changes.

  • managed to implement?

3 answers

2

As the question asks in PHP, I’ll answer that if anyone has the same question...

In the PHP you have two options to download content from the web. You can use both the function file_get_contents how much Curl

With the PHP you won’t have problems with Cross-Origin, but may have blocking problems due to Header, but depending on the case, it is possible to use it anyway.

The function file_get_contents was created to read input data, files etc. However, you can use it for requests as well.

<?php

$cnpj = filter_input(INPUT_GET, "cnpj", FILTER_SANITIZE_STRING);

if (empty($cnpj)) die("Informe um CNPJ");

echo file_get_contents("http://receitaws.com.br/v1/cnpj/{$cnpj}");

Already the function cURL, she is an "extension" that connects with libcurl. This library allows you to make requests with several protocols, among them: https, ftp, Gopher, telnet etc..

<?php

$cnpj = filter_input(INPUT_GET, "cnpj", FILTER_SANITIZE_STRING);

if (empty($cnpj)) die("Informe um CNPJ");

$ch = curl_init();
curl_setopt_array($ch, [
    /* Define URL */
    CURLOPT_URL            => "http://receitaws.com.br/v1/cnpj/{$cnpj}",

    /* Informa que você quer o retorno */
    CURLOPT_RETURNTRANSFER => true,

    /**
     * (Opcional)
     * Como há limitações para acessar a URL acima,
     * Você pode utilziar proxies para evitar isso.
     */
]);

/* Acessa URL e captura o retorno */
$response = curl_exec($ch);

/* Fecha a conexão */
curl_close($ch);

echo $response;

To learn more about both, I leave as a hint the question Difference between file_get_contents and Curl?

To access through the JavaScript, just use XMLHttpRequest or similar.

$.getJSON("consulta_cnpj.php?cnpj="+ cnpj, function(dados) {

    if (!("erro" in dados)) {
        $("#logradouro").val(dados.logradouro);
        $("#bairro").val(dados.bairro);
        $("#municipio").val(dados.municipio);
        $("#uf").val(dados.uf);
        $("#nome").val(dados.abertura);
    else {
        alert("CNPJ não encontrado.");
    }
});

0

The problem is that you are making a Cross-Origin request. This means that your domain is trying to access via another Domain Client, which is not normally allowed.

To solve your problem you have two ways:

1 - Use an API that already allows this, such as https://www.hubdodesenvolvedor.com.br/detalhes/cnpj

2 - Use an Access Proxy that does Cross Origin, such as https://crossorigin.me/ or https://enable-cors.org/.

How would this look:

$.getJSON("https://crossorigin.me/http://receitaws.com.br/v1/cnpj/"+ cnpj, function(dados)

0

The secret here is the getJSON does not catch straight from the recipe: $.getJSON("http://receitaws.com.br/v1/cnpj/"+ cnpj, function(dados) but create a file that creates a JSON and then yes take the data from it: $.getJSON("pegaCNPJ.php?cnpj="+ cnpj, function(dados)

Must be valid JSON. See mine:

{ "atividade_principal": "Aluguel de outras máquinas e equipamentos comerciais e industriais não especificados anteriormente, sem operador", "fantasia": "CALPHER", "nome": "CAXR MAQXAS E EQUXNTOS LTDA", "cnpj": "11.036.404/9991-04", "logradouro": "R ALFREDO ACHCAR,", "numero": "XXXX-A", "complemento": "EDIF: X;", "bairro": "NOVA VILA", "municipio": "CAFUNDO", "uf": "SP", "cep": "XX.XX0-000", "telefone": "(19) XXXX-6XXX / (19) XXX9-XXX2", "email": "[email protected]", "status": "OK" }

Browser other questions tagged

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