{"openapi":"3.0.3","info":{"title":"Facttura Public API","version":"2.8.0","description":"API pública de Facttura para organizaciones (v2).\n\n**Contrato**: respuestas exitosas usan `{ data, metadata? }`; los errores usan `{ error: { code, message, details? } }` con códigos estables.\n\n**Convenciones**: recursos en inglés, terminología SII (DTE, folio, RUT) como sustantivos propios, todos los campos JSON en camelCase (`rutEmisor`, `tipoDte`, `mntTotal`).\n\n**Emisión asíncrona**: `POST /documents` responde `202` con `status: processing`. Consulta `GET /documents/{id}` o espera el webhook para conocer el resultado.\n\n**Documentos unificados**: `/documents` es una sola colección para todo DTE relevante — los que emites (`direction=issued`) y los que recibes (`direction=received`, libro de compras). Las lecturas son locales sobre la copia sincronizada; la emisión y los comandos de libro ejecutan contra el SII.\n\n**Idempotencia**: el header `Idempotency-Key` es obligatorio en la emisión de documentos y lotes, y opcional en las demás escrituras. Reutilizar una clave con un payload distinto responde `409 IDEMPOTENCY_CONFLICT`.\n\n**Modo Demo para partners**: la misma superficie v2 opera sobre un workspace aislado con datos ficticios. La emisión individual, los lotes y las sincronizaciones se simulan localmente; las credenciales SII se marcan como configuradas sin contactar al SII ni conservar las claves enviadas; BHE, eventos y PDFs externos se sirven desde simulaciones locales. Los lotes reservan cuota por documento y cada documento se procesa mediante el simulador. Aplican cuotas y expiración del workspace, siempre con el envelope de error v2.\n\n**Webhooks firmados**: el secreto se revela una sola vez al crear o rotar el destino. Las entregas usan HMAC-SHA256 sobre `<timestamp>.<raw-body>`. Consulta la sección Webhooks para el contrato completo y ejemplos."},"servers":[{"url":"https://app.facttura.com/api/v2","description":"Producción"}],"tags":[{"name":"Context","description":"Identidad y permisos de la conexión autenticada, sin efectos tributarios."},{"name":"Companies","description":"Empresas emisoras de la organización"},{"name":"Documents","description":"Colección unificada de DTE: emisiones propias (issued/facttura) y documentos del libro SII sincronizado (received y ventas externas). Lecturas locales; comandos por documento contra el SII."},{"name":"Webhooks","description":"Destinos de notificación saliente.\n\n## Secreto de firma\n\nFacttura genera un secreto de 32 bytes al crear el webhook. El secreto aparece **una sola vez** en la respuesta `201` de creación y en la respuesta de `POST /webhooks/{id}/rotate-secret`. No aparece en listados, actualizaciones ni en las entregas del webhook. Guárdalo en un gestor de secretos.\n\n## Validación HMAC\n\nCada entrega incluye `X-Webhook-Event`, `X-Webhook-Id`, `X-Facttura-Timestamp`, `X-Facttura-Signature`, `X-Facttura-Environment` y `X-Facttura-Livemode`. La firma usa HMAC-SHA256 y hexadecimal minúsculo:\n\n```text\nsigned_payload = X-Facttura-Timestamp + \".\" + raw_request_body\nexpected = HMAC_SHA256_HEX(webhook_secret, signed_payload)\nX-Facttura-Signature = \"sha256=\" + expected\n```\n\nValida contra el cuerpo HTTP crudo, usa comparación de tiempo constante, rechaza timestamps antiguos (recomendado: más de 5 minutos) y deduplica reintentos mediante `X-Webhook-Id`.\n\n## Evento de documentos emitidos\n\nEl evento implementado es `document.created`. Se entrega cuando el DTE ya tiene folio y terminó su procesamiento. El estado final aparece como `status: \"completed\"` dentro del payload. No existe un evento `document.completed`. Los cambios posteriores de estado SII, como `accepted` o `rejected`, deben consultarse mediante `GET /documents/{id}`.\n\n## Evento de documentos cancelados\n\n`document.cancelled` se entrega cuando un documento queda en `status: \"cancelled\"` y ya no puede emitirse. Usa el mismo payload que `document.created`, con `X-Webhook-Id` y `id` iguales a `document.cancelled:<id>`, más `cancellation.reason`:\n\n- `annulled`: el documento tenía folio y el SII confirmó su nota de anulación. `siiSubmissionStatus` es `submitted`.\n- `withdrawn`: el documento nunca llegó al SII (folio 0) y fue retirado antes de emitirse. `siiSubmissionStatus` es `not_submitted`; no requiere nota de crédito.\n\nPara recibirlo, incluye `document.cancelled` en `events` del webhook. Los webhooks existentes no lo reciben hasta suscribirse.\n\n### Headers de ejemplo\n\n```http\nContent-Type: application/json\nUser-Agent: Facttura-Webhook/2.0\nX-Webhook-Event: document.created\nX-Webhook-Id: document.created:1842\nX-Facttura-Timestamp: 1788987000\nX-Facttura-Signature: sha256=6a2d3c4e5f...\nX-Facttura-Environment: production\nX-Facttura-Livemode: true\n```\n\n## Vector de prueba verificable\n\nUsa este vector ficticio para probar tu implementación:\n\n```text\nsecret = 8d7f4d7e2a1c9f86b6d4b3a8ef8a4b75f20c84bfe58171c9f2282ab42c36a951\ntimestamp = 1788987000\nraw_body = {\"id\":\"document.created:1842\",\"type\":\"document.created\",\"version\":\"1\",\"status\":\"completed\"}\nexpected_signature = sha256=4f9b39040084902f1856d398c453c733f345eb8bd81e4e953ea9729fc93d5770\n```\n\n### Node.js\n\n```js\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\n\nconst received = request.headers[\"x-facttura-signature\"] ?? \"\";\nconst timestamp = request.headers[\"x-facttura-timestamp\"] ?? \"\";\nconst digest = createHmac(\"sha256\", process.env.FACTTURA_WEBHOOK_SECRET)\n  .update(`${timestamp}.${request.rawBody}`)\n  .digest(\"hex\");\nconst expected = `sha256=${digest}`;\nconst valid = received.length === expected.length &&\n  timingSafeEqual(Buffer.from(received), Buffer.from(expected));\n```\n"},{"name":"BHE received","description":"Informes de Boletas de Honorarios Electrónicas recibidas"}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","description":"Token de API de organización (oat_...)"}},"parameters":{"Page":{"name":"page","in":"query","schema":{"type":"integer","minimum":1,"default":1}},"PerPage":{"name":"perPage","in":"query","schema":{"type":"integer","minimum":1,"maximum":100,"default":50}},"IdempotencyKeyRequired":{"name":"Idempotency-Key","in":"header","required":true,"schema":{"type":"string","minLength":8,"maxLength":255,"pattern":"^[a-zA-Z0-9._-]+$"},"description":"Clave única de la operación. Obligatoria en emisión."},"IdempotencyKeyOptional":{"name":"Idempotency-Key","in":"header","required":false,"schema":{"type":"string","minLength":8,"maxLength":255,"pattern":"^[a-zA-Z0-9._-]+$"},"description":"Clave única de la operación (opcional)."}},"schemas":{"ErrorResponse":{"type":"object","required":["error"],"properties":{"error":{"type":"object","required":["code","message"],"properties":{"code":{"type":"string","enum":["VALIDATION_ERROR","UNAUTHORIZED","INSUFFICIENT_SCOPE","SUBSCRIPTION_REQUIRED","NOT_FOUND","CONFLICT","IDEMPOTENCY_CONFLICT","IDEMPOTENCY_KEY_REQUIRED","QUOTA_EXCEEDED","SII_UNAVAILABLE","SII_CREDENTIALS_REQUIRED","INTERNAL_ERROR","DEMO_WORKSPACE_REQUIRED","DEMO_WORKSPACE_EXPIRED","DEMO_OPERATION_NOT_AVAILABLE","OPERATION_NOT_AVAILABLE_IN_ENVIRONMENT"]},"message":{"type":"string","description":"Mensaje en español para humanos"},"details":{"type":"array","items":{"type":"object","required":["message"],"properties":{"field":{"type":"string"},"message":{"type":"string"}},"additionalProperties":false}}},"additionalProperties":false}},"additionalProperties":false},"PaginationMetadata":{"type":"object","properties":{"total":{"type":"integer"},"perPage":{"type":"integer"},"currentPage":{"type":"integer"},"lastPage":{"type":"integer"},"firstPage":{"type":"integer"},"firstPageUrl":{"type":"string","nullable":true},"lastPageUrl":{"type":"string","nullable":true},"nextPageUrl":{"type":"string","nullable":true},"previousPageUrl":{"type":"string","nullable":true}},"additionalProperties":false,"required":["total","perPage","currentPage","lastPage"]},"ChileanRegion":{"type":"string","description":"Región chilena canónica. Facttura normaliza alias comunes como `Metropolitana`, `RM` y `Región Metropolitana de Santiago` a `Región Metropolitana`.","enum":["Arica y Parinacota","Tarapacá","Antofagasta","Atacama","Coquimbo","Valparaíso","Región Metropolitana","O'Higgins","Maule","Ñuble","Biobío","La Araucanía","Los Ríos","Los Lagos","Aysén","Magallanes"],"example":"Región Metropolitana"},"Company":{"type":"object","required":["id","organizationId","rut","razonSocial","email","address","region","city","actividadesEconomicas","hasOrganizationCredential","createdAt","updatedAt"],"properties":{"id":{"type":"integer","example":87},"organizationId":{"type":"integer","example":12},"rut":{"type":"string","example":"76086428-5"},"razonSocial":{"type":"string","example":"Empresa Sandbox SpA"},"email":{"type":"string","format":"email","example":"facturacion@example.com"},"address":{"type":"string","example":"Av. Ejemplo 123"},"region":{"$ref":"#/components/schemas/ChileanRegion"},"city":{"type":"string","example":"Santiago"},"businessType":{"type":"string","nullable":true,"example":"Servicios de software"},"phone":{"type":"string","nullable":true,"example":"+56912345678"},"logoPath":{"type":"string","nullable":true},"logoUrl":{"type":"string","format":"uri","nullable":true},"siiConnectionStatus":{"type":"string","nullable":true,"example":"connected"},"actividadEconomica":{"type":"string","nullable":true,"example":"620200"},"actividadesEconomicas":{"type":"array","items":{"$ref":"#/components/schemas/CompanyActivity"}},"hasOrganizationCredential":{"type":"boolean","description":"Indica si la clave tributaria de la empresa está configurada.","example":true},"siiCredential":{"$ref":"#/components/schemas/SiiCredentialStatus","nullable":true},"createdAt":{"type":"string","format":"date-time","example":"2026-08-31T14:20:00.000Z"},"updatedAt":{"type":"string","format":"date-time","example":"2026-08-31T14:25:00.000Z"}},"additionalProperties":false},"CreateCompanyRequest":{"type":"object","required":["rutNumber","rutDv","razonSocial","email","address","region","city"],"properties":{"rutNumber":{"type":"string","minLength":7,"maxLength":9},"rutDv":{"type":"string","pattern":"^[0-9Kk]$"},"razonSocial":{"type":"string","maxLength":250},"email":{"type":"string","format":"email"},"address":{"type":"string"},"region":{"$ref":"#/components/schemas/ChileanRegion"},"city":{"type":"string"},"businessType":{"type":"string","maxLength":200},"phone":{"type":"string","maxLength":20},"actividadEconomica":{"type":"string","maxLength":10}}},"UpdateCompanyRequest":{"type":"object","properties":{"rutNumber":{"type":"string"},"rutDv":{"type":"string"},"razonSocial":{"type":"string"},"email":{"type":"string","format":"email"},"address":{"type":"string"},"region":{"$ref":"#/components/schemas/ChileanRegion"},"city":{"type":"string"},"businessType":{"type":"string"},"phone":{"type":"string"},"actividadEconomica":{"type":"string"}}},"DteIdDoc":{"type":"object","required":["tipoDte","folio","fchEmis"],"properties":{"tipoDte":{"type":"integer","enum":[33,34,39,41,43,46,52,56,61,110,111,112],"description":"Código SII del documento. Para Factura Electrónica use 33.","example":33},"folio":{"type":"integer","enum":[0],"description":"Debe enviarse siempre en 0. Facttura asigna el folio durante el procesamiento; en Sandbox será un folio sintético sin validez tributaria.","example":0},"fchEmis":{"type":"string","format":"date","description":"Fecha de emisión en formato AAAA-MM-DD.","example":"2026-09-01"},"indTraslado":{"type":"integer","minimum":1,"maximum":9,"description":"Obligatorio en guías de despacho (52). Tipo de traslado según el SII: 1 operación constituye venta, 2 ventas por efectuar, 3 consignaciones, 4 entrega gratuita, 5 traslados internos, 6 otros traslados no venta, 7 guía de devolución, 8 traslado para exportación, 9 venta para exportación.","example":6},"tipoDespacho":{"type":"integer","enum":[1,2,3],"description":"Opcional en guías de despacho. Se guarda, pero el portal del SII que usa Facttura no lo incluye en el documento emitido.","example":2}},"additionalProperties":true},"DteEmisor":{"type":"object","required":["rutEmisor","rznSoc","giroEmis","acteco","dirOrigen","cmnaOrigen"],"description":"En Sandbox, rutEmisor debe pertenecer a una empresa de la organización asociada al token Sandbox.","properties":{"rutEmisor":{"type":"string","pattern":"^\\d{7,8}-[0-9Kk]$","example":"76086428-5"},"rznSoc":{"type":"string","maxLength":100,"example":"Empresa Sandbox SpA"},"giroEmis":{"type":"string","maxLength":80,"example":"Servicios de software"},"acteco":{"type":"array","minItems":1,"maxItems":4,"items":{"type":"integer","minimum":100000,"maximum":999999},"example":[620200]},"dirOrigen":{"type":"string","maxLength":60,"example":"Av. Ejemplo 123"},"cmnaOrigen":{"type":"string","maxLength":20,"example":"Santiago"}},"additionalProperties":true},"DteReceptor":{"type":"object","required":["rutRecep"],"description":"Para DTE 33 el receptor es obligatorio. En Sandbox puede ser ficticio, pero el RUT debe tener formato y dígito verificador válidos. No se aceptan RUT genéricos o placeholders como 0, 66.666.666-6 o variantes compuestas solo por ceros. El SII exige dirección, comuna y ciudad del receptor en facturas, guías y notas (en exportación, sin comuna). Envíelas siempre: si faltan y Facttura no las tiene registradas para ese RUT, la emisión se rechaza con 422 RECEPTOR_DATA_REQUIRED antes de crear el documento.","properties":{"rutRecep":{"type":"string","pattern":"^\\d{7,8}-[0-9Kk]$","example":"12345678-5"},"rznSocRecep":{"type":"string","maxLength":100,"example":"Cliente ficticio Sandbox"},"giroRecep":{"type":"string","maxLength":40,"example":"Servicios informáticos"},"dirRecep":{"type":"string","maxLength":70,"example":"Av. Cliente 456"},"cmnaRecep":{"type":"string","maxLength":20,"example":"Providencia"},"ciudadRecep":{"type":"string","maxLength":20,"example":"Santiago"}},"additionalProperties":true},"DteTotales":{"type":"object","required":["mntTotal"],"description":"Para DTE 33 también son obligatorios mntNeto, tasaIva e iva. Los montos deben cuadrar con las líneas de detalle.","properties":{"mntNeto":{"type":"number","minimum":0,"example":1000},"tasaIva":{"type":"number","minimum":0,"maximum":100,"example":19},"iva":{"type":"number","minimum":0,"example":190},"mntTotal":{"type":"number","minimum":0,"example":1190}},"additionalProperties":true},"DteDetalleLine":{"type":"object","required":["nroLinDet","nmbItem","montoItem"],"properties":{"nroLinDet":{"type":"integer","minimum":1,"maximum":60,"example":1},"nmbItem":{"type":"string","minLength":1,"maxLength":80,"example":"Servicio mensual"},"qtyItem":{"type":"number","minimum":0,"example":1},"prcItem":{"type":"number","minimum":0,"example":1000},"montoItem":{"type":"number","example":1000}},"additionalProperties":true},"DteEncabezado":{"type":"object","required":["idDoc","emisor","receptor","totales"],"properties":{"idDoc":{"$ref":"#/components/schemas/DteIdDoc"},"emisor":{"$ref":"#/components/schemas/DteEmisor"},"receptor":{"$ref":"#/components/schemas/DteReceptor"},"totales":{"$ref":"#/components/schemas/DteTotales"},"transporte":{"$ref":"#/components/schemas/DteTransporte"}},"additionalProperties":true},"DteTransporte":{"type":"object","description":"Transporte en la estructura del esquema DTE del SII. En facturas y guías, rutTrans, patente y chofer van todos juntos o se omiten; si falta alguno, la emisión se rechaza con 422 VALIDATION_ERROR. El portal del SII que usa Facttura imprime transportista, patente y chofer; dirDest, cmnaDest y ciudadDest se guardan pero el portal no los incluye en el documento emitido.","properties":{"patente":{"type":"string","maxLength":8,"example":"HHKB88"},"rutTrans":{"type":"string","description":"RUT del transportista, con guión y dígito verificador.","example":"78035214-0"},"chofer":{"$ref":"#/components/schemas/DteChofer"},"dirDest":{"type":"string","maxLength":70,"example":"Sotomayor 60"},"cmnaDest":{"type":"string","maxLength":20,"example":"Valparaíso"},"ciudadDest":{"type":"string","maxLength":20,"example":"Valparaíso"}},"additionalProperties":true},"DteChofer":{"type":"object","required":["rutChofer","nombreChofer"],"description":"Chofer que realiza el transporte (Transporte > Chofer en el esquema del SII). rutChofer y nombreChofer no se aceptan directamente dentro de transporte.","properties":{"rutChofer":{"type":"string","description":"RUT del chofer, con guión y dígito verificador.","example":"16251809-7"},"nombreChofer":{"type":"string","minLength":1,"maxLength":30,"example":"Luis Lufi"}},"additionalProperties":false},"DteDocument":{"type":"object","required":["encabezado","detalle"],"description":"DTE en vocabulario SII con claves camelCase. La propiedad pública es dte, no DTE; sus campos usan encabezado.idDoc.tipoDte, emisor.rutEmisor, totales.mntTotal y detalle[].nmbItem. En facturas, guías y facturas de exportación, el SII exige que el documento quepa en una página y Facttura rechaza con 422 VALIDATION_ERROR, antes de crearlo, lo que el SII no aceptaría: más de 10 líneas de detalle; más de 17 líneas impresas (11 en exportación), contando 1 por línea, 1 más cada 4 líneas, 1 por cada 45 caracteres o salto de línea de cada dscItem, y 1 por cada referencia o pago más 1 por su encabezado; líneas sin prcItem o con qtyItem menor a 1; palabras de más de 30 caracteres en dscItem; más de 3 referencias o pagos; y en facturas y guías, datos de transporte incompletos (rutTrans, patente y chofer.rutChofer/chofer.nombreChofer van todos o ninguno).","properties":{"encabezado":{"$ref":"#/components/schemas/DteEncabezado"},"detalle":{"type":"array","minItems":1,"maxItems":60,"items":{"$ref":"#/components/schemas/DteDetalleLine"}},"referencia":{"type":"array","description":"Para DTE 56, use codRef=3 con tpoDocRef 33/34 para corregir montos o codRef=1 con tpoDocRef 61 para anular una Nota de Crédito. codRef=2 no está disponible para Notas de Débito.","maxItems":40,"items":{"type":"object","additionalProperties":true}}},"additionalProperties":true},"CreateDocumentRequest":{"type":"object","required":["dte"],"properties":{"dte":{"$ref":"#/components/schemas/DteDocument"},"sendEmailToEmisor":{"type":"boolean"},"sendEmailToReceptor":{"type":"boolean"},"allowMissingReceptor":{"type":"boolean","description":"No se recomienda para DTE 33 o 34; normalmente estas facturas requieren receptor."}},"example":{"dte":{"encabezado":{"idDoc":{"tipoDte":33,"folio":0,"fchEmis":"2026-09-01"},"emisor":{"rutEmisor":"76086428-5","rznSoc":"Empresa Sandbox SpA","giroEmis":"Servicios de software","acteco":[620200],"dirOrigen":"Av. Ejemplo 123","cmnaOrigen":"Santiago"},"receptor":{"rutRecep":"12345678-5","rznSocRecep":"Cliente ficticio Sandbox","giroRecep":"Servicios informáticos","dirRecep":"Av. Cliente 456","cmnaRecep":"Providencia","ciudadRecep":"Santiago"},"totales":{"mntNeto":1000,"tasaIva":19,"iva":190,"mntTotal":1190}},"detalle":[{"nroLinDet":1,"nmbItem":"Servicio mensual","qtyItem":1,"prcItem":1000,"montoItem":1000}]}}},"DocumentTracking":{"type":"object","required":["id","direction","origin","status","environment","livemode","siiSubmissionStatus"],"properties":{"id":{"type":"string","format":"uuid","description":"UUID del documento; úsalo en GET /documents/{id}"},"jobId":{"type":"string","format":"uuid","nullable":true},"direction":{"type":"string","enum":["issued"],"example":"issued"},"origin":{"type":"string","enum":["facttura"],"example":"facttura"},"status":{"type":"string","enum":["processing","accepted","failed","pending_receptor","cancelled"]},"completeReceptorUrl":{"type":"string","nullable":true},"completeReceptorFormUrl":{"type":"string","nullable":true},"environment":{"type":"string","enum":["production","sandbox"]},"livemode":{"type":"boolean"},"siiSubmissionStatus":{"type":"string","enum":["submitted","not_submitted"]}},"additionalProperties":false},"Webhook":{"type":"object","required":["id","url","name","active","events","companyIds","companies","createdAt","updatedAt"],"description":"Destino de webhook. Las respuestas ordinarias nunca incluyen el secreto de firma.","properties":{"id":{"type":"integer","example":24},"url":{"type":"string","format":"uri","example":"https://partner.example.com/webhooks/facttura"},"name":{"type":"string","nullable":true,"example":"Documentos Sandbox"},"active":{"type":"boolean","example":true},"events":{"type":"array","items":{"type":"string","enum":["document.created","document.cancelled","purchase_document.created"]},"example":["document.created","purchase_document.created"]},"companyIds":{"type":"array","items":{"type":"integer"},"example":[87]},"companies":{"type":"array","items":{"$ref":"#/components/schemas/WebhookCompany"}},"createdAt":{"type":"string","format":"date-time","example":"2026-08-31T15:00:00.000Z"},"updatedAt":{"type":"string","format":"date-time","example":"2026-08-31T15:00:00.000Z"}},"additionalProperties":false},"CreateWebhookRequest":{"type":"object","required":["url"],"properties":{"url":{"type":"string","format":"uri"},"name":{"type":"string"},"active":{"type":"boolean"},"events":{"type":"array","items":{"type":"string","enum":["document.created","document.cancelled","purchase_document.created"]},"example":["document.created"]},"companyIds":{"type":"array","items":{"type":"integer"}}}},"SyncPeriod":{"type":"object","properties":{"company":{"type":"object","properties":{"id":{"type":"integer"},"rut":{"type":"string"},"name":{"type":"string"}},"required":["id","rut","name"],"additionalProperties":false},"period":{"type":"string","example":"2026-08"},"status":{"type":"string","enum":["queued","syncing","completed","failed","not_synced"]},"lastCompletedAt":{"type":"string","format":"date-time","nullable":true},"error":{"type":"string","nullable":true}},"required":["company","period","status","lastCompletedAt","error"],"additionalProperties":false},"UnifiedDocument":{"type":"object","required":["id","direction","origin","status","registry","documentTypeCode","documentTypeName","folio","issuedAt","period","emitter","receiver","amounts","isCancelled"],"description":"Documento unificado: DTE emitido o recibido, con estado de emisión (si es de Facttura) y estado en el registro SII (si el sync lo conoce)","properties":{"id":{"type":"string","format":"uuid"},"direction":{"type":"string","enum":["issued","received"]},"origin":{"type":"string","enum":["facttura","external"],"description":"facttura = emitido vía Facttura; external = emitido fuera y conocido por el registro SII"},"status":{"type":"string","enum":["processing","accepted","failed","pending_receptor","cancelled"],"nullable":true,"description":"Ciclo de emisión; null para documentos externos"},"registry":{"type":"object","nullable":true,"description":"Estado en el libro SII; null si el sync aún no conoce el documento","properties":{"accountingStatus":{"type":"string","enum":["registered","pending","not_included","claimed"],"nullable":true},"siiEventState":{"type":"string","nullable":true},"lastSyncedAt":{"type":"string","format":"date-time","nullable":true}},"additionalProperties":false},"documentTypeCode":{"type":"integer","nullable":true,"example":33},"documentTypeName":{"type":"string","nullable":true},"folio":{"type":"integer","nullable":true},"issuedAt":{"type":"string","nullable":true},"period":{"type":"string","nullable":true,"example":"2026-08"},"emitter":{"type":"object","properties":{"rutNumber":{"type":"string","nullable":true},"rutDv":{"type":"string","nullable":true},"name":{"type":"string","nullable":true}},"additionalProperties":false},"receiver":{"type":"object","nullable":true,"properties":{"rutNumber":{"type":"string"},"rutDv":{"type":"string","nullable":true},"name":{"type":"string","nullable":true}},"additionalProperties":false},"amounts":{"type":"object","properties":{"net":{"type":"number","nullable":true},"exempt":{"type":"number","nullable":true},"vat":{"type":"number","nullable":true},"total":{"type":"number","nullable":true}},"additionalProperties":false},"isCancelled":{"type":"boolean"}},"additionalProperties":false},"UnifiedDocumentDetail":{"allOf":[{"$ref":"#/components/schemas/UnifiedDocument"},{"type":"object","properties":{"document":{"$ref":"#/components/schemas/DteResponseDocument","nullable":true},"error":{"type":"string","nullable":true},"pdfUrl":{"type":"string","nullable":true},"cediblePdfUrl":{"type":"string","nullable":true},"environment":{"type":"string","enum":["production","sandbox"],"nullable":true},"livemode":{"type":"boolean","nullable":true},"siiSubmissionStatus":{"type":"string","enum":["submitted","not_submitted"],"nullable":true}}}]},"SiiCredentialStatus":{"type":"object","required":["id","companyId","hasPassword","hasCertPassword"],"properties":{"id":{"type":"integer","example":41},"organizationId":{"type":"integer","example":12},"companyId":{"type":"integer","example":87},"username":{"type":"string","nullable":true,"example":"12345678-5"},"hasPassword":{"type":"boolean","example":true},"hasCertPassword":{"type":"boolean","example":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"additionalProperties":false},"CompanyActivity":{"type":"object","required":["id","codigo","descripcion"],"properties":{"id":{"type":"integer","example":5},"codigo":{"type":"string","example":"620200"},"descripcion":{"type":"string","example":"ACTIVIDADES DE CONSULTORÍA DE INFORMÁTICA"}},"additionalProperties":false},"WebhookCompany":{"type":"object","required":["id","razonSocial"],"properties":{"id":{"type":"integer","example":87},"razonSocial":{"type":"string","example":"Empresa Sandbox SpA"}},"additionalProperties":false},"DteResponseIdDoc":{"type":"object","required":["tipoDte","folio","fchEmis"],"properties":{"tipoDte":{"type":"integer","example":33},"folio":{"type":"integer","minimum":0,"example":1001},"fchEmis":{"type":"string","format":"date","example":"2026-08-31"}},"additionalProperties":true},"DteResponseEncabezado":{"type":"object","required":["idDoc","emisor","receptor","totales"],"properties":{"idDoc":{"$ref":"#/components/schemas/DteResponseIdDoc"},"emisor":{"$ref":"#/components/schemas/DteEmisor"},"receptor":{"$ref":"#/components/schemas/DteReceptor"},"totales":{"$ref":"#/components/schemas/DteTotales"}},"additionalProperties":true},"DteResponseDocument":{"type":"object","required":["encabezado","detalle"],"properties":{"encabezado":{"$ref":"#/components/schemas/DteResponseEncabezado"},"detalle":{"type":"array","items":{"$ref":"#/components/schemas/DteDetalleLine"}},"referencia":{"type":"array","items":{"type":"object","additionalProperties":true}}},"additionalProperties":true},"BheAnnualAmounts":{"type":"object","required":["emisionesVigentes","emisionesAnuladas","honorarioBruto","retencionTerceros","retencionContribuyente","totalLiquido"],"properties":{"emisionesVigentes":{"type":"integer","example":3},"emisionesAnuladas":{"type":"integer","example":0},"honorarioBruto":{"type":"number","example":450000},"retencionTerceros":{"type":"number","example":65250},"retencionContribuyente":{"type":"number","example":0},"totalLiquido":{"type":"number","example":384750}},"additionalProperties":false},"BheAnnualMonth":{"type":"object","required":["mes","emisionesVigentes","emisionesAnuladas","honorarioBruto","retencionTerceros","retencionContribuyente","totalLiquido"],"properties":{"mes":{"type":"string","example":"Agosto"},"emisionesVigentes":{"type":"integer","example":3},"emisionesAnuladas":{"type":"integer","example":0},"honorarioBruto":{"type":"number","example":450000},"retencionTerceros":{"type":"number","example":65250},"retencionContribuyente":{"type":"number","example":0},"totalLiquido":{"type":"number","example":384750}},"additionalProperties":false},"BheAnnualReport":{"type":"object","required":["nombreContribuyente","rut","dv","anio","esSociedadProfesionales","meses","totales"],"properties":{"nombreContribuyente":{"type":"string","example":"Empresa Sandbox SpA"},"rut":{"type":"string","example":"76086428"},"dv":{"type":"string","example":"5"},"anio":{"type":"string","example":"2026"},"esSociedadProfesionales":{"type":"boolean","example":false},"meses":{"type":"array","items":{"$ref":"#/components/schemas/BheAnnualMonth"}},"totales":{"$ref":"#/components/schemas/BheAnnualAmounts"}},"additionalProperties":false},"BheMonthlyTotals":{"type":"object","required":["honorarioBruto","retencionReceptor","totalLiquido"],"properties":{"honorarioBruto":{"type":"number","example":150000},"retencionReceptor":{"type":"number","example":21750},"totalLiquido":{"type":"number","example":128250}},"additionalProperties":false},"BheMonthlyDocument":{"type":"object","required":["nroBoleta","rutEmisor","dvEmisor","nombreEmisor","fechaBoleta","totalHonorarios","retencionReceptor","honorariosLiquidos","estado","codigoBarras","codComuna"],"properties":{"nroBoleta":{"type":"string","example":"1024"},"rutEmisor":{"type":"string","example":"12345678"},"dvEmisor":{"type":"string","example":"5"},"nombreEmisor":{"type":"string","example":"Profesional Sandbox"},"fechaBoleta":{"type":"string","example":"31/08/2026"},"totalHonorarios":{"type":"number","example":150000},"retencionReceptor":{"type":"number","example":21750},"honorariosLiquidos":{"type":"number","example":128250},"estado":{"type":"string","example":"VIGENTE"},"fechaAnulacion":{"type":"string","example":""},"codigoBarras":{"type":"string","example":"123456789012"},"esSocProfesional":{"type":"string","example":"NO"},"codComuna":{"type":"string","example":"13101"}},"additionalProperties":false},"BheMonthlyReport":{"type":"object","required":["nombreContribuyente","rut","dv","anio","mes","totalBoletas","paginaActual","paginasTotales","totales","boletas"],"properties":{"nombreContribuyente":{"type":"string","example":"Empresa Sandbox SpA"},"rut":{"type":"string","example":"76086428"},"dv":{"type":"string","example":"5"},"anio":{"type":"string","example":"2026"},"mes":{"type":"string","example":"Agosto"},"totalBoletas":{"type":"integer","example":1},"paginaActual":{"type":"integer","example":1},"paginasTotales":{"type":"integer","example":1},"totales":{"$ref":"#/components/schemas/BheMonthlyTotals"},"boletas":{"type":"array","items":{"$ref":"#/components/schemas/BheMonthlyDocument"}}},"additionalProperties":false},"BheDailyTotals":{"type":"object","required":["honorarioBruto","retencionEmisor","retencionReceptor","totalLiquido"],"properties":{"honorarioBruto":{"type":"number","example":150000},"retencionEmisor":{"type":"number","example":0},"retencionReceptor":{"type":"number","example":21750},"totalLiquido":{"type":"number","example":128250}},"additionalProperties":false},"BheDailyDocument":{"type":"object","required":["nroBoleta","usuEmisor","fechaEmision","rutReceptor","dvReceptor","nombreReceptor","fechaBoleta","totalHonorarios","retencionEmisor","retencionReceptor","honorariosLiquidos","estado","codigoBarras","codComuna"],"properties":{"nroBoleta":{"type":"string","example":"1024"},"usuEmisor":{"type":"string","example":"12345678-5"},"fechaEmision":{"type":"string","example":"31/08/2026"},"rutReceptor":{"type":"string","example":"76086428"},"dvReceptor":{"type":"string","example":"5"},"nombreReceptor":{"type":"string","example":"Empresa Sandbox SpA"},"fechaBoleta":{"type":"string","example":"31/08/2026"},"totalHonorarios":{"type":"number","example":150000},"esSocProfesional":{"type":"string","example":"NO"},"emailEnvio":{"type":"string","format":"email","example":"profesional@example.com"},"retencionEmisor":{"type":"number","example":0},"retencionReceptor":{"type":"number","example":21750},"honorariosLiquidos":{"type":"number","example":128250},"estado":{"type":"string","example":"VIGENTE"},"fechaAnulacion":{"type":"string","example":""},"codigoBarras":{"type":"string","example":"123456789012"},"codComuna":{"type":"string","example":"13101"}},"additionalProperties":false},"BheDailyReport":{"type":"object","required":["nombreContribuyente","rut","dv","fecha","anio","mes","dia","totalBoletas","totales","boletas"],"properties":{"nombreContribuyente":{"type":"string","example":"Empresa Sandbox SpA"},"rut":{"type":"string","example":"76086428"},"dv":{"type":"string","example":"5"},"fecha":{"type":"string","example":"31/08/2026"},"anio":{"type":"string","example":"2026"},"mes":{"type":"string","example":"08"},"dia":{"type":"string","example":"31"},"totalBoletas":{"type":"integer","example":1},"totales":{"$ref":"#/components/schemas/BheDailyTotals"},"boletas":{"type":"array","items":{"$ref":"#/components/schemas/BheDailyDocument"}}},"additionalProperties":false},"DocumentBatchItemError":{"type":"object","required":["code","message"],"properties":{"code":{"type":"string","example":"VALIDATION_ERROR"},"message":{"type":"string","example":"El monto total no coincide con el detalle."},"field":{"type":"string","nullable":true,"example":"dte.encabezado.totales.mntTotal"}},"additionalProperties":false},"DocumentBatchItem":{"type":"object","required":["index","status"],"properties":{"index":{"type":"integer","minimum":0,"example":0},"clientReferenceId":{"type":"string","nullable":true,"example":"order-2026-0001"},"status":{"type":"string","enum":["queued","error"],"example":"queued"},"uuid":{"type":"string","format":"uuid","nullable":true,"example":"4b29f128-1085-4ccc-9a48-03a2f0c5f8b2"},"error":{"$ref":"#/components/schemas/DocumentBatchItemError","nullable":true}},"additionalProperties":false},"DocumentBatchMetadata":{"type":"object","required":["summary","simulated"],"properties":{"summary":{"type":"object","required":["total","queued","failed"],"properties":{"total":{"type":"integer","example":2},"queued":{"type":"integer","example":2},"failed":{"type":"integer","example":0}},"additionalProperties":false},"simulated":{"type":"boolean","example":true}},"additionalProperties":false},"SynchronizationResult":{"type":"object","required":["queued","simulated","company","period","operations"],"properties":{"queued":{"type":"boolean","example":false},"simulated":{"type":"boolean","example":true},"company":{"type":"string","example":"76086428-5"},"period":{"type":"string","example":"2026-08"},"operations":{"type":"array","items":{"type":"string","enum":["purchase","sale"]},"example":["purchase","sale"]}},"additionalProperties":false},"DocumentEventResult":{"type":"object","required":["id","event","alreadyRegistered"],"properties":{"id":{"type":"string","format":"uuid","example":"d6e76f80-3cbc-4bb5-8bb3-218afbc46040"},"event":{"type":"string","enum":["ACD","ERM","RCD","RFP","RFT"],"example":"ACD"},"alreadyRegistered":{"type":"boolean","example":false}},"additionalProperties":false},"PurchaseTypeChangeResult":{"type":"object","required":["id","purchaseType"],"properties":{"id":{"type":"string","format":"uuid","example":"d6e76f80-3cbc-4bb5-8bb3-218afbc46040"},"purchaseType":{"type":"integer","minimum":1,"maximum":7,"example":1}},"additionalProperties":false},"CompanyResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Company"}},"additionalProperties":false},"CompanyListResponse":{"type":"object","required":["data","metadata"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Company"}},"metadata":{"$ref":"#/components/schemas/PaginationMetadata"}},"additionalProperties":false},"WebhookResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Webhook"}},"additionalProperties":false},"WebhookListResponse":{"type":"object","required":["data","metadata"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Webhook"}},"metadata":{"$ref":"#/components/schemas/PaginationMetadata"}},"additionalProperties":false},"DocumentTrackingResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/DocumentTracking"}},"additionalProperties":false},"UnifiedDocumentListResponse":{"type":"object","required":["data","metadata"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/UnifiedDocument"}},"metadata":{"$ref":"#/components/schemas/PaginationMetadata"}},"additionalProperties":false},"UnifiedDocumentDetailResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/UnifiedDocumentDetail"}},"additionalProperties":false},"DocumentBatchResponse":{"type":"object","required":["data","metadata"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/DocumentBatchItem"}},"metadata":{"$ref":"#/components/schemas/DocumentBatchMetadata"}},"additionalProperties":false},"DocumentBatch422Response":{"oneOf":[{"$ref":"#/components/schemas/ErrorResponse"},{"$ref":"#/components/schemas/DocumentBatchResponse"}],"description":"Puede ser un error global de validación o un lote procesado con errores por documento."},"SyncPeriodListResponse":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SyncPeriod"}}},"additionalProperties":false},"SynchronizationResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/SynchronizationResult"}},"additionalProperties":false},"DocumentEventResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/DocumentEventResult"}},"additionalProperties":false},"PurchaseTypeChangeResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/PurchaseTypeChangeResult"}},"additionalProperties":false},"BheAnnualResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/BheAnnualReport"}},"additionalProperties":false},"BheMonthlyResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/BheMonthlyReport"}},"additionalProperties":false},"BheDailyResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/BheDailyReport"}},"additionalProperties":false},"WebhookWithSecret":{"type":"object","required":["id","url","name","active","events","companyIds","companies","createdAt","updatedAt","secret"],"description":"Webhook recién creado o con secreto recién rotado. `secret` se revela una sola vez.","properties":{"id":{"type":"integer","example":24},"url":{"type":"string","format":"uri","example":"https://partner.example.com/webhooks/facttura"},"name":{"type":"string","nullable":true,"example":"Documentos Sandbox"},"active":{"type":"boolean","example":true},"events":{"type":"array","items":{"type":"string","enum":["document.created","document.cancelled","purchase_document.created"]},"example":["document.created","purchase_document.created"]},"companyIds":{"type":"array","items":{"type":"integer"},"example":[87]},"companies":{"type":"array","items":{"$ref":"#/components/schemas/WebhookCompany"}},"createdAt":{"type":"string","format":"date-time","example":"2026-08-31T15:00:00.000Z"},"updatedAt":{"type":"string","format":"date-time","example":"2026-08-31T15:00:00.000Z"},"secret":{"type":"string","minLength":64,"maxLength":64,"pattern":"^[a-f0-9]{64}$","description":"Secreto HMAC. Guárdalo ahora: no vuelve a aparecer en respuestas ordinarias.","example":"8d7f4d7e2a1c9f86b6d4b3a8ef8a4b75f20c84bfe58171c9f2282ab42c36a951"}},"additionalProperties":false},"WebhookSecretResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/WebhookWithSecret"}},"additionalProperties":false},"ApiContext":{"type":"object","required":["organizationId","environment","livemode","permissions"],"properties":{"organizationId":{"type":"integer","minimum":1},"environment":{"type":"string","enum":["production","sandbox"]},"livemode":{"type":"boolean"},"permissions":{"type":"object","required":["companiesRead","documentsRead","documentsWrite"],"properties":{"companiesRead":{"type":"boolean"},"documentsRead":{"type":"boolean"},"documentsWrite":{"type":"boolean"}},"additionalProperties":false}},"additionalProperties":false},"ApiContextResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/ApiContext"}},"additionalProperties":false}},"examples":{"Company":{"summary":"Empresa","value":{"data":{"id":87,"organizationId":12,"rut":"76086428-5","razonSocial":"Empresa Sandbox SpA","email":"facturacion@example.com","address":"Av. Ejemplo 123","region":"Región Metropolitana","city":"Santiago","businessType":"Servicios de software","phone":"+56912345678","logoPath":null,"logoUrl":null,"siiConnectionStatus":"connected","actividadEconomica":"620200","actividadesEconomicas":[{"id":5,"codigo":"620200","descripcion":"ACTIVIDADES DE CONSULTORÍA DE INFORMÁTICA"}],"hasOrganizationCredential":true,"siiCredential":{"id":41,"organizationId":12,"companyId":87,"username":"12345678-5","hasPassword":true,"hasCertPassword":true,"createdAt":"2026-08-31T14:20:00.000Z","updatedAt":"2026-08-31T14:25:00.000Z"},"createdAt":"2026-08-31T14:20:00.000Z","updatedAt":"2026-08-31T14:25:00.000Z"}}},"CompanyList":{"summary":"Listado paginado de empresas","value":{"data":[{"id":87,"organizationId":12,"rut":"76086428-5","razonSocial":"Empresa Sandbox SpA","email":"facturacion@example.com","address":"Av. Ejemplo 123","region":"Región Metropolitana","city":"Santiago","businessType":"Servicios de software","phone":"+56912345678","logoPath":null,"logoUrl":null,"siiConnectionStatus":"connected","actividadEconomica":"620200","actividadesEconomicas":[{"id":5,"codigo":"620200","descripcion":"ACTIVIDADES DE CONSULTORÍA DE INFORMÁTICA"}],"hasOrganizationCredential":true,"siiCredential":{"id":41,"organizationId":12,"companyId":87,"username":"12345678-5","hasPassword":true,"hasCertPassword":true,"createdAt":"2026-08-31T14:20:00.000Z","updatedAt":"2026-08-31T14:25:00.000Z"},"createdAt":"2026-08-31T14:20:00.000Z","updatedAt":"2026-08-31T14:25:00.000Z"}],"metadata":{"total":1,"perPage":50,"currentPage":1,"lastPage":1,"firstPage":1,"firstPageUrl":"/api/v2/companies?page=1","lastPageUrl":"/api/v2/companies?page=1","nextPageUrl":null,"previousPageUrl":null}}},"Webhook":{"summary":"Webhook configurado","value":{"data":{"id":24,"url":"https://partner.example.com/webhooks/facttura","name":"Documentos Sandbox","active":true,"events":["document.created","purchase_document.created"],"companyIds":[87],"companies":[{"id":87,"razonSocial":"Empresa Sandbox SpA"}],"createdAt":"2026-08-31T15:00:00.000Z","updatedAt":"2026-08-31T15:00:00.000Z"}}},"WebhookList":{"summary":"Listado paginado de webhooks","value":{"data":[{"id":24,"url":"https://partner.example.com/webhooks/facttura","name":"Documentos Sandbox","active":true,"events":["document.created","purchase_document.created"],"companyIds":[87],"companies":[{"id":87,"razonSocial":"Empresa Sandbox SpA"}],"createdAt":"2026-08-31T15:00:00.000Z","updatedAt":"2026-08-31T15:00:00.000Z"}],"metadata":{"total":1,"perPage":50,"currentPage":1,"lastPage":1,"firstPage":1,"firstPageUrl":"/api/v2/webhooks?page=1","lastPageUrl":"/api/v2/webhooks?page=1","nextPageUrl":null,"previousPageUrl":null}}},"DocumentTracking":{"summary":"Emisión aceptada para procesamiento","value":{"data":{"id":"d6e76f80-3cbc-4bb5-8bb3-218afbc46040","jobId":"34429a75-9331-482a-8df3-6b3a40b1f986","direction":"issued","origin":"facttura","status":"processing","environment":"sandbox","livemode":false,"siiSubmissionStatus":"not_submitted"}}},"DocumentList":{"summary":"Listado paginado de documentos","value":{"data":[{"id":"d6e76f80-3cbc-4bb5-8bb3-218afbc46040","direction":"issued","origin":"facttura","status":"accepted","registry":{"accountingStatus":"registered","siiEventState":null,"lastSyncedAt":"2026-08-31T15:05:00.000Z"},"documentTypeCode":33,"documentTypeName":"Factura Electrónica","folio":1001,"issuedAt":"2026-08-31","period":"2026-08","emitter":{"rutNumber":"76086428","rutDv":"5","name":"Empresa Sandbox SpA"},"receiver":{"rutNumber":"12345678","rutDv":"5","name":"Cliente ficticio Sandbox"},"amounts":{"net":10000,"exempt":0,"vat":1900,"total":11900},"isCancelled":false}],"metadata":{"total":1,"perPage":50,"currentPage":1,"lastPage":1}}},"DocumentDetail":{"summary":"Documento emitido y aceptado","value":{"data":{"id":"d6e76f80-3cbc-4bb5-8bb3-218afbc46040","direction":"issued","origin":"facttura","status":"accepted","registry":{"accountingStatus":"registered","siiEventState":null,"lastSyncedAt":"2026-08-31T15:05:00.000Z"},"documentTypeCode":33,"documentTypeName":"Factura Electrónica","folio":1001,"issuedAt":"2026-08-31","period":"2026-08","emitter":{"rutNumber":"76086428","rutDv":"5","name":"Empresa Sandbox SpA"},"receiver":{"rutNumber":"12345678","rutDv":"5","name":"Cliente ficticio Sandbox"},"amounts":{"net":10000,"exempt":0,"vat":1900,"total":11900},"isCancelled":false,"document":{"encabezado":{"idDoc":{"tipoDte":33,"folio":1001,"fchEmis":"2026-08-31"},"emisor":{"rutEmisor":"76086428-5","rznSoc":"Empresa Sandbox SpA","giroEmis":"Servicios de software","acteco":[620200],"dirOrigen":"Av. Ejemplo 123","cmnaOrigen":"Santiago"},"receptor":{"rutRecep":"12345678-5","rznSocRecep":"Cliente ficticio Sandbox","giroRecep":"Servicios informáticos","dirRecep":"Av. Cliente 456","cmnaRecep":"Providencia","ciudadRecep":"Santiago"},"totales":{"mntNeto":10000,"tasaIva":19,"iva":1900,"mntTotal":11900}},"detalle":[{"nroLinDet":1,"nmbItem":"Impresión de stickers personalizados","qtyItem":100,"prcItem":100,"montoItem":10000}]},"error":null,"pdfUrl":"https://files.example.com/dte-33-1001.pdf","cediblePdfUrl":"https://files.example.com/dte-33-1001-cedible.pdf","environment":"sandbox","livemode":false,"siiSubmissionStatus":"not_submitted"}}},"DocumentBatch":{"summary":"Lote encolado","value":{"data":[{"index":0,"clientReferenceId":"order-2026-0001","status":"queued","uuid":"4b29f128-1085-4ccc-9a48-03a2f0c5f8b2","error":null}],"metadata":{"summary":{"total":1,"queued":1,"failed":0},"simulated":true}}},"DocumentBatchWithErrors":{"summary":"Resultado con error por documento","value":{"data":[{"index":0,"clientReferenceId":"order-2026-0001","status":"error","uuid":null,"error":{"code":"VALIDATION_ERROR","message":"El monto total no coincide con el detalle.","field":"dte.encabezado.totales.mntTotal"}}],"metadata":{"summary":{"total":1,"queued":0,"failed":1},"simulated":true}}},"SyncPeriods":{"summary":"Cobertura de sincronización","value":{"data":[{"company":{"id":87,"rut":"76086428-5","name":"Empresa Sandbox SpA"},"period":"2026-08","status":"completed","lastCompletedAt":"2026-08-31T15:05:00.000Z","error":null}]}},"Synchronization":{"summary":"Sincronización Sandbox completada localmente","value":{"data":{"queued":false,"simulated":true,"company":"76086428-5","period":"2026-08","operations":["purchase","sale"]}}},"DocumentEvent":{"summary":"Evento registrado","value":{"data":{"id":"d6e76f80-3cbc-4bb5-8bb3-218afbc46040","event":"ACD","alreadyRegistered":false}}},"PurchaseTypeChange":{"summary":"Tipo de compra actualizado","value":{"data":{"id":"d6e76f80-3cbc-4bb5-8bb3-218afbc46040","purchaseType":1}}},"BheAnnual":{"summary":"Informe anual BHE recibidas","value":{"data":{"nombreContribuyente":"Empresa Sandbox SpA","rut":"76086428","dv":"5","anio":"2026","esSociedadProfesionales":false,"meses":[{"mes":"Agosto","emisionesVigentes":1,"emisionesAnuladas":0,"honorarioBruto":150000,"retencionTerceros":21750,"retencionContribuyente":0,"totalLiquido":128250}],"totales":{"emisionesVigentes":1,"emisionesAnuladas":0,"honorarioBruto":150000,"retencionTerceros":21750,"retencionContribuyente":0,"totalLiquido":128250}}}},"BheMonthly":{"summary":"Informe mensual BHE recibidas","value":{"data":{"nombreContribuyente":"Empresa Sandbox SpA","rut":"76086428","dv":"5","anio":"2026","mes":"Agosto","totalBoletas":1,"paginaActual":1,"paginasTotales":1,"totales":{"honorarioBruto":150000,"retencionReceptor":21750,"totalLiquido":128250},"boletas":[{"nroBoleta":"1024","rutEmisor":"12345678","dvEmisor":"5","nombreEmisor":"Profesional Sandbox","fechaBoleta":"31/08/2026","totalHonorarios":150000,"retencionReceptor":21750,"honorariosLiquidos":128250,"estado":"VIGENTE","fechaAnulacion":"","codigoBarras":"123456789012","esSocProfesional":"NO","codComuna":"13101"}]}}},"BheDaily":{"summary":"Informe diario BHE recibidas","value":{"data":{"nombreContribuyente":"Empresa Sandbox SpA","rut":"76086428","dv":"5","fecha":"31/08/2026","anio":"2026","mes":"08","dia":"31","totalBoletas":1,"totales":{"honorarioBruto":150000,"retencionEmisor":0,"retencionReceptor":21750,"totalLiquido":128250},"boletas":[{"nroBoleta":"1024","usuEmisor":"12345678-5","fechaEmision":"31/08/2026","rutReceptor":"76086428","dvReceptor":"5","nombreReceptor":"Empresa Sandbox SpA","fechaBoleta":"31/08/2026","totalHonorarios":150000,"esSocProfesional":"NO","emailEnvio":"profesional@example.com","retencionEmisor":0,"retencionReceptor":21750,"honorariosLiquidos":128250,"estado":"VIGENTE","fechaAnulacion":"","codigoBarras":"123456789012","codComuna":"13101"}]}}},"ValidationError":{"summary":"Solicitud inválida","value":{"error":{"code":"VALIDATION_ERROR","message":"La solicitud contiene datos inválidos","details":[{"field":"dte.encabezado.idDoc.folio","message":"Folio must be 0 (system generates the folio)"}]}}},"SiiCredentialsRequired":{"summary":"Faltan credenciales SII","value":{"error":{"code":"SII_CREDENTIALS_REQUIRED","message":"Faltan credenciales SII del representante."}}},"Unauthorized":{"summary":"Token inválido","value":{"error":{"code":"UNAUTHORIZED","message":"Token de API ausente o inválido."}}},"SubscriptionRequired":{"summary":"Suscripción requerida","value":{"error":{"code":"SUBSCRIPTION_REQUIRED","message":"Tu suscripción no permite esta operación."}}},"InsufficientScope":{"summary":"Scope insuficiente","value":{"error":{"code":"INSUFFICIENT_SCOPE","message":"El token no tiene el scope requerido."}}},"DemoWorkspaceRequired":{"summary":"Workspace Demo requerido","value":{"error":{"code":"DEMO_WORKSPACE_REQUIRED","message":"Debes usar un workspace Demo activo."}}},"NotFound":{"summary":"Recurso no encontrado","value":{"error":{"code":"NOT_FOUND","message":"El recurso solicitado no existe en esta organización."}}},"IdempotencyConflict":{"summary":"Clave reutilizada con otro payload","value":{"error":{"code":"IDEMPOTENCY_CONFLICT","message":"La Idempotency-Key ya fue utilizada con una solicitud diferente."}}},"Conflict":{"summary":"Conflicto de estado","value":{"error":{"code":"CONFLICT","message":"La operación entra en conflicto con el estado actual del recurso."}}},"DemoWorkspaceExpired":{"summary":"Workspace Demo expirado","value":{"error":{"code":"DEMO_WORKSPACE_EXPIRED","message":"El workspace Demo expiró."}}},"QuotaExceeded":{"summary":"Cuota excedida","value":{"error":{"code":"QUOTA_EXCEEDED","message":"Se alcanzó la cuota disponible para esta operación."}}},"SiiUnavailable":{"summary":"SII no disponible","value":{"error":{"code":"SII_UNAVAILABLE","message":"El servicio del SII no está disponible temporalmente."}}},"WebhookCreated":{"summary":"Webhook creado; el secreto solo aparece en esta respuesta","value":{"data":{"id":24,"url":"https://partner.example.com/webhooks/facttura","name":"Documentos Sandbox","active":true,"events":["document.created","purchase_document.created"],"companyIds":[87],"companies":[{"id":87,"razonSocial":"Empresa Sandbox SpA"}],"createdAt":"2026-08-31T15:00:00.000Z","updatedAt":"2026-08-31T15:00:00.000Z","secret":"8d7f4d7e2a1c9f86b6d4b3a8ef8a4b75f20c84bfe58171c9f2282ab42c36a951"}}},"DocumentCreatedWebhookDelivery":{"summary":"Entrega de document.created","description":"Ejemplo representativo del contrato real. Las URLs y datos tributarios son ficticios.","value":{"id":"document.created:1842","type":"document.created","version":"1","occurredAt":"2026-09-09T20:45:00.000Z","environment":"production","livemode":true,"siiSubmissionStatus":"submitted","uuid":"916d3554-20f4-47bb-a6a2-e798e074ca19","status":"completed","pdfUrl":"https://files.example.com/document.pdf","cediblePdfUrl":"https://files.example.com/document-cedible.pdf","data":{"Encabezado":{"IdDoc":{"TipoDTE":33,"Folio":152,"FchEmis":"2026-09-09","FmaPago":2},"Emisor":{"RUTEmisor":"76123456-7","RznSoc":"Empresa Emisora SpA","GiroEmis":"Servicios informáticos","Acteco":[620200],"DirOrigen":"Av. Providencia 123","CmnaOrigen":"Providencia"},"Receptor":{"RUTRecep":"76543210-K","RznSocRecep":"Cliente SpA","GiroRecep":"Comercio","DirRecep":"Av. Apoquindo 456","CmnaRecep":"Las Condes"},"Totales":{"MntNeto":100000,"IVA":19000,"TasaIVA":19,"MntTotal":119000}},"Detalle":[{"NroLinDet":1,"NmbItem":"Servicio mensual","QtyItem":1,"UnmdItem":"UN","PrcItem":100000,"MontoItem":100000}]}}},"ApiContext":{"summary":"Conexión de Sandbox con lectura de empresas y documentos","value":{"data":{"organizationId":12,"environment":"sandbox","livemode":false,"permissions":{"companiesRead":true,"documentsRead":true,"documentsWrite":false}}}},"ContextUnavailable":{"summary":"Entorno no verificable","value":{"error":{"code":"INTERNAL_ERROR","message":"No se pudo comprobar el entorno de la organización."}}}},"responses":{"UnauthorizedResponse":{"description":"Token ausente o inválido (UNAUTHORIZED).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"unauthorized":{"$ref":"#/components/examples/Unauthorized"}}}}},"SubscriptionRequiredResponse":{"description":"La suscripción no permite la operación (SUBSCRIPTION_REQUIRED).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"subscriptionRequired":{"$ref":"#/components/examples/SubscriptionRequired"}}}}},"ForbiddenResponse":{"description":"Scope insuficiente o workspace Demo requerido.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"insufficientScope":{"$ref":"#/components/examples/InsufficientScope"},"demoWorkspaceRequired":{"$ref":"#/components/examples/DemoWorkspaceRequired"}}}}},"NotFoundResponse":{"description":"El recurso no existe en la organización autenticada (NOT_FOUND).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"notFound":{"$ref":"#/components/examples/NotFound"}}}}},"ConflictResponse":{"description":"Conflicto de estado o de idempotencia.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"idempotencyConflict":{"$ref":"#/components/examples/IdempotencyConflict"},"conflict":{"$ref":"#/components/examples/Conflict"}}}}},"DemoWorkspaceExpiredResponse":{"description":"El workspace Demo expiró (DEMO_WORKSPACE_EXPIRED).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"demoWorkspaceExpired":{"$ref":"#/components/examples/DemoWorkspaceExpired"}}}}},"ValidationErrorResponse":{"description":"La solicitud no cumple el contrato o faltan credenciales SII.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"validationError":{"$ref":"#/components/examples/ValidationError"},"siiCredentialsRequired":{"$ref":"#/components/examples/SiiCredentialsRequired"}}}}},"QuotaExceededResponse":{"description":"Cuota o rate limit excedido (QUOTA_EXCEEDED).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"quotaExceeded":{"$ref":"#/components/examples/QuotaExceeded"}}}}},"SiiUnavailableResponse":{"description":"El SII no está disponible o rechazó la operación (SII_UNAVAILABLE).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"siiUnavailable":{"$ref":"#/components/examples/SiiUnavailable"}}}}},"ContextUnavailableResponse":{"description":"No se pudo comprobar el contexto autenticado.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"contextUnavailable":{"$ref":"#/components/examples/ContextUnavailable"}}}}}}},"paths":{"/companies":{"get":{"tags":["Companies"],"summary":"Listar empresas","operationId":"listCompanies","security":[{"BearerAuth":[]}],"description":"Requiere scope `companies:read`.","responses":{"200":{"description":"Listado paginado","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompanyListResponse"},"examples":{"companyList":{"$ref":"#/components/examples/CompanyList"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"$ref":"#/components/parameters/Page"},{"$ref":"#/components/parameters/PerPage"}]},"post":{"tags":["Companies"],"summary":"Crear empresa","operationId":"createCompany","security":[{"BearerAuth":[]}],"description":"Requiere scope `companies:write`. Acepta el header `Idempotency-Key` (opcional). `region` debe usar uno de los valores de `ChileanRegion`; alias comunes como `Metropolitana` y `RM` se normalizan. La creación no configura credenciales SII: use los endpoints `/companies/{id}/organization-credential` y `/companies/{id}/representative-credential` después de crear la empresa.","responses":{"201":{"description":"Empresa creada","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompanyResponse"},"examples":{"company":{"$ref":"#/components/examples/Company"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCompanyRequest"}}}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"}]}},"/companies/{id}":{"get":{"tags":["Companies"],"summary":"Obtener empresa","operationId":"getCompany","security":[{"BearerAuth":[]}],"description":"Requiere scope `companies:read`.","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompanyResponse"},"examples":{"company":{"$ref":"#/components/examples/Company"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID de la empresa"}]},"patch":{"tags":["Companies"],"summary":"Actualizar empresa","operationId":"updateCompany","security":[{"BearerAuth":[]}],"description":"Requiere scope `companies:write`. Acepta el header `Idempotency-Key` (opcional).","responses":{"200":{"description":"Empresa actualizada","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompanyResponse"},"examples":{"company":{"$ref":"#/components/examples/Company"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID de la empresa"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCompanyRequest"}}}}},"delete":{"tags":["Companies"],"summary":"Eliminar empresa","operationId":"deleteCompany","security":[{"BearerAuth":[]}],"description":"Requiere scope `companies:write`. Acepta el header `Idempotency-Key` (opcional).","responses":{"204":{"description":"Empresa eliminada"},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID de la empresa"}]}},"/document-batches":{"post":{"tags":["Documents"],"summary":"Emitir lote de documentos (asíncrono)","operationId":"createDocumentBatch","security":[{"BearerAuth":[]}],"description":"Requiere scope `documents:write`. El header `Idempotency-Key` es **obligatorio**. En modo Demo cada documento del lote se procesa mediante el simulador, sin contacto con el SII, y consume una unidad de las cuotas de documentos y contactos.","responses":{"202":{"description":"Lote aceptado; resultados asíncronos por documento (jobs simulados en Demo)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DocumentBatchResponse"},"examples":{"documentBatch":{"$ref":"#/components/examples/DocumentBatch"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"description":"El lote contiene documentos inválidos (VALIDATION_ERROR)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DocumentBatch422Response"},"examples":{"documentErrors":{"$ref":"#/components/examples/DocumentBatchWithErrors"},"validationError":{"$ref":"#/components/examples/ValidationError"}}}}},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["documents"],"properties":{"documents":{"type":"array","items":{"$ref":"#/components/schemas/CreateDocumentRequest"}}}}}}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyRequired"}]}},"/webhooks":{"get":{"tags":["Webhooks"],"summary":"Listar webhooks","operationId":"listWebhooks","security":[{"BearerAuth":[]}],"description":"Requiere scope `webhooks:read`.","responses":{"200":{"description":"Listado paginado","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookListResponse"},"examples":{"webhookList":{"$ref":"#/components/examples/WebhookList"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"$ref":"#/components/parameters/Page"},{"$ref":"#/components/parameters/PerPage"}]},"post":{"tags":["Webhooks"],"summary":"Crear webhook","operationId":"createWebhook","security":[{"BearerAuth":[]}],"description":"Requiere scope `webhooks:write`. Acepta el header `Idempotency-Key` (opcional). Los únicos eventos aceptados son `document.created` y `purchase_document.created`.\n\nCuando crea un destino nuevo (`201`), la respuesta incluye `data.secret` una sola vez. Si la misma URL ya existía (`200`), la respuesta ordinaria no vuelve a revelar el secreto.","responses":{"200":{"description":"Webhook existente actualizado (misma URL)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookResponse"},"examples":{"webhook":{"$ref":"#/components/examples/Webhook"}}}}},"201":{"description":"Webhook creado","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookSecretResponse"},"examples":{"webhookCreated":{"$ref":"#/components/examples/WebhookCreated"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateWebhookRequest"}}}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"}]}},"/webhooks/{id}":{"patch":{"tags":["Webhooks"],"summary":"Actualizar webhook","operationId":"updateWebhook","security":[{"BearerAuth":[]}],"description":"Requiere scope `webhooks:write`. Acepta el header `Idempotency-Key` (opcional). Los únicos eventos aceptados son `document.created` y `purchase_document.created`.","responses":{"200":{"description":"Webhook actualizado","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookResponse"},"examples":{"webhook":{"$ref":"#/components/examples/Webhook"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID del webhook"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateWebhookRequest"}}}}},"delete":{"tags":["Webhooks"],"summary":"Eliminar webhook","operationId":"deleteWebhook","security":[{"BearerAuth":[]}],"description":"Requiere scope `webhooks:write`. Acepta el header `Idempotency-Key` (opcional).","responses":{"204":{"description":"Webhook eliminado"},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID del webhook"}]}},"/bhe-received/reports/annual":{"get":{"tags":["BHE received"],"summary":"Informe anual de BHE recibidas","operationId":"getBheAnnualReport","security":[{"BearerAuth":[]}],"description":"Requiere scope `bhe:read`. Consulta en vivo al SII con las credenciales de la organización.","parameters":[{"name":"company","in":"query","schema":{"type":"string"},"description":"RUT de la empresa, ej. 77644429-4","required":true},{"name":"year","in":"query","schema":{"type":"integer","minimum":2020,"maximum":2030},"required":true}],"responses":{"200":{"description":"Informe anual","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BheAnnualResponse"},"examples":{"bheAnnual":{"$ref":"#/components/examples/BheAnnual"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}}}},"/bhe-received/reports/monthly":{"get":{"tags":["BHE received"],"summary":"Informe mensual de BHE recibidas","operationId":"getBheMonthlyReport","security":[{"BearerAuth":[]}],"description":"Requiere scope `bhe:read`. Consulta en vivo al SII con las credenciales de la organización.","parameters":[{"name":"company","in":"query","schema":{"type":"string"},"description":"RUT de la empresa, ej. 77644429-4","required":true},{"name":"year","in":"query","schema":{"type":"integer","minimum":2020,"maximum":2030},"required":true},{"name":"month","in":"query","schema":{"type":"integer","minimum":1,"maximum":12},"required":true},{"name":"page","in":"query","schema":{"type":"integer","minimum":1,"default":1},"description":"Página del informe (1-based)"}],"responses":{"200":{"description":"Informe mensual (el SII pagina de a 100 boletas)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BheMonthlyResponse"},"examples":{"bheMonthly":{"$ref":"#/components/examples/BheMonthly"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}}}},"/bhe-received/reports/daily":{"get":{"tags":["BHE received"],"summary":"Informe diario de BHE recibidas","operationId":"getBheDailyReport","security":[{"BearerAuth":[]}],"description":"Requiere scope `bhe:read`. Consulta en vivo al SII con las credenciales de la organización.","parameters":[{"name":"company","in":"query","schema":{"type":"string"},"description":"RUT de la empresa, ej. 77644429-4","required":true},{"name":"year","in":"query","schema":{"type":"integer","minimum":2020,"maximum":2030},"required":true},{"name":"month","in":"query","schema":{"type":"integer","minimum":1,"maximum":12},"required":true},{"name":"day","in":"query","schema":{"type":"integer","minimum":1,"maximum":31},"required":true}],"responses":{"200":{"description":"Informe diario","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BheDailyResponse"},"examples":{"bheDaily":{"$ref":"#/components/examples/BheDaily"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}}}},"/bhe-received/documents/pdf":{"get":{"tags":["BHE received"],"summary":"PDF de una boleta recibida","operationId":"getBheDocumentPdf","security":[{"BearerAuth":[]}],"description":"Requiere scope `bhe:read`. Consulta en vivo al SII con las credenciales de la organización.","parameters":[{"name":"company","in":"query","schema":{"type":"string"},"description":"RUT de la empresa, ej. 77644429-4","required":true},{"name":"barcode","in":"query","schema":{"type":"string"},"description":"Código de barras de la boleta (viene en el informe mensual)","required":true},{"name":"communeCode","in":"query","schema":{"type":"string"},"description":"Código de comuna de la boleta (viene en el informe mensual)","required":true}],"responses":{"200":{"description":"PDF","content":{"application/pdf":{"schema":{"type":"string","format":"binary"}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}}}},"/sync-periods":{"get":{"tags":["Documents"],"summary":"Cobertura de sincronización por período","operationId":"listSyncPeriods","security":[{"BearerAuth":[]}],"description":"Requiere scope `sii-documents:read`.","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SyncPeriodListResponse"},"examples":{"syncPeriods":{"$ref":"#/components/examples/SyncPeriods"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"name":"company","in":"query","schema":{"type":"string"}},{"name":"period","in":"query","schema":{"type":"string","example":"2026-08"}}]}},"/synchronizations":{"post":{"tags":["Documents"],"summary":"Solicitar sincronización de un período","operationId":"createSynchronization","security":[{"BearerAuth":[]}],"description":"Requiere scope `sii-documents:write`. Acepta el header `Idempotency-Key` (opcional). En modo Demo se completa inmediatamente sobre los datos ficticios locales, sin encolar trabajo ni contactar al SII.","responses":{"202":{"description":"Sincronización aceptada (encolada en producción; completada localmente en Demo)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SynchronizationResponse"},"examples":{"synchronization":{"$ref":"#/components/examples/Synchronization"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["company","period"],"properties":{"company":{"type":"string","example":"77644429-4"},"period":{"type":"string","example":"2026-08"},"operations":{"type":"array","items":{"type":"string","enum":["purchase","sale"]},"description":"Por defecto ambas"}}}}}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"}]}},"/documents":{"get":{"tags":["Documents"],"summary":"Listar documentos (emitidos y recibidos)","operationId":"listDocuments","security":[{"BearerAuth":[]}],"description":"Requiere scope `documents:read`. Colección unificada: emisiones propias y documentos del libro SII sincronizado, deduplicados.","responses":{"200":{"description":"Listado paginado","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnifiedDocumentListResponse"},"examples":{"documentList":{"$ref":"#/components/examples/DocumentList"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"$ref":"#/components/parameters/Page"},{"$ref":"#/components/parameters/PerPage"},{"name":"direction","in":"query","schema":{"type":"string","enum":["issued","received"]},"description":"issued = ventas propias; received = compras recibidas"},{"name":"origin","in":"query","schema":{"type":"string","enum":["facttura","external"]},"description":"Solo emitidos: vía Facttura o por fuera"},{"name":"status","in":"query","schema":{"type":"string","enum":["processing","accepted","failed","pending_receptor","cancelled"]},"description":"Ciclo de emisión (solo documentos de Facttura)"},{"name":"accountingStatus","in":"query","schema":{"type":"string","enum":["registered","pending","not_included","claimed"]},"description":"Estado contable en el libro SII"},{"name":"period","in":"query","schema":{"type":"string","pattern":"^\\d{4}-(0[1-9]|1[0-2])$","example":"2026-08"}},{"name":"company","in":"query","schema":{"type":"string"},"description":"RUT de la empresa, ej. 77644429-4"},{"name":"documentType","in":"query","schema":{"type":"integer"},"description":"Código de tipo de DTE, ej. 33"},{"name":"folio","in":"query","schema":{"type":"integer"}},{"name":"counterpartRut","in":"query","schema":{"type":"string"},"description":"RUT de la contraparte"},{"name":"includeMissing","in":"query","schema":{"type":"boolean"},"description":"Incluye documentos desaparecidos del libro SII"}]},"post":{"tags":["Documents"],"summary":"Emitir documento (asíncrono)","operationId":"createDocument","security":[{"BearerAuth":[]}],"description":"Requiere scope `documents:write`. El header `Idempotency-Key` es **obligatorio**. API v2 recibe la propiedad `dte` y todos los campos en camelCase; no use `DTE` ni PascalCase. `folio` debe ser 0 para que Facttura lo asigne. En Sandbox, el emisor debe ser una empresa de la organización del token y el receptor puede ser ficticio siempre que tenga un RUT formalmente válido; DTE 33 rechaza RUT genéricos. Si cambia el payload, use una nueva Idempotency-Key: reutilizarla con otro contenido responde 409 antes de validar el documento.","x-codeSamples":[{"lang":"Shell","label":"curl · DTE 33 Sandbox","source":"curl --request POST \\\n  --url 'https://app.facttura.com/api/v2/documents' \\\n  --header 'Authorization: Bearer [TOKEN_SANDBOX]' \\\n  --header 'Content-Type: application/json' \\\n  --header 'Idempotency-Key: ejemplo-sandbox-dte33-0001' \\\n  --data '{\n    \"dte\": {\n      \"encabezado\": {\n        \"idDoc\": {\"tipoDte\": 33, \"folio\": 0, \"fchEmis\": \"2026-09-01\"},\n        \"emisor\": {\n          \"rutEmisor\": \"76086428-5\",\n          \"rznSoc\": \"Empresa Sandbox SpA\",\n          \"giroEmis\": \"Servicios de software\",\n          \"acteco\": [620200],\n          \"dirOrigen\": \"Av. Ejemplo 123\",\n          \"cmnaOrigen\": \"Santiago\"\n        },\n        \"receptor\": {\"rutRecep\": \"12345678-5\", \"rznSocRecep\": \"Cliente ficticio Sandbox\", \"giroRecep\": \"Servicios informáticos\", \"dirRecep\": \"Av. Cliente 456\", \"cmnaRecep\": \"Providencia\", \"ciudadRecep\": \"Santiago\"},\n        \"totales\": {\"mntNeto\": 1000, \"tasaIva\": 19, \"iva\": 190, \"mntTotal\": 1190}\n      },\n      \"detalle\": [\n        {\"nroLinDet\": 1, \"nmbItem\": \"Servicio mensual\", \"qtyItem\": 1, \"prcItem\": 1000, \"montoItem\": 1000}\n      ]\n    }\n  }'"}],"responses":{"202":{"description":"Emisión aceptada y en proceso","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DocumentTrackingResponse"},"examples":{"documentTracking":{"$ref":"#/components/examples/DocumentTracking"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateDocumentRequest"}}}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyRequired"}]}},"/documents/{id}":{"get":{"tags":["Documents"],"summary":"Detalle unificado del documento","operationId":"getDocument","security":[{"BearerAuth":[]}],"description":"Requiere scope `documents:read`. Incluye el ciclo de emisión (si es de Facttura) y el bloque registry con el estado en el libro SII (si el sync lo conoce).","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnifiedDocumentDetailResponse"},"examples":{"documentDetail":{"$ref":"#/components/examples/DocumentDetail"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}},"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"},"description":"UUID del documento"}]}},"/documents/{id}/pdf":{"get":{"tags":["Documents"],"summary":"PDF del documento","operationId":"getDocumentPdf","security":[{"BearerAuth":[]}],"description":"Requiere scope `documents:read`. PDF local para emisiones de Facttura; proxy en vivo al SII para documentos externos. En modo Demo los PDFs se generan localmente con marca de agua y nunca se consultan al SII.","responses":{"200":{"description":"PDF (o redirección al PDF local)","content":{"application/pdf":{"schema":{"type":"string","format":"binary"}}}},"302":{"description":"Redirección al PDF generado por Facttura"},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}},"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"},"description":"UUID del documento"}]}},"/documents/{id}/events":{"post":{"tags":["Documents"],"summary":"Aceptar o reclamar un documento recibido","operationId":"submitDocumentEvent","security":[{"BearerAuth":[]}],"description":"Requiere scope `sii-documents:write`. Solo documentos recibidos (compras). Ejecuta contra el SII en vivo y actualiza la copia local. Acepta el header `Idempotency-Key` (opcional).","responses":{"200":{"description":"Evento registrado en el SII","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DocumentEventResponse"},"examples":{"documentEvent":{"$ref":"#/components/examples/DocumentEvent"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"},"description":"UUID del documento"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["event"],"properties":{"event":{"type":"string","enum":["ACD","ERM","RCD","RFP","RFT"],"description":"ACD=Acepta Contenido, ERM=Acuse de Mercaderías, RCD=Reclamo Contenido, RFP=Reclamo Falta Parcial, RFT=Reclamo Falta Total"}}}}}}}},"/documents/{id}/purchase-type-changes":{"post":{"tags":["Documents"],"summary":"Cambiar el tipo de compra","operationId":"changeDocumentPurchaseType","security":[{"BearerAuth":[]}],"description":"Requiere scope `sii-documents:write`. Solo documentos recibidos (compras). Acepta el header `Idempotency-Key` (opcional).","responses":{"200":{"description":"Tipo de compra actualizado en el SII","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PurchaseTypeChangeResponse"},"examples":{"purchaseTypeChange":{"$ref":"#/components/examples/PurchaseTypeChange"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}},"parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"},"description":"UUID del documento"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["purchaseType"],"properties":{"purchaseType":{"type":"integer","minimum":1,"maximum":7,"description":"1=Del Giro, 2=Supermercados, 3=Bienes Raíces, 4=Activo Fijo, 5=IVA Uso Común, 6=IVA no Recuperable, 7=No Corresp. Incluir"}}}}}}}},"/companies/{id}/organization-credential":{"put":{"tags":["Companies"],"summary":"Configurar clave tributaria de la empresa","operationId":"updateCompanyOrganizationCredential","security":[{"BearerAuth":[]}],"description":"Requiere scope `companies:write`. Acepta el header `Idempotency-Key` (opcional). En producción guarda la clave tributaria (login SII de la organización; el usuario es el RUT de la empresa), la valida contra el SII y sincroniza los datos de la carta SII. En Demo y customer Sandbox la operación se simula: responde exitosamente, no contacta al SII y sustituye el valor enviado por un marcador interno no secreto. La respuesta nunca incluye el secreto; el estado queda visible en `hasOrganizationCredential`. Un resultado exitoso en Sandbox no confirma que la credencial sea válida en producción.","parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID de la empresa"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["password"],"properties":{"password":{"type":"string","format":"password","description":"Clave tributaria del RUT de la empresa"}}}}}},"responses":{"200":{"description":"Credencial configurada. En producción se valida y sincroniza con el SII; en Demo y Sandbox la configuración es simulada","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompanyResponse"},"examples":{"company":{"$ref":"#/components/examples/Company"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}}}},"/companies/{id}/representative-credential":{"patch":{"tags":["Companies"],"summary":"Configurar credenciales del representante legal","operationId":"updateCompanyRepresentativeCredential","security":[{"BearerAuth":[]}],"description":"Requiere scope `companies:write`. Acepta el header `Idempotency-Key` (opcional). Actualización parcial: envía cualquier combinación de `username`, `password` y `certificatePassword` (al menos uno). En producción, cuando cambian usuario o clave se validan contra el SII antes de guardarse. En Demo y customer Sandbox la operación se simula: responde exitosamente, no contacta al SII y sustituye las claves enviadas por marcadores internos no secretos. La respuesta nunca incluye secretos; el estado queda visible en `siiCredential.hasPassword` / `hasCertPassword`. Un resultado exitoso en Sandbox no confirma que las credenciales sean válidas en producción.","parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID de la empresa"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","minProperties":1,"properties":{"username":{"type":"string","description":"RUT del representante legal, ej. 12345678-9"},"password":{"type":"string","format":"password","description":"Clave tributaria del representante"},"certificatePassword":{"type":"string","format":"password","description":"Clave del certificado digital"}}}}}},"responses":{"200":{"description":"Credenciales configuradas. En producción se validan con el SII; en Demo y Sandbox la configuración es simulada","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompanyResponse"},"examples":{"company":{"$ref":"#/components/examples/Company"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"422":{"$ref":"#/components/responses/ValidationErrorResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"502":{"$ref":"#/components/responses/SiiUnavailableResponse"}}}},"/webhooks/{id}/rotate-secret":{"post":{"tags":["Webhooks"],"summary":"Rotar secreto de firma","operationId":"rotateWebhookSecret","security":[{"BearerAuth":[]}],"description":"Requiere scope `webhooks:write`. Invalida inmediatamente el secreto anterior y devuelve el nuevo valor una sola vez. Acepta `Idempotency-Key` (opcional).","parameters":[{"$ref":"#/components/parameters/IdempotencyKeyOptional"},{"name":"id","in":"path","required":true,"schema":{"type":"integer"},"description":"ID del webhook"}],"responses":{"200":{"description":"Secreto rotado","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookSecretResponse"},"examples":{"webhookSecretRotated":{"$ref":"#/components/examples/WebhookCreated"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"402":{"$ref":"#/components/responses/SubscriptionRequiredResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"404":{"$ref":"#/components/responses/NotFoundResponse"},"409":{"$ref":"#/components/responses/ConflictResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"}}}},"/context":{"get":{"tags":["Context"],"summary":"Consultar contexto de la conexión autenticada","operationId":"getApiContext","security":[{"BearerAuth":[]}],"description":"Comprueba organización, entorno y permisos efectivos del token antes de preparar una integración. No requiere scopes adicionales ni suscripción activa. No contacta al SII ni emite documentos. Los permisos describen los scopes del token; no garantizan una suscripción vigente, credenciales SII válidas ni autorización de un tipo de DTE. El entorno proviene de la organización autenticada, nunca del query. Respuesta privada sin caché. Demo conserva sus límites de workspace y cuota.","responses":{"200":{"description":"Contexto de la conexión","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiContextResponse"},"examples":{"context":{"$ref":"#/components/examples/ApiContext"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedResponse"},"403":{"$ref":"#/components/responses/ForbiddenResponse"},"410":{"$ref":"#/components/responses/DemoWorkspaceExpiredResponse"},"429":{"$ref":"#/components/responses/QuotaExceededResponse"},"503":{"$ref":"#/components/responses/ContextUnavailableResponse"}}}}}}