> ## Documentation Index
> Fetch the complete documentation index at: https://docs.timbrix.mx/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK de TypeScript

> Instala @timbrix/sdk y timbra tu primer CFDI de prueba en menos de 5 minutos

`@timbrix/sdk` es el cliente oficial de Timbrix para Node.js (18+) y el navegador — tipado completo (sin `any`), sin dependencias además de [`ky`](https://github.com/sindresorhus/ky), y con manejo de errores tipado listo para usar.

<Card title="Paquete en npm" icon="npm" href="https://www.npmjs.com/package/@timbrix/sdk" horizontal>
  `@timbrix/sdk`
</Card>

## Instalación

<CodeGroup>
  ```bash npm theme={null}
  npm install @timbrix/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @timbrix/sdk
  ```

  ```bash yarn theme={null}
  yarn add @timbrix/sdk
  ```
</CodeGroup>

## Quickstart

Sigue el mismo flujo que en [Quickstart](/quickstart) — regístrate en [app.timbrix.mx/register](https://app.timbrix.mx/register), copia tu **API key de sandbox** desde **Configuración → API Keys**, y crea cliente → producto → CFDI en ese orden.

```typescript theme={null}
import { Timbrix } from "@timbrix/sdk"

const client = new Timbrix({ apiKey: "sk_test_..." })

// La organización se resuelve a partir de la key — no necesitas organizationId.
const customer = await client.customers.create({
  legalName: "Cliente de Prueba SA de CV",
  taxId: "DUM901231AB3",
  taxSystem: "601",
  email: "facturas@cliente-prueba.mx",
  defaultInvoiceUse: "G01",
  addressStreet: "Blvd. Atardecer",
  addressExterior: "142",
  addressNeighborhood: "Centro",
  addressCity: "Huatabampo",
  addressMunicipality: "Huatabampo",
  addressZip: "86500",
  addressState: "Sonora",
})

const product = await client.products.create({
  description: "Servicio de prueba",
  productKey: 84111506,
  unitKey: "E48",
  price: 100.0,
})

const invoice = await client.invoices.create({
  type: "I",
  series: "A",
  folioNumber: "1",
  date: new Date().toISOString(),
  paymentForm: "01",
  paymentMethod: "PUE",
  use: "G03",
  customerId: customer.id,
  items: [{ productId: product.id, quantity: 1, amount: 100.0 }],
})

console.log(invoice.uuid) // folio fiscal asignado por el SAT vía el PAC
```

Para pasar a producción, cambia la API key de sandbox por una `sk_live_...` — la URL base, los endpoints y las respuestas son idénticos en ambos entornos.

## Autenticación

<CodeGroup>
  ```typescript API key theme={null}
  import { Timbrix } from "@timbrix/sdk"

  // Integraciones servidor-a-servidor. Se envía como X-API-Key.
  // La organización se resuelve de la key, así que la mayoría de los
  // métodos aceptan organizationId como opcional en vez de requerido.
  const client = new Timbrix({ apiKey: "sk_live_..." })
  ```

  ```typescript Bearer token theme={null}
  import { Timbrix } from "@timbrix/sdk"

  // Actuando como un usuario de Timbrix ya autenticado (p. ej. vía OAuth).
  // Se envía como Authorization: Bearer <token>. organizationId es
  // requerido en los métodos que lo necesitan.
  const client = new Timbrix({ bearerToken: "eyJhbGciOi..." })
  ```
</CodeGroup>

No hay una URL base distinta para sandbox — la misma `https://api.timbrix.mx` recibe ambos tipos de key, y el API decide el entorno según la key usada. Ver [Authentication](/api-reference/introduction#authentication) para el flujo de OAuth 2.0.

## Manejo de errores

Toda petición fallida rechaza con un `TimbrixApiError` — nunca el `HTTPError` genérico de `ky`. Incluye el mensaje del API (los arreglos de validación se unen en un solo string), el código de error de dominio, una sugerencia opcional y el status HTTP:

```typescript theme={null}
import { Timbrix, TimbrixApiError } from "@timbrix/sdk"

const client = new Timbrix({ apiKey: "sk_live_..." })

try {
  await client.organizations.get("no-existe")
} catch (error) {
  if (error instanceof TimbrixApiError) {
    console.error(error.statusCode) // 404
    console.error(error.code) // "NOT_FOUND"
    console.error(error.message) // "Organization not found"
  }
}
```

Los errores de rate limit (`statusCode === 429`) reciben automáticamente un hint `(retry after Ns)` en `message` cuando el API envía un header `Retry-After`.

## Referencia completa

El [README del paquete](https://www.npmjs.com/package/@timbrix/sdk) documenta cada resource (`invoices`, `customers`, `products`, `sat`, `organizations`, `webhooks`, `apiKeys`, `oauth`, `auth`, `users`) con ejemplos. Para el detalle de cada endpoint REST subyacente, ver [API Reference](/api-reference/introduction).
