Exemplo da API Simples Nacional com NodeJS

NodeJS

Aprenda a integrar a API Simples Nacional do SintegraWS com NodeJS utilizando exemplos de código práticos.

Siga o exemplo abaixo para implementar a API Simples Nacional com NodeJS no seu ambiente de desenvolvimento e aprimorar a confiabilidade do seu sistema.

  (async () => {
    // Aqui você define os valores dos parâmetros da API:
    // Este código assume Node.js 18+ com fetch e AbortController nativos
    const token = 'SEU_TOKEN_AQUI';
    const cnpj = '06990590000123';
    // Antes de tudo, validar o CNPJ
    if (!isValidCNPJ(cnpj)) {
      console.error("CNPJ inválido!");
      return;
    }
  
    // Montando a URL com parâmetros codificados
    const url = `https://www.sintegraws.com.br/api/v1/execute-api.php?token=${encodeURIComponent(token)}&cnpj=${encodeURIComponent(cnpj)}&plugin=SN`;
  
    // Criar AbortController para implementar o timeout manualmente
    const controller = new AbortController();
    const signal = controller.signal;
  
    // Timeout de 120 segundos
    const timeout = setTimeout(() => {
      controller.abort();
    }, 120000);
  
    try {
      const response = await fetch(url, { signal });
      if (!response.ok) {
        throw new Error(`Erro na requisição: ${response.status} ${response.statusText}`);
      }
  
      const data = await response.json();
      if (data.status === "OK") {
        console.log("Status está OK!");
      } else {
        console.log("Status não está OK ou não encontrado.");
      }
    } catch (error) {
      console.error('Erro ao chamar a API:', error);
    } finally {
      clearTimeout(timeout);
    }
  })();

  // Essa função é utilizada para validar o CNPJ antes de realizar a chamada na API
  function isValidCNPJ(cnpj) {
    // Remove todos os caracteres não-numéricos
    cnpj = cnpj.replace(/[^\d]+/g, '');
    // Verifica se tem 14 dígitos
    if (cnpj.length !== 14) return false;
    // Verifica se todos os dígitos são iguais
    if (/^(.)\1+$/.test(cnpj)) return false;

    let tamanho = cnpj.length - 2;
    let numeros = cnpj.substring(0, tamanho);
    let digitos = cnpj.substring(tamanho);
    let soma = 0;
    let pos = tamanho - 7;

    for (let i = tamanho; i >= 1; i--) {
      soma += parseInt(numeros.charAt(tamanho - i)) * pos--;
      if (pos < 2) pos = 9;
    }

    let resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    if (resultado !== parseInt(digitos.charAt(0))) return false;

    tamanho += 1;
    numeros = cnpj.substring(0, tamanho);
    soma = 0;
    pos = tamanho - 7;

    for (let i = tamanho; i >= 1; i--) {
      soma += parseInt(numeros.charAt(tamanho - i)) * pos--;
      if (pos < 2) pos = 9;
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    return (resultado === parseInt(digitos.charAt(1)));
  }
  (async () => {
    // Aqui você define os valores dos parâmetros da API:
    const token = 'SEU_TOKEN_AQUI';
    const cnpj = '06990590000123';
    // Antes de tudo, validar o CNPJ
    if (!isValidCNPJ(cnpj)) {
      console.error("CNPJ inválido!");
      return;
    }
  
    // Montando a URL com os parâmetros codificados para evitar problemas com caracteres especiais
    const url = `https://www.sintegraws.com.br/api/v1/execute-api.php?token=${encodeURIComponent(token)}&cnpj=${encodeURIComponent(cnpj)}&plugin=SN`;
  
    // Criamos um AbortController para permitir cancelar a requisição, caso atinja o timeout
    const controller = new AbortController();
    const signal = controller.signal;
  
    // Definimos um timeout de 120 segundos (120.000 milissegundos).
    // Se a requisição não responder nesse tempo, abortamos.
    const timeout = setTimeout(() => {
      controller.abort();
    }, 120000);
  
    try {
      // Fazendo a requisição GET usando fetch e aguardando a resposta.
      // Passamos o 'signal' do AbortController para poder abortar se necessário.
      const response = await fetch(url, { signal });
  
      // Verificando se o status da resposta é OK (200)
      if (!response.ok) {
        // Se não for, lançamos um erro para cair no bloco catch
        throw new Error(`Erro na requisição: ${response.status} ${response.statusText}`);
      }
  
      // Convertendo a resposta para JSON
      const data = await response.json();
  
      // Aqui você pode manipular os dados retornados da API.
      // Vamos apenas verificar se o campo "status" é "OK"
      if (data.status === "OK") {
        console.log("Status está OK!");
      } else {
        console.log("Status não está OK ou não encontrado.");
      }
    } catch (error) {
      // Tratando qualquer erro que possa ocorrer durante a requisição ou o processamento,
      // incluindo o erro de timeout (AbortError) ou problemas de rede.
      console.error('Erro ao chamar a API:', error);
    } finally {
      // Limpamos o timeout, garantindo que não fique pendente após o término da operação.
      clearTimeout(timeout);
    }
  })();

  // Essa função é utilizada para validar o CNPJ antes de realizar a chamada na API
  function isValidCNPJ(cnpj) {
    // Remove todos os caracteres não-numéricos
    cnpj = cnpj.replace(/[^\d]+/g, '');
    // Verifica se tem 14 dígitos
    if (cnpj.length !== 14) return false;
    // Verifica se todos os dígitos são iguais
    if (/^(.)\1+$/.test(cnpj)) return false;

    let tamanho = cnpj.length - 2;
    let numeros = cnpj.substring(0, tamanho);
    let digitos = cnpj.substring(tamanho);
    let soma = 0;
    let pos = tamanho - 7;

    for (let i = tamanho; i >= 1; i--) {
      soma += parseInt(numeros.charAt(tamanho - i)) * pos--;
      if (pos < 2) pos = 9;
    }

    let resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    if (resultado !== parseInt(digitos.charAt(0))) return false;

    tamanho += 1;
    numeros = cnpj.substring(0, tamanho);
    soma = 0;
    pos = tamanho - 7;

    for (let i = tamanho; i >= 1; i--) {
      soma += parseInt(numeros.charAt(tamanho - i)) * pos--;
      if (pos < 2) pos = 9;
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    return (resultado === parseInt(digitos.charAt(1)));
  }
  package main

  import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "time"
  )

  func main() {
    // Aqui você define os valores dos parâmetros da API:
    token := "SEU_TOKEN_AQUI"
    cnpj := "06990590000123"

    if !isValidCNPJ(cnpj) {
      fmt.Println("CNPJ inválido!")
      return
    }


    // Montando a URL com parâmetros codificados
    requestUrl := "https://www.sintegraws.com.br/api/v1/execute-api.php?token=" + url.QueryEscape(token) + "&cnpj=" + url.QueryEscape(cnpj) + "&plugin=SN"

    client := http.Client{
      Timeout: 120 * time.Second,
    }

    resp, err := client.Get(requestUrl)
    if err != nil {
      fmt.Println("Erro ao chamar a API:", err)
      return
    }
    defer resp.Body.Close()

    if resp.StatusCode < 200 || resp.StatusCode >= 300 {
      fmt.Printf("Erro na requisição: %d\n", resp.StatusCode)
      return
    }

    body, err := io.ReadAll(resp.Body)
    if err != nil {
      fmt.Println("Erro ao ler resposta:", err)
      return
    }

    var data map[string]interface{}
    if err := json.Unmarshal(body, &data); err != nil {
      fmt.Println("Erro ao converter JSON:", err)
      return
    }

    if data["status"] == "OK" {
      fmt.Println("Status está OK!")
    } else {
      fmt.Println("Status não está OK ou não encontrado.")
    }
  }

  func digitsOnly(value string) string {
    digits := make([]rune, 0, len(value))
    for _, char := range value {
      if char >= '0' && char <= '9' {
        digits = append(digits, char)
      }
    }
    return string(digits)
  }

  func isValidCNPJ(cnpj string) bool {
    cnpj = digitsOnly(cnpj)
    if len(cnpj) != 14 {
      return false
    }

    allEqual := true
    for i := 1; i < len(cnpj); i++ {
      if cnpj[i] != cnpj[0] {
        allEqual = false
        break
      }
    }
    if allEqual {
      return false
    }

    weights1 := []int{5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
    weights2 := []int{6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}

    sum := 0
    for i := 0; i < 12; i++ {
      sum += int(cnpj[i]-'0') * weights1[i]
    }
    digit := sum % 11
    if digit < 2 {
      digit = 0
    } else {
      digit = 11 - digit
    }
    if digit != int(cnpj[12]-'0') {
      return false
    }

    sum = 0
    for i := 0; i < 13; i++ {
      sum += int(cnpj[i]-'0') * weights2[i]
    }
    digit = sum % 11
    if digit < 2 {
      digit = 0
    } else {
      digit = 11 - digit
    }
    return digit == int(cnpj[13]-'0')
  }
  <?php
  $token = 'SEU_TOKEN_AQUI';
  $cnpj = '06990590000123';

  if (!isValidCNPJ($cnpj)) {
    echo 'CNPJ inválido!';
    exit;
  }


  $query = [
    'token' => $token,
    'cnpj' => $cnpj,
    'plugin' => 'SN'
  ];

  $url = 'https://www.sintegraws.com.br/api/v1/execute-api.php?' . http_build_query($query);

  $curl = curl_init();
  curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => 'GET',
  ]);

  $response = curl_exec($curl);
  $error = curl_error($curl);
  curl_close($curl);

  if ($error) {
    echo 'Erro ao chamar a API: ' . $error;
    exit;
  }

  $data = json_decode($response, true);

  if (isset($data['status']) && $data['status'] === 'OK') {
    echo 'Status está OK!';
  } else {
    echo 'Status não está OK ou não encontrado.';
  }

  function onlyDigits($value)
  {
    return preg_replace('/\D/', '', $value);
  }

  function isValidCNPJ($cnpj)
  {
    $cnpj = onlyDigits($cnpj);
    if (strlen($cnpj) != 14) return false;
    if (preg_match('/^(\d)\1{13}$/', $cnpj)) return false;

    $weights1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
    $weights2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];

    $sum = 0;
    for ($i = 0; $i < 12; $i++) {
      $sum += intval($cnpj[$i]) * $weights1[$i];
    }
    $digit = $sum % 11;
    $digit = $digit < 2 ? 0 : 11 - $digit;
    if (intval($cnpj[12]) != $digit) return false;

    $sum = 0;
    for ($i = 0; $i < 13; $i++) {
      $sum += intval($cnpj[$i]) * $weights2[$i];
    }
    $digit = $sum % 11;
    $digit = $digit < 2 ? 0 : 11 - $digit;

    return intval($cnpj[13]) == $digit;
  }
  import requests

  def only_digits(value):
      return ''.join(char for char in value if char.isdigit())

  def is_valid_cnpj(cnpj):
      cnpj = only_digits(cnpj)
      if len(cnpj) != 14 or cnpj == cnpj[0] * 14:
          return False

      weights_1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
      weights_2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]

      total = sum(int(cnpj[i]) * weights_1[i] for i in range(12))
      digit = total % 11
      digit = 0 if digit < 2 else 11 - digit
      if int(cnpj[12]) != digit:
          return False

      total = sum(int(cnpj[i]) * weights_2[i] for i in range(13))
      digit = total % 11
      digit = 0 if digit < 2 else 11 - digit
      return int(cnpj[13]) == digit

  # Aqui você define os valores dos parâmetros da API:
  token = 'SEU_TOKEN_AQUI'
  cnpj = '06990590000123'

  if not is_valid_cnpj(cnpj):
      print('CNPJ inválido!')
      raise SystemExit


  params = {
      'token': token,
      'cnpj': cnpj,
      'plugin': 'SN'
  }

  try:
      response = requests.get('https://www.sintegraws.com.br/api/v1/execute-api.php', params=params, timeout=120)
      response.raise_for_status()
      data = response.json()

      if data.get('status') == 'OK':
          print('Status está OK!')
      else:
          print('Status não está OK ou não encontrado.')
  except requests.RequestException as error:
      print('Erro ao chamar a API:', error)
  using System;
  using System.Net.Http;
  using System.Text.Json;
  using System.Threading.Tasks;

  class Program
  {
    static async Task Main()
    {
      // Aqui você define os valores dos parâmetros da API:
      var token = "SEU_TOKEN_AQUI";
      var cnpj = "06990590000123";

      if (!IsValidCNPJ(cnpj))
      {
        Console.WriteLine("CNPJ inválido!");
        return;
      }


      var url = $"https://www.sintegraws.com.br/api/v1/execute-api.php?token={Uri.EscapeDataString(token)}&cnpj={Uri.EscapeDataString(cnpj)}&plugin=SN";

      using var client = new HttpClient();
      client.Timeout = TimeSpan.FromSeconds(120);

      try
      {
        var response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync();
        var data = JsonSerializer.Deserialize<JsonElement>(json);

        if (data.TryGetProperty("status", out var status) && status.GetString() == "OK")
        {
          Console.WriteLine("Status está OK!");
        }
        else
        {
          Console.WriteLine("Status não está OK ou não encontrado.");
        }
      }
      catch (Exception error)
      {
        Console.WriteLine($"Erro ao chamar a API: {error.Message}");
      }
    }

    static string OnlyDigits(string value)
    {
      var digits = "";
      foreach (var character in value)
      {
        if (char.IsDigit(character))
        {
          digits += character;
        }
      }
      return digits;
    }

    static bool IsValidCNPJ(string cnpj)
    {
      cnpj = OnlyDigits(cnpj);
      if (cnpj.Length != 14) return false;

      var allEqual = true;
      for (var i = 1; i < cnpj.Length; i++)
      {
        if (cnpj[i] != cnpj[0])
        {
          allEqual = false;
          break;
        }
      }
      if (allEqual) return false;

      var weights1 = new[] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
      var weights2 = new[] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };

      var sum = 0;
      for (var i = 0; i < 12; i++)
      {
        sum += (cnpj[i] - '0') * weights1[i];
      }
      var digit = sum % 11;
      digit = digit < 2 ? 0 : 11 - digit;
      if ((cnpj[12] - '0') != digit) return false;

      sum = 0;
      for (var i = 0; i < 13; i++)
      {
        sum += (cnpj[i] - '0') * weights2[i];
      }
      digit = sum % 11;
      digit = digit < 2 ? 0 : 11 - digit;

      return (cnpj[13] - '0') == digit;
    }
  }
  import java.io.IOException;
  import java.net.URI;
  import java.net.URLEncoder;
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.nio.charset.StandardCharsets;
  import java.time.Duration;

  public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
      // Aqui você define os valores dos parâmetros da API:
      String token = "SEU_TOKEN_AQUI";
      String cnpj = "06990590000123";

      if (!isValidCNPJ(cnpj)) {
          System.err.println("CNPJ inválido!");
          return;
      }


      String url = "https://www.sintegraws.com.br/api/v1/execute-api.php?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8) + "&cnpj=" + URLEncoder.encode(cnpj, StandardCharsets.UTF_8) + "&plugin=SN";

      HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(120))
        .build();

      HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(url))
        .timeout(Duration.ofSeconds(120))
        .GET()
        .build();

      HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

      if (response.statusCode() >= 200 && response.statusCode() < 300) {
        System.out.println(response.body());
      } else {
        System.out.println("Erro na requisição: " + response.statusCode());
      }
    }

    private static String onlyDigits(String value) {
        return value.replaceAll("\\D", "");
    }

    private static boolean isValidCNPJ(String cnpj) {
        cnpj = onlyDigits(cnpj);
        if (cnpj.length() != 14) return false;
        if (cnpj.matches("(\\d)\\1{13}")) return false;

        int[] weights1 = {5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2};
        int[] weights2 = {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2};

        int sum = 0;
        for (int i = 0; i < 12; i++) {
            sum += Character.getNumericValue(cnpj.charAt(i)) * weights1[i];
        }
        int digit = sum % 11;
        digit = digit < 2 ? 0 : 11 - digit;
        if (Character.getNumericValue(cnpj.charAt(12)) != digit) return false;

        sum = 0;
        for (int i = 0; i < 13; i++) {
            sum += Character.getNumericValue(cnpj.charAt(i)) * weights2[i];
        }
        digit = sum % 11;
        digit = digit < 2 ? 0 : 11 - digit;

        return Character.getNumericValue(cnpj.charAt(13)) == digit;
    }
  }
  import Foundation

  func isValidCNPJ(_ cnpj: String) -> Bool {
    let numbers = cnpj.filter { $0.isNumber }.compactMap { Int(String($0)) }
    if numbers.count != 14 { return false }
    if Set(numbers).count == 1 { return false }

    let weights1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
    let weights2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]

    var sum = 0
    for index in 0..<12 {
      sum += numbers[index] * weights1[index]
    }
    var digit = sum % 11
    digit = digit < 2 ? 0 : 11 - digit
    if digit != numbers[12] { return false }

    sum = 0
    for index in 0..<13 {
      sum += numbers[index] * weights2[index]
    }
    digit = sum % 11
    digit = digit < 2 ? 0 : 11 - digit

    return digit == numbers[13]
  }

  // Aqui você define os valores dos parâmetros da API:
  let token = "SEU_TOKEN_AQUI"
  let cnpj = "06990590000123"

  guard isValidCNPJ(cnpj) else {
    print("CNPJ inválido!")
    exit(0)
  }


  var components = URLComponents(string: "https://www.sintegraws.com.br/api/v1/execute-api.php")!
  components.queryItems = [
    URLQueryItem(name: "token", value: token),
    URLQueryItem(name: "cnpj", value: cnpj),
    URLQueryItem(name: "plugin", value: "SN")
  ]

  let request = URLRequest(url: components.url!, timeoutInterval: 120)

  URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
      print("Erro ao chamar a API: \(error)")
      return
    }

    guard let data = data else {
      print("Resposta vazia")
      return
    }

    do {
      let json = try JSONSerialization.jsonObject(with: data, options: [])
      print(json)
    } catch {
      print("Erro ao converter JSON: \(error)")
    }
  }.resume()
  #Include "protheus.ch"
  
  User Function ChamarAPI()
    // Aqui você define os valores dos parâmetros da API
    Local cToken           := "SEU_TOKEN_AQUI"
    Local cCNPJ            := "06990590000123"
    Local cBaseURL       := "https://www.sintegraws.com.br/api/v1/execute-api.php"
    Local cURL, cResp    := ""
    Local nStatus        := 0
    Local oJson

    If !IsValidCNPJ(cCNPJ)
      Conout("CNPJ inválido!")
      Return
    EndIf

    cURL := cBaseURL + ;
    "?token="             + URLEncode(cToken) + ;
    "&cnpj="              + URLEncode(cCNPJ) + ;
    "&plugin=SN"

    HttpSetTimeOut(120000)
    cResp := HttpGet(cURL)
    nStatus := HttpResult()

    If nStatus <> 200
      Conout("Erro na requisição: " + Ltrim(Str(nStatus)))
      Return
    EndIf

    If Empty(cResp)
      Conout("Resposta vazia.")
      Return
    EndIf

    oJson := JsonDecode(cResp)
    If oJson == Nil
      Conout("Erro ao decodificar JSON.")
      Return
    EndIf

    If oJson["status"] == "OK"
      Conout("Status está OK!")
    Else
      Conout("Status não está OK ou não encontrado.")
    EndIf
  Return

  Static Function IsValidCNPJ(cCnpj)
    Local cClean := ""
    Local aPeso1 := {5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
    Local aPeso2 := {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
    Local i, nSum, nRest

    For i := 1 To Len(cCnpj)
      If IsDigit(SubStr(cCnpj,i,1))
        cClean += SubStr(cCnpj,i,1)
      EndIf
    Next i

    If Len(cClean) <> 14
      Return .F.
    EndIf

    If (cClean == Replicate(SubStr(cClean,1,1),14))
      Return .F.
    EndIf

    nSum := 0
    For i := 1 To 12
      nSum += Val(SubStr(cClean,i,1)) * aPeso1[i]
    Next i
    nRest := nSum % 11
    If nRest < 2
      nRest := 0
    Else
      nRest := 11 - nRest
    EndIf
    If nRest <> Val(SubStr(cClean,13,1))
      Return .F.
    EndIf

    nSum := 0
    For i := 1 To 13
      nSum += Val(SubStr(cClean,i,1)) * aPeso2[i]
    Next i
    nRest := nSum % 11
    If nRest < 2
      nRest := 0
    Else
      nRest := 11 - nRest
    EndIf

    Return (nRest == Val(SubStr(cClean,14,1)))
  EndFunc
  REPORT z_chamar_api.
  
  DATA: lv_token               TYPE string VALUE 'SEU_TOKEN_AQUI',
        lv_cnpj                TYPE string VALUE '06990590000123',
        lv_url                 TYPE string,
        lv_response            TYPE string,
        lv_status_code         TYPE i,
        lv_encoded_token       TYPE string,
        lv_encoded_cnpj        TYPE string,
        lv_valid_cnpj          TYPE abap_bool.
  
  CALL FUNCTION 'ESCAPE_URL'
    EXPORTING unescaped = lv_token
    IMPORTING escaped   = lv_encoded_token.
  
  CALL FUNCTION 'ESCAPE_URL'
    EXPORTING unescaped = lv_cnpj
    IMPORTING escaped   = lv_encoded_cnpj.

  PERFORM is_valid_cnpj USING lv_cnpj CHANGING lv_valid_cnpj.
  IF lv_valid_cnpj <> abap_true.
    WRITE: / 'CNPJ inválido!'.
    EXIT.
  ENDIF.
  
  lv_url = |https://www.sintegraws.com.br/api/v1/execute-api.php?token={ lv_encoded_token }&cnpj={ lv_encoded_cnpj }&plugin=SN|.
  
  DATA(lo_http_client) = NEW cl_http_client( ).
  
  CALL METHOD cl_http_client=>create_by_url
    EXPORTING url = lv_url
    IMPORTING client = lo_http_client
    EXCEPTIONS OTHERS = 4.
  
  IF sy-subrc <> 0.
    WRITE: / 'Erro ao criar o HTTP Client'.
    EXIT.
  ENDIF.
  
  lo_http_client->timeout = 120.
  lo_http_client->request->set_header_field( name = '~request_method' value = 'GET' ).
  
  CALL METHOD lo_http_client->send
    EXCEPTIONS OTHERS = 4.
  
  IF sy-subrc <> 0.
    WRITE: / 'Erro ao enviar requisição HTTP.'.
    EXIT.
  ENDIF.
  
  CALL METHOD lo_http_client->receive
    EXCEPTIONS OTHERS = 4.
  
  IF sy-subrc <> 0.
    WRITE: / 'Erro ao receber resposta HTTP.'.
    EXIT.
  ENDIF.
  
  lv_status_code = lo_http_client->response->get_status( ).
  IF lv_status_code <> 200.
    WRITE: / |Erro na requisição: { lv_status_code }|.
    lo_http_client->close( ).
    EXIT.
  ENDIF.
  
  lv_response = lo_http_client->response->get_data( ).
  lo_http_client->close( ).
  
  DATA(lo_json) = NEW /ui2/cl_json( ).
  DATA(ls_result) = lo_json->deserialize( EXPORTING json = lv_response ).
  
  DATA(lv_status) = VALUE string( ls_result[ 'status' ] ).
  
  IF lv_status = 'OK'.
    WRITE: / 'Status está OK!'.
  ELSE.
    WRITE: / 'Status não está OK ou não encontrado.'.
  ENDIF.
  
  FORM is_valid_cnpj USING p_cnpj TYPE string CHANGING p_valid TYPE abap_bool.
    DATA: lv_cnpj TYPE string,
          lv_sum TYPE i,
          lv_digit TYPE i,
          lv_index TYPE i,
          lv_offset TYPE i,
          lv_weight TYPE i.

    lv_cnpj = p_cnpj.
    REPLACE ALL NON DIGITS IN lv_cnpj WITH ''.
  
    IF strlen( lv_cnpj ) <> 14.
      p_valid = abap_false.
      RETURN.
    ENDIF.
  
    DATA lv_first TYPE c LENGTH 1.
    lv_first = lv_cnpj(1).
  
    IF lv_cnpj = lv_first && lv_cnpj = lv_first(14).
      p_valid = abap_false.
      RETURN.
    ENDIF.

    lv_sum = 0.
    DO 12 TIMES.
      lv_index = sy-index.
      lv_offset = lv_index - 1.
      CASE lv_index.
        WHEN 1. lv_weight = 5.
        WHEN 2. lv_weight = 4.
        WHEN 3. lv_weight = 3.
        WHEN 4. lv_weight = 2.
        WHEN 5. lv_weight = 9.
        WHEN 6. lv_weight = 8.
        WHEN 7. lv_weight = 7.
        WHEN 8. lv_weight = 6.
        WHEN 9. lv_weight = 5.
        WHEN 10. lv_weight = 4.
        WHEN 11. lv_weight = 3.
        WHEN 12. lv_weight = 2.
      ENDCASE.
      lv_sum = lv_sum + lv_cnpj+lv_offset(1) * lv_weight.
    ENDDO.
    lv_digit = lv_sum MOD 11.
    IF lv_digit < 2.
      lv_digit = 0.
    ELSE.
      lv_digit = 11 - lv_digit.
    ENDIF.
    IF lv_digit <> lv_cnpj+12(1).
      p_valid = abap_false.
      RETURN.
    ENDIF.

    lv_sum = 0.
    DO 13 TIMES.
      lv_index = sy-index.
      lv_offset = lv_index - 1.
      CASE lv_index.
        WHEN 1. lv_weight = 6.
        WHEN 2. lv_weight = 5.
        WHEN 3. lv_weight = 4.
        WHEN 4. lv_weight = 3.
        WHEN 5. lv_weight = 2.
        WHEN 6. lv_weight = 9.
        WHEN 7. lv_weight = 8.
        WHEN 8. lv_weight = 7.
        WHEN 9. lv_weight = 6.
        WHEN 10. lv_weight = 5.
        WHEN 11. lv_weight = 4.
        WHEN 12. lv_weight = 3.
        WHEN 13. lv_weight = 2.
      ENDCASE.
      lv_sum = lv_sum + lv_cnpj+lv_offset(1) * lv_weight.
    ENDDO.
    lv_digit = lv_sum MOD 11.
    IF lv_digit < 2.
      lv_digit = 0.
    ELSE.
      lv_digit = 11 - lv_digit.
    ENDIF.
    IF lv_digit <> lv_cnpj+13(1).
      p_valid = abap_false.
      RETURN.
    ENDIF.
  
    p_valid = abap_true.
  ENDFORM.