Cowisar Partner Documents API
1. What it is and the base URL
The Cowisar Partner Documents API lets an external system create, read, update, delete, duplicate, convert, correct and send a business's invoices and estimates without using the Cowisar app. It is the same engine the app itself uses, exposed over the website key the business owner mints in Ajustes. Nothing about the app's safety rules changes: a document that HOLDS its own country's fiscal evidence (the e-CF number or fiscal document id in the DR; the CFDI uuid, NF-e key or protocol number elsewhere) is never deleted, it is corrected with a credit or debit note; any other document is the owner's to delete, unless it is already applied (converted) or carries a payment a provider actually processed. Manual and installment payments delete together with the document.
Server-to-server only. This API is for your backend. Never embed a key in browser JavaScript, in a page a visitor can inspect, or in any client-side code: browsers cannot call this API (CORS refuses them), and a key shipped to a browser is a leaked key. Keep it on a server you control; if it leaks, rotate it immediately.
Base URL: https://api.cowisar.com
Two request dialects are deliberate and documented below. Every response, from both families, uses camelCase field names:
- Document endpoints (
/api/v1/partner/invoices,/api/v1/partner/estimates) take camelCase request fields: display currency units plus*Cents. - Intake requests (
/api/v1/partner/products,/api/v1/partner/sales, and the rest of the connector family) keep snake_case field names (product_id,issue_fiscal).
If you are an AI assistant reading this to build an integration: the entire contract is on this page, and the "Copy for LLM" button copies this exact markdown.
How it works, in plain words
- Your system stays yours. You send the sale as inputs: what was sold (description, quantity, unit price, tax rate per line), the customer, discounts, currency. Cowisar computes every figure (line totals, per-line tax, discounts, document totals) with the same engine the app uses. You never send totals; there is no field for them.
- Fiscal documents are Cowisar's job. On conversion, Cowisar assigns the legal fiscal number, builds and signs the electronic document, files it with the tax authority, and returns the number and status. You never build fiscal logic or XML, and you never talk to the tax authority.
- Two failure families, kept distinct: blocked before submission (422
PRESEND_BLOCKED: fix the data and convert again) and rejected by the tax authority (422DGII_REJECTED: correct it and resubmit). Thecodetells a machine which one; thereasontells a person why. - Unreachable tax authority is neither family: a conversion that cannot reach the tax authority right now does not fail. The document is converted into a deferred proforma, the call is accepted with 202, and Cowisar fiscalizes it automatically once the tax authority answers again (see "Deferred outcome" on the conversion doors). Treat 202 as accepted, not yet fiscalized.
- Identity is never writable through the API: the business's tax id, name and fiscal credentials always come from Cowisar. The key says which business; the caller cannot override it.
- Every response carries
X-Request-Id: quote it in a support ticket and we can find the exact request. Limits are per key and per IP; on429, respectRetry-After.
2. Keys, scopes and access
In the app: Ajustes -> Conexión de tu sitio web -> Crear clave. The key is shown once (64 hex characters). Cowisar stores it encrypted and can never show it again; if it is lost, rotate it and the old one stops working immediately.
Who manages keys. The business owner mints, rotates and deactivates keys. The owner can also grant a member the api permission at the modify level, and that member manages keys the same way. A member with view access holds their own key at the read-only level: that member creates, rotates and deactivates their key, and the key's scopes clamp to read, so it fetches data and never creates or changes anything. A caller without the grant is refused by the platform gate with 403 MODULE_ACCESS_DENIED. A member deactivates their own key with the absent-keyId path; either the owner or a granted-modify member can deactivate any key of the business by keyId. A deactivated or dead key is permanent for that credential; asking for a new key issues a fresh one.
Scopes. Every key carries a set of scopes drawn from exactly these seven strings:
read, write, fiscal, send, money, subscriptions, reports
The owner picks the scopes when creating the key (all seven by default). A request whose key lacks one of the scopes the endpoint requires answers 403 SERVICE_SCOPE_MISSING with a requiredScopes array naming what is missing. Section 3.6 maps every endpoint to the scopes it needs. A key's scopes are set when the key is created and do not change.
Liveness. A key acts as the member who created it. When that member is removed from the business, the key stops working: its next request answers 401 SERVICE_AUTH_INVALID. The same happens when the member's api permission resolves to none for the business: the key's next request answers 401 SERVICE_AUTH_INVALID and the key is turned off. View access keeps the key live as a read-only key (its effective scopes narrow to read while the level holds); modify keeps it live as stored. Re-granting access does not revive a dead key; mint a new one.
Every partner request carries the credential header:
x-service-token: <the 64-hex website key>
?businessId= is OPTIONAL. When it is omitted, the request acts on the business the key is bound to. When it is present, it must identify that same business, otherwise the request is refused with 403 SERVICE_TOKEN_BUSINESS_MISMATCH (a repeated parameter is refused the same way). The app shows the business's public id next to the key (Ajustes -> Conexión de tu sitio web), and the platform resolves a public id to its business before authentication, so that public id is the recommended value when you choose to send the parameter.
All responses are JSON except the PDF endpoints, which return application/pdf.
3. Conventions
3.1 Response envelope
Success bodies carry success: true. Failures carry:
{ "success": false, "error": "<generic sentence>", "code": "<MACHINE_CODE>" }
codeis the machine-readable identifier your integration should branch on. Every code is documented in section 3.7.erroris a short, generic English sentence for developers.reasoncarries either a stable machine token (for example USENOTEENDPOINT and NOTPARTNEREXPOSED on create-door sequence refusals; those tokens are part of the contract and safe to branch on) or opaque text from the underlying provider (for example the tax authority). Opaque provider text is for humans: show it if you wish, but never parse it.
Some refusals merge extra typed metadata into the body (limitData, creditData, details, costCents, balanceCents, invoice{...}). Metadata never overwrites success, error or code.
Uncoded branches map to a small fixed set:
- any uncoded 404 becomes
NOT_FOUND; - any uncoded parameter or body validation becomes
INVALID_INPUT; - any uncoded 500 becomes
INTERNAL_ERROR.
3.2 Platform exceptions (answers that arrive BEFORE the routers)
These do not use the envelope above. They are answered by the platform layer, not the documents routers:
| What happened | Status | Body |
|---|---|---|
| Business binding lookup failed | 404 | { "error": "BUSINESS_NOT_FOUND", "message": "..." } |
| Global API rate limit (600/minute) | 429 | { "error": "TOO_MANY_REQUESTS", "message": "...", "retryAfter": <seconds> } plus a Retry-After header |
| Key rate limit (60/minute per key) | 429 | same TOO_MANY_REQUESTS body plus a Retry-After header |
| IP backstop rate limit (240/minute per IP) | 429 | same TOO_MANY_REQUESTS body plus a Retry-After header |
| Request exceeded the server timeout | 503 | { "error": "Request timeout" } |
| Malformed JSON body | 400 | parser-shaped error (not the envelope) |
| Body too large | 413 | parser-shaped error (not the envelope) |
| Authentication lookup fault | 401/403 | the error handler's nested body |
Module access refused (a caller without the api grant reaches the key-management endpoints) | 403 | { "success": false, "error": "MODULE_ACCESS_DENIED", "zone": "<zone>" } |
3.3 Idempotency-Key
Idempotency-Key is REQUIRED on every mutating route. Hygiene rules:
- Exactly one header value. An array, a missing header, or an empty value is refused with
400 IDEMPOTENCY_KEY_INVALID. - The value is trimmed before the length check. After trimming, a length greater than 64 is refused with
400 IDEMPOTENCY_KEY_INVALID. - The value is case-sensitive.
The header's behavior per operation is exactly the table below. No replay guarantee lives outside it. For rows that are not dedup-backed, the header is a contract check only; it is never implied replay protection.
Idempotency behavior per operation
| Operation | First call | Same-key replay | Reused key with different operation or source |
|---|---|---|---|
Invoice create (POST /invoices; the /sales keys share this class) | 201 {success, invoice{...}} | 200 {success, invoice{<ORIGINAL>}, deduplicated:true} | 409 IDEMPOTENCY_KEY_REUSED, nothing written |
| Estimate create | 201 {success, estimate{id,estimateNumber}} | 200 same plus deduplicated:true | 409 same |
| Invoice duplicate | 200 {success, newInvoiceId} | 200 {success, newInvoiceId:<original duplicate id>, deduplicated:true} | 409 |
| Estimate duplicate | 200 {success, estimate{id,estimateNumber}} | 200 same plus deduplicated:true | 409 |
Invoice edit (PUT /invoices/:invoiceId/edit) | 200 {success, invoice{...}}, or 202 deferred, or 422 fiscal failure | 200/202/422 same body (original outcome, no second write) | 409, nothing written |
| Credit-note / debit-note | 201 {success, note{...}, noteNumber} | 200 same stored body plus deduplicated:true (original outcome, no second write) | 409 |
| Estimate convert-to-invoice | 200 {success, invoiceId, invoiceNumber}, or 202 {success, deferred, deferredReason, invoice{id, invoiceNumber, totalCents}} when the tax authority is unreachable (deferred outcome) | 200 same plus deduplicated:true | 409 |
| convert-to-fiscal | 200 (converts in place), or 202 {success, deferred, deferredReason, invoice{id, invoiceNumber, totalCents}} when the document is DEFERRED (the tax authority is unreachable, or a signing request is queued / already live and will complete the document by itself: deferredReason: "signing_request_queued"). A deferred answer always carries warning + warningMessage naming the wait, and never an error key | 200/202 same stored body (original outcome, no second write); already fiscal: 400 ONLY_PROFORMA_CONVERTIBLE | 409 |
| resubmit-fiscal | 200 or 422 | 200 same stored body (original outcome, no second write); serialized per invoice (row lock inside the service) so two attempts never overlap; a sequential second call hits the state guards (409 NOT_REJECTED or the terminal state's own refusal) only after the stored success is absent | 409, nothing written |
| cancel, restore, mark-applied, recover, reject | per-endpoint behavior below | Second call returns the operation's OWN existing refusal (frozen per endpoint below; never claimed as replay-success) | n/a |
| send | 200 {success, deliveryMethod} | 200 same stored body (original outcome, no second write) | 409, nothing written |
Identity rule for the 409. The key namespace is BUSINESS-WIDE. The stored (business_id, idempotency_key) row must match the requested operation and the full request identity: the body, the path invoice id, and for notes the note type (credit or debit). Any mismatch answers 409 IDEMPOTENCY_KEY_REUSED and nothing is written. Cross-table (invoice vs estimate) keys never collide because they live in separate tables. A hard-deleted document frees its key (partial index).
Only 2xx outcomes are stored. POST /invoices replays with HTTP 200 and deduplicated: true, carrying the original invoice. Estimate create, foreign-payment create, sales, subscription create, report create, report message, credit-note and debit-note replays answer HTTP 200 with the stored body and deduplicated: true. POST /invoices/:id/send, convert-to-fiscal and resubmit-fiscal replay their stored 2xx status and body verbatim. Every non-2xx outcome (402 insufficient credits, 422 delivery failure, 403 refusal, 500) stores nothing and may be retried with the SAME Idempotency-Key.
3.4 Rate limits
Every key has its own buckets; two keys never share one:
- Mutations: 60 requests per minute per key. Document mutations and intake mutations (customers, sales, subscriptions, reports) draw from the same per-key budget.
- Document reads: 60 requests per minute per key, a separate bucket, on the invoice and estimate list, detail and PDF endpoints.
- The other GETs (products, customers lookup, subscription lookup, report read) have no per-key read bucket: the IP backstop and the global limiter below cover them.
- IP backstop: 240 requests per minute per IP, the ceiling when many keys share one egress IP.
- A global API limiter (600 requests per minute) also applies to every call.
All answer 429 with the platform-exception body plus Retry-After.
3.5 Units table (read this before sending money)
Field units differ by endpoint family and by response shape. Each difference is stated explicitly:
| Field | Where | Unit |
|---|---|---|
items[].unitPrice | request (documents) | display currency units (for example dollars), exactly like the app's wire. Precision stays sub-cent until the service converts it; the API layer never pre-rounds. |
discount | request (documents) | currency units ONLY when discountType = "fixed"; otherwise a percentage value |
items[].taxRate | request (documents) | percentage, 0 to 100 |
items[].itbis_retention_rate, items[].isr_retention_rate | request (invoice edit lines) | fraction from 0 to 1 (0.30 means 30%) |
subtotal, taxAmount, total, amountPaid, amountDue, item prices, payment amounts, refund amounts | response detail and edit bodies | display currency units |
the same values with a Cents suffix (totalCents, amountDueCents, and so on) | response detail and edit bodies | integer cents, ALONGSIDE the display-unit fields above |
total, amountDue | response list rows | display currency units |
note.total | create credit/debit note response | display currency units |
priceCents (products), totalCents (sales receipt), webhook *_cents (amount_cents, total_cents), costCents/balanceCents (blocked-send metadata) | intake responses and webhooks | integer cents |
issueDate, dueDate, validUntil | request and response | calendar date YYYY-MM-DD |
created_at, paid_at, refunded_at and other metadata timestamps | response | ISO-8601 UTC |
A display-unit value and its *Cents sibling are two honest views of the same integer cents; they are never re-derived from each other. Calendar dates are stored as calendar days, not instants. Metadata timestamps are UTC instants.
STORAGE IS MAJOR x 100 FOR EVERY CURRENCY, and the conversion lives in exactly two helpers: centsToProviderSmallestUnit divides storage cents by 10 (2 - decimals) and providerSmallestUnitToCents multiplies back. decimals is 2 almost everywhere and 0 for CLP, PYG, JPY and KRW. So a *Cents field is a storage unit whose factor is 100 of the major unit in every currency, and it is a real minor-unit cent only where decimals is 2. The client renders amounts with currencyDecimals, never by assuming two decimals.
3.6 Scopes
Exactly seven scope strings exist: read, write, fiscal, send, money, subscriptions, reports. A key carries a subset chosen by the owner (all seven by default). A request that needs a scope the key does not carry answers 403 SERVICE_SCOPE_MISSING with the missing scopes in requiredScopes.
| Endpoint group | Required scopes |
|---|---|
| All GETs: invoice list/detail/pdf, estimate list/detail/pdf, foreign payment list/detail, products, customers lookup, subscription lookup, report detail and thread | read |
Invoice create (POST /invoices) | write, plus fiscal when the body's invoiceType is any non-proforma type (fiscal, credit_note, debit_note, purchase, minor_expense), plus subscriptions when the body carries recurrence |
Invoice update (PUT /:invoiceId), delete, duplicate, restore | write |
Invoice edit (PUT /:invoiceId/edit) | write, plus fiscal when the body's invoiceType is a non-proforma type |
| Invoice convert-to-fiscal, resubmit-fiscal, credit-note, debit-note | fiscal |
| Invoice cancel, mark-applied | money |
| Invoice and estimate send | send |
| Estimate create, update, delete, duplicate, recover, reject | write |
| Estimate convert-to-invoice | write, plus fiscal when the body's invoiceType is a non-proforma type |
Foreign payment create (POST /foreign-payments) | fiscal |
POST /customers | write |
POST /sales | write and money |
POST /subscriptions and pause / resume / cancel | subscriptions |
POST /reports, POST /reports/:id/messages (the family's writes; reading a report rides read above) | reports |
Key management (mint, rotate, deactivate) is not a scope: the owner or a member the owner grants the api permission at the modify level performs it, as described in section 2. A member at the view level manages their own key, and that key carries only read.
3.7 Error codes
These machine codes are part of the contract and will not be renamed. error carries a generic sentence, code the machine constant, and reason any opaque token or provider text.
Credentials and scopes:
| Code | Status | When |
|---|---|---|
SERVICE_AUTH_MISSING | 401 | the x-service-token header is absent |
SERVICE_AUTH_INVALID | 401 | the key is unknown, inactive, its member left the business, or the member's api permission resolved to none |
SERVICE_TOKEN_BUSINESS_MISMATCH | 403 | ?businessId= names a different business than the key's |
SERVICE_SCOPE_MISSING | 403 | the key lacks a scope the endpoint requires (requiredScopes lists them) |
INVALID_SCOPES | 400 | a key was created with an unknown, empty or duplicated scope |
INVALID_KEY_FORMAT | 400 | a key with an invalid format |
KEY_EXISTS | 409 | the member already has a key for this business |
Request validation:
| Code | Status | When |
|---|---|---|
INVALID_INPUT | 400 | malformed or missing parameter or body field without a more specific code |
UNKNOWN_FIELD | 400 | the body carries a field the endpoint does not accept (field, and itemIndex for item fields) |
IDEMPOTENCY_KEY_INVALID | 400 | the Idempotency-Key header is missing, empty, repeated, or longer than 64 characters |
IDEMPOTENCY_KEY_IN_PROGRESS | 409 | the same edit is still running under this key; a retry after it finishes replays the stored outcome |
IDEMPOTENCY_KEY_REUSED | 409 | the key was already used for a different operation or source document |
ITEMS_REQUIRED | 400 | a document or note was sent without items |
INVALID_ITEM | 400 | an item is malformed (estimate per-line discounts other than zero are refused here) |
INVALID_ITEMS | 400 | the items array refers to unknown or foreign products |
INVALID_CLIENT | 400 | the client reference is malformed |
INVALID_TAX_ID | 400 | a typed client's tax id fails the country's validation; the document is refused and nothing is written |
INVALID_NAME | 400 | a typed client's name is unusable (an individual needs at least two words) |
INVALID_PHONE | 400 | a typed client's phone is not a valid international number |
INVALID_EMAIL | 400 | a typed client's email is malformed |
DUPLICATE_NAME | 409 | a client with that name already exists under a DIFFERENT tax id; send the saved clientId instead |
DUPLICATE_TAX_ID | 409 | a client with that tax id already exists and could not be linked; send the saved clientId instead |
INVALID_TAX_RATE | 400 | a taxRate outside 0 to 100, or a per-line retention rate outside the fraction range 0 to 1 |
INVALID_EXCHANGE_RATE | 400 | the exchange rate is not a positive number below 1000 |
INVALID_CURRENCY | 400 | the currency is not one of the system's currencies |
INVALID_FISCAL_SEQUENCE | 400 | fiscalSequenceType is not a known e-CF sequence |
INVALID_REFERENCE | 400 | a productId or clientId belongs to another business |
INVALID_BODY | 400 | a body field is malformed (for example a sellerId that is not a positive integer or null) |
INVALID_FORMAT | 400 | a value is malformed in a way the service reports as a format refusal (estimate doors) |
INVALID_STATE | 400/422 | the resource is not in a state that allows the operation (estimate doors answer 400) |
INVALID_SUPPLIER_ID | 400 | the supplier id is not a positive integer |
INVALID_COUNTRY_CODE | 400 | The supplier country must be an ISO 3166-1 numeric code, three digits. |
SUPPLIER_REQUIRED | 400/422 | a supplier record is required and the request carried none: 400 on create, 422 when the document is refused through the fiscal fall-through (a supplier-less proforma converted or edited into an E41/E47) |
INVALID_BRANCH_ID | 400 | the branch id is not valid |
BRANCH_NOT_FOUND | 404 | the branch id does not belong to this business |
Business rules:
| Code | Status | When |
|---|---|---|
INVOICE_LIMIT_REACHED | 403 | the business's invoice quota is exhausted |
ESTIMATE_LIMIT_REACHED | 403 | the business's estimate quota is exhausted |
CREDIT_LIMIT_EXCEEDED | 409 | the client's credit limit would be exceeded (send skipCreditCheck to bypass; see section 5) |
CREDIT_REFERENCE_LINE_REQUIRED | 400 | a partial credit-note line names no referenceInvoiceItemId (a full annulment needs none) |
CREDIT_REQUIRES_CLIENT | 400 | a credit sale was requested without a resolvable client |
CLIENT_INACTIVE | 400 | the client is inactive |
FISCAL_COMPLIANCE_INCOMPLETE | 409 | the business's fiscal configuration is incomplete |
FISCAL_NOT_EDITABLE | 409 | a fiscal document refuses this content edit |
PAID_NOT_EDITABLE | 409 | the document already has a recorded payment, so its content cannot be edited |
STATUS_NOT_EDITABLE | 409 | the document's state no longer allows content edits (cancelled, void, refunded, disputed, applied or failed) |
INVOICE_DELETE_BLOCKED_LINKED | 400 | another record still points at this document (a live payment plan, a voided e-CF sequence, a foreign payment filing, a referencing invoice, or a live Stripe payment link); nothing was deleted |
INVOICE_NOT_DELETABLE | 400 | the document carries no deletable state: it already has a fiscal number or a fiscal document id, or it was already converted to fiscal |
PAYMENT_PROCESSED | 400 | the document has a payment processed by a provider (Stripe, PayPal); use that provider's refund or cancel flow |
INVOICE_NOT_CANCELLABLE | 400 | the invoice's status cannot be cancelled |
ONLY_PROFORMA_CONVERTIBLE | 400 | convert-to-fiscal was attempted on a document that is not a proforma |
ESTIMATE_NOT_CONVERTIBLE | 400 | the estimate cannot be converted (already converted, or not in a convertible state) |
OPERATION_NOT_ALLOWED | 400 | the operation is not allowed for this estimate (converted delete, item edit in its state) |
NOTE_REQUIRES_FISCAL_EVIDENCE | 400 | a credit or debit note was requested against a document that holds no fiscal comprobante (no e-NCF number and no fiscal document id), so there is nothing to reverse fiscally |
NOT_REJECTED | 409 | resubmit-fiscal was attempted on an invoice that is not in a rejected state |
RETRY_LOCKED | 409 | resubmit-fiscal was attempted on a document UNCHANGED since the last DGII rejection; nothing was mutated and no DGII call was made (the retry state rides the body) |
REISSUE_SOURCE_BLOCKED | 409 | create declared a reissueSourceInvoiceId whose source is not yet fully retired: the source has no durable transition, stock is not reversed, or settled/pending refund money remains (see the create section); nothing was created |
REISSUE_SOURCE_NOT_FOUND | 409 | the reissue source is not in this business |
DUPLICATE_PAYMENT_REFERENCE | 409 | the sale's payment reference was already recorded |
PAYMENT_REFUND_PENDING | 202 | The payment was captured and its refund is pending; the invoice is not settled. |
PAYMENT_SETTLEMENT_FAILED | 500 | The payment could not be recorded against the invoice. |
INSUFFICIENT_CREDITS | 402 | the business's messaging wallet cannot pay for the send |
FISCAL_REJECTED | 403 | a genuine tax-authority rejection blocks the operation |
FEATURE_UNAVAILABLE | 423 | the business has the support lane off (report endpoints) |
TEST_BUSINESS_COMMERCE_BLOCKED | 403 | a test business refuses commercial operations |
CUSTOMER_NOT_FOUND | 404 | the customer does not exist for this business |
REPORT_NOT_FOUND | 404 | the report does not exist for this business (or was not filed through the API) |
SUBSCRIPTION_CANCELLED | 409 | the subscription is already cancelled |
TICKET_CLOSED | 409 | the report is closed and refuses new messages |
Fiscal transitions:
| Code | Status | When |
|---|---|---|
DGII_REJECTED | 422 | the tax authority rejected the e-CF; its text rides in reason |
PRESEND_BLOCKED | 422 | our own pre-send gate stopped the document before the tax authority received it; the blocking detail rides in reason (never a tax-authority rejection) |
FISCAL_FAILED | 422 | a fiscal failure without a machine code; the provider's text rides in reason (the error field always carries the generic sentence) |
BUSINESS_INCOMPLETE | 422 | the business profile is incomplete for this fiscal operation; the detail rides in reason |
MISSING_CLIENT_RNC | 422 | a buyer tax id is required for this document type |
E32_GTE_MISSING_RNC | 422 | a consumer e-CF above the threshold requires the buyer tax id |
MISSING_EXCHANGE_RATE | 422 | an exchange rate is required for a foreign-currency document |
FISCAL_NOT_CONFIGURED | 422 | the fiscal configuration is incomplete for this document |
FISCAL_NOT_REQUIRED | 422 | the document does not require fiscal issuance |
DGII_UNAVAILABLE | 422 | fiscal processing could not be completed; retry later. The convert doors never answer this: when the tax authority is unreachable they park the document and answer 202 (see the deferred outcome on those doors). |
SEQUENCE_EXHAUSTED | 422 | the fiscal sequence is exhausted; request a new range |
NOT_CERTIFIED | 422 | the business is not certified for fiscal issuance yet |
ACCEPTED_PROFORMA_UNCONVERTED | 422 | DGII accepted the reissue but the invoice type needs a manual review; contact support with the invoice number |
MISSING_PURCHASE_BUYER_RNC | 422 | the supplier for this purchase must have a registered tax ID (RNC) |
CONTENT_CORRECTION_REQUIRED | 422 | create a new corrected document instead of resubmitting this one |
NOT_RETRYABLE_CAUSE | 422 | this document cannot be resubmitted; follow the guidance shown for its cause |
Signing lane (a document that a linked device must sign):
| Code | Status | When |
|---|---|---|
SIGNING_AGENT_OFFLINE | 422 | the device that signs this business's documents is not reachable now; the document was not sent to the tax authority |
SIGNING_STATE_UNAVAILABLE | 422 | the signing state could not be read, so the document was not sent; retry once the signing service answers |
SIGNING_REQUEST_QUEUED | 422 | the document waits for a signature before it can be sent; a live request exists for it |
SIGNING_DEVICE_NOT_LINKED | 422 | the signing device is not linked to this business, so it cannot sign for it |
SIGNING_UNKNOWN_TERMINAL | 422 | the signing service ended with a failure this integration does not recognise, so the document was not sent; retry or contact support |
Concurrency:
| Code | Status | When |
|---|---|---|
INVOICE_DUPLICATE | 200/409 | a concurrent same-key create raced; resolved to the replay or to 409 IDEMPOTENCY_KEY_REUSED |
ESTIMATE_DUPLICATE | 200/409 | the same race resolution for estimate creates |
Platform and generic:
| Code | Status | When |
|---|---|---|
BUSINESS_NOT_FOUND | 404 | the business binding could not be resolved (platform layer) |
TOO_MANY_REQUESTS | 429 | a rate limit refused the call (platform layer) |
NOT_FOUND | 404 | the resource does not exist or does not belong to this business |
INTERNAL_ERROR | 500 | an unexpected server fault |
4. Intake endpoints (connector family)
These endpoints use snake_case field names and integer cents. They share the key, the scopes and the optional ?businessId= binding. Their mutating routes refuse unknown body fields with 400 UNKNOWN_FIELD.
GET /api/v1/partner/products
Returns the products your site may sell. Prices are integer cents in the business's document currency.
{
"success": true,
"products": [
{ "id": 41, "name": "Cafe 454g", "priceCents": 38000, "currency": "DOP",
"isSubscription": false, "interval": null },
{ "id": 42, "name": "Plan mensual", "priceCents": 150000, "currency": "DOP",
"isSubscription": true, "interval": "monthly" }
]
}
interval is one of weekly, biweekly, monthly, quarterly, yearly (null for one-off products).
POST /api/v1/partner/sales (requires Idempotency-Key)
Records a sale. Body client, items[], payment, issue_fiscal.
{
"client": { "name": "Ana Perez", "phone": "+18095551234", "email": "[email protected]" },
"items": [{ "product_id": 41, "quantity": 2 }],
"payment": { "status": "paid", "reference": "WEB-10231", "method": "card" },
"issue_fiscal": false
}
payment.status: "paid" means your site already collected the money; reference is then required and is the fence against recording the same money twice (a repeat reference, even with a different Idempotency-Key, answers 409 DUPLICATE_PAYMENT_REFERENCE). issue_fiscal: true asks Cowisar to issue the fiscal document right away. A fiscal failure never loses the sale: the receipt still returns. When the fiscal attempt errored, the receipt carries a nested fiscal block with the normalized error:
{ "success": true, "invoiceId": 912, "invoiceNumber": "F-000912", "totalCents": 76000,
"currency": "DOP", "status": "pending", "clientId": 77,
"customerUuid": "2f6b0f8a-6a1e-4b7e-9d0f-3a9c5e7b1c42",
"fiscal": { "code": "PRESEND_BLOCKED",
"error": "The document was blocked before being sent to the tax authority.",
"reason": "<the provider's text, when present>", "blockedPresend": true } }
code is the machine constant (section 3.7), error a short generic English sentence, reason the provider's own text when there is any, and blockedPresend: true marks a document our own pre-send gate stopped before the tax authority received it. The fiscal block appears only when the fiscal attempt errored; the raw provider exception is never echoed.
Response 201 (first time) / 200 (replay):
{ "success": true, "invoiceId": 912, "invoiceNumber": "F-000912", "totalCents": 76000,
"currency": "DOP", "status": "paid", "clientId": 77,
"customerUuid": "2f6b0f8a-6a1e-4b7e-9d0f-3a9c5e7b1c42", "deduplicated": true }
Errors: 400 INVALID_INPUT, 400 IDEMPOTENCY_KEY_INVALID, 400 UNKNOWN_FIELD, 400 INVALID_ITEMS (unknown or foreign product), 409 DUPLICATE_PAYMENT_REFERENCE, 403 INVOICE_LIMIT_REACHED.
The rest of the connector family (customers, subscriptions, support reports) keeps the same key and binding:
POST /api/v1/partner/customers(requiresIdempotency-Key): register or link a customer; answers{ success, customerUuid, clientId, name, phone, email }.GET /api/v1/partner/customers/:customer_uuid: the same customer row.POST /api/v1/partner/subscriptions(requiresIdempotency-Key): answers{ success, subscriptionId, status, frequency, nextChargeDate, customerUuid, manageUrl? }.GET /api/v1/partner/subscriptions/:id: the same subscription row.POST /api/v1/partner/subscriptions/:id/pause,/resume,/cancel(each requiresIdempotency-Key): answer{ success, subscriptionId, status }.POST /api/v1/partner/reports(requiresIdempotency-Key):201 { success, ticketId, status: "open", deduplicated: false }; a replay answers200withdeduplicated: true.GET /api/v1/partner/reports/:id:{ success, ticket: { id, businessId, category, status, subject, source, createdAt, updatedAt, lastReplyAt }, messages: [{ id, ticketId, senderType, content, attachments: [{ filename, contentType, size, proxyUrl }], createdAt }] }.POST /api/v1/partner/reports/:id/messages(requiresIdempotency-Key):201 { success, messageId, deduplicated: false }; a replay answers200withdeduplicated: true. The append posts as the key's owner (senderType: "api"); a closed report answers409 TICKET_CLOSED.
Support reports ship off by default for a business. While the support lane is off, all three report endpoints answer 423 FEATURE_UNAVAILABLE; the owner enables it in Ajustes. The read and append endpoints operate only on reports filed through the API: a report from any other channel answers 404 REPORT_NOT_FOUND.
GET /api/v1/web/connector/* (key management and webhooks)
The app's own surface, driven with a normal user session (?businessId= on every call). It is documented because a partner integrating deeply may want to automate key rotation and webhook management; it is not part of the website integration contract. The owner manages keys, and a member the owner grants the api permission at the modify level manages them too. A member at the view level manages their own key, which is read-only (its scopes clamp to read). Webhook endpoint and delivery management stay at the modify level, and a caller without the grant is refused with 403 MODULE_ACCESS_DENIED.
| method + path | returns |
|---|---|
GET /keys | { success: true, keys: [{ id, masked, active, created_at, last_used_at, rotated_at, scopes, ownerName }] }; ownerName is a string or null (the app localizes the display fallback); the owner sees every key of the business, a member sees only their own |
POST /keys | body { scopes? } (default: all seven); 201 { success, key, key_hint, scopes } once; 409 KEY_EXISTS while a live key exists; 400 INVALID_SCOPES; refused with 403 MODULE_ACCESS_DENIED when the caller is neither the owner nor a granted member; a view-level member mints their own key, clamped to read |
POST /keys/rotate | owner or granted member (view included on their own key); 200 { success, key, scopes } once, the scopes preserved at modify and clamped to read at view (404 KEY_NOT_FOUND when there is none) |
POST /keys/deactivate | 200 { success: true, active: false, changed }; body { keyId? }: absent deactivates the caller's own key (any member with access, view included), present deactivates any key of the business (owner or granted modify); a malformed keyId answers 400 INVALID_KEY_ID |
GET /endpoints | { endpoints: [{ id, url, enabled_events, active, description, created_at, updated_at }] } |
POST /endpoints | 201 { endpoint, secret } once (400 INVALID_URL / 400 INVALID_ENABLED_EVENTS) |
PATCH /endpoints/:id | 200 { endpoint } (400 NO_FIELDS, 404 ENDPOINT_NOT_FOUND) |
DELETE /endpoints/:id | 200 { deleted: true } |
GET /event-samples | { headers, events }: one sample envelope per catalog event |
POST /endpoints/:id/test | 202 { event_id, delivery_id }; body {event_type} optional, default ping |
GET /deliveries?endpoint_id=&limit=50 | { deliveries: [...] } (limit default 50, max 200) |
POST /deliveries/:id/redeliver | 200 { delivery_id, status: "pending" } |
5. Invoices
All invoice endpoints live under /api/v1/partner/invoices. Every one requires the x-service-token header and the scopes listed in section 3.6. ?businessId= is optional. Mutating routes (POST, PUT, DELETE) require Idempotency-Key.
Fields are camelCase; detail and edit bodies carry display-unit money alongside *Cents (see the units table). Responses contain only the documented fields: internal identifiers, staff details and raw fiscal artifacts are never included.
Request levers (documented contract)
The create and edit doors accept these optional fields. Their behavior is stable and part of the contract:
| Field | Where | Semantics |
|---|---|---|
skipCreditCheck | invoice create | true skips the client's credit-limit check for a credit sale. Without it, a credit sale that would push the client's pending balance past their limit answers 409 CREDIT_LIMIT_EXCEEDED. |
skipAutoPayment | invoice create | Without it, a cash proforma may be auto-settled at creation per the business's payment settings. true keeps the new document unpaid (the caller records the payment later). |
kitchenOrder | invoice create | true tags the proforma as a kitchen order when the business has restaurant mode on, so it appears on the kitchen board; it also refreshes the table's pre-bill when a tableIdentifier is present. |
sellerId | invoice create/edit | Positive integer: attributes the document to a seller of this business (commission). A seller of another business answers 404. null or "" clears the attribution. |
insuranceCompany, insurancePolicy | invoice create | Free-text insurance attribution stored on the document and used by the insurance reports. |
recurrence | invoice create | Object { frequency, anchorDate, mode? }. Creates a linked recurring schedule for the resolved client: frequency one of weekly, biweekly, monthly, quarterly, yearly; anchorDate a future-or-today YYYY-MM-DD; mode auto_send (default: each cycle sends the invoice to the client) or auto_charge (each cycle charges the client's saved card). A failure here does not fail the invoice: the response carries recurrenceError naming the missing or invalid piece. |
The ten fiscal document types
Every fiscal document carries an e-CF type code. The ten types the API issues are:
| Code | NCF class | Name |
|---|---|---|
| E31 | B01 | Fiscal credit invoice |
| E32 | B02 | Consumer invoice |
| E33 | B03 | Debit note |
| E34 | B04 | Credit note |
| E41 | B11 | Purchase invoice |
| E43 | B13 | Minor expenses receipt |
| E44 | B14 | Special regimes receipt |
| E45 | B15 | Government receipt |
| E46 | B16 | Export invoice |
| E47 | B17 | Foreign payments receipt |
On the partner create door only B01 (fiscal credit invoice) and B02 (consumer invoice) are available; the special-regime document kinds (E44 through E46) are not available on this door, and credit and debit notes have their own endpoints.
GET /api/v1/partner/invoices
List invoices. Query: page, limit (max 50), search, status, statusNot, invoiceType, insurance, referenceInvoiceId, createdBy, createdByNot, origin.
Response 200:
{
"success": true,
"invoices": [
{ "id": 912, "invoiceNumber": "F-000912", "status": "pending", "total": 760.00, "amountDue": 760.00 }
],
"pagination": { "page": 1, "limit": 20, "hasMore": false, "totalCount": 1, "totalPages": 1 }
}
List rows carry display-unit total and amountDue. The web stats block is omitted from this surface.
GET /api/v1/partner/invoices/:invoiceId
Read one invoice, including refundable and creditNoteInvoiceId.
{ "success": true,
"invoice": { "id": 912, "invoiceNumber": "F-000912", "status": "pending",
"subtotal": 760.00, "taxAmount": 0.00, "total": 760.00, "amountPaid": 0.00, "amountDue": 760.00,
"totalCents": 76000, "refundable": false, "creditNoteInvoiceId": null } }
POST /api/v1/partner/invoices (requires Idempotency-Key)
Create an invoice. Body fields include clientId, clientName, clientTaxId, clientPhone, clientEmail, clientAddress, items[], invoiceType, fiscalSequenceType, expenseClassificationCode, reissueSourceInvoiceId, dueDate, discount, discountType, taxRate, taxInclusive, notes, terms, footerText, language, exchangeRate, baseCurrency, currency, paymentCondition, defaultPaymentMethod, tableIdentifier, orderType, insuranceCompany, insurancePolicy, affectsInventory, recurrence, autoCreateIsService, plus the levers documented above. Each item carries description, quantity, unitPrice, productId, taxRate, is_service and optional notes (the canonical plural; a singular note is an unknown field and is refused).
On this door invoiceType accepts proforma (the default), fiscal, purchase or minor_expense; any other value answers 400 INVALID_INPUT (credit and debit notes have their own endpoints).
On this door fiscalSequenceType accepts B01 and B02 only: a note code (B03, B04) answers 400 INVALID_FISCAL_SEQUENCE naming its note endpoint, and a special-regime code (B14 through B16) answers 400 INVALID_FISCAL_SEQUENCE because those document kinds are not available on this door; each refusal carries a reason token (USENOTEENDPOINT or NOTPARTNEREXPOSED).
purchase records the business's own purchase: the supplier data travels in the client fields (clientTaxId and clientName), and the e-CF refuses to issue when that tax id or legal name is missing. minor_expense records small expenses: it is ITBIS-exempt, so the stored tax is always zero, and a document discount is refused with 400 INVALID_INPUT. On these two types fiscalSequenceType does not apply: a body that carries B01 or B02 answers 400 INVALID_INPUT, and a note or special-regime code is refused first by the rule above; the optional expenseClassificationCode (a DGII classification code from 01 to 11) classifies the document for the expense reports.
orderType accepts "dine_in", "takeout", or absent/null. Only "dine_in" carries the statutory 10% Propina Legal tip on the stored document; "takeout" and absent never do. Any other value is rejected with 400 INVALID_INPUT (the same rule applies to the PUT /edit door).
items[].unitPrice is display currency units. discount is currency units only when discountType = "fixed", otherwise a percentage. Every *Cents field on an invoice is in that invoice's currency.
Strictness: an unknown body field (top-level or per item) answers 400 UNKNOWN_FIELD; a currency outside the system's currencies answers 400 INVALID_CURRENCY; an unknown fiscalSequenceType answers 400 INVALID_FISCAL_SEQUENCE; a productId or clientId of another business answers 400 INVALID_REFERENCE; out-of-range tax rates answer 400 INVALID_TAX_RATE.
{
"clientName": "Ana Perez", "clientPhone": "+18095551234",
"items": [{ "description": "Cafe 454g", "quantity": 2, "unitPrice": 380.00, "taxRate": 18 }],
"invoiceType": "proforma", "dueDate": "2026-11-01"
}
Response 201:
{ "success": true,
"invoice": { "id": 912, "invoiceNumber": "F-000912", "invoiceType": "proforma",
"totalCents": 76000, "status": "pending", "clientId": 77 } }
Replay per the idempotency table (200 plus deduplicated:true). Errors include 400 ITEMS_REQUIRED, 400 INVALID_ITEM, 400 INVALID_TAX_RATE, 400 INVALID_EXCHANGE_RATE, 400 INVALID_CURRENCY, 400 INVALID_FISCAL_SEQUENCE, 400 INVALID_REFERENCE, 400 UNKNOWN_FIELD, 403 INVOICE_LIMIT_REACHED, 409 CREDIT_LIMIT_EXCEEDED, 400 CLIENT_INACTIVE, 409 FISCAL_COMPLIANCE_INCOMPLETE, 409 IDEMPOTENCY_KEY_REUSED, 409 REISSUE_SOURCE_BLOCKED. A typed client (clientName/clientTaxId) that cannot be saved refuses the document: 400 INVALID_TAX_ID, 400 INVALID_NAME, 400 INVALID_PHONE, 400 INVALID_EMAIL, 409 DUPLICATE_NAME, 409 DUPLICATE_TAX_ID. An existing client is linked when the same tax id matches, or when the name matches and no tax id was sent.
PUT /api/v1/partner/invoices/:invoiceId (requires Idempotency-Key)
Update an editable proforma's lines and totals. Request: items (required), taxRate, discount, discountType, taxInclusive, tableIdentifier.
{ "items": [{ "description": "Cafe 454g", "quantity": 3, "unitPrice": 380.00 }], "taxRate": 18 }
Response 200:
{ "success": true, "invoice": { "id": 912, "invoiceNumber": "F-000912", "totalCents": 114000 } }
Errors: 409 PAID_NOT_EDITABLE when the document already has a recorded payment, 409 STATUS_NOT_EDITABLE when its state no longer allows edits, 422 INVALID_STATE when the document is not editable, 404 NOT_FOUND, 400 UNKNOWN_FIELD, 400 INVALID_TAX_RATE.
PUT /api/v1/partner/invoices/:invoiceId/edit (requires Idempotency-Key)
Edit an existing invoice in place (proforma full edit, proforma to fiscal in-place convert, or fiscal scalar-only edit). The request accepts exactly these top-level keys: clientId, clientName, clientTaxId, clientPhone, clientEmail, clientAddress, items, invoiceType, fiscalDocumentType, issueDate, dueDate, discount, discountType, taxRate, taxInclusive, notes, terms, footerText, language, exchangeRate, baseCurrency, currency, paymentCondition, defaultPaymentMethod, orderType, tableIdentifier, sellerId. Create-only fields (fiscalSequenceType, recurrence, insuranceCompany, insurancePolicy, skipCreditCheck, skipAutoPayment, kitchenOrder, autoCreateIsService, affectsInventory) are not part of this door and answer 400 UNKNOWN_FIELD. Edit lines additionally accept itbis_retention_rate, isr_retention_rate and excludeFromDiscountBase (each retention rate is a fraction from 0 to 1: 0.30 means 30%), and the rate lives on the line, not on the document.
{ "issueDate": "2026-10-03", "dueDate": "2026-11-01", "fiscalDocumentType": "E32", "clientId": 77 }
Response 200: { "success": true, "invoice": { ... } }. A fiscal failure returns 422 with {error, code, reason?, invoice{id, invoiceType}}.
Replay: a retry with the same Idempotency-Key and the same body returns the original 200, 202 or 422 response without writing again, so one edit never settles a second payment. Reusing the key with a different body answers 409 IDEMPOTENCY_KEY_REUSED and writes nothing. A request refused before any write (for example 409 PAID_NOT_EDITABLE) is not stored, so correcting the state (for example reversing a payment) and retrying with the same key proceeds.
Deferred outcome (202). When an in-place edit fiscalizes a proforma and Cowisar cannot reach the tax authority at this moment, the edit does not fail. The document is converted into a deferred proforma and Cowisar fiscalizes it automatically as soon as the tax authority answers again. The response is 202:
{ "success": true, "deferred": true, "deferredReason": "dgii_unavailable_provider_error",
"invoice": { "id": 912, "invoiceNumber": "F-000912", "totalCents": 76000 },
"warning": "dgii_unavailable", "warningMessage": "El procesamiento fiscal no se pudo completar en este momento. Tu factura se convirtió en una proforma y podrás convertirla a fiscal más tarde." }
Treat 202 as ACCEPTED, not yet fiscalized: the edited document exists and stays valid, but it has not been fiscalized. The parked row may still carry a retained e-NCF from the interrupted attempt; a retained identifier confers no fiscal validity and is not an issued number. Do not resend the request; Cowisar retries on its own. deferredReason names the machine cause, and the warning / warningMessage pair carries the same copy the create door emits (a document parked by our own pre-send gate instead carries warning: "presend_blocked" with warningCode and warningDetails).
DELETE /api/v1/partner/invoices/:invoiceId (requires Idempotency-Key)
Delete a document that carries no fiscal value. A document is deletable when it has no fiscal number and no fiscal document id, is not a converted (applied) document, and carries no provider-processed payment; its manual payment records (cash, transfer) are deleted with it in the same step. A document holding an e-NCF is never deletable.
Response 200: { "success": true }.
Frozen guards: 400 INVOICE_NOT_DELETABLE (a fiscal number or fiscal document id is present, or the document is converted), 400 PAYMENT_PROCESSED (a payment was processed by a provider such as Stripe or PayPal and must go through that provider's refund or cancel flow), and 400 INVOICE_DELETE_BLOCKED_LINKED (another record still points at this document: a live payment plan, a voided e-CF sequence, a foreign payment filing, a referencing invoice, or a live Stripe payment link). An estimate created from this document is not a blocker: only its provenance link (converted_to_invoice_id) is cleared, and the estimate keeps its own number and its converted status.
GET /api/v1/partner/invoices/:invoiceId/pdf
Download the invoice PDF. Real bytes with Content-Disposition and render identity headers (X-Render-Id, X-Render-Input-Hash, X-Document-Sha256, X-Document-Format, X-Document-Language).
POST /api/v1/partner/invoices/:invoiceId/duplicate (requires Idempotency-Key)
Duplicate an invoice. No body.
Response 200: { "success": true, "newInvoiceId": 913 }. Replay per the idempotency table. 403 INVOICE_LIMIT_REACHED on limit.
POST /api/v1/partner/invoices/:invoiceId/convert-to-fiscal (requires Idempotency-Key)
Convert a proforma to a fiscal document. Body: fiscalDocumentType?, clientTaxId?, clientName?, affectsInventory?.
{ "fiscalDocumentType": "E32", "clientTaxId": "101010101" }
Response 200:
{ "success": true, "fiscalNumber": "E310000000001",
"invoice": { "id": 912, "invoiceNumber": "F-000912", "totalCents": 76000 } }
Deferred outcome (202). When Cowisar cannot reach the tax authority at this moment, the conversion does not fail. The document is converted into a deferred proforma and Cowisar fiscalizes it automatically as soon as the tax authority answers again. The response is 202:
{ "success": true, "deferred": true, "deferredReason": "dgii_unavailable_provider_error",
"invoice": { "id": 912, "invoiceNumber": "F-000912", "totalCents": 76000 },
"warning": "dgii_unavailable", "warningMessage": "El procesamiento fiscal no se pudo completar en este momento. Tu factura se convirtió en una proforma y podrás convertirla a fiscal más tarde." }
Treat 202 as ACCEPTED, not yet fiscalized: the document exists and stays valid, but it has not been fiscalized. The parked row may still carry a retained e-NCF from the interrupted attempt; a retained identifier confers no fiscal validity and is not an issued number. Do not resend the request; Cowisar retries on its own. deferredReason names the machine cause, and the warning / warningMessage pair carries the same copy the create door emits (a document parked by our own pre-send gate instead carries warning: "presend_blocked" with warningCode and warningDetails). Converting a document that is already deferred returns this same 202 with its current reason, without another signing attempt.
Already fiscal answers 400 ONLY_PROFORMA_CONVERTIBLE. Any other fiscal failure answers 422 with {error, code, reason?, invoice{id, invoiceType}}; DGII_REJECTED carries the tax authority's text in reason, and PRESEND_BLOCKED carries the blocking detail in reason (it never means the tax authority rejected anything).
POST /api/v1/partner/invoices/:invoiceId/resubmit-fiscal (requires Idempotency-Key)
Resubmit a DGII-rejected fiscal invoice. No body. The service serializes per invoice (row lock) so two attempts never overlap. Replay per the idempotency table: a retry with the same key returns the stored 2xx body; every non-2xx stores nothing and may be retried with the same key.
Response 200: { "success": true, "fiscalNumber": "E310000000001" }. 409 NOT_REJECTED when the invoice is not a resubmit candidate. 409 RETRY_LOCKED when the document is UNCHANGED since the last rejection and no external-fix attestation was given: nothing was mutated and no number was spent; editing the content (or the owner's attested external fix) unlocks the retry. Otherwise 422 with the same DGII_REJECTED / PRESEND_BLOCKED split as convert-to-fiscal.
POST /api/v1/partner/invoices/:invoiceId/credit-note (requires Idempotency-Key)
Create a credit note against an issued fiscal invoice. Request: items (required), reason?, modificationCode?, affectsInventory? (default true).
Every line of a PARTIAL credit note carries referenceInvoiceItemId: the id of the invoice line it credits, from the reference invoice's own items. A line that names its reference is matched to exactly that line, so two lines of one product at different prices, or a credit of part of a line, cannot be confused. An explicit full annulment (modificationCode: 1) needs no reference, because its lines reproduce the reference line for line.
{ "items": [{ "description": "Cafe 454g", "quantity": 1, "unitPrice": 380.00, "taxRate": 18, "referenceInvoiceItemId": 7012 }], "reason": "Devolucion", "modificationCode": 3 }
Response 201:
{ "success": true,
"note": { "id": 950, "invoiceNumber": "NC-000950", "total": 380.00, "status": "applied" },
"noteNumber": "E310000000002" }
note.total is display currency units. Replay per the idempotency table. Errors include 400 ITEMS_REQUIRED, 400 INVALID_ITEM, 400 CREDIT_REFERENCE_LINE_REQUIRED (a partial credit line that names no reference), 400 INVALID_REFERENCE (a referenceInvoiceItemId that belongs to another invoice), and note guards carrying details.
POST /api/v1/partner/invoices/:invoiceId/debit-note (requires Idempotency-Key)
Create a debit note. Request identical to credit-note, except affectsInventory defaults to false.
Response 201: { "success": true, "note": {...}, "noteNumber": "..." }. Replay per the idempotency table.
POST /api/v1/partner/invoices/:invoiceId/cancel (requires Idempotency-Key)
Cancel an invoice. Body: { reason? }.
Response 200: { "success": true }.
Frozen guard: 400 INVOICE_NOT_CANCELLABLE when the status is not cancellable. A second call returns the operation's own refusal; it is never claimed as replay-success.
POST /api/v1/partner/invoices/:invoiceId/restore (requires Idempotency-Key)
Restore a cancelled proforma. No body.
Response 200: { "success": true, "restoredStatus": "pending" }. A second call returns the operation's own refusal.
POST /api/v1/partner/invoices/:invoiceId/mark-applied (requires Idempotency-Key)
Mark a pending credit note as applied. No body.
Response 200: { "success": true }. A missing or foreign invoice answers the same 404 NOT_FOUND.
POST /api/v1/partner/invoices/:invoiceId/send (requires Idempotency-Key)
Send an invoice to the client. Body: { recipientPhone?, channel?, recipientEmail? } (channel one of whatsapp, email, both).
Response 200: { "success": true, "deliveryMethod": "business_whatsapp" }.
Replay per the idempotency table: a retry with the same key returns the stored 2xx body without delivering again; every non-2xx (402 insufficient credits, 422 delivery failure, 403 refusal, 500) stores nothing and may be retried with the same key. A genuine DGII-rejected document is refused 403 FISCAL_REJECTED; a pre-send block answers 422 PRESEND_BLOCKED with the blocking detail in reason. Insufficient credits answer 402 with costCents and balanceCents; other delivery failures answer 422. shared_to_owner is owner delivery, never proof of client receipt.
6. Estimates
All estimate endpoints live under /api/v1/partner/estimates. Every one requires the x-service-token header and the scopes listed in section 3.6. ?businessId= is optional. Mutating routes require Idempotency-Key.
GET /api/v1/partner/estimates
List estimates. Query: page, limit, search, status, statusNot, bucket, bucketNot, createdBy, createdByNot.
Response 200:
{
"success": true,
"estimates": [
{ "id": 55, "estimateNumber": "P-000055", "status": "sent", "total": 760.00, "validUntil": "2026-11-01" }
],
"pagination": { "page": 1, "limit": 20, "hasMore": false, "totalCount": 1, "totalPages": 1 }
}
GET /api/v1/partner/estimates/:id
Read one estimate.
{ "success": true,
"estimate": { "id": 55, "estimateNumber": "P-000055", "status": "sent",
"subtotal": 760.00, "taxAmount": 0.00, "total": 760.00, "totalCents": 76000,
"validUntil": "2026-11-01" } }
POST /api/v1/partner/estimates (requires Idempotency-Key)
Create an estimate. Body includes clientId, clientName, clientTaxId, clientPhone, clientEmail, clientAddress, items[], validUntil, discount, discountType, taxRate, taxInclusive, notes, terms, footerText, language, currency, exchangeRate, baseCurrency, paymentCondition, paymentTermsDays, autoCreateIsService. Each item carries description, quantity, unitPrice, productId, taxRate, is_service, notes, discount and exclude_from_discount_base.
items[].unitPrice is display currency units. A nonzero per-line item discount is refused with 400 INVALID_ITEM (a per-line discount other than zero is not supported on estimates). Every *Cents field on an estimate is in that estimate's currency.
Strictness is the same as invoices: unknown fields answer 400 UNKNOWN_FIELD, an out-of-vocabulary currency answers 400 INVALID_CURRENCY, a foreign productId or clientId answers 400 INVALID_REFERENCE, and out-of-range tax rates answer 400 INVALID_TAX_RATE.
{
"clientName": "Ana Perez", "clientPhone": "+18095551234",
"items": [{ "description": "Cafe 454g", "quantity": 2, "unitPrice": 380.00, "taxRate": 18 }],
"validUntil": "2026-11-01"
}
Response 201:
{ "success": true, "estimate": { "id": 55, "estimateNumber": "P-000055" } }
Replay per the idempotency table (200 plus deduplicated:true). 403 ESTIMATE_LIMIT_REACHED on limit. A typed client (clientName/clientTaxId) that cannot be saved refuses the estimate: 400 INVALID_TAX_ID, 400 INVALID_NAME, 400 INVALID_PHONE, 400 INVALID_EMAIL, 409 DUPLICATE_NAME, 409 DUPLICATE_TAX_ID. An existing client is linked when the same tax id matches, or when the name matches and no tax id was sent.
PUT /api/v1/partner/estimates/:id (requires Idempotency-Key)
Update an estimate header and/or line items. Body optional items (must be a non-empty array when present), clientId, clientName, clientTaxId, clientPhone, clientEmail, clientAddress, validUntil, discount, discountType, taxInclusive, notes, terms, footerText, paymentCondition, paymentTermsDays.
{ "items": [{ "description": "Cafe 454g", "quantity": 3, "unitPrice": 380.00 }], "taxInclusive": false }
Response 200: { "success": true, "estimate": { ... } }. validUntil null is refused with 400 INVALID_INPUT (never silently dropped). Errors: 400 ITEMS_REQUIRED, 400 INVALID_ITEM, 400 UNKNOWN_FIELD, 400 OPERATION_NOT_ALLOWED (items cannot be modified in the estimate's state), 404 NOT_FOUND. A typed client (clientName/clientTaxId) that cannot be saved refuses the update with the same codes as create: 400 INVALID_TAX_ID, 400 INVALID_NAME, 400 INVALID_PHONE, 400 INVALID_EMAIL, 409 DUPLICATE_NAME, 409 DUPLICATE_TAX_ID. An existing client is linked when the same tax id matches, or when the name matches and no tax id was sent.
DELETE /api/v1/partner/estimates/:id (requires Idempotency-Key)
Hard-delete a draft estimate (remove a mistake). A converted estimate is blocked.
Response 200: { "success": true }. Errors: 404 NOT_FOUND, and 400 ESTIMATE_NOT_CONVERTIBLE when the estimate was already converted or is not convertible.
GET /api/v1/partner/estimates/:id/pdf
Download the estimate PDF. Query ?format selects the layout (receipt for the 80mm thermal layout). Real bytes with the same render identity headers as the invoice PDF.
POST /api/v1/partner/estimates/:id/duplicate (requires Idempotency-Key)
Duplicate an estimate. No body.
Response 200: { "success": true, "estimate": { "id": 56, "estimateNumber": "P-000056" } }. Replay per the idempotency table.
POST /api/v1/partner/estimates/:id/convert-to-invoice (requires Idempotency-Key)
Convert an estimate to an invoice. Body: { invoiceType?, fiscalDocumentType? }. Always creates a proforma; when invoiceType = "fiscal" it chains through the fiscal conversion.
{ "invoiceType": "proforma" }
Response 200:
{ "success": true, "invoiceId": 912, "invoiceNumber": "F-000912" }
Deferred outcome (202). When invoiceType = "fiscal" and Cowisar cannot reach the tax authority at this moment, the conversion does not fail. The proforma invoice is created, the estimate is marked converted, and the document is parked as a deferred proforma that Cowisar fiscalizes automatically once the tax authority answers again. The response is 202:
{ "success": true, "deferred": true, "deferredReason": "dgii_unavailable_provider_error",
"invoice": { "id": 912, "invoiceNumber": "F-000912", "totalCents": 76000 },
"warning": "dgii_unavailable", "warningMessage": "El procesamiento fiscal no se pudo completar en este momento. Tu factura se convirtió en una proforma y podrás convertirla a fiscal más tarde." }
Treat 202 as ACCEPTED, not yet fiscalized: the invoice exists and stays valid, but it has not been fiscalized. The parked row may still carry a retained e-NCF from the interrupted attempt; a retained identifier confers no fiscal validity and is not an issued number. Do not resend the request; Cowisar retries on its own. deferredReason names the machine cause, and the warning / warningMessage pair carries the same copy the create door emits (a document parked by our own pre-send gate instead carries warning: "presend_blocked" with warningCode and warningDetails).
Replay per the idempotency table (200 plus deduplicated:true). Transitioning the estimate and copying the invoice happen in the same transaction so overlapping calls cannot double-create.
Which 422s have already committed a document. If the fiscal leg fails, the proforma invoice has already been created and the estimate has already been marked converted. In that case the response is 422 WITH invoiceId and invoiceNumber:
{ "success": false, "error": "DGII rejected the electronic document.", "code": "DGII_REJECTED",
"reason": "...", "invoiceId": 912, "invoiceNumber": "F-000912" }
A rejection BEFORE the proforma exists (a pre-fiscal client validation, for example a missing client RNC) returns 422 WITHOUT invoiceId; nothing was committed.
POST /api/v1/partner/estimates/:id/send (requires Idempotency-Key)
Send an estimate to the client. Body: { recipientPhone?, channel?, recipientEmail? } (channel one of whatsapp, email, both; default whatsapp). A recipient is required for the chosen channel (recipientPhone for WhatsApp).
Response 200: { "success": true, "deliveryMethod": "business_whatsapp" }.
A missing or foreign id answers 404 before any test-business shortcut. A bad channel answers 400 INVALID_INPUT. Insufficient credits answer 402 with costCents and balanceCents; other failures answer 422. Both-channel partial success and owner fallback are honored. A converted-estimate resend preserves its converted status and invoice link. NOT replay-protected.
POST /api/v1/partner/estimates/:id/recover (requires Idempotency-Key)
Recover a rejected estimate (reopen as sent). No body.
Response 200: { "success": true, "estimate": { ... } }. A second call returns the operation's own refusal.
POST /api/v1/partner/estimates/:id/reject (requires Idempotency-Key)
Mark an estimate as rejected. Body: { reason? }.
Response 200: { "success": true }. A second call returns the operation's own refusal.
7. Foreign payments (E47)
A foreign payment records money a business paid to a supplier abroad and, in the same call, issues the E47 e-CF the tax authority requires for it. The call writes the payment into the business's foreign-payments filing (the record behind the monthly 609 report) and issues the linked fiscal document, so the payment carries its legal e-CF number. The engine computes every figure; you send inputs and never build fiscal logic. All foreign-payment endpoints live under /api/v1/partner/foreign-payments. Every one requires the x-service-token header and the scopes listed in section 3.6. ?businessId= is optional. The mutating route requires Idempotency-Key.
E47 carries no ITBIS: the payment amount is exempt. When the request carries no isrWithheldCents, the engine withholds the ISR the E47 itself freezes: the provider record's own ISR rate applied to each payment line. A provider record with no rate withholds zero, never a statutory 27 percent. When the request carries no presumedIncomeCents, the presumed income is the payment amount. Every retention amount is integer cents.
The three payment amounts in every foreign-payment response (amountCents, presumedIncomeCents and isrWithheldCents) are filing-currency cents, and each response names that currency with filingCurrency: the E47's baseCurrency when the document records one, otherwise DOP. Those amounts are not what the caller sent: a payment charged in a foreign currency is converted once, at the document's own stored exchange rate, into that currency, and readers always see the stored filing cents.
GET /api/v1/partner/foreign-payments
List foreign payments. Query: period (YYYY-MM, filters by fiscal period), page, pageSize.
Response 200:
{
"success": true,
"payments": [
{ "id": 21, "supplierName": "Amazon Web Services", "supplierCountry": "840",
"serviceType": "7", "paymentDate": "2026-10-05", "amountCents": 120000,
"isrWithheldCents": 32400, "presumedIncomeCents": 120000, "fiscalPeriod": "2026-10",
"documentNumber": "INV-88421", "invoiceId": 912, "invoiceNumber": "F-000912",
"eNcf": "E470000675901" }
],
"pagination": { "page": 1, "pageSize": 20, "total": 1, "totalCount": 1, "hasMore": false, "totalPages": 1 }
}
total and totalCount carry the same number.
GET /api/v1/partner/foreign-payments/:id
Read one foreign payment.
{ "success": true,
"payment": { "id": 21, "supplierName": "Amazon Web Services", "supplierCountry": "840",
"serviceType": "7", "paymentDate": "2026-10-05", "amountCents": 120000,
"isrWithheldCents": 32400, "presumedIncomeCents": 120000, "fiscalPeriod": "2026-10",
"documentNumber": "INV-88421", "invoiceId": 912, "invoiceNumber": "F-000912",
"eNcf": "E470000675901" } }
A foreign id answers 404 NOT_FOUND.
POST /api/v1/partner/foreign-payments (requires Idempotency-Key)
Register a foreign payment and issue its E47 e-CF in one call. Body fields:
| Field | Required | Notes |
|---|---|---|
supplierName | yes | string, up to 255 characters |
supplierIdType | no | "1" or "2" |
supplierTaxId | no | string, up to 20 characters (the supplier's foreign id) |
supplierCountry | yes | ISO 3166-1 numeric, 3 digits (for example "840"), normalized by the shared country check. The allowed values are listed at GET /api/v1/partner/reference/countries (this section, below) |
serviceType | yes | "1" to "8" (the 609 service-type code) |
serviceDetail | no | a code valid for the chosen serviceType |
isRelatedParty | no | boolean, default false |
documentNumber | no | string, up to 50 characters (identified together with the provider record; two providers may reuse the same number) |
paymentDate | yes | calendar date YYYY-MM-DD |
amountCents | yes | positive integer cents (the exempt total) |
currency | no | ISO code, default the business's document currency |
exchangeRate | no | positive number below 1000 |
presumedIncomeCents | no | non-negative integer cents, derived when absent |
isrWithheldCents | no | non-negative integer cents; when absent it is derived from the provider record's ISR rate (zero when the record carries no rate) |
retentionDate | no | calendar date YYYY-MM-DD, or null |
clientName | no | string; the client name shown on the E47 document, defaulting to the provider record's name (the 609 payee always comes from supplierId) |
clientTaxId | no | string; a foreign id the provider emits as IdentificadorExtranjero |
supplierId | yes | positive integer: the provider record the payee snapshot is taken from |
items[] | no | line detail; each carries description (string) and amountCents (positive integer cents) |
When items[] is present, its amounts must sum to amountCents; a mismatch answers 400 INVALID_ITEMS. When it is absent, one line is built from amountCents. An out-of-vocabulary country or service type answers 400 INVALID_INPUT, and an unknown body field answers 400 UNKNOWN_FIELD.
supplierId is required: it names the provider record the payment is made to. The payee name and tax id are taken from that record, never from the caller, and no client row is created. The ISR the 609 files is the retention the E47 itself froze from the provider record's own rate; when the record carries no rate, the withheld ISR is zero, never the statutory 27 percent.
{
"supplierName": "Amazon Web Services",
"supplierTaxId": "US-EIN-555666777",
"supplierCountry": "840",
"serviceType": "7",
"serviceDetail": "71",
"paymentDate": "2026-10-05",
"amountCents": 120000,
"supplierId": 44,
"documentNumber": "INV-88421"
}
Response 201:
{
"success": true,
"payment": {
"id": 21, "supplierName": "Amazon Web Services", "supplierIdType": null,
"supplierTaxId": "US-EIN-555666777", "supplierCountry": "840",
"serviceType": "7", "serviceDetail": "71", "isRelatedParty": false,
"documentNumber": "INV-88421", "paymentDate": "2026-10-05", "amountCents": 120000,
"retentionDate": null, "presumedIncomeCents": 120000, "isrWithheldCents": 32400,
"fiscalPeriod": "2026-10", "invoiceId": 912, "invoiceNumber": "F-000912",
"eNcf": "E470000675901"
},
"deduplicated": false
}
The filing row feeds the monthly 609 report; the linked invoice carries the legal e-CF number. eNcf is null when the issuance is deferred (fiscal processing could not be completed): the payment is recorded and the fiscal document is retried later.
Replay per the idempotency table (200 plus deduplicated: true, the same stored payment). The same key with a different amount or body answers 409 IDEMPOTENCY_KEY_REUSED, and nothing is written. A documentNumber already filed for the SAME provider record answers 409 DUPLICATE_PAYMENT_REFERENCE before anything is issued; a different provider may file the same number, and a filing for the same provider and number that is being created right now answers the same 409.
| Status | code | When |
|---|---|---|
| 400 | INVALID_INPUT | a country or service type outside the vocabulary, or another malformed field |
| 400 | UNKNOWN_FIELD | the body carries a field the contract does not define |
| 400 | INVALID_ITEMS | the items[] amounts do not sum to amountCents, or a line is malformed |
| 404 | NOT_FOUND | the requested payment id does not exist for this business |
| 409 | DUPLICATE_PAYMENT_REFERENCE | a filing already exists for this provider record and documentNumber, or another filing for that pair is being created right now |
| 409 | IDEMPOTENCY_KEY_REUSED | the same key was reused with a different body |
| 422 | FISCAL_NOT_CONFIGURED | the business's fiscal configuration is incomplete for this document |
| 422 | SEQUENCE_EXHAUSTED | the E47 fiscal sequence is exhausted; request a new range |
| 422 | DGII_UNAVAILABLE | fiscal processing could not be completed; the payment is recorded and the document is retried |
| 400 | SUPPLIER_REQUIRED | no usable supplierId in the body for the provider record |
| 409 | RETENTION_MISMATCH | the sent ISR amount disagrees with the ISR the E47 froze at the provider record's rate |
| 400 | MISSING_EXCHANGE_RATE | a payment in a foreign currency with no exchange rate to the filing currency; the payment is refused before anything is issued, and nothing is charged |
GET /api/v1/partner/reference/countries
Requires scope read. Returns every supplier country the shared ISO map allows (config/isoCountryCodes.ts), sorted by alpha2, with the localized name where the map carries one. Send the numeric value as supplierCountry when registering a foreign payment.
Response 200:
{
"success": true,
"countries": [
{ "alpha2": "AF", "numeric": "004", "nameEn": "AF", "nameEs": "AF" },
{ "alpha2": "US", "numeric": "840", "nameEn": "United States", "nameEs": "Estados Unidos" }
]
}
The full list (the same entries the endpoint returns; nameEn repeats the alpha2 code where the map carries no localized name):
| alpha2 | numeric | nameEn |
|---|---|---|
| AF | 004 | AF |
| AX | 248 | AX |
| AL | 008 | AL |
| DZ | 012 | DZ |
| AS | 016 | AS |
| AD | 020 | AD |
| AO | 024 | AO |
| AI | 660 | AI |
| AQ | 010 | AQ |
| AG | 028 | AG |
| AR | 032 | AR |
| AM | 051 | AM |
| AW | 533 | AW |
| AU | 036 | AU |
| AT | 040 | AT |
| AZ | 031 | AZ |
| BS | 044 | BS |
| BH | 048 | BH |
| BD | 050 | BD |
| BB | 052 | BB |
| BY | 112 | BY |
| BE | 056 | BE |
| BZ | 084 | BZ |
| BJ | 204 | BJ |
| BM | 060 | BM |
| BT | 064 | BT |
| BO | 068 | BO |
| BQ | 535 | BQ |
| BA | 070 | BA |
| BW | 072 | BW |
| BV | 074 | BV |
| BR | 076 | Brazil |
| IO | 086 | IO |
| BN | 096 | BN |
| BG | 100 | BG |
| BF | 854 | BF |
| BI | 108 | BI |
| CV | 132 | CV |
| KH | 116 | KH |
| CM | 120 | CM |
| CA | 124 | Canada |
| KY | 136 | KY |
| CF | 140 | CF |
| TD | 148 | TD |
| CL | 152 | CL |
| CN | 156 | China |
| CX | 162 | CX |
| CC | 166 | CC |
| CO | 170 | Colombia |
| KM | 174 | KM |
| CG | 178 | CG |
| CD | 180 | CD |
| CK | 184 | CK |
| CR | 188 | CR |
| CI | 384 | CI |
| HR | 191 | HR |
| CU | 192 | CU |
| CW | 531 | CW |
| CY | 196 | CY |
| CZ | 203 | CZ |
| DK | 208 | DK |
| DJ | 262 | DJ |
| DM | 212 | DM |
| DO | 214 | DO |
| EC | 218 | EC |
| EG | 818 | EG |
| SV | 222 | SV |
| GQ | 226 | GQ |
| ER | 232 | ER |
| EE | 233 | EE |
| SZ | 748 | SZ |
| ET | 231 | ET |
| FK | 238 | FK |
| FO | 234 | FO |
| FJ | 242 | FJ |
| FI | 246 | FI |
| FR | 250 | France |
| GF | 254 | GF |
| PF | 258 | PF |
| TF | 260 | TF |
| GA | 266 | GA |
| GM | 270 | GM |
| GE | 268 | GE |
| DE | 276 | Germany |
| GH | 288 | GH |
| GI | 292 | GI |
| GR | 300 | GR |
| GL | 304 | GL |
| GD | 308 | GD |
| GP | 312 | GP |
| GU | 316 | GU |
| GT | 320 | GT |
| GG | 831 | GG |
| GN | 324 | GN |
| GW | 624 | GW |
| GY | 328 | GY |
| HT | 332 | HT |
| HM | 334 | HM |
| VA | 336 | VA |
| HN | 340 | HN |
| HK | 344 | HK |
| HU | 348 | HU |
| IS | 352 | IS |
| IN | 356 | IN |
| ID | 360 | ID |
| IR | 364 | IR |
| IQ | 368 | IQ |
| IE | 372 | IE |
| IM | 833 | IM |
| IL | 376 | IL |
| IT | 380 | Italy |
| JM | 388 | JM |
| JP | 392 | JP |
| JE | 832 | JE |
| JO | 400 | JO |
| KZ | 398 | KZ |
| KE | 404 | KE |
| KI | 296 | KI |
| KP | 408 | KP |
| KR | 410 | KR |
| KW | 414 | KW |
| KG | 417 | KG |
| LA | 418 | LA |
| LV | 428 | LV |
| LB | 422 | LB |
| LS | 426 | LS |
| LR | 430 | LR |
| LY | 434 | LY |
| LI | 438 | LI |
| LT | 440 | LT |
| LU | 442 | LU |
| MO | 446 | MO |
| MG | 450 | MG |
| MW | 454 | MW |
| MY | 458 | MY |
| MV | 462 | MV |
| ML | 466 | ML |
| MT | 470 | MT |
| MH | 584 | MH |
| MQ | 474 | MQ |
| MR | 478 | MR |
| MU | 480 | MU |
| YT | 175 | YT |
| MX | 484 | Mexico |
| FM | 583 | FM |
| MD | 498 | MD |
| MC | 492 | MC |
| MN | 496 | MN |
| ME | 499 | ME |
| MS | 500 | MS |
| MA | 504 | MA |
| MZ | 508 | MZ |
| MM | 104 | MM |
| MK | 807 | MK |
| NA | 516 | NA |
| NR | 520 | NR |
| NP | 524 | NP |
| NL | 528 | NL |
| NC | 540 | NC |
| NZ | 554 | NZ |
| NI | 558 | NI |
| NE | 562 | NE |
| NG | 566 | NG |
| NU | 570 | NU |
| NF | 574 | NF |
| MP | 580 | MP |
| NO | 578 | NO |
| OM | 512 | OM |
| PK | 586 | PK |
| PW | 585 | PW |
| PS | 275 | PS |
| PA | 591 | Panama |
| PG | 598 | PG |
| PY | 600 | PY |
| PE | 604 | PE |
| PH | 608 | PH |
| PN | 612 | PN |
| PL | 616 | PL |
| PT | 620 | PT |
| PR | 630 | PR |
| QA | 634 | QA |
| RE | 638 | RE |
| RO | 642 | RO |
| RU | 643 | RU |
| RW | 646 | RW |
| BL | 652 | BL |
| SH | 654 | SH |
| KN | 659 | KN |
| LC | 662 | LC |
| MF | 663 | MF |
| PM | 666 | PM |
| VC | 670 | VC |
| WS | 882 | WS |
| SM | 674 | SM |
| ST | 678 | ST |
| SA | 682 | SA |
| SN | 686 | SN |
| RS | 688 | RS |
| SC | 690 | SC |
| SL | 694 | SL |
| SG | 702 | SG |
| SX | 534 | SX |
| SK | 703 | SK |
| SI | 705 | SI |
| SB | 090 | SB |
| SO | 706 | SO |
| ZA | 710 | ZA |
| GS | 239 | GS |
| SS | 728 | SS |
| ES | 724 | Spain |
| LK | 144 | LK |
| SD | 729 | SD |
| SR | 740 | SR |
| SJ | 744 | SJ |
| SE | 752 | SE |
| CH | 756 | CH |
| SY | 760 | SY |
| TW | 158 | TW |
| TJ | 762 | TJ |
| TZ | 834 | TZ |
| TH | 764 | TH |
| TL | 626 | TL |
| TG | 768 | TG |
| TK | 772 | TK |
| TO | 776 | TO |
| TT | 780 | TT |
| TN | 788 | TN |
| TR | 792 | TR |
| TM | 795 | TM |
| TC | 796 | TC |
| TV | 798 | TV |
| UG | 800 | UG |
| UA | 804 | UA |
| AE | 784 | AE |
| GB | 826 | United Kingdom |
| US | 840 | United States |
| UM | 581 | UM |
| UY | 858 | UY |
| UZ | 860 | UZ |
| VU | 548 | VU |
| VE | 862 | VE |
| VN | 704 | VN |
| VG | 092 | VG |
| VI | 850 | VI |
| WF | 876 | WF |
| EH | 732 | EH |
| YE | 887 | YE |
| ZM | 894 | ZM |
| ZW | 716 | ZW |
8. Webhooks
Cowisar POSTs a signed JSON envelope to your registered URL when something happens (a sale was paid, a subscription was cancelled, a customer was created). Register an endpoint in Ajustes -> Conexión de tu sitio web -> Webhooks, choose which events it wants, and copy the signing secret (shown once). Every envelope carries the business it belongs to in business_id (the business's numeric id).
POST /your/hook HTTP/1.1
Content-Type: application/json
X-Cowisar-Event: invoice.paid
X-Cowisar-Delivery-Id: 8123
X-Cowisar-Signature: t=1758662400,v1=6f1c...e2
{ "id": 412, "type": "invoice.paid", "created_at": "2026-09-23T17:20:00.512Z",
"business_id": 123, "data": { "invoice_id": 912, "invoice_number": "F-000912",
"amount_cents": 76000, "currency": "DOP", "payment_provider": "partner_api",
"paid_at": "2026-09-23T17:20:00.501Z", "customer_uuid": "2f6b0f8a-6a1e-4b7e-9d0f-3a9c5e7b1c42" } }
A test delivery carries test: true at the envelope's top level; a real event omits the key entirely.
Delivery guarantee
Delivery is at least once, never exactly once. A delivery Cowisar could not confirm is retried in the background, and an operator can also replay one by hand, so the same event may arrive more than once with the SAME X-Cowisar-Delivery-Id. Treat that header as the deduplication key: if you already processed that id, answer 2xx again and do nothing. The signature timestamp lets you reject a stale replay. Retries follow a fixed schedule that starts one minute after a failure (see "Delivery, retries and the log" below), and an endpoint is never disabled automatically: an endpoint you disable stops receiving immediately.
Event catalog (v1)
| type | data |
|---|---|
ping | { endpoint_id } |
invoice.created | { invoice_id, invoice_number, total_cents, currency, client_id, customer_uuid } |
invoice.paid | { invoice_id, invoice_number, amount_cents, currency, payment_provider, paid_at, customer_uuid } |
invoice.refunded | { invoice_id, amount_cents, currency, refunded_at, customer_uuid } |
subscription.created | { subscription_id, product_id, client_id, amount_cents, currency, interval, next_charge_date, customer_uuid } |
subscription.renewed | { subscription_id, cycle_invoice_id, amount_cents, currency, period_start, period_end, customer_uuid } |
subscription.paused / subscription.resumed | { subscription_id, customer_uuid } |
subscription.cancelled | { subscription_id, cancelled_at, reason, customer_uuid } |
store_order.placed | { store_order_id, public_id, total_cents, currency, client_id, customer_uuid } |
store_order.paid | { store_order_id, public_id, total_cents, currency, client_id, customer_uuid, payment_provider } |
store_order.cancelled | { store_order_id, public_id, total_cents, currency, client_id, customer_uuid, reason } |
store_order.delivered | { store_order_id, public_id, total_cents, currency, client_id, customer_uuid } |
customer.created | { client_id, customer_uuid, name, phone, email } |
report.replied | { report_id, status, message: { id, sender_type, sender_name, content, created_at } } |
report.status_changed | { report_id, previous_status, status } |
Verify the signature
v1 is HMAC-SHA256(secret, "<t>.<raw body>"), hex, over the exact bytes you received. Compare in constant time and reject a t older than a few minutes. Parse the JSON only AFTER verifying the raw body.
import crypto from 'node:crypto';
export function verify(secret, header, rawBody, toleranceSeconds = 300) {
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
const t = Number(parts.t);
if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
const a = Buffer.from(expected, 'hex');
const b = Buffer.from(parts.v1 ?? '', 'hex');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
Delivery, retries and the log
- One delivery row per (event, endpoint).
2xx= delivered; anything else (or a timeout after 10s) is a failed attempt. - Failed attempts follow the schedule
1m, 5m, 30m, 2h, 12h: each rung waits that long after the failure before the next attempt. The whole schedule is used. The fifth failed attempt schedules the 12h rung, and the SIXTH failed attempt is the last one: the delivery is marked failed and nothing further is sent automatically. It stays in your delivery log, and a redeliver puts it back in flight. - An internal retry sits below that schedule: if an attempt could not be finished or recorded at all (a brief infrastructure hiccup, not an answer from your server), the same delivery is run again up to two more times, waiting 30 seconds and then 60 seconds, and only then does the rung above count. It never adds a rung and never shortens one.
- A disabled endpoint receives nothing. A delivery that is still pending when the endpoint is switched off is closed as failed with the reason
endpoint disabledand is not retried. Cowisar never disables an endpoint for you: a partner outage does not close an endpoint. - Delivery is at-least-once, not exactly-once. The same envelope (same
id) can arrive more than once. Dedupe on the envelopeidbefore applying anything, and answer2xxonce you have durably recorded it. - Emission is deduplicated by an internal key, so a retried business operation produces one event row.
- Emission is not transactional with the business write. The document or sale commits first; if enqueuing the event fails, the write still succeeds and only a warning is logged. Treat webhooks as notifications, not as a guarantee that a matching event exists for every change, and reconcile with the read endpoints when it matters.
9. Copy for LLM
This page is the canonical contract, served as HTML at https://api.cowisar.com/docs and as raw markdown at https://api.cowisar.com/docs/api.md. The "Copy for LLM" button copies this exact markdown so you can hand the whole contract to your AI assistant and build against it. llms.txt and llms-full.txt are also published at the host root.