Cowisar Partner API

Developer documentation

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 (422 DGII_REJECTED: correct it and resubmit). The code tells a machine which one; the reason tells 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; on 429, respect Retry-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>" }
  • code is the machine-readable identifier your integration should branch on. Every code is documented in section 3.7.
  • error is a short, generic English sentence for developers.
  • reason carries 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 happenedStatusBody
Business binding lookup failed404{ "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)429same TOO_MANY_REQUESTS body plus a Retry-After header
IP backstop rate limit (240/minute per IP)429same TOO_MANY_REQUESTS body plus a Retry-After header
Request exceeded the server timeout503{ "error": "Request timeout" }
Malformed JSON body400parser-shaped error (not the envelope)
Body too large413parser-shaped error (not the envelope)
Authentication lookup fault401/403the 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

OperationFirst callSame-key replayReused 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 create201 {success, estimate{id,estimateNumber}}200 same plus deduplicated:true409 same
Invoice duplicate200 {success, newInvoiceId}200 {success, newInvoiceId:<original duplicate id>, deduplicated:true}409
Estimate duplicate200 {success, estimate{id,estimateNumber}}200 same plus deduplicated:true409
Invoice edit (PUT /invoices/:invoiceId/edit)200 {success, invoice{...}}, or 202 deferred, or 422 fiscal failure200/202/422 same body (original outcome, no second write)409, nothing written
Credit-note / debit-note201 {success, note{...}, noteNumber}200 same stored body plus deduplicated:true (original outcome, no second write)409
Estimate convert-to-invoice200 {success, invoiceId, invoiceNumber}, or 202 {success, deferred, deferredReason, invoice{id, invoiceNumber, totalCents}} when the tax authority is unreachable (deferred outcome)200 same plus deduplicated:true409
convert-to-fiscal200 (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 key200/202 same stored body (original outcome, no second write); already fiscal: 400 ONLY_PROFORMA_CONVERTIBLE409
resubmit-fiscal200 or 422200 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 absent409, nothing written
cancel, restore, mark-applied, recover, rejectper-endpoint behavior belowSecond call returns the operation's OWN existing refusal (frozen per endpoint below; never claimed as replay-success)n/a
send200 {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:

FieldWhereUnit
items[].unitPricerequest (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.
discountrequest (documents)currency units ONLY when discountType = "fixed"; otherwise a percentage value
items[].taxRaterequest (documents)percentage, 0 to 100
items[].itbis_retention_rate, items[].isr_retention_raterequest (invoice edit lines)fraction from 0 to 1 (0.30 means 30%)
subtotal, taxAmount, total, amountPaid, amountDue, item prices, payment amounts, refund amountsresponse detail and edit bodiesdisplay currency units
the same values with a Cents suffix (totalCents, amountDueCents, and so on)response detail and edit bodiesinteger cents, ALONGSIDE the display-unit fields above
total, amountDueresponse list rowsdisplay currency units
note.totalcreate credit/debit note responsedisplay currency units
priceCents (products), totalCents (sales receipt), webhook *_cents (amount_cents, total_cents), costCents/balanceCents (blocked-send metadata)intake responses and webhooksinteger cents
issueDate, dueDate, validUntilrequest and responsecalendar date YYYY-MM-DD
created_at, paid_at, refunded_at and other metadata timestampsresponseISO-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 groupRequired scopes
All GETs: invoice list/detail/pdf, estimate list/detail/pdf, foreign payment list/detail, products, customers lookup, subscription lookup, report detail and threadread
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, restorewrite
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-notefiscal
Invoice cancel, mark-appliedmoney
Invoice and estimate sendsend
Estimate create, update, delete, duplicate, recover, rejectwrite
Estimate convert-to-invoicewrite, plus fiscal when the body's invoiceType is a non-proforma type
Foreign payment create (POST /foreign-payments)fiscal
POST /customerswrite
POST /saleswrite and money
POST /subscriptions and pause / resume / cancelsubscriptions
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:

CodeStatusWhen
SERVICE_AUTH_MISSING401the x-service-token header is absent
SERVICE_AUTH_INVALID401the key is unknown, inactive, its member left the business, or the member's api permission resolved to none
SERVICE_TOKEN_BUSINESS_MISMATCH403?businessId= names a different business than the key's
SERVICE_SCOPE_MISSING403the key lacks a scope the endpoint requires (requiredScopes lists them)
INVALID_SCOPES400a key was created with an unknown, empty or duplicated scope
INVALID_KEY_FORMAT400a key with an invalid format
KEY_EXISTS409the member already has a key for this business

Request validation:

CodeStatusWhen
INVALID_INPUT400malformed or missing parameter or body field without a more specific code
UNKNOWN_FIELD400the body carries a field the endpoint does not accept (field, and itemIndex for item fields)
IDEMPOTENCY_KEY_INVALID400the Idempotency-Key header is missing, empty, repeated, or longer than 64 characters
IDEMPOTENCY_KEY_IN_PROGRESS409the same edit is still running under this key; a retry after it finishes replays the stored outcome
IDEMPOTENCY_KEY_REUSED409the key was already used for a different operation or source document
ITEMS_REQUIRED400a document or note was sent without items
INVALID_ITEM400an item is malformed (estimate per-line discounts other than zero are refused here)
INVALID_ITEMS400the items array refers to unknown or foreign products
INVALID_CLIENT400the client reference is malformed
INVALID_TAX_ID400a typed client's tax id fails the country's validation; the document is refused and nothing is written
INVALID_NAME400a typed client's name is unusable (an individual needs at least two words)
INVALID_PHONE400a typed client's phone is not a valid international number
INVALID_EMAIL400a typed client's email is malformed
DUPLICATE_NAME409a client with that name already exists under a DIFFERENT tax id; send the saved clientId instead
DUPLICATE_TAX_ID409a client with that tax id already exists and could not be linked; send the saved clientId instead
INVALID_TAX_RATE400a taxRate outside 0 to 100, or a per-line retention rate outside the fraction range 0 to 1
INVALID_EXCHANGE_RATE400the exchange rate is not a positive number below 1000
INVALID_CURRENCY400the currency is not one of the system's currencies
INVALID_FISCAL_SEQUENCE400fiscalSequenceType is not a known e-CF sequence
INVALID_REFERENCE400a productId or clientId belongs to another business
INVALID_BODY400a body field is malformed (for example a sellerId that is not a positive integer or null)
INVALID_FORMAT400a value is malformed in a way the service reports as a format refusal (estimate doors)
INVALID_STATE400/422the resource is not in a state that allows the operation (estimate doors answer 400)
INVALID_SUPPLIER_ID400the supplier id is not a positive integer
INVALID_COUNTRY_CODE400The supplier country must be an ISO 3166-1 numeric code, three digits.
SUPPLIER_REQUIRED400/422a 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_ID400the branch id is not valid
BRANCH_NOT_FOUND404the branch id does not belong to this business

Business rules:

CodeStatusWhen
INVOICE_LIMIT_REACHED403the business's invoice quota is exhausted
ESTIMATE_LIMIT_REACHED403the business's estimate quota is exhausted
CREDIT_LIMIT_EXCEEDED409the client's credit limit would be exceeded (send skipCreditCheck to bypass; see section 5)
CREDIT_REFERENCE_LINE_REQUIRED400a partial credit-note line names no referenceInvoiceItemId (a full annulment needs none)
CREDIT_REQUIRES_CLIENT400a credit sale was requested without a resolvable client
CLIENT_INACTIVE400the client is inactive
FISCAL_COMPLIANCE_INCOMPLETE409the business's fiscal configuration is incomplete
FISCAL_NOT_EDITABLE409a fiscal document refuses this content edit
PAID_NOT_EDITABLE409the document already has a recorded payment, so its content cannot be edited
STATUS_NOT_EDITABLE409the document's state no longer allows content edits (cancelled, void, refunded, disputed, applied or failed)
INVOICE_DELETE_BLOCKED_LINKED400another 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_DELETABLE400the document carries no deletable state: it already has a fiscal number or a fiscal document id, or it was already converted to fiscal
PAYMENT_PROCESSED400the document has a payment processed by a provider (Stripe, PayPal); use that provider's refund or cancel flow
INVOICE_NOT_CANCELLABLE400the invoice's status cannot be cancelled
ONLY_PROFORMA_CONVERTIBLE400convert-to-fiscal was attempted on a document that is not a proforma
ESTIMATE_NOT_CONVERTIBLE400the estimate cannot be converted (already converted, or not in a convertible state)
OPERATION_NOT_ALLOWED400the operation is not allowed for this estimate (converted delete, item edit in its state)
NOTE_REQUIRES_FISCAL_EVIDENCE400a 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_REJECTED409resubmit-fiscal was attempted on an invoice that is not in a rejected state
RETRY_LOCKED409resubmit-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_BLOCKED409create 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_FOUND409the reissue source is not in this business
DUPLICATE_PAYMENT_REFERENCE409the sale's payment reference was already recorded
PAYMENT_REFUND_PENDING202The payment was captured and its refund is pending; the invoice is not settled.
PAYMENT_SETTLEMENT_FAILED500The payment could not be recorded against the invoice.
INSUFFICIENT_CREDITS402the business's messaging wallet cannot pay for the send
FISCAL_REJECTED403a genuine tax-authority rejection blocks the operation
FEATURE_UNAVAILABLE423the business has the support lane off (report endpoints)
TEST_BUSINESS_COMMERCE_BLOCKED403a test business refuses commercial operations
CUSTOMER_NOT_FOUND404the customer does not exist for this business
REPORT_NOT_FOUND404the report does not exist for this business (or was not filed through the API)
SUBSCRIPTION_CANCELLED409the subscription is already cancelled
TICKET_CLOSED409the report is closed and refuses new messages

Fiscal transitions:

CodeStatusWhen
DGII_REJECTED422the tax authority rejected the e-CF; its text rides in reason
PRESEND_BLOCKED422our 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_FAILED422a fiscal failure without a machine code; the provider's text rides in reason (the error field always carries the generic sentence)
BUSINESS_INCOMPLETE422the business profile is incomplete for this fiscal operation; the detail rides in reason
MISSING_CLIENT_RNC422a buyer tax id is required for this document type
E32_GTE_MISSING_RNC422a consumer e-CF above the threshold requires the buyer tax id
MISSING_EXCHANGE_RATE422an exchange rate is required for a foreign-currency document
FISCAL_NOT_CONFIGURED422the fiscal configuration is incomplete for this document
FISCAL_NOT_REQUIRED422the document does not require fiscal issuance
DGII_UNAVAILABLE422fiscal 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_EXHAUSTED422the fiscal sequence is exhausted; request a new range
NOT_CERTIFIED422the business is not certified for fiscal issuance yet
ACCEPTED_PROFORMA_UNCONVERTED422DGII accepted the reissue but the invoice type needs a manual review; contact support with the invoice number
MISSING_PURCHASE_BUYER_RNC422the supplier for this purchase must have a registered tax ID (RNC)
CONTENT_CORRECTION_REQUIRED422create a new corrected document instead of resubmitting this one
NOT_RETRYABLE_CAUSE422this document cannot be resubmitted; follow the guidance shown for its cause

Signing lane (a document that a linked device must sign):

CodeStatusWhen
SIGNING_AGENT_OFFLINE422the device that signs this business's documents is not reachable now; the document was not sent to the tax authority
SIGNING_STATE_UNAVAILABLE422the signing state could not be read, so the document was not sent; retry once the signing service answers
SIGNING_REQUEST_QUEUED422the document waits for a signature before it can be sent; a live request exists for it
SIGNING_DEVICE_NOT_LINKED422the signing device is not linked to this business, so it cannot sign for it
SIGNING_UNKNOWN_TERMINAL422the signing service ended with a failure this integration does not recognise, so the document was not sent; retry or contact support

Concurrency:

CodeStatusWhen
INVOICE_DUPLICATE200/409a concurrent same-key create raced; resolved to the replay or to 409 IDEMPOTENCY_KEY_REUSED
ESTIMATE_DUPLICATE200/409the same race resolution for estimate creates

Platform and generic:

CodeStatusWhen
BUSINESS_NOT_FOUND404the business binding could not be resolved (platform layer)
TOO_MANY_REQUESTS429a rate limit refused the call (platform layer)
NOT_FOUND404the resource does not exist or does not belong to this business
INTERNAL_ERROR500an 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 (requires Idempotency-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 (requires Idempotency-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 requires Idempotency-Key): answer { success, subscriptionId, status }.
  • POST /api/v1/partner/reports (requires Idempotency-Key): 201 { success, ticketId, status: "open", deduplicated: false }; a replay answers 200 with deduplicated: 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 (requires Idempotency-Key): 201 { success, messageId, deduplicated: false }; a replay answers 200 with deduplicated: true. The append posts as the key's owner (senderType: "api"); a closed report answers 409 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 + pathreturns
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 /keysbody { 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/rotateowner 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/deactivate200 { 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 /endpoints201 { endpoint, secret } once (400 INVALID_URL / 400 INVALID_ENABLED_EVENTS)
PATCH /endpoints/:id200 { endpoint } (400 NO_FIELDS, 404 ENDPOINT_NOT_FOUND)
DELETE /endpoints/:id200 { deleted: true }
GET /event-samples{ headers, events }: one sample envelope per catalog event
POST /endpoints/:id/test202 { 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/redeliver200 { 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:

FieldWhereSemantics
skipCreditCheckinvoice createtrue 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.
skipAutoPaymentinvoice createWithout 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).
kitchenOrderinvoice createtrue 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.
sellerIdinvoice create/editPositive integer: attributes the document to a seller of this business (commission). A seller of another business answers 404. null or "" clears the attribution.
insuranceCompany, insurancePolicyinvoice createFree-text insurance attribution stored on the document and used by the insurance reports.
recurrenceinvoice createObject { 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:

CodeNCF className
E31B01Fiscal credit invoice
E32B02Consumer invoice
E33B03Debit note
E34B04Credit note
E41B11Purchase invoice
E43B13Minor expenses receipt
E44B14Special regimes receipt
E45B15Government receipt
E46B16Export invoice
E47B17Foreign 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:

FieldRequiredNotes
supplierNameyesstring, up to 255 characters
supplierIdTypeno"1" or "2"
supplierTaxIdnostring, up to 20 characters (the supplier's foreign id)
supplierCountryyesISO 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)
serviceTypeyes"1" to "8" (the 609 service-type code)
serviceDetailnoa code valid for the chosen serviceType
isRelatedPartynoboolean, default false
documentNumbernostring, up to 50 characters (identified together with the provider record; two providers may reuse the same number)
paymentDateyescalendar date YYYY-MM-DD
amountCentsyespositive integer cents (the exempt total)
currencynoISO code, default the business's document currency
exchangeRatenopositive number below 1000
presumedIncomeCentsnonon-negative integer cents, derived when absent
isrWithheldCentsnonon-negative integer cents; when absent it is derived from the provider record's ISR rate (zero when the record carries no rate)
retentionDatenocalendar date YYYY-MM-DD, or null
clientNamenostring; the client name shown on the E47 document, defaulting to the provider record's name (the 609 payee always comes from supplierId)
clientTaxIdnostring; a foreign id the provider emits as IdentificadorExtranjero
supplierIdyespositive integer: the provider record the payee snapshot is taken from
items[]noline 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.

StatuscodeWhen
400INVALID_INPUTa country or service type outside the vocabulary, or another malformed field
400UNKNOWN_FIELDthe body carries a field the contract does not define
400INVALID_ITEMSthe items[] amounts do not sum to amountCents, or a line is malformed
404NOT_FOUNDthe requested payment id does not exist for this business
409DUPLICATE_PAYMENT_REFERENCEa filing already exists for this provider record and documentNumber, or another filing for that pair is being created right now
409IDEMPOTENCY_KEY_REUSEDthe same key was reused with a different body
422FISCAL_NOT_CONFIGUREDthe business's fiscal configuration is incomplete for this document
422SEQUENCE_EXHAUSTEDthe E47 fiscal sequence is exhausted; request a new range
422DGII_UNAVAILABLEfiscal processing could not be completed; the payment is recorded and the document is retried
400SUPPLIER_REQUIREDno usable supplierId in the body for the provider record
409RETENTION_MISMATCHthe sent ISR amount disagrees with the ISR the E47 froze at the provider record's rate
400MISSING_EXCHANGE_RATEa 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):

alpha2numericnameEn
AF004AF
AX248AX
AL008AL
DZ012DZ
AS016AS
AD020AD
AO024AO
AI660AI
AQ010AQ
AG028AG
AR032AR
AM051AM
AW533AW
AU036AU
AT040AT
AZ031AZ
BS044BS
BH048BH
BD050BD
BB052BB
BY112BY
BE056BE
BZ084BZ
BJ204BJ
BM060BM
BT064BT
BO068BO
BQ535BQ
BA070BA
BW072BW
BV074BV
BR076Brazil
IO086IO
BN096BN
BG100BG
BF854BF
BI108BI
CV132CV
KH116KH
CM120CM
CA124Canada
KY136KY
CF140CF
TD148TD
CL152CL
CN156China
CX162CX
CC166CC
CO170Colombia
KM174KM
CG178CG
CD180CD
CK184CK
CR188CR
CI384CI
HR191HR
CU192CU
CW531CW
CY196CY
CZ203CZ
DK208DK
DJ262DJ
DM212DM
DO214DO
EC218EC
EG818EG
SV222SV
GQ226GQ
ER232ER
EE233EE
SZ748SZ
ET231ET
FK238FK
FO234FO
FJ242FJ
FI246FI
FR250France
GF254GF
PF258PF
TF260TF
GA266GA
GM270GM
GE268GE
DE276Germany
GH288GH
GI292GI
GR300GR
GL304GL
GD308GD
GP312GP
GU316GU
GT320GT
GG831GG
GN324GN
GW624GW
GY328GY
HT332HT
HM334HM
VA336VA
HN340HN
HK344HK
HU348HU
IS352IS
IN356IN
ID360ID
IR364IR
IQ368IQ
IE372IE
IM833IM
IL376IL
IT380Italy
JM388JM
JP392JP
JE832JE
JO400JO
KZ398KZ
KE404KE
KI296KI
KP408KP
KR410KR
KW414KW
KG417KG
LA418LA
LV428LV
LB422LB
LS426LS
LR430LR
LY434LY
LI438LI
LT440LT
LU442LU
MO446MO
MG450MG
MW454MW
MY458MY
MV462MV
ML466ML
MT470MT
MH584MH
MQ474MQ
MR478MR
MU480MU
YT175YT
MX484Mexico
FM583FM
MD498MD
MC492MC
MN496MN
ME499ME
MS500MS
MA504MA
MZ508MZ
MM104MM
MK807MK
NA516NA
NR520NR
NP524NP
NL528NL
NC540NC
NZ554NZ
NI558NI
NE562NE
NG566NG
NU570NU
NF574NF
MP580MP
NO578NO
OM512OM
PK586PK
PW585PW
PS275PS
PA591Panama
PG598PG
PY600PY
PE604PE
PH608PH
PN612PN
PL616PL
PT620PT
PR630PR
QA634QA
RE638RE
RO642RO
RU643RU
RW646RW
BL652BL
SH654SH
KN659KN
LC662LC
MF663MF
PM666PM
VC670VC
WS882WS
SM674SM
ST678ST
SA682SA
SN686SN
RS688RS
SC690SC
SL694SL
SG702SG
SX534SX
SK703SK
SI705SI
SB090SB
SO706SO
ZA710ZA
GS239GS
SS728SS
ES724Spain
LK144LK
SD729SD
SR740SR
SJ744SJ
SE752SE
CH756CH
SY760SY
TW158TW
TJ762TJ
TZ834TZ
TH764TH
TL626TL
TG768TG
TK772TK
TO776TO
TT780TT
TN788TN
TR792TR
TM795TM
TC796TC
TV798TV
UG800UG
UA804UA
AE784AE
GB826United Kingdom
US840United States
UM581UM
UY858UY
UZ860UZ
VU548VU
VE862VE
VN704VN
VG092VG
VI850VI
WF876WF
EH732EH
YE887YE
ZM894ZM
ZW716ZW

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)

typedata
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 disabled and 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 envelope id before applying anything, and answer 2xx once 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.