HALPIITax ID

HALPII Tax ID in Google Sheets

Last reviewed 2026-11-21 · HALPII S.A.C.

One Apps Script, pasted into your spreadsheet, adds three formulas and a small menu. Each formula answers one tax ID per cell, or two ranges of the same size.

Status. Not on the Google Workspace Marketplace. You copy the script on this page into your spreadsheet: that is the whole installation.
FormulaReturns
=HALPII_TAXID(country; id)The verdict: pass, review or fail
=HALPII_TAXID_MOTIVO(country; id)The verdict and its reasons, for example pass: Taxpayer is active with SUNAT.; [solo formato] marks a check that stopped at the format
=HALPII_TAXID_NOMBRE(country; id)The legal name, when the source publishes it

Ranges of up to 50 rows: =HALPII_TAXID(A2:A50; B2:B50). The argument separator is ; or , depending on the spreadsheet’s locale. The script’s messages are in Spanish; the reasons come from the API in English.

Install it

  1. Open your spreadsheet and select Extensions → Apps Script.
  2. Replace the content of Code.gs with the script at the end of this page.
  3. In Project Settings, tick Show "appsscript.json" manifest file in editor; back in the editor, replace appsscript.json with the manifest below. Save.
  4. Reload the spreadsheet. Select HALPII Tax ID → Guardar clave, authorize the script, and paste a no-cost API key (100 lookups a month). Without a key the formulas use a small daily allowance per network.
  5. Type =HALPII_TAXID("PE"; "20615614841") in a cell. It shows pass: that RUC is HALPII S.A.C., the company that runs this service.

Cache, limits and the key

  • Each answer is cached for 6 hours in the document cache, so the three formulas on the same ID make one call. Errors are not cached.
  • A 429 (limit reached) or 503 (source not answering, not billed) with a wait of 5 seconds or less is retried once; a longer wait shows Error: … in the cell with the time the limit resets.
  • The key is kept in the document properties of this spreadsheet and sent as X-API-Key. A copy of the spreadsheet does not carry it, and anyone with edit access can read it in Apps Script: share the sheet as view-only with people who should not use your key. Borrar clave in the menu removes it.
  • Ver consultas usadas shows the usage of the key; that call is not a lookup.

Permissions

ScopeWhy
spreadsheets.currentonlyThis spreadsheet only
script.external_requestCall https://taxid.halpii.com, and only that host
script.container.uiShow the menu, the key prompt and messages

Only the country code and the tax ID leave the spreadsheet, with your key.

The script

Code.gs (260 lines)
/**
 * HALPII Tax ID para Google Sheets.
 *
 * Fórmulas:
 *   =HALPII_TAXID(país; número)          veredicto: pass, review o fail
 *   =HALPII_TAXID_MOTIVO(país; número)   veredicto y motivo, por ejemplo "pass: Taxpayer is active with SUNAT."
 *   =HALPII_TAXID_NOMBRE(país; número)   razón social, cuando la fuente la publica
 * Las tres aceptan una celda o dos rangos del mismo tamaño (=HALPII_TAXID(A2:A50; B2:B50)).
 * En hojas con configuración regional de EE. UU. el separador es la coma: =HALPII_TAXID("PE", B2).
 *
 * La clave se guarda en las Propiedades del documento (menú HALPII Tax ID → Guardar clave).
 * Las respuestas se guardan en caché 6 horas (el máximo de CacheService); un error no se guarda.
 *
 * Licencia MIT · HALPII S.A.C. · contacto@halpii.com
 */

var HALPII_BASE_URL = 'https://taxid.halpii.com';
var HALPII_KEY_PROPERTY = 'HALPII_TAXID_API_KEY';
var HALPII_CACHE_SECONDS = 21600; // 6 h
/** Una fórmula personalizada tiene 30 s para responder: una fórmula con rango atiende como máximo estas filas. */
var HALPII_MAX_ROWS = 50;
/** Un 429 o 503 se reintenta una vez dentro de la fórmula solo si la espera es corta. */
var HALPII_MAX_WAIT_S = 5;
var HALPII_DEDICATED = { PE: 'pe/ruc', MX: 'mx/rfc', CO: 'co/nit', CR: 'cr/cedula' };

// ---------------------------------------------------------------------------- fórmulas

/**
 * Valida un número de identificación tributaria y devuelve el veredicto: pass, review o fail.
 *
 * @param {string|Array<Array<string>>} pais Código de país de dos letras (PE, MX, CO, ES...) o un rango.
 * @param {string|Array<Array<string>>} numero El número (RUC, RFC, NIT, NIF...) o un rango del mismo tamaño.
 * @return pass, review o fail.
 * @customfunction
 */
function HALPII_TAXID(pais, numero) {
  return halpiiMap_(pais, numero, function (r) {
    return r.assessment ? r.assessment.verdict : '';
  });
}

/**
 * Devuelve el veredicto y el motivo (en inglés, tal como lo da la API).
 *
 * @param {string|Array<Array<string>>} pais Código de país de dos letras, o un rango.
 * @param {string|Array<Array<string>>} numero El número, o un rango del mismo tamaño.
 * @return Por ejemplo "pass: Taxpayer is active with SUNAT."
 * @customfunction
 */
function HALPII_TAXID_MOTIVO(pais, numero) {
  return halpiiMap_(pais, numero, function (r) {
    var a = r.assessment || {};
    var reasons = (a.reasons || []).join(' ');
    var level = r.verification_level === 'format' ? ' [solo formato]' : '';
    return (a.verdict || '') + level + (reasons ? ': ' + reasons : '');
  });
}

/**
 * Devuelve la razón social, cuando la fuente la publica.
 *
 * @param {string|Array<Array<string>>} pais Código de país de dos letras, o un rango.
 * @param {string|Array<Array<string>>} numero El número, o un rango del mismo tamaño.
 * @return La razón social, o vacío.
 * @customfunction
 */
function HALPII_TAXID_NOMBRE(pais, numero) {
  return halpiiMap_(pais, numero, function (r) {
    return r.legal_name || '';
  });
}

/** Aplica pick() a una consulta, o a cada fila de dos rangos del mismo tamaño. */
function halpiiMap_(pais, numero, pick) {
  if (!Array.isArray(numero)) return halpiiOne_(pais, numero, pick);
  if (numero.length > HALPII_MAX_ROWS) {
    throw new Error('Máximo ' + HALPII_MAX_ROWS + ' filas por fórmula: divide el rango en partes.');
  }
  return numero.map(function (row, i) {
    return row.map(function (cell, j) {
      var cc = pais;
      if (Array.isArray(pais)) cc = pais[i] && pais[i][j] !== undefined ? pais[i][j] : (pais[i] || [])[0];
      return halpiiOne_(cc, cell, pick);
    });
  });
}

function halpiiEmpty_(v) {
  return v === '' || v === null || v === undefined;
}

function halpiiOne_(pais, numero, pick) {
  if (halpiiEmpty_(pais) || halpiiEmpty_(numero)) return '';
  try {
    return pick(halpiiLookup_(String(pais), String(numero)));
  } catch (e) {
    // Un mensaje legible en la celda, en lugar de cortar toda la columna.
    return 'Error: ' + (e && e.message ? e.message : e);
  }
}

// ---------------------------------------------------------------------------- consulta, caché y errores

/** La ruta de la API para una consulta (Perú, México, Colombia y Costa Rica tienen la suya). */
function halpiiTarget_(pais, numero) {
  var cc = String(pais).trim().toUpperCase();
  var value = String(numero).trim();
  if (!/^[A-Z]{2}$/.test(cc)) throw new Error('El país debe ser un código de dos letras, como PE o ES. Llegó "' + pais + '".');
  if (!value) throw new Error('El número está vacío.');
  if (value.length > 64) throw new Error('El número tiene más de 64 caracteres.');
  if (HALPII_DEDICATED[cc]) return HALPII_BASE_URL + '/v1/' + HALPII_DEDICATED[cc] + '/' + encodeURIComponent(value);
  return HALPII_BASE_URL + '/v1/validate?country=' + cc + '&id=' + encodeURIComponent(value);
}

function halpiiKey_() {
  try {
    return PropertiesService.getDocumentProperties().getProperty(HALPII_KEY_PROPERTY) || '';
  } catch (e) {
    return '';
  }
}

function halpiiCache_() {
  try {
    return CacheService.getDocumentCache() || CacheService.getScriptCache();
  } catch (e) {
    return CacheService.getScriptCache();
  }
}

function halpiiCacheKey_(url, key) {
  // La respuesta puede cambiar con y sin clave (el nombre de una persona natural solo va a quien tiene clave).
  return 'htx1|' + (key ? 'k' : 'n') + '|' + url;
}

function halpiiFetch_(url, key) {
  var headers = { Accept: 'application/json' };
  if (key) headers['X-API-Key'] = key;
  return UrlFetchApp.fetch(url, { method: 'get', headers: headers, muteHttpExceptions: true });
}

function halpiiHeader_(res, name) {
  var h = res.getHeaders ? res.getHeaders() : {};
  for (var k in h) if (k.toLowerCase() === name) return String(h[k]);
  return null;
}

/** Segundos de espera de un 429 o 503: Retry-After, o hasta x-ratelimit-reset. */
function halpiiWaitSeconds_(res) {
  var ra = halpiiHeader_(res, 'retry-after');
  if (ra !== null && !isNaN(Number(ra))) return Number(ra);
  var reset = halpiiHeader_(res, 'x-ratelimit-reset');
  if (reset) {
    var t = Date.parse(reset);
    if (!isNaN(t)) return Math.max(0, Math.ceil((t - Date.now()) / 1000));
  }
  return null;
}

/** Convierte la respuesta en un resultado, o lanza un Error con el mensaje de la API en español. */
function halpiiParse_(res) {
  var code = res.getResponseCode();
  var body = null;
  try {
    body = JSON.parse(res.getContentText());
  } catch (e) {
    body = null;
  }
  if (code >= 200 && code < 300 && body) return body;
  // Un número mal formado vuelve como consulta con format_valid false: veredicto fail.
  if (code === 400 && body && body.format_valid !== undefined) return body;
  var msg = body && body.error ? body.error : 'HTTP ' + code;
  var reset = halpiiHeader_(res, 'x-ratelimit-reset');
  if (code === 401) msg = 'clave no válida. Menú HALPII Tax ID → Guardar clave. (' + msg + ')';
  else if (code === 429) msg = 'se alcanzó el límite de consultas' + (reset ? ' (se renueva ' + reset + ')' : '') + '. Con una clave tienes más consultas: menú HALPII Tax ID → Guardar clave.';
  else if (code === 503) msg = 'la fuente oficial no respondió (no se cobra). Vuelve a calcular más tarde.';
  var err = new Error(msg);
  err.status = code;
  throw err;
}

/** Una consulta, desde la caché cuando se puede. Reintenta una vez un 429/503 con espera corta. */
function halpiiLookup_(pais, numero) {
  var url = halpiiTarget_(pais, numero);
  var key = halpiiKey_();
  var cache = halpiiCache_();
  var ck = halpiiCacheKey_(url, key);
  var hit = cache.get(ck);
  if (hit) return JSON.parse(hit);
  var res = halpiiFetch_(url, key);
  var code = res.getResponseCode();
  if (code === 429 || code === 503) {
    var wait = halpiiWaitSeconds_(res);
    if (wait !== null && wait <= HALPII_MAX_WAIT_S) {
      Utilities.sleep(Math.max(1, wait) * 1000);
      res = halpiiFetch_(url, key);
    }
  }
  var result = halpiiParse_(res);
  try {
    cache.put(ck, JSON.stringify(result), HALPII_CACHE_SECONDS);
  } catch (e) {
    // Más de 100 KB: no se guarda en caché.
  }
  return result;
}

// ---------------------------------------------------------------------------- menú

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('HALPII Tax ID')
    .addItem('Guardar clave', 'halpiiGuardarClave')
    .addItem('Borrar clave', 'halpiiBorrarClave')
    .addItem('Ver consultas usadas', 'halpiiVerUso')
    .addToUi();
}

function halpiiGuardarClave() {
  var ui = SpreadsheetApp.getUi();
  var r = ui.prompt(
    'HALPII Tax ID',
    'Pega tu clave de API. Se guarda en las Propiedades de ESTE documento: cualquier persona con permiso de edición podría verla.',
    ui.ButtonSet.OK_CANCEL
  );
  if (r.getSelectedButton() !== ui.Button.OK) return;
  var key = String(r.getResponseText() || '').trim();
  if (!key) return;
  PropertiesService.getDocumentProperties().setProperty(HALPII_KEY_PROPERTY, key);
  ui.alert('Clave guardada. Las fórmulas la usan desde la próxima vez que se calculen.');
}

function halpiiBorrarClave() {
  PropertiesService.getDocumentProperties().deleteProperty(HALPII_KEY_PROPERTY);
  SpreadsheetApp.getUi().alert('Clave borrada de este documento.');
}

/** GET /v1/usage no es una consulta: no gasta cupo. */
function halpiiVerUso() {
  var ui = SpreadsheetApp.getUi();
  var key = halpiiKey_();
  if (!key) return ui.alert('Primero guarda tu clave (menú HALPII Tax ID → Guardar clave).');
  try {
    var u = halpiiParse_(halpiiFetch_(HALPII_BASE_URL + '/v1/usage', key));
    var lines = [];
    if (u.plan) lines.push('Plan: ' + u.plan);
    if (u.monthly_limit !== undefined) lines.push('Usadas este mes: ' + u.used_this_month + ' de ' + u.monthly_limit + ' (se renueva ' + u.resets_at + ')');
    if (u.daily_limit) lines.push('Tope diario: ' + u.daily_limit);
    if (u.used_today !== undefined) lines.push('Usadas hoy: ' + u.used_today);
    ui.alert(lines.length ? lines.join('\n') : JSON.stringify(u));
  } catch (e) {
    ui.alert('No se pudo leer el uso: ' + e.message);
  }
}

// Para las pruebas en Node (test/code.test.mjs); Apps Script ignora esta línea.
if (typeof module !== 'undefined') {
  module.exports = { HALPII_TAXID: HALPII_TAXID, HALPII_TAXID_MOTIVO: HALPII_TAXID_MOTIVO, HALPII_TAXID_NOMBRE: HALPII_TAXID_NOMBRE, halpiiTarget_: halpiiTarget_ };
}
appsscript.json
{
  "timeZone": "America/Lima",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets.currentonly",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/script.container.ui"
  ],
  "urlFetchWhitelist": ["https://taxid.halpii.com/"]
}

What the verdict means

VerdictMeaning
passRegistered and in good standing per the official source
reviewNeeds a human look: an unusual status, a not-found the source cannot rule out, or a check that stopped at the format. Mexico RFCs never get pass, because Mexico publishes no RFC registry
failMalformed, wrong check digit, not active, or on a tax-authority list

MIT licence. Source: folder google-sheets of the halpii-taxid-integraciones repository. Google Sheets is a trademark of Google LLC. HALPII Tax ID is an independent service run by HALPII S.A.C. and is not affiliated with or endorsed by Google or by any tax authority.