apiempresas 1.6.1 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,280 +1,233 @@
1
- # APIEmpresas.es - Node.js SDK
2
-
3
- SDK oficial para interactuar con la API de [APIEmpresas.es](https://apiempresas.es) desde Node.js utilizando TypeScript o JavaScript.
4
-
5
- ## Instalación
6
-
7
- ```bash
8
- npm install apiempresas
9
- ```
10
-
11
- ## Inicialización
12
-
13
- ```typescript
14
- import { ApiEmpresas } from 'apiempresas';
15
-
16
- const api = new ApiEmpresas({
17
- apiKey: 'TU_API_KEY', // Obligatorio
18
- });
19
- ```
20
-
21
- ## Uso Básico
22
-
23
- ### 1. Obtener datos de una empresa
24
-
25
- ```typescript
26
- async function fetchCompany() {
27
- try {
28
- const company = await api.companies.get('A15075062');
29
- console.log(company.name);
30
- } catch (error) {
31
- console.error('Error fetching company:', error.message);
32
- }
33
- }
34
- ```
35
-
36
- ### 2. Historial de Actos del BORME
37
-
38
- ```typescript
39
- async function fetchBorme() {
40
- const bormeData = await api.companies.borme('A15075062');
41
- console.log(bormeData.events);
42
- }
43
- ```
44
-
45
- ### 3. Consulta Múltiple (Batch)
46
-
47
- ```typescript
48
- async function fetchBatch() {
49
- const response = await api.companies.batch({
50
- cifs: ['A15075062', 'A46103834']
51
- });
52
- console.log('Resultados:', response.data);
53
- console.log('Coste:', response.meta.cost);
54
- }
55
- ```
56
-
57
- ### 4. Administradores, búsqueda con varios resultados, Match y Radar
58
-
59
- ```typescript
60
- // Administradores y cargos (Pro/Business)
61
- const conAdmins = await api.companies.get('A15075062', { admin: true });
62
-
63
- // Varias empresas por nombre, con paginación
64
- let pagina = await api.companies.searchMultiple('software', { limit: 20 });
65
- while (pagina.meta.next_cursor) {
66
- pagina = await api.companies.searchMultiple('software', { cursor: pagina.meta.next_cursor });
67
- }
68
-
69
- // Match (Business): el sector del vendedor es obligatorio
70
- const match = await api.companies.match('A15075062', 'software');
71
-
72
- // Radar de empresas nuevas (todos los planes: 10 resultados en Free con nombre y CIF ocultos, 100 en Pro, 1.000 en Business). range: 'hoy' (por defecto) o días atrás ('7', '30')
73
- const nuevas = await api.companies.radar({ province: 'Madrid', range: '7' });
74
- // Filtros añadidos en 1.2.0: cnae, min_score, main_act_type, has_phone
75
- const software = await api.companies.radar({ cnae: '62', min_score: 70, has_phone: true });
76
- ```
77
-
78
- Requiere Node.js 18 o superior (usa `fetch` nativo).
79
-
80
- ### 5. Verificación KYB (Pro) — 2 consultas
81
-
82
- ```typescript
83
- const v = await api.companies.verify('A46103834', {
84
- name: 'Mercadona SA', // se compara con la razón social
85
- person: 'Juan Roig Alfonso', // ¿es administrador vigente?
86
- vat: true, // NIF-IVA en VIES
87
- iban: 'ES9121000418450200051332' // (1.5.0) ¿está bien formado? No dice de quién es la cuenta
88
- });
89
- console.log(v.decision_hint); // 'pass' | 'review' | 'fail'
90
- console.log(v.flags); // alertas con code, severity y message
91
- ```
92
-
93
- Cada empresa trae además `status_code` (ACTIVE, INSOLVENCY, EXTINCT...), `status_source`, `status_date` y, en Pro/Business, `financials` (tramo de tamaño y último año de cuentas). Los administradores traen `since`. Desde la 1.3.0 la respuesta lleva también `identifiers` (código LEI) y `legal_form` (forma jurídica con su código ISO 20275) en todos los planes, y en Pro/Business `group` (matriz directa y última según GLEIF) y `ownership` (socio único según el BORME). En `verify`, con `person`, `checks.person.is_sole_shareholder` dice si quien firma es el socio único. Desde la 1.5.0, en Pro/Business, `size` (tramo de empleados con su fuente: Kit Digital, TED o PLACSP; null si no consta) y `address_density` (cuántas sociedades activas comparten la dirección exacta), y en `verify` con `iban`, `checks.iban` (si no es válido, alerta `IBAN_INVALID` y `decision_hint` review). `filter()` admite `size_category` (micro, small, medium, large).
94
-
95
- ### Nombre a CIF (Pro)
96
-
97
- ```typescript
98
- const { data, meta } = await api.companies.reconcile(['Mercadona', { name: 'Talleres Pérez', province: 'Madrid' }]);
99
- // data[i].status: match (con company.cif) | ambiguous (candidates) | no_match. Solo se cobran los match.
100
- ```
101
-
102
- ### Validar el NIF de tus clientes antes de facturar (Pro, Business o saldo; desde 1.6.0)
103
-
104
- ```typescript
105
- const { data, meta } = await api.companies.verifyBatch([
106
- { cif: 'A46103834', name: 'Mercadona', ref: 'cliente-0001' }, // name: la razón social que tienes guardada
107
- { cif: 'A15075062', name: 'Inditex', ref: 'cliente-0002' }, // ref: tu identificador, vuelve tal cual
108
- 'B12345674', // o el NIF suelto
109
- ]);
110
- data.forEach((fila) => console.log(fila.input, fila.invoice_hint)); // 'ok' | 'revisar' | 'no_facturar'
111
- // await api.companies.verifyBatch(['A46103834'], { vat: true }); // también VIES
112
- ```
113
-
114
- Por cada NIF, en el mismo orden: `valid_format`, `exists`, `legal_name`, `address`, `status_code`, `name_check` (si das `name`) e `invoice_hint` (`ok`, `revisar` o `no_facturar`) con sus motivos en `flags`. `meta` trae `requested`, `found`, `cost`, `truncated` y `summary`. Hasta 1.000 NIF por llamada; con `vat` (lotes de hasta 20) comprueba también el NIF-IVA en VIES. Cobra 1 consulta por sociedad encontrada: los NIF inválidos, de personas o que no constan no se cobran; si no te llega el saldo, las filas que no caben vuelven con `processed: false`. No sustituye la comprobación contra el censo de la AEAT.
115
- Los tipos `VerifyBatchItem`, `VerifyBatchRow` y `VerifyBatchMeta` se exportan desde el paquete.
116
-
117
- ### Segmentos de empresas
118
-
119
- ```typescript
120
- const total = await api.companies.count({ cnae: ['62'], province: 'MADRID', has_phone: true }); // gratis
121
- const { data, meta } = await api.companies.filter({ cnae: ['62'], province: 'MADRID', limit: 100 }); // Business: 5 consultas por fila
122
- // Siguiente página: api.companies.filter({ ...mismosFiltros, cursor: meta.next_cursor })
123
- ```
124
-
125
- ### 6. Vigilancia de empresas (Pro: 100, Business: 1.000) — sin coste
126
-
127
- ```typescript
128
- await api.watchlist.add(['A46103834', 'A28015865']);
129
- const { data: vigiladas, meta } = await api.watchlist.list(); // meta.watch_limit
130
- const { data: cambios } = await api.watchlist.events({ since: '2026-09-01', types: ['borme_act', 'status_change'] });
131
- await api.watchlist.remove('A28015865');
132
- ```
133
-
134
- ### 7. Webhooks (Business)
135
-
136
- ```typescript
137
- const hook = await api.webhooks.create({ url: 'https://tu-servidor.com/apiempresas', event: 'watchlist.*' });
138
-
139
- // (1.5.0) Sociedades nuevas del BORME del día, con filtros opcionales
140
- const nuevas = await api.webhooks.create({
141
- url: 'https://tu-servidor.com/nuevas',
142
- event: 'company.created',
143
- filters: { province: ['MADRID', 'BARCELONA'], keywords: ['software', 'informática'], min_capital: 3000 }
144
- });
145
- // Guarda hook.secret: con él se comprueba la firma.
146
- await api.webhooks.test(hook.id); // envía un test.ping y devuelve lo que respondió tu servidor
147
-
148
- // Historial de entregas (lo más reciente primero): estado, intentos, código HTTP y error
149
- const { data, meta } = await api.webhooks.deliveries(hook.id, { status: 'dead', limit: 20 });
150
- ```
151
-
152
- En tu servidor, comprueba la firma con el cuerpo **en bruto** (no el JSON ya parseado):
153
-
154
- ```typescript
155
- import express from 'express';
156
- import { constructWebhookEvent } from 'apiempresas';
157
-
158
- app.post('/apiempresas', express.raw({ type: 'application/json' }), (req, res) => {
159
- try {
160
- const evento = constructWebhookEvent(req.body, req.header('X-ApiEmpresas-Signature'), process.env.APIEMPRESAS_WEBHOOK_SECRET!);
161
- // evento.event: company.created | company.borme_act | company.status_changed | company.risk_level_changed | test.ping
162
- // Usa evento.id (o la cabecera X-ApiEmpresas-Delivery) para no procesar dos veces el mismo envío.
163
- res.sendStatus(200);
164
- } catch {
165
- res.sendStatus(400);
166
- }
167
- });
168
- ```
169
-
170
- Si tu servidor no responde 2xx, se reintenta a los 1 min, 5 min, 30 min, 2 h y 6 h.
171
-
172
- ### 8. Licitaciones públicas abiertas (Business) — 1 consulta
173
-
174
- ```typescript
175
- // Concursos en plazo: Plataforma de Contratación del Sector Público y plataformas autonómicas
176
- const { tenders, pagination } = await api.tenders.list({ q: 'limpieza', province: 'Madrid', type: 'services' });
177
- console.log(pagination.total, tenders[0].title, tenders[0].deadline, tenders[0].url);
178
-
179
- // Las parecidas a los contratos que una empresa ya ha ganado (ordenadas por match_score)
180
- const forCompany = await api.tenders.forCompany('A82018474');
181
- ```
182
-
183
- ### 9. Listas de sanciones (Business) — 1 consulta
184
-
185
- ```typescript
186
- // Una empresa y sus administradores vigentes, en las listas de la UE, la ONU y OFAC
187
- const r = await api.sanctions.screen({ cif: 'A46103834' });
188
- console.log(r.summary.result); // 'clear' | 'possible_match' | 'match'
189
-
190
- // Un nombre suelto
191
- const p = await api.sanctions.screen({ name: 'Vladimir Putin', type: 'person' });
192
- // Cada coincidencia trae level (strong | possible), list, programs, countries y birth_dates para confirmarla
193
- ```
194
-
195
- En `companies.verify()` con Business, el resultado incluye `checks.sanctions`.
196
-
197
- ### 10. Subvenciones y ayudas públicas (Business, desde 1.5.0) — 1 consulta
198
-
199
- ```typescript
200
- // Concesiones de la BDNS desde 2022 (Kit Digital incluido)
201
- const s = await api.companies.subsidies('B12345678', { year: 2025, limit: 50 });
202
- console.log(s.summary.total_grants, s.summary.total_amount); // importes en texto con dos decimales
203
- console.log(s.summary.by_year, s.summary.top_calls);
204
- for (const g of s.grants) console.log(g.grant_date, g.amount, g.call);
205
- ```
206
-
207
- ### 11. Feed de cambios (Business, desde 1.5.0) — 1 consulta por página
208
-
209
- ```typescript
210
- // Todas las sociedades con un acto en el BORME desde una fecha (hasta 30 días atrás)
211
- const { data, meta } = await api.companies.changes({ since: '2026-10-19', types: ['address', 'officers'], province: 'MADRID' });
212
- // Siguiente página: api.companies.changes({ ...mismosFiltros, cursor: meta.next_cursor })
213
-
214
- // O recorre todas las páginas
215
- for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) {
216
- console.log(c.id, c.cif, c.change_types, c.status_code); // usa c.id para no procesar dos veces el mismo cambio
217
- }
218
- ```
219
-
220
- Solo salen sociedades con CIF: las recién constituidas todavía no lo tienen y llegan por el webhook `company.created`. Los tipos de cambio están en `catalog().change_types`.
221
-
222
- ### 12. Estadísticas del BORME (todos los planes, desde 1.5.0) — 1 consulta
223
-
224
- ```typescript
225
- const st = await api.stats({ metrics: ['incorporations', 'dissolutions'], province: 'MADRID', from: '2025-01', to: '2025-12' });
226
- console.log(st.totals.incorporations);
227
- for (const fila of st.series) console.log(fila.period, fila.incorporations);
228
- // Por años: api.stats({ group: 'year', from: '2015', to: '2025' })
229
- ```
230
-
231
- ## Entorno de Pruebas (Sandbox)
232
-
233
- Para probar la integración sin consumir saldo, apunta a la URL del Sandbox con tu misma API Key. Devuelve datos simulados: `A15075062` (empresa encontrada) y `B00000000` (no encontrada). Tiene también `subsidies()` y `changes()`; `stats()` y `usage()` no.
234
-
235
- ```typescript
236
- const api = new ApiEmpresas({
237
- apiKey: 'TU_API_KEY',
238
- baseURL: 'https://apiempresas.es/api/sandbox/v1'
239
- });
240
- ```
241
-
242
- ## Consumo
243
-
244
- ```typescript
245
- const u = await api.usage(); // no gasta consultas; no está en el Sandbox
246
- console.log(u.stats.remaining_calls, u.stats.wallet_balance, u.stats.quota_resets_at);
247
- ```
248
-
249
- ## Valores de los filtros
250
-
251
- ```typescript
252
- const cat = await api.catalog(); // no gasta consultas; también en el Sandbox
253
- console.log(cat.province, cat.size_band, cat.radar.priority, cat.webhook_events, cat.change_types);
254
- ```
255
-
256
- ## Manejo de Errores
257
-
258
- El SDK arrojará un `ApiError` detallado si ocurre algún problema (ej. Plan Insuficiente, CIF inválido).
259
-
260
- ```typescript
261
- import { ApiError } from 'apiempresas';
262
-
263
- try {
264
- await api.companies.score('B00000000');
265
- } catch (error) {
266
- if (error instanceof ApiError) {
267
- console.error(`Status: ${error.status}`);
268
- console.error(`Message: ${error.message}`);
269
- console.error(`Code: ${error.code}`); // p. ej. QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID
270
- console.error(`Request: ${error.requestId}`); // dáselo a soporte
271
- console.error(`Retry after: ${error.retryAfter}`); // segundos, en los 429 por velocidad
272
- console.error(`Plan: ${error.requiredPlan} ${error.checkoutUrl}`); // en los 403 de plan
273
- }
274
- }
275
- ```
276
-
277
- Un `429` con `code: 'TOO_MANY_REQUESTS'` se resuelve esperando y reintentando; con `code: 'QUOTA_EXCEEDED'` no: hay que recargar saldo o cambiar de plan. `errorCode` sigue devolviendo el campo `error` de la respuesta, como en versiones anteriores.
278
-
279
- ## Licencia
280
- MIT
1
+ # Spanish company data API – Node.js & TypeScript SDK
2
+
3
+ Official Node.js and TypeScript SDK for [SpainCompanyAPI](https://spaincompanyapi.com) (APIEmpresas.es): Spanish company data by tax ID (CIF/NIF). Use it to verify Spanish companies (KYB), validate customer tax IDs before invoicing, and get directors, registry filings (BORME), sanctions screening, public contracts and grants.
4
+
5
+ - **Docs in English:** [spaincompanyapi.com/docs](https://spaincompanyapi.com/docs)
6
+ - **Free API key:** 100 requests, no card required. [Sign up](https://spaincompanyapi.com/register?intent=api&plan=free&source=npm_sdk)
7
+ - **Coverage:** over 4.7 million Spanish companies, updated every working day from the Commercial Registry gazette (BORME) and other public registers.
8
+
9
+ > Versión en español al final de este documento.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install apiempresas
15
+ ```
16
+
17
+ Requires Node.js 18 or later (it uses the native `fetch`).
18
+
19
+ ## Quick start
20
+
21
+ ```typescript
22
+ import { ApiEmpresas } from 'apiempresas';
23
+
24
+ const api = new ApiEmpresas({
25
+ apiKey: process.env.APIEMPRESAS_API_KEY!,
26
+ baseURL: 'https://spaincompanyapi.com/api/v1', // optional: same API, error messages in English
27
+ });
28
+
29
+ const company = await api.companies.get('A46103834');
30
+ console.log(company.name, company.status_code); // MERCADONA SA ACTIVE
31
+ ```
32
+
33
+ The default base URL is `https://apiempresas.es/api/v1`. Both hosts serve the same API and the same key; `spaincompanyapi.com` returns error messages in English.
34
+
35
+ ## Verify a Spanish company (KYB) – `/companies/verify`
36
+
37
+ One call checks that the company exists and is operating, that the name you were given matches the legal name, that the signer is a current director, and optionally the EU VAT number (VIES). Pro plan, 2 requests.
38
+
39
+ ```typescript
40
+ const v = await api.companies.verify('A46103834', {
41
+ name: 'Mercadona SA', // compared with the registered legal name
42
+ person: 'Juan Roig Alfonso', // is this person a current director (or sole shareholder)?
43
+ vat: true, // EU VAT number registered in VIES?
44
+ iban: 'ES9121000418450200051332', // well formed? (it does not tell you who owns the account)
45
+ });
46
+
47
+ console.log(v.decision_hint); // 'pass' | 'review' | 'fail'
48
+ console.log(v.flags); // red flags with code, severity and message
49
+ console.log(v.checks); // name, person, vat, iban (and sanctions on Business)
50
+ ```
51
+
52
+ A company whose tax ID has been revoked by the Spanish Tax Agency returns `decision_hint: 'fail'` with the flag `TAX_ID_REVOKED`. Every flag explains its reason, so your code can decide what to block and what to send to manual review.
53
+
54
+ ## Validate customer tax IDs before invoicing – `/companies/verify/batch`
55
+
56
+ Up to 1,000 tax IDs per call. Each row comes back in the same order with an `invoice_hint`. Pro, Business or credits; 1 request per company found (malformed, personal and not-found tax IDs are free).
57
+
58
+ ```typescript
59
+ const { data, meta } = await api.companies.verifyBatch([
60
+ { cif: 'A46103834', name: 'Mercadona', ref: 'customer-0001' }, // name: the legal name you hold
61
+ { cif: 'A15075062', name: 'Inditex', ref: 'customer-0002' }, // ref: your own id, returned as is
62
+ 'B12345674', // or just the tax ID
63
+ ]);
64
+
65
+ for (const row of data) {
66
+ console.log(row.input, row.legal_name, row.invoice_hint, row.flags);
67
+ }
68
+ console.log(meta.requested, meta.found, meta.cost, meta.summary);
69
+
70
+ // Also check the EU VAT number in VIES (batches of up to 20)
71
+ await api.companies.verifyBatch(['A46103834'], { vat: true });
72
+ ```
73
+
74
+ `invoice_hint` values are Spanish strings: `ok`, `revisar` (review) and `no_facturar` (do not invoice). Each row has `valid_format`, `exists`, `legal_name`, `address` (registered office), `status_code`, `name_check` (if you send `name`) and `flags`. If your balance runs out, rows that do not fit come back with `processed: false`. This is not a check against the Tax Agency census. The `VerifyBatchItem`, `VerifyBatchRow` and `VerifyBatchMeta` types are exported.
75
+
76
+ ## Company data
77
+
78
+ ```typescript
79
+ // Directors and positions (Pro/Business)
80
+ const withDirectors = await api.companies.get('A15075062', { admin: true });
81
+
82
+ // Registry events published in the BORME
83
+ const borme = await api.companies.borme('A15075062');
84
+ console.log(borme.events);
85
+
86
+ // Several companies by name, with pagination
87
+ let page = await api.companies.searchMultiple('software', { limit: 20 });
88
+ while (page.meta.next_cursor) {
89
+ page = await api.companies.searchMultiple('software', { cursor: page.meta.next_cursor });
90
+ }
91
+
92
+ // Several tax IDs in one call
93
+ const batch = await api.companies.batch({ cifs: ['A15075062', 'A46103834'] });
94
+ console.log(batch.data, batch.meta.cost);
95
+
96
+ // Name to tax ID (Pro): only matches are charged
97
+ const rec = await api.companies.reconcile(['Mercadona', { name: 'Talleres Pérez', province: 'Madrid' }]);
98
+ // rec.data[i].status: match (with company.cif) | ambiguous (candidates) | no_match
99
+ ```
100
+
101
+ Each company includes `status_code` (ACTIVE, INSOLVENCY, IN_LIQUIDATION, DISSOLVED, MERGED, EXTINCT…), `status_source`, `status_date`, `status_confidence` and `status_confidence_reasons`, `tax_id_revocation` (type `TaxIdRevocation`, null if never published), `identifiers` (LEI) and `legal_form` (with its ISO 20275 code). The API response also carries `nace`, the NACE Rev. 2 code next to the Spanish CNAE. On Pro/Business it also includes `financials` (size band), `group` (parent companies per GLEIF), `ownership` (sole shareholder per the BORME), `size` (headcount band with its source) and `address_density`.
102
+
103
+ ## Segments and new companies
104
+
105
+ ```typescript
106
+ const total = await api.companies.count({ cnae: ['62'], province: 'MADRID', has_phone: true }); // free
107
+ const { data, meta } = await api.companies.filter({ cnae: ['62'], province: 'MADRID', limit: 100 }); // Business: 5 requests per row
108
+ // Next page: api.companies.filter({ ...sameFilters, cursor: meta.next_cursor })
109
+
110
+ // Newly incorporated companies (all plans: 10 results on Free with name and tax ID hidden, 100 on Pro, 1,000 on Business)
111
+ const recent = await api.companies.radar({ province: 'Madrid', range: '7', cnae: '62', min_score: 70 });
112
+
113
+ // Match (Business): the seller's sector is required
114
+ const match = await api.companies.match('A15075062', 'software');
115
+ ```
116
+
117
+ ## Monitoring and webhooks
118
+
119
+ ```typescript
120
+ // Watchlist (Pro: 100 companies, Business: 1,000), free of charge
121
+ await api.watchlist.add(['A46103834', 'A28015865']);
122
+ const { data: changes } = await api.watchlist.events({ since: '2026-09-01', types: ['borme_act', 'status_change'] });
123
+
124
+ // Webhooks (Business)
125
+ const hook = await api.webhooks.create({ url: 'https://your-server.com/apiempresas', event: 'watchlist.*' });
126
+ // New companies from today's BORME, with optional filters
127
+ await api.webhooks.create({ url: 'https://your-server.com/new', event: 'company.created', filters: { province: ['MADRID'], min_capital: 3000 } });
128
+ await api.webhooks.test(hook.id);
129
+ const deliveries = await api.webhooks.deliveries(hook.id, { status: 'dead', limit: 20 });
130
+ ```
131
+
132
+ Verify the signature on your server with the **raw** body:
133
+
134
+ ```typescript
135
+ import express from 'express';
136
+ import { constructWebhookEvent } from 'apiempresas';
137
+
138
+ app.post('/apiempresas', express.raw({ type: 'application/json' }), (req, res) => {
139
+ try {
140
+ const event = constructWebhookEvent(req.body, req.header('X-ApiEmpresas-Signature'), process.env.APIEMPRESAS_WEBHOOK_SECRET!);
141
+ // event.event: company.created | company.borme_act | company.status_changed | company.risk_level_changed | test.ping
142
+ // Use event.id (or the X-ApiEmpresas-Delivery header) to avoid processing the same delivery twice.
143
+ res.sendStatus(200);
144
+ } catch {
145
+ res.sendStatus(400);
146
+ }
147
+ });
148
+ ```
149
+
150
+ Failed deliveries are retried after 1 min, 5 min, 30 min, 2 h and 6 h.
151
+
152
+ ## Sanctions, tenders, grants, changes feed and statistics
153
+
154
+ ```typescript
155
+ // Sanctions lists (EU, UN, OFAC) for a company and its current directors (Business)
156
+ const s = await api.sanctions.screen({ cif: 'A46103834' });
157
+ console.log(s.summary.result); // 'clear' | 'possible_match' | 'match'
158
+
159
+ // Open public tenders (Business)
160
+ const { tenders } = await api.tenders.list({ q: 'limpieza', /* tender texts are in Spanish */ province: 'Madrid', type: 'services' });
161
+ const similar = await api.tenders.forCompany('A82018474');
162
+
163
+ // Public grants since 2022 (Business)
164
+ const grants = await api.companies.subsidies('B12345678', { year: 2025 });
165
+
166
+ // Changes feed: every company with a BORME event since a date, up to 30 days back (Business)
167
+ for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) {
168
+ console.log(c.id, c.cif, c.change_types);
169
+ }
170
+
171
+ // BORME statistics (all plans)
172
+ const st = await api.stats({ metrics: ['incorporations', 'dissolutions'], province: 'MADRID', from: '2025-01', to: '2025-12' });
173
+ ```
174
+
175
+ ## Sandbox, usage and filter values
176
+
177
+ ```typescript
178
+ // Sandbox: same key, mock data, no requests used (A15075062 found, B00000000 not found)
179
+ const sandbox = new ApiEmpresas({ apiKey: 'YOUR_API_KEY', baseURL: 'https://spaincompanyapi.com/api/sandbox/v1' });
180
+
181
+ const u = await api.usage(); // free; not available in the sandbox
182
+ const cat = await api.catalog(); // free; valid values for provinces, size bands, webhook events, change types…
183
+ ```
184
+
185
+ ## Errors
186
+
187
+ ```typescript
188
+ import { ApiError } from 'apiempresas';
189
+
190
+ try {
191
+ await api.companies.get('B00000000');
192
+ } catch (error) {
193
+ if (error instanceof ApiError) {
194
+ console.error(error.status, error.code, error.message); // e.g. 429 TOO_MANY_REQUESTS
195
+ console.error(error.requestId); // give it to support
196
+ console.error(error.retryAfter); // seconds, on rate-limit 429s
197
+ console.error(error.requiredPlan, error.checkoutUrl); // on plan 403s
198
+ }
199
+ }
200
+ ```
201
+
202
+ A `429` with `TOO_MANY_REQUESTS` is solved by waiting and retrying; with `QUOTA_EXCEEDED` you need more credits or a higher plan. Errors and companies not found (404) do not use requests.
203
+
204
+ ## Links
205
+
206
+ - Website and pricing: [spaincompanyapi.com](https://spaincompanyapi.com)
207
+ - API documentation: [spaincompanyapi.com/docs](https://spaincompanyapi.com/docs)
208
+ - How to verify a Spanish company: [guide](https://spaincompanyapi.com/how-to-verify-a-spanish-company)
209
+ - Postman collection: [Spain Company API](https://www.postman.com/papelo-amh-3796893/apiempresas/collection/maf0il5/spain-company-api)
210
+ - Support: soporte@apiempresas.es
211
+
212
+ ## License
213
+
214
+ MIT
215
+
216
+ ---
217
+
218
+ ## En español
219
+
220
+ SDK oficial de [APIEmpresas.es](https://apiempresas.es) para Node.js y TypeScript: datos de empresas españolas por CIF, verificación KYB (`companies.verify`), validación del NIF de clientes antes de facturar (`companies.verifyBatch`, hasta 1.000 por llamada), administradores, BORME, listas de sanciones, licitaciones, subvenciones, vigilancia y webhooks. Los nombres de los métodos y los campos son los mismos que en los ejemplos de arriba.
221
+
222
+ ```bash
223
+ npm install apiempresas
224
+ ```
225
+
226
+ ```typescript
227
+ import { ApiEmpresas } from 'apiempresas';
228
+ const api = new ApiEmpresas({ apiKey: 'TU_API_KEY' }); // por defecto https://apiempresas.es/api/v1
229
+ const v = await api.companies.verify('A46103834', { name: 'Mercadona SA', vat: true });
230
+ console.log(v.decision_hint); // pass | review | fail
231
+ ```
232
+
233
+ Documentación en español: [apiempresas.es/documentation](https://apiempresas.es/documentation). Plan gratis de 100 consultas sin tarjeta en [apiempresas.es](https://apiempresas.es/register?intent=api&plan=free&source=npm_sdk).
@@ -5,8 +5,8 @@ import { Webhooks } from './resources/Webhooks';
5
5
  import { Tenders } from './resources/Tenders';
6
6
  import { Sanctions } from './resources/Sanctions';
7
7
  import { verifyWebhookSignature, constructWebhookEvent } from './webhooks/signature';
8
- /** Versión del SDK, enviada en el User-Agent. */
9
- export declare const SDK_VERSION = "1.6.1";
8
+ /** SDK version, sent in the User-Agent. */
9
+ export declare const SDK_VERSION = "1.8.1";
10
10
  export declare class ApiEmpresas {
11
11
  private apiKey;
12
12
  private baseURL;
@@ -8,8 +8,8 @@ const Webhooks_1 = require("./resources/Webhooks");
8
8
  const Tenders_1 = require("./resources/Tenders");
9
9
  const Sanctions_1 = require("./resources/Sanctions");
10
10
  const signature_1 = require("./webhooks/signature");
11
- /** Versión del SDK, enviada en el User-Agent. */
12
- exports.SDK_VERSION = '1.6.1';
11
+ /** SDK version, sent in the User-Agent. */
12
+ exports.SDK_VERSION = '1.8.1';
13
13
  /**
14
14
  * Mensaje legible del cuerpo de error. Según el error, la API lo pone en
15
15
  * message, detail, error (texto) o messages (errores de validación).
package/dist/types.d.ts CHANGED
@@ -46,6 +46,16 @@ export interface Company {
46
46
  status_source?: string | null;
47
47
  /** Fecha del hecho que fija el estado (YYYY-MM-DD). */
48
48
  status_date?: string | null;
49
+ /** Todos los planes (desde 1.7.0): cuánto fiarse de status_code. null si UNKNOWN. No cambia el estado. */
50
+ status_confidence?: StatusConfidence | null;
51
+ /** Motivos de status_confidence (RECENT_REGISTRY_ACT, OLD_INSOLVENCY, ACTIVITY_AFTER_STATUS...). */
52
+ status_confidence_reasons?: StatusConfidenceReason[];
53
+ /**
54
+ * Todos los planes (desde 1.8.0): revocación o rehabilitación del NIF por la Agencia Tributaria publicada
55
+ * en el BOE. null si el BOE nunca ha publicado nada de ese NIF. Con status REVOKED el NIF no vale ante
56
+ * Hacienda y los bancos no pueden hacerle cobros ni pagos.
57
+ */
58
+ tax_id_revocation?: TaxIdRevocation | null;
49
59
  /** Pro/Business: tramo de tamaño y año de las últimas cuentas vistas. */
50
60
  financials?: CompanyFinancials | null;
51
61
  /** Todos los planes (desde 1.3.0): código LEI de GLEIF. */
@@ -77,6 +87,22 @@ export interface Company {
77
87
  };
78
88
  }
79
89
  export type StatusCode = 'ACTIVE' | 'PRESUMED_ACTIVE' | 'INSOLVENCY' | 'IN_LIQUIDATION' | 'DISSOLVED' | 'REGISTRY_CLOSED' | 'MERGED' | 'INACTIVE' | 'EXTINCT' | 'UNKNOWN';
90
+ /** (desde 1.7.0) */
91
+ export type StatusConfidence = 'high' | 'medium' | 'low';
92
+ /** (desde 1.7.0) Motivos de status_confidence. Pueden aparecer otros nuevos: trátalo como string. */
93
+ export type StatusConfidenceReason = 'RECENT_REGISTRY_ACT' | 'NO_RECENT_REGISTRY_ACT' | 'DATED_REGISTRY_EVENT' | 'NO_STATUS_DATE' | 'OLD_INSOLVENCY' | 'ACTIVITY_AFTER_STATUS' | 'REVERSIBLE_STATUS' | 'PRESUMED_STATUS' | 'NOT_FROM_COMMERCIAL_REGISTRY' | (string & {});
94
+ /** (desde 1.8.0) NIF revocado o rehabilitado por la Agencia Tributaria (BOE). */
95
+ export interface TaxIdRevocation {
96
+ /** REVOKED: revocado. REHABILITATED: revocado y después rehabilitado. */
97
+ status: 'REVOKED' | 'REHABILITATED';
98
+ /** Fecha del BOE (YYYY-MM-DD). */
99
+ date: string | null;
100
+ /** Identificador del anuncio, p. ej. BOE-A-2026-12345. */
101
+ boe_id: string | null;
102
+ /** Enlace al anuncio en boe.es. */
103
+ boe_url: string | null;
104
+ source: 'boe';
105
+ }
80
106
  export interface CompanyIdentifiers {
81
107
  lei: string | null;
82
108
  /** Estado del LEI en GLEIF: ISSUED, LAPSED, RETIRED... */
@@ -180,6 +206,11 @@ export interface VerifyResult {
180
206
  status_code: StatusCode | null;
181
207
  status_source: string | null;
182
208
  status_date: string | null;
209
+ /** (desde 1.7.0) Igual que en Company. Informativo: no cambia decision_hint. */
210
+ status_confidence?: StatusConfidence | null;
211
+ status_confidence_reasons?: StatusConfidenceReason[];
212
+ /** (desde 1.8.0) Igual que en Company. Con REVOKED: alerta TAX_ID_REVOKED (critical) y decision_hint fail. */
213
+ tax_id_revocation?: TaxIdRevocation | null;
183
214
  identifiers?: CompanyIdentifiers;
184
215
  legal_form?: CompanyLegalForm;
185
216
  group?: CompanyGroup | null;
@@ -826,7 +857,8 @@ export interface VerifyBatchOptions {
826
857
  export type InvoiceHint = 'ok' | 'revisar' | 'no_facturar';
827
858
  export interface VerifyBatchFlag {
828
859
  /** EXTINCT, MERGED, INSOLVENCY, DISSOLVED, IN_LIQUIDATION, REGISTRY_CLOSED, INACTIVE, STATUS_UNKNOWN,
829
- * NAME_MISMATCH, VAT_NOT_IN_VIES, PERSON_NIF, FAKE_CIF, NOT_FOUND, INVALID_FORMAT, NOT_PROCESSED_QUOTA. */
860
+ * NAME_MISMATCH, VAT_NOT_IN_VIES, PERSON_NIF, FAKE_CIF, NOT_FOUND, INVALID_FORMAT, NOT_PROCESSED_QUOTA,
861
+ * TAX_ID_REVOKED (desde 1.8.0). */
830
862
  code: string;
831
863
  severity: 'info' | 'low' | 'medium' | 'high';
832
864
  message: string;
@@ -853,6 +885,11 @@ export interface VerifyBatchRow {
853
885
  /** ACTIVE, INSOLVENCY, DISSOLVED, IN_LIQUIDATION, EXTINCT, MERGED, REGISTRY_CLOSED, INACTIVE, UNKNOWN... */
854
886
  status_code?: string;
855
887
  status_date?: string | null;
888
+ /** (desde 1.7.0) Igual que en Company. Informativo: no cambia invoice_hint. */
889
+ status_confidence?: StatusConfidence | null;
890
+ status_confidence_reasons?: StatusConfidenceReason[];
891
+ /** (desde 1.8.0) Igual que en Company. Con REVOKED: alerta TAX_ID_REVOKED e invoice_hint no_facturar. */
892
+ tax_id_revocation?: TaxIdRevocation | null;
856
893
  /** Solo si enviaste name: parecido 0-100 y si coincide (desde 80). */
857
894
  name_check?: {
858
895
  provided: string;
package/package.json CHANGED
@@ -1,36 +1,56 @@
1
- {
2
- "name": "apiempresas",
3
- "version": "1.6.1",
4
- "description": "SDK oficial de APIEmpresas.es para Node.js y TypeScript",
5
- "main": "dist/index.js",
6
- "files": [
7
- "dist",
8
- "README.md"
9
- ],
10
- "engines": {
11
- "node": ">=18"
12
- },
13
- "types": "dist/index.d.ts",
14
- "scripts": {
15
- "build": "tsc",
16
- "test": "jest",
17
- "prepublishOnly": "npm run build"
18
- },
19
- "keywords": [
20
- "apiempresas",
21
- "empresas",
22
- "cif",
23
- "borme",
24
- "registro mercantil",
25
- "españa"
26
- ],
27
- "author": "APIEmpresas",
28
- "license": "MIT",
29
- "devDependencies": {
30
- "@types/jest": "^29.5.12",
31
- "@types/node": "^20.11.19",
32
- "jest": "^29.7.0",
33
- "ts-jest": "^29.1.2",
34
- "typescript": "^5.3.3"
35
- }
36
- }
1
+ {
2
+ "name": "apiempresas",
3
+ "version": "1.8.1",
4
+ "description": "Official Node.js and TypeScript SDK for SpainCompanyAPI (APIEmpresas.es): Spanish company data by tax ID (CIF/NIF), KYB verification, bulk tax ID validation before invoicing, directors, BORME filings and sanctions screening.",
5
+ "main": "dist/index.js",
6
+ "files": [
7
+ "dist",
8
+ "README.md"
9
+ ],
10
+ "engines": {
11
+ "node": ">=18"
12
+ },
13
+ "types": "dist/index.d.ts",
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "test": "jest",
17
+ "prepublishOnly": "npm run build"
18
+ },
19
+ "keywords": [
20
+ "spain",
21
+ "spanish companies",
22
+ "spanish company data",
23
+ "company data api",
24
+ "kyb",
25
+ "know your business",
26
+ "company verification",
27
+ "business verification",
28
+ "tax id validation",
29
+ "cif",
30
+ "nif",
31
+ "vat",
32
+ "vies",
33
+ "e-invoicing",
34
+ "borme",
35
+ "commercial registry",
36
+ "directors",
37
+ "sanctions screening",
38
+ "apiempresas",
39
+ "spaincompanyapi",
40
+ "empresas",
41
+ "registro mercantil"
42
+ ],
43
+ "homepage": "https://spaincompanyapi.com/docs",
44
+ "bugs": {
45
+ "email": "soporte@apiempresas.es"
46
+ },
47
+ "author": "APIEmpresas",
48
+ "license": "MIT",
49
+ "devDependencies": {
50
+ "@types/jest": "^29.5.12",
51
+ "@types/node": "^20.11.19",
52
+ "jest": "^29.7.0",
53
+ "ts-jest": "^29.1.2",
54
+ "typescript": "^5.3.3"
55
+ }
56
+ }