apiempresas 1.8.0 → 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,157 +1,135 @@
1
- # APIEmpresas.es - Node.js SDK
1
+ # Spanish company data API – Node.js & TypeScript SDK
2
2
 
3
- > **English:** official Node.js/TypeScript SDK for the Spanish company data API (CIF lookup, KYB, directors, BORME filings). English documentation and free API key (100 requests, no card) at [spaincompanyapi.com](https://spaincompanyapi.com/docs).
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
4
 
5
- SDK oficial para interactuar con la API de [APIEmpresas.es](https://apiempresas.es) desde Node.js utilizando TypeScript o JavaScript.
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.
6
8
 
7
- ## Instalación
9
+ > Versión en español al final de este documento.
10
+
11
+ ## Installation
8
12
 
9
13
  ```bash
10
14
  npm install apiempresas
11
15
  ```
12
16
 
13
- ## Inicialización
17
+ Requires Node.js 18 or later (it uses the native `fetch`).
18
+
19
+ ## Quick start
14
20
 
15
21
  ```typescript
16
22
  import { ApiEmpresas } from 'apiempresas';
17
23
 
18
24
  const api = new ApiEmpresas({
19
- apiKey: 'TU_API_KEY', // Obligatorio
25
+ apiKey: process.env.APIEMPRESAS_API_KEY!,
26
+ baseURL: 'https://spaincompanyapi.com/api/v1', // optional: same API, error messages in English
20
27
  });
21
- ```
22
28
 
23
- ## Uso Básico
29
+ const company = await api.companies.get('A46103834');
30
+ console.log(company.name, company.status_code); // MERCADONA SA ACTIVE
31
+ ```
24
32
 
25
- ### 1. Obtener datos de una empresa
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.
26
34
 
27
- ```typescript
28
- async function fetchCompany() {
29
- try {
30
- const company = await api.companies.get('A15075062');
31
- console.log(company.name);
32
- } catch (error) {
33
- console.error('Error fetching company:', error.message);
34
- }
35
- }
36
- ```
35
+ ## Verify a Spanish company (KYB) – `/companies/verify`
37
36
 
38
- ### 2. Historial de Actos del BORME
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.
39
38
 
40
39
  ```typescript
41
- async function fetchBorme() {
42
- const bormeData = await api.companies.borme('A15075062');
43
- console.log(bormeData.events);
44
- }
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)
45
50
  ```
46
51
 
47
- ### 3. Consulta Múltiple (Batch)
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.
48
53
 
49
- ```typescript
50
- async function fetchBatch() {
51
- const response = await api.companies.batch({
52
- cifs: ['A15075062', 'A46103834']
53
- });
54
- console.log('Resultados:', response.data);
55
- console.log('Coste:', response.meta.cost);
56
- }
57
- ```
54
+ ## Validate customer tax IDs before invoicing – `/companies/verify/batch`
58
55
 
59
- ### 4. Administradores, búsqueda con varios resultados, Match y Radar
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).
60
57
 
61
58
  ```typescript
62
- // Administradores y cargos (Pro/Business)
63
- const conAdmins = await api.companies.get('A15075062', { admin: true });
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
64
 
65
- // Varias empresas por nombre, con paginación
66
- let pagina = await api.companies.searchMultiple('software', { limit: 20 });
67
- while (pagina.meta.next_cursor) {
68
- pagina = await api.companies.searchMultiple('software', { cursor: pagina.meta.next_cursor });
65
+ for (const row of data) {
66
+ console.log(row.input, row.legal_name, row.invoice_hint, row.flags);
69
67
  }
68
+ console.log(meta.requested, meta.found, meta.cost, meta.summary);
70
69
 
71
- // Match (Business): el sector del vendedor es obligatorio
72
- const match = await api.companies.match('A15075062', 'software');
73
-
74
- // 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')
75
- const nuevas = await api.companies.radar({ province: 'Madrid', range: '7' });
76
- // Filtros añadidos en 1.2.0: cnae, min_score, main_act_type, has_phone
77
- const software = await api.companies.radar({ cnae: '62', min_score: 70, has_phone: true });
70
+ // Also check the EU VAT number in VIES (batches of up to 20)
71
+ await api.companies.verifyBatch(['A46103834'], { vat: true });
78
72
  ```
79
73
 
80
- Requiere Node.js 18 o superior (usa `fetch` nativo).
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.
81
75
 
82
- ### 5. Verificación KYB (Pro) — 2 consultas
76
+ ## Company data
83
77
 
84
78
  ```typescript
85
- const v = await api.companies.verify('A46103834', {
86
- name: 'Mercadona SA', // se compara con la razón social
87
- person: 'Juan Roig Alfonso', // ¿es administrador vigente?
88
- vat: true, // NIF-IVA en VIES
89
- iban: 'ES9121000418450200051332' // (1.5.0) ¿está bien formado? No dice de quién es la cuenta
90
- });
91
- console.log(v.decision_hint); // 'pass' | 'review' | 'fail'
92
- console.log(v.flags); // alertas con code, severity y message
93
- ```
94
-
95
- 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). Desde la 1.7.0 (tipos), en todos los planes, `status_confidence` (`high`, `medium` o `low`; null si UNKNOWN) y `status_confidence_reasons`: cuánto fiarse de `status_code` y por qué. También en `verify` y en `verifyBatch`; no cambian `decision_hint` ni `invoice_hint`. Desde la 1.8.0 (tipos), en todos los planes, `tax_id_revocation` (tipo `TaxIdRevocation`): si la Agencia Tributaria ha revocado (`REVOKED`) o rehabilitado (`REHABILITATED`) el NIF según el BOE, con fecha y enlace; null si nunca se ha publicado. Un NIF revocado da la alerta `TAX_ID_REVOKED` y `decision_hint: fail` en `verify`, e `invoice_hint: no_facturar` en `verifyBatch`.
79
+ // Directors and positions (Pro/Business)
80
+ const withDirectors = await api.companies.get('A15075062', { admin: true });
96
81
 
97
- ### Nombre a CIF (Pro)
82
+ // Registry events published in the BORME
83
+ const borme = await api.companies.borme('A15075062');
84
+ console.log(borme.events);
98
85
 
99
- ```typescript
100
- const { data, meta } = await api.companies.reconcile(['Mercadona', { name: 'Talleres Pérez', province: 'Madrid' }]);
101
- // data[i].status: match (con company.cif) | ambiguous (candidates) | no_match. Solo se cobran los match.
102
- ```
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
+ }
103
91
 
104
- ### Validar el NIF de tus clientes antes de facturar (Pro, Business o saldo; desde 1.6.0)
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);
105
95
 
106
- ```typescript
107
- const { data, meta } = await api.companies.verifyBatch([
108
- { cif: 'A46103834', name: 'Mercadona', ref: 'cliente-0001' }, // name: la razón social que tienes guardada
109
- { cif: 'A15075062', name: 'Inditex', ref: 'cliente-0002' }, // ref: tu identificador, vuelve tal cual
110
- 'B12345674', // o el NIF suelto
111
- ]);
112
- data.forEach((fila) => console.log(fila.input, fila.invoice_hint)); // 'ok' | 'revisar' | 'no_facturar'
113
- // await api.companies.verifyBatch(['A46103834'], { vat: true }); // también VIES
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
114
99
  ```
115
100
 
116
- 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.
117
- Los tipos `VerifyBatchItem`, `VerifyBatchRow` y `VerifyBatchMeta` se exportan desde el paquete.
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`.
118
102
 
119
- ### Segmentos de empresas
103
+ ## Segments and new companies
120
104
 
121
105
  ```typescript
122
- const total = await api.companies.count({ cnae: ['62'], province: 'MADRID', has_phone: true }); // gratis
123
- const { data, meta } = await api.companies.filter({ cnae: ['62'], province: 'MADRID', limit: 100 }); // Business: 5 consultas por fila
124
- // Siguiente página: api.companies.filter({ ...mismosFiltros, cursor: meta.next_cursor })
125
- ```
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 })
126
109
 
127
- ### 6. Vigilancia de empresas (Pro: 100, Business: 1.000) — sin coste
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 });
128
112
 
129
- ```typescript
130
- await api.watchlist.add(['A46103834', 'A28015865']);
131
- const { data: vigiladas, meta } = await api.watchlist.list(); // meta.watch_limit
132
- const { data: cambios } = await api.watchlist.events({ since: '2026-09-01', types: ['borme_act', 'status_change'] });
133
- await api.watchlist.remove('A28015865');
113
+ // Match (Business): the seller's sector is required
114
+ const match = await api.companies.match('A15075062', 'software');
134
115
  ```
135
116
 
136
- ### 7. Webhooks (Business)
117
+ ## Monitoring and webhooks
137
118
 
138
119
  ```typescript
139
- const hook = await api.webhooks.create({ url: 'https://tu-servidor.com/apiempresas', event: 'watchlist.*' });
140
-
141
- // (1.5.0) Sociedades nuevas del BORME del día, con filtros opcionales
142
- const nuevas = await api.webhooks.create({
143
- url: 'https://tu-servidor.com/nuevas',
144
- event: 'company.created',
145
- filters: { province: ['MADRID', 'BARCELONA'], keywords: ['software', 'informática'], min_capital: 3000 }
146
- });
147
- // Guarda hook.secret: con él se comprueba la firma.
148
- await api.webhooks.test(hook.id); // envía un test.ping y devuelve lo que respondió tu servidor
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'] });
149
123
 
150
- // Historial de entregas (lo más reciente primero): estado, intentos, código HTTP y error
151
- const { data, meta } = await api.webhooks.deliveries(hook.id, { status: 'dead', limit: 20 });
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 });
152
130
  ```
153
131
 
154
- En tu servidor, comprueba la firma con el cuerpo **en bruto** (no el JSON ya parseado):
132
+ Verify the signature on your server with the **raw** body:
155
133
 
156
134
  ```typescript
157
135
  import express from 'express';
@@ -159,9 +137,9 @@ import { constructWebhookEvent } from 'apiempresas';
159
137
 
160
138
  app.post('/apiempresas', express.raw({ type: 'application/json' }), (req, res) => {
161
139
  try {
162
- const evento = constructWebhookEvent(req.body, req.header('X-ApiEmpresas-Signature'), process.env.APIEMPRESAS_WEBHOOK_SECRET!);
163
- // evento.event: company.created | company.borme_act | company.status_changed | company.risk_level_changed | test.ping
164
- // Usa evento.id (o la cabecera X-ApiEmpresas-Delivery) para no procesar dos veces el mismo envío.
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.
165
143
  res.sendStatus(200);
166
144
  } catch {
167
145
  res.sendStatus(400);
@@ -169,114 +147,87 @@ app.post('/apiempresas', express.raw({ type: 'application/json' }), (req, res) =
169
147
  });
170
148
  ```
171
149
 
172
- Si tu servidor no responde 2xx, se reintenta a los 1 min, 5 min, 30 min, 2 h y 6 h.
150
+ Failed deliveries are retried after 1 min, 5 min, 30 min, 2 h and 6 h.
173
151
 
174
- ### 8. Licitaciones públicas abiertas (Business) — 1 consulta
152
+ ## Sanctions, tenders, grants, changes feed and statistics
175
153
 
176
154
  ```typescript
177
- // Concursos en plazo: Plataforma de Contratación del Sector Público y plataformas autonómicas
178
- const { tenders, pagination } = await api.tenders.list({ q: 'limpieza', province: 'Madrid', type: 'services' });
179
- console.log(pagination.total, tenders[0].title, tenders[0].deadline, tenders[0].url);
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'
180
158
 
181
- // Las parecidas a los contratos que una empresa ya ha ganado (ordenadas por match_score)
182
- const forCompany = await api.tenders.forCompany('A82018474');
183
- ```
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');
184
162
 
185
- ### 9. Listas de sanciones (Business) — 1 consulta
163
+ // Public grants since 2022 (Business)
164
+ const grants = await api.companies.subsidies('B12345678', { year: 2025 });
186
165
 
187
- ```typescript
188
- // Una empresa y sus administradores vigentes, en las listas de la UE, la ONU y OFAC
189
- const r = await api.sanctions.screen({ cif: 'A46103834' });
190
- console.log(r.summary.result); // 'clear' | 'possible_match' | 'match'
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
+ }
191
170
 
192
- // Un nombre suelto
193
- const p = await api.sanctions.screen({ name: 'Vladimir Putin', type: 'person' });
194
- // Cada coincidencia trae level (strong | possible), list, programs, countries y birth_dates para confirmarla
171
+ // BORME statistics (all plans)
172
+ const st = await api.stats({ metrics: ['incorporations', 'dissolutions'], province: 'MADRID', from: '2025-01', to: '2025-12' });
195
173
  ```
196
174
 
197
- En `companies.verify()` con Business, el resultado incluye `checks.sanctions`.
198
-
199
- ### 10. Subvenciones y ayudas públicas (Business, desde 1.5.0) — 1 consulta
175
+ ## Sandbox, usage and filter values
200
176
 
201
177
  ```typescript
202
- // Concesiones de la BDNS desde 2022 (Kit Digital incluido)
203
- const s = await api.companies.subsidies('B12345678', { year: 2025, limit: 50 });
204
- console.log(s.summary.total_grants, s.summary.total_amount); // importes en texto con dos decimales
205
- console.log(s.summary.by_year, s.summary.top_calls);
206
- for (const g of s.grants) console.log(g.grant_date, g.amount, g.call);
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…
207
183
  ```
208
184
 
209
- ### 11. Feed de cambios (Business, desde 1.5.0) — 1 consulta por página
185
+ ## Errors
210
186
 
211
187
  ```typescript
212
- // Todas las sociedades con un acto en el BORME desde una fecha (hasta 30 días atrás)
213
- const { data, meta } = await api.companies.changes({ since: '2026-10-19', types: ['address', 'officers'], province: 'MADRID' });
214
- // Siguiente página: api.companies.changes({ ...mismosFiltros, cursor: meta.next_cursor })
188
+ import { ApiError } from 'apiempresas';
215
189
 
216
- // O recorre todas las páginas
217
- for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) {
218
- console.log(c.id, c.cif, c.change_types, c.status_code); // usa c.id para no procesar dos veces el mismo cambio
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
+ }
219
199
  }
220
200
  ```
221
201
 
222
- 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`.
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.
223
203
 
224
- ### 12. Estadísticas del BORME (todos los planes, desde 1.5.0) — 1 consulta
204
+ ## Links
225
205
 
226
- ```typescript
227
- const st = await api.stats({ metrics: ['incorporations', 'dissolutions'], province: 'MADRID', from: '2025-01', to: '2025-12' });
228
- console.log(st.totals.incorporations);
229
- for (const fila of st.series) console.log(fila.period, fila.incorporations);
230
- // Por años: api.stats({ group: 'year', from: '2015', to: '2025' })
231
- ```
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
232
211
 
233
- ## Entorno de Pruebas (Sandbox)
212
+ ## License
234
213
 
235
- 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.
236
-
237
- ```typescript
238
- const api = new ApiEmpresas({
239
- apiKey: 'TU_API_KEY',
240
- baseURL: 'https://apiempresas.es/api/sandbox/v1'
241
- });
242
- ```
214
+ MIT
243
215
 
244
- ## Consumo
216
+ ---
245
217
 
246
- ```typescript
247
- const u = await api.usage(); // no gasta consultas; no está en el Sandbox
248
- console.log(u.stats.remaining_calls, u.stats.wallet_balance, u.stats.quota_resets_at);
249
- ```
218
+ ## En español
250
219
 
251
- ## Valores de los filtros
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.
252
221
 
253
- ```typescript
254
- const cat = await api.catalog(); // no gasta consultas; también en el Sandbox
255
- console.log(cat.province, cat.size_band, cat.radar.priority, cat.webhook_events, cat.change_types);
222
+ ```bash
223
+ npm install apiempresas
256
224
  ```
257
225
 
258
- ## Manejo de Errores
259
-
260
- El SDK arrojará un `ApiError` detallado si ocurre algún problema (ej. Plan Insuficiente, CIF inválido).
261
-
262
226
  ```typescript
263
- import { ApiError } from 'apiempresas';
264
-
265
- try {
266
- await api.companies.score('B00000000');
267
- } catch (error) {
268
- if (error instanceof ApiError) {
269
- console.error(`Status: ${error.status}`);
270
- console.error(`Message: ${error.message}`);
271
- console.error(`Code: ${error.code}`); // p. ej. QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID
272
- console.error(`Request: ${error.requestId}`); // dáselo a soporte
273
- console.error(`Retry after: ${error.retryAfter}`); // segundos, en los 429 por velocidad
274
- console.error(`Plan: ${error.requiredPlan} ${error.checkoutUrl}`); // en los 403 de plan
275
- }
276
- }
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
277
231
  ```
278
232
 
279
- 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.
280
-
281
- ## Licencia
282
- MIT
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/package.json CHANGED
@@ -1,36 +1,56 @@
1
- {
2
- "name": "apiempresas",
3
- "version": "1.8.0",
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
+ }