HALPIITax ID

Validate B2B customer tax IDs in Shopify

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

When a business customer signs up with a tax ID, you can check it before you extend payment terms or remove tax, and keep the verdict on the customer record. This guide shows two ways with what Shopify already offers.

Status. There is no HALPII app for Shopify. This is a guide: two ways to check B2B customers with what Shopify already offers, and what each one requires.

Where the tax ID lives

  • A customer metafield, for example custom.tax_id, filled by your sign-up form or by staff. The country comes from the customer’s default address.
  • Shopify B2B companies: a company location can hold a tax registration ID. Shopify’s B2B features depend on your plan; check Shopify’s documentation for yours.

Option 1: Shopify Flow, no server

  1. In Shopify Flow, start a workflow with the Customer created trigger (or a B2B company trigger, where your plan has one).
  2. Add a condition that the tax ID metafield is not empty.
  3. Add the Send HTTP request action, where your plan includes it: method GET, URL https://taxid.halpii.com/v1/pe/ruc/ followed by the metafield inserted with Flow’s variable picker (other countries: the routes below), and the header X-API-Key with your key.
  4. Add a Run code step that turns the response into verdict, reasons, legalName and pending (the code is in the repository, folder shopify), then a condition on verdict with Add customer tags, for example taxid-review, or taxid-pendiente when a limit was reached or the source did not answer. If your Flow cannot read the response in later steps, use option 2.
CountryEndpoint
Peru (RUC)GET /v1/pe/ruc/{ruc}
Mexico (RFC)GET /v1/mx/rfc/{rfc}
Colombia (NIT)GET /v1/co/nit/{nit}
Costa Rica (cédula)GET /v1/cr/cedula/{cedula}
Every other countryGET /v1/validate?country=XX&id=… (optional &id_type=…)

Anyone who can edit the workflow can read the key in it. Use a key for this purpose only; on the Monthly plan, set a low daily cap with PUT /v1/limits.

Option 2: a webhook and a small handler

Subscribe a handler to the customers/create webhook. It verifies Shopify’s signature, reads the tax ID and country, calls HALPII Tax ID, and writes the verdict back as metafields (halpii.taxid_verdict, halpii.taxid_checked_at) plus a tag when the verdict is not pass, so staff can filter the customer list.

// Webhook de Shopify (customers/create) que valida el número tributario del cliente con HALPII Tax ID
// y guarda el veredicto en el propio cliente. Sintaxis de Cloudflare Worker; en cualquier servidor es igual.
//
// - El número se lee del metacampo del cliente custom.tax_id; el país, de su dirección predeterminada.
// - Escribe los metacampos halpii.taxid_verdict y halpii.taxid_checked_at, y una etiqueta taxid-<veredicto>
//   cuando no es pass, para filtrar la lista de clientes.
// - 503 (la fuente oficial no respondió, no se cobra): responde 503 para que Shopify reintente el webhook.
// - 429 (límite alcanzado): no tiene sentido que Shopify reintente en minutos; etiqueta taxid-pendiente.
//
// Variables (wrangler secret put ...): SHOP (tu-tienda.myshopify.com), SHOPIFY_ADMIN_TOKEN,
// SHOPIFY_WEBHOOK_SECRET, HALPII_TAXID_KEY.
// Licencia MIT · HALPII S.A.C.

const API_VERSION = '2025-10';
const ROUTES = { PE: 'pe/ruc', MX: 'mx/rfc', CO: 'co/nit', CR: 'cr/cedula' };

export function taxidUrl(country, taxId) {
  const cc = String(country).trim().toUpperCase();
  const id = encodeURIComponent(String(taxId).trim());
  return ROUTES[cc] ? `https://taxid.halpii.com/v1/${ROUTES[cc]}/${id}` : `https://taxid.halpii.com/v1/validate?country=${cc}&id=${id}`;
}

export default {
  async fetch(req, env) {
    if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
    const raw = await req.text();
    if (!(await validHmac(raw, req.headers.get('x-shopify-hmac-sha256'), env.SHOPIFY_WEBHOOK_SECRET))) {
      return new Response('Unauthorized', { status: 401 });
    }
    const gid = JSON.parse(raw).admin_graphql_api_id;
    const { data } = await shopify(
      env,
      `query($id: ID!) { customer(id: $id) {
        metafield(namespace: "custom", key: "tax_id") { value }
        defaultAddress { countryCodeV2 } } }`,
      { id: gid },
    );
    const taxId = data?.customer?.metafield?.value;
    const country = data?.customer?.defaultAddress?.countryCodeV2;
    if (!taxId || !country) return new Response('Sin número tributario');

    const res = await fetch(taxidUrl(country, taxId), { headers: { Accept: 'application/json', 'X-API-Key': env.HALPII_TAXID_KEY } });
    if (res.status === 503) return new Response('Fuente sin responder; Shopify reintentará', { status: 503 });
    if (res.status === 429) {
      await tag(env, gid, 'taxid-pendiente');
      return new Response('Límite alcanzado; marcado como pendiente');
    }
    const result = await res.json().catch(() => ({}));
    // 200, o 400 con veredicto fail (número mal formado). Cualquier otro caso: error.
    const verdict = result?.assessment?.verdict ?? 'error';

    await shopify(env, `mutation($m: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $m) { userErrors { message } } }`, {
      m: [
        { ownerId: gid, namespace: 'halpii', key: 'taxid_verdict', type: 'single_line_text_field', value: verdict },
        { ownerId: gid, namespace: 'halpii', key: 'taxid_checked_at', type: 'date_time', value: new Date().toISOString() },
      ],
    });
    if (verdict !== 'pass') await tag(env, gid, `taxid-${verdict}`);
    return new Response('OK');
  },
};

function tag(env, gid, t) {
  return shopify(env, `mutation($id: ID!, $t: [String!]!) { tagsAdd(id: $id, tags: $t) { userErrors { message } } }`, { id: gid, t: [t] });
}

async function shopify(env, query, variables) {
  const res = await fetch(`https://${env.SHOP}/admin/api/${API_VERSION}/graphql.json`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': env.SHOPIFY_ADMIN_TOKEN },
    body: JSON.stringify({ query, variables }),
  });
  return res.json();
}

export async function validHmac(body, given, secret) {
  if (!given || !secret) return false;
  const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(body)));
  const expected = btoa(String.fromCharCode(...mac));
  if (expected.length !== given.length) return false;
  let diff = 0; // comparación en tiempo constante
  for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);
  return diff === 0;
}

When HALPII answers 503 (source not answering, not billed), the handler answers 503 too, and Shopify delivers the webhook again later. When a limit was reached (429) it tags the customer taxid-pendiente instead of making Shopify retry. A no-cost key gives 100 lookups a month.

What each option requires

OptionRequires
Shopify FlowShopify Flow with the Send HTTP request action on your plan; a HALPII Tax ID key
Webhook handler, for your own storeA custom app for your store with the customer read and write scopes, for the Admin API token (no review needed for a single store); the webhook created under Settings → Notifications → Webhooks; a server or Worker to run the handler
Blocking checkoutAn app with a Cart and Checkout Validation Function. Functions cannot call outside services at checkout, so validate at sign-up and let the function read the stored metafield
A public app for other storesA Shopify Partner account and Shopify’s app review. HALPII has not created one

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

Source: folder shopify of the halpii-taxid-integraciones repository. Shopify is a trademark of Shopify Inc. HALPII Tax ID is an independent service run by HALPII S.A.C. and is not affiliated with or endorsed by Shopify or by any tax authority.