# Corvo API documentation

> REST API and MCP server to issue Brazilian service invoices (NFS-e) for MEI and Simples Nacional companies.

Base URL: https://api.corvo.tech/v1 · MCP: https://api.corvo.tech/mcp · Site: https://www.corvo.tech/en

---

## Introduction

Issue Brazilian NFS-e for MEI and Simples Nacional companies with a REST API or an AI agent (MCP): tax calculation, multiple companies and webhooks.

The Corvo API lets you register companies (MEI and Simples Nacional), upload A1 certificates, calculate taxes before issuing, issue service invoices (NFS-e) and track their full lifecycle via webhooks. AI agents such as Claude Code, Cursor and Codex can do the same through the MCP server (see AI agents).

### Quickstart

From signup to your first invoice, in the test environment. In test no certificate is needed; production needs a `corvo_live_` key and an A1 certificate.

- Create a free account at https://www.corvo.tech/login?mode=signup (no credit card).
- In the dashboard, create a test key. It starts with `corvo_test_`; invoices issued with it have no fiscal value.
- Register the issuer company with `POST /v1/companies` (`legalName`, `taxId`, `taxRegime` and `municipalityCode` are required).
- Issue the invoice with `POST /v1/invoices`. The answer is `202` with status `queued`: issuance is asynchronous.
- Track it with `GET /v1/invoices/:id` or receive the `nfse.invoice.authorized` / `nfse.invoice.rejected` webhook.
- Go to production: create a `corvo_live_` key and upload the company's A1 certificate, through the dashboard or the API (`POST /v1/companies/:companyId/certificates`).

```bash
export BASE_URL='https://api.corvo.tech/v1'
export CORVO_API_KEY='corvo_test_your_key'

# 3. Register the company
curl -X POST "$BASE_URL/companies" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"legalName":"Example Company Ltda","taxId":"11222333000181","taxRegime":"MEI","municipalityCode":"3550308"}'

# 4. Issue the invoice (202, status queued)
curl -X POST "$BASE_URL/invoices" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: pedido_123_emissao' \
  -d '{"companyTaxId":"11222333000181","amount":100,"service":{"description":"Consulting"}}'

# 5. Track it
curl "$BASE_URL/invoices/<id>" -H "X-API-Key: $CORVO_API_KEY
```

All paths in this documentation are relative to `BASE_URL` (`https://api.corvo.tech/v1`).

### Response formats

REST successes use `{ "data": ... }` and listings add `pagination`. JSON dates are ISO 8601 strings; optional fields may be absent and nullable fields may be `null`.

| Operation | JSON format |
| --- | --- |
| Create, fetch or update a company | `{ "data": Company }` |
| List companies | `{ "data": Company[], "pagination": {...} }` |
| Delete a company | `{ "data": null }` |
| Certificate upload / listing | `{ "data": Certificate } / paginated listing` |
| Issue / fetch an invoice | `{ "data": Invoice }` |
| List invoices and events | `{ "data": [ ... ], "pagination": {...} }` |
| Download URL / email | `{ "data": ... }` |
| Webhooks and deliveries | `{ "data": ... } or paginated listing` |
| Plan & quotas | `{ "data": ... }` |

Resources come directly inside `data`: an invoice is `data`, a list is `data[]`. Read `data` exactly once. PDF/XML, redirects, OAuth, MCP/JSON-RPC, health checks and `204` responses keep their own formats.

### All operations

All paths below include the default prefix. Status codes represent success according to the HTTP contract matrix; errors follow the `ERROR_*` format described under Errors.

| Method | Path | Function | Success |
| --- | --- | --- | --- |
| POST | `/v1/companies` | Register a company | 201 |
| GET | `/v1/companies` | List companies | 200 |
| GET | `/v1/companies/:id` | Fetch a company | 200 |
| PATCH | `/v1/companies/:id` | Update a company | 200 |
| DELETE | `/v1/companies/:id` | Delete a company | 200 |
| POST | `/v1/companies/:companyId/certificates` | Upload a certificate | 201 |
| GET | `/v1/companies/:companyId/certificates` | List certificates | 200 |
| DELETE | `/v1/companies/:companyId/certificates/:certId` | Revoke a certificate | 204 |
| POST | `/v1/invoices` | Request issuance | 202 |
| POST | `/v1/invoices/batches` | Request issuance of up to 50 invoices | 202 |
| POST | `/v1/invoices/calculate` | Calculate taxes without issuing | 200 |
| GET | `/v1/invoices` | List invoices | 200 |
| GET | `/v1/invoices/:id` | Fetch an invoice | 200 |
| GET | `/v1/invoices/:id/xml` | Download XML | 200 |
| GET | `/v1/invoices/:id/pdf` | Download PDF | 200 |
| GET | `/v1/invoices/:id/events` | Fetch event history | 200 |
| POST | `/v1/invoices/:id/download-url` | Generate a signed URL | 200 |
| POST | `/v1/invoices/:id/email` | Request email delivery | 202 |
| POST | `/v1/invoices/:id/cancel` | Cancel an invoice | 200/202 |
| GET | `/v1/webhooks` | List webhook configurations | 200 |
| POST | `/v1/webhooks` | Register a webhook | 201 |
| DELETE | `/v1/webhooks/:id` | Delete a webhook | 200 |
| POST | `/v1/webhooks/:id/test` | Send a test event | 200 |
| GET | `/v1/webhooks/deliveries` | List deliveries | 200 |
| GET | `/v1/webhooks/deliveries/stats` | Fetch delivery statistics | 200 |
| POST | `/v1/webhooks/deliveries/:id/retry` | Schedule a retry | 200 |
| POST | `/v1/invoices/:id/substitute` | Substitute an authorized invoice | 202 |
| GET | `/v1/customers` | List saved customers | 200 |
| GET | `/v1/customers/:taxId` | Get a saved customer | 200 |
| PATCH | `/v1/customers/:taxId` | Correct a saved customer | 200 |
| DELETE | `/v1/customers/:taxId` | Forget a saved customer | 200 |
| GET | `/v1/schedules` | List schedules and recurrences | 200 |
| GET | `/v1/schedules/:id` | Get a schedule | 200 |
| GET | `/v1/schedules/:id/runs` | Run history of a schedule | 200 |
| PATCH | `/v1/schedules/:id` | Change a schedule | 200 |
| POST | `/v1/schedules/:id/pause` | Pause a schedule | 200 |
| POST | `/v1/schedules/:id/resume` | Resume a schedule | 200 |
| POST | `/v1/schedules/:id/cancel` | Cancel a schedule | 200 |
| GET | `/v1/billing/plan` | Fetch plan and consumption | 200 |
| GET | `/v1/billing/usage` | Fetch availability and quotas | 200 |
| POST | `/v1/billing/upgrade` | Schedule a plan change | 200 |
| POST | `/v1/billing/downgrade` | Schedule a plan change | 200 |
| GET | `/v1/plans` | List plan prices (public) | 200 |
| GET | `/v1/plans/:slug` | Fetch one plan price (public) | 200 |
| GET | `/v1/plans/recommend` | Recommend the cheapest way to cover N notes a month (public) | 200 |

IDs in paths represent identifiers of resources returned by the API. Store them as strings; do not use a CNPJ in place of a `:id`.

### Integration sequence

- `POST /v1/companies` — register the company with its CNPJ, tax regime and fiscal municipality (`municipalityCode`); set `defaultServiceCode` to simplify invoices.
- In `live`, upload a valid A1 certificate (.p12) matching the CNPJ, with its password (`POST /v1/companies/:companyId/certificates`). The municipal registration is optional: provide it only if the city registered the company in the national registry.
- `POST /v1/invoices` — use `companyTaxId` (company CNPJ) to request issuance (the `live` environment requires the company to be ready).
- Track the lifecycle with `GET /v1/invoices/:id` and webhooks — issuance is asynchronous.

---

## Frequently asked questions

### Does Corvo cover my company's municipality?

Corvo issues through the NFS-e national environment, run by the Receita Federal. The municipalities already on the national standard are listed in the documentation, searchable by name, state or IBGE code. Being on the list does not guarantee that every invoice is accepted: the Receita decides. [See the list of municipalities](https://www.corvo.tech/en/docs/municipalities)

### Does Corvo issue the invoice for me?

Yes. You send the sale data through the API, or through a payment integration, and Corvo builds the invoice, signs it with the company's A1 certificate (not needed in test), sends it to the Receita and returns the result. If you want, it also emails the PDF and XML to your customer. Today Corvo serves MEI and Simples Nacional companies. [Read the getting-started guide](https://www.corvo.tech/en/docs)

### Can I issue invoices for more than one CNPJ on Corvo?

Yes. The recurring plans (Solo, Equipe, Empresa and Escala) have unlimited companies, each with its own certificate and its own usage, without building a new integration for each one. With single invoices only, no plan, the account has 1 company. [See the plans](https://www.corvo.tech/en)

### Which payment platforms does Corvo integrate with?

Corvo integrates with Woovi and AbacatePay. Once connected, every approved payment becomes an NFS-e automatically, with no code. If there is a refund, the invoice can be cancelled on its own, if you turn that option on. [See how to connect](https://www.corvo.tech/en/docs/payment-integrations)

### Does Corvo have an SDK for my language or an MCP server for AI agents?

Yes. Corvo has official SDKs for Node.js, Python, Go, PHP, Ruby, Rust, Java, Elixir and .NET, with the same operations in all of them, and you can also call the REST API directly. For AI agents, Corvo has an MCP server: Claude Code, Cursor, Codex, VS Code, Windsurf and Claude Desktop connect with a browser login, and you pick the workspace and the environment (test or live) on the approval screen. [See the SDKs](https://www.corvo.tech/en/docs/sdks) [See the MCP server](https://www.corvo.tech/en/docs/mcp)

### Is Corvo open source? Can I run it myself?

Yes. The API, the worker and the dashboard are public on GitHub under AGPL-3.0. You can read the code, run it on your own servers with Docker Compose, and send issues and pull requests. The hosted service at corvo.tech runs the same project, with the A1 certificates, the data and the billing handled for you. [See the code on GitHub](https://github.com/corvo-technology/corvo-nfse)

---

## SDKs

Official libraries for Node.js, Python, Go, PHP, Ruby, Rust, Java, Elixir and .NET.

Corvo has official SDKs in nine languages. They call the same API this documentation describes, with the same operations, field names and tax rules, so every guide here applies to all of them.

### Install

| Language | Package | Install | Source |
| --- | --- | --- | --- |
| Node.js / TypeScript | `corvo-nfse-node` (npm) | `npm install corvo-nfse-node` | `corvo-technology/corvo-nfse-node` |
| Python | `corvo-nfse` (PyPI) | `pip install corvo-nfse` | `corvo-technology/corvo-nfse-python` |
| Go | `github.com/corvo-technology/corvo-nfse-go` (Go modules) | `go get github.com/corvo-technology/corvo-nfse-go` | `corvo-technology/corvo-nfse-go` |
| PHP | `corvo-technology/corvo-nfse` (Packagist) | `composer require corvo-technology/corvo-nfse` | `corvo-technology/corvo-nfse-php` |
| Ruby | `corvo-nfse` (RubyGems) | `gem install corvo-nfse` | `corvo-technology/corvo-nfse-ruby` |
| Rust | `corvo-nfse` (crates.io) | `cargo add corvo-nfse` | `corvo-technology/corvo-nfse-rust` |
| Java | `tech.corvo:corvo-nfse` (Maven Central) | `implementation("tech.corvo:corvo-nfse:0.1.1")` | `corvo-technology/corvo-nfse-java` |
| Elixir | `corvo_nfse` (Hex) | `{:corvo_nfse, "~> 0.1.1"}` | `corvo-technology/corvo-nfse-elixir` |
| .NET | `Corvo.Nfse` (NuGet) | `dotnet add package Corvo.Nfse` | `corvo-technology/corvo-nfse-dotnet` |

> Start with a test key: invoices issued with a `corvo_test_` key have no fiscal value.

### What every SDK does

- Authenticates with `X-API-Key`. It reads `CORVO_API_KEY`, and `CORVO_BASE_URL` if you use a different API URL.
- The key decides the environment: `corvo_test_...` for test and `corvo_live_...` for live.
- Errors come back as a typed result with `code`, `status`, `requestId`, `details` and `retryAfter`, not as an exception. The iterate helpers raise when a page fails.
- Lists are cursor-paginated, and every SDK has an iterate helper that walks all pages.
- Creating an invoice and sending an email accept an idempotency key, sent as `Idempotency-Key`.
- Webhook signature verification (`X-Corvo-Signature`) in constant time.

### Issue an invoice

The same call in each language. Each example reads the key from `CORVO_API_KEY` and passes an idempotency key, so repeating the call never issues the invoice twice.

```js
import { Corvo } from "corvo-nfse-node";

const corvo = new Corvo(); // reads CORVO_API_KEY

const { data: invoice, error } = await corvo.invoices.create(
  {
    companyTaxId: "11222333000181",
    service: { description: "Consultoria" },
    amount: 450,
    competenceDate: "2026-10-16",
  },
  { idempotencyKey: "order-42" },
);
```

```text
from corvo_nfse import Corvo

async with Corvo() as corvo:  # reads CORVO_API_KEY
    invoice, error = await corvo.invoices.create(
        {
            "companyTaxId": "11222333000181",
            "service": {"description": "Consultoria"},
            "amount": 450,
            "competenceDate": "2026-10-16",
        },
        idempotency_key="order-42",
    )
```

```text
client := corvonfse.NewClient(corvonfse.Options{}) // reads CORVO_API_KEY

invoice, err := client.Invoices.Create(ctx, corvonfse.InvoiceCreateParams{
	CompanyTaxID:   "11222333000181",
	Service:        corvonfse.InvoiceServiceInput{Description: "Consultoria"},
	Amount:         450,
	CompetenceDate: "2026-10-16",
}, "order-42")
```

```text
$corvo = new \CorvoNfse\Client(); // reads CORVO_API_KEY

$result = $corvo->invoices->create([
    'companyTaxId' => '11222333000181',
    'service' => ['description' => 'Consultoria'],
    'amount' => 450,
    'competenceDate' => '2026-10-16',
], idempotencyKey: 'order-42');
```

```text
client = CorvoNfse::Client.new # reads CORVO_API_KEY

invoice, error = client.invoices.create(
  {
    companyTaxId: "11222333000181",
    service: { description: "Consultoria" },
    amount: 450,
    competenceDate: "2026-10-16"
  },
  idempotency_key: "order-42"
)
```

```text
let corvo = Corvo::from_env()?; // reads CORVO_API_KEY

let invoice = corvo
    .invoices()
    .create(
        &InvoiceCreateParams {
            company_tax_id: Some("11222333000181".into()),
            service: InvoiceServiceInput {
                description: Some("Consultoria".into()),
                ..Default::default()
            },
            amount: 450.0,
            competence_date: "2026-10-16".into(),
            ..Default::default()
        },
        Some("order-42"),
    )
    .await?;
```

```text
Corvo corvo = Corvo.builder().build(); // reads CORVO_API_KEY

InvoiceCreateParams params = InvoiceCreateParams.of(
        null,
        InvoiceCreateParams.Service.ofDescription("Consultoria"),
        450.0,
        "2026-10-16")
    .withCompanyTaxId("11222333000181");

Result<Invoice> invoice = corvo.invoices().create(params, "order-42").join();
```

```text
client = CorvoNfse.new() # reads CORVO_API_KEY

{:ok, invoice} =
  CorvoNfse.Resources.Invoices.create(
    client,
    %{
      "companyTaxId" => "11222333000181",
      "service" => %{"description" => "Consultoria"},
      "amount" => 450,
      "competenceDate" => "2026-10-16"
    },
    idempotency_key: "order-42"
  )
```

```text
using var client = new CorvoClient(); // reads CORVO_API_KEY

var invoice = await client.Invoices.CreateAsync(
    new InvoiceCreateParams
    {
        CompanyTaxId = "11222333000181",
        Service = new InvoiceServiceInput { Description = "Consultoria" },
        Amount = 450m,
        CompetenceDate = "2026-10-16",
    },
    idempotencyKey: "order-42");
```

Changing plans and the billing portal exist only in the dashboard, so they are not in the SDKs. The source of every SDK is in github.com/corvo-technology.

Source: https://www.corvo.tech/en/docs/sdks

---

## Authentication

Authenticate every request with an API key.

Keys have the format `corvo_test_` or `corvo_live_` followed by 40 lowercase hexadecimal characters.

> The full key is displayed only at creation.

### Headers

| Header | Usage |
| --- | --- |
| `X-API-Key` | Required for key authentication. |
| `Content-Type: application/json` | JSON bodies. |
| `Idempotency-Key` | Optional on issuance and email requests; recommended for safe retries of those operations. |

Certificate upload uses `multipart/form-data`. With `curl -F`, let curl generate the `Content-Type` with the boundary. Downloads return PDF or XML with no JSON envelope.

### Environments

- Companies, certificates and invoices are accessed in the key's persisted environment: `test` or `live`.
- In `live`, issuance verifies the company, blocks and active certificate; credits and issuance limits also apply.
- In `test`, issuance requires an existing company but skips the readiness and certificate checks of the `live` flow.
- Webhook deliveries use the explicit `?environment=test|live` filter; without it, they may return both of the account's environments, regardless of the key's environment.

> Credits, plan and webhook settings belong to the account. A `test` key with `full_access` can manage webhooks and read credits and billing. Plan changes, checkout and the billing portal exist only in the dashboard.

> The server resolves the account from authentication; resources of another account return `404`.

### Scopes

| Code used in this reference | Scope |
| --- | --- |
| F | `full_access` |
| I | `invoices_issue` |
| V | `invoices_view` |
| RW | `invoices_read_write` |

F accepts every operation listed. I allows issuing and requesting email. V allows fetching invoices, documents, events and download URLs. RW combines invoice issuance and fetching, company fetching, certificate listing, and fetching of webhooks/deliveries/statistics. RW does not allow modifying companies, certificates, webhooks, credits or plans. Even F only reaches API-key-enabled routes; scope permissions do not open other routes.

### Example

```bash
export BASE_URL='https://api.corvo.tech/v1'
export CORVO_API_KEY='corvo_test_your_key'

curl "$BASE_URL/companies" -H "X-API-Key: $CORVO_API_KEY"
```

Source: https://www.corvo.tech/en/docs/authentication

---

## Errors

Error body, `ERROR_*` codes, status codes and retry guidance.

Fields not declared in the DTOs are rejected, including inside nested objects. Every REST failure uses the same body; there is no separate `error` field anymore.

### Error format

```json
{
  "statusCode": 400,
  "code": "ERROR_VALIDATION",
  "message": "Request validation failed",
  "details": [
    {
      "field": "customer.taxId",
      "code": "ERROR_INVALID_TAX_ID",
      "message": "Invalid tax ID"
    }
  ],
  "requestId": "9f1fc995-4ee4-4a92-b285-cf8dff227a97"
}
```

Decide by `code` and HTTP status. `message` is always an English string (never an array) meant for diagnostics. `details` is optional: for validation it is an array of `{ field, code, message }`; for application errors it holds typed public objects. `requestId` matches the `X-Request-Id` header and can be quoted to support. `5xx` failures use sanitized messages with no internal details.

> Errors on PDF/XML downloads follow this contract too. Redirects, OAuth, MCP/JSON-RPC, health checks and `204` responses keep their own formats.

### HTTP status codes

| HTTP | Usage |
| --- | --- |
| 200 / 201 / 202 | Action completed / resource created / asynchronous processing accepted. |
| 204 | Operation completed with no body. |
| 400 | Invalid DTO, parameter, JSON, UUID, `limit` or cursor. |
| 401 / 403 | Missing or invalid authentication / access denied (scope, endpoint not enabled for API keys, blocked company). |
| 404 | Resource not found, including resources of another tenant. |
| 409 / 410 | Conflict (duplicate CNPJ, idempotency conflict, documents not ready yet) / resource retired. |
| 413 / 415 | Payload too large / unsupported encoding. |
| 422 | Fiscal validation in the domain or a rejected business rule (readiness, certificate, quota). |
| 429 | Rate limit or cooldown; honor `Retry-After`. |
| 500 / 502 / 503 / 504 | Internal error / invalid dependency / unavailability / timeout. |

### Common codes

| code | When it happens |
| --- | --- |
| `ERROR_VALIDATION` | Invalid body or query; see `details[]`. |
| `ERROR_INVALID_LIMIT` | `limit` outside 1–1000 or not an integer (400). |
| `ERROR_INVALID_CURSOR` | Tampered cursor, or one from another collection, tenant or filter (400). |
| `ERROR_RATE_LIMIT_EXCEEDED` | Request limit exceeded (429). |
| `ERROR_INSUFFICIENT_CREDITS` / `ERROR_QUOTA_EXCEEDED` | Not enough credits or quota to issue. |
| `ERROR_COMPANY_NOT_READY` / `ERROR_COMPANY_BLOCKED` | Company without an active certificate in `live`, or blocked. |
| `ERROR_IDEMPOTENCY_CONFLICT` | Same `Idempotency-Key` with a different payload (409). |
| `ERROR_TAX_REGIME_NOT_SUPPORTED` | Only MEI and Simples Nacional companies are supported (422). |
| `ERROR_VALIDATION` with `details[].code` `ERROR_DEDUCTION_NOT_ALLOWED_FOR_REGIME` or `ERROR_SIMPLES_SUBLIMIT_NOT_SUPPORTED` | A deduction from the ISS base that a MEI or a Simples company cannot declare, or a Simples company above a sublimit (`regApTribSN` 2 or 3), which is not supported yet (422). |
| `ERROR_GONE` | Retired operation, such as one-off credit purchases (410). |

### Best practices

- For non-2xx responses, keep the status, `code` and `requestId` in diagnostics — never log the API key.
- Retry with backoff on 429/503; on 429 wait for `Retry-After`. On issuance, preserve the idempotency key and the payload.
- Do not repeat validation errors without fixing the data listed in `details`.

Source: https://www.corvo.tech/en/docs/errors

---

## Rate limits

Request limits per identity and per IP, in 60-second windows.

| Identity | Limit per 60-second window |
| --- | --- |
| Validated API key (summed across endpoints) | 300 |
| Public routes, per IP | 120 |
| Whole tenant (all keys and sessions together) | 600 |
| Pre-authentication protection, per IP | 1200 |

Sensitive routes have extra per-route budgets on top of the general limit: OTP, magic link, OAuth and Turnstile (10 to 30 per minute per IP), MCP client registration, token and revocation (10 to 30 per minute per IP), and the costly authenticated routes `POST /invoices`, `POST /invoices/calculate` (120 per minute per tenant), `POST /invoices/batches` (10 per minute per tenant) and certificate upload (10 per minute per tenant). Health checks, preflight and Stripe receiving are exempt. Creating more API keys does not raise your ceiling: the tenant-wide limit applies across all of them.

Headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (Unix timestamp in seconds). On `429`, the `Retry-After` header gives the seconds until you can retry and the body carries `code: "ERROR_RATE_LIMIT_EXCEEDED"`. On sensitive routes, the route-specific headers replace the general ones.

> Honor `Retry-After` before retrying and use exponential backoff during spikes. Do not treat the plan's `throughputRps` as the HTTP limit. When the server is saturated it answers `503` with `code: "ERROR_SERVER_BUSY"` and `Retry-After: 1`: retry with backoff.

Source: https://www.corvo.tech/en/docs/rate-limits

---

## Companies

Register and manage the companies used for NFS-e issuance.

Permissions: fetches use `nfse.companies.view`; writes use `nfse.companies.manage`.

### From signup to issuing

- `POST /v1/companies` with `taxRegime` and `municipalityCode`. `municipalReg` is optional.
- `POST /v1/companies/:id/certificates` with the A1 certificate.
- `POST /v1/invoices`.

> The regime sent when creating the company creates its fiscal profile, valid from today and already approved by the caller (user or API key). Without a customer or with a CPF customer there is no approval step or service setup: classification comes from the official catalog by `service.code`. With a CNPJ customer the federal withholding depends on the service policy: create the service profile with `withholdingPolicy` `NONE_CONFIRMED` or `CONFIGURED` and approve it, otherwise the calculation returns `blocked` with `TAX_APPLICABILITY_UNKNOWN`. `GET /v1/companies/:id` shows `status` and `setupGaps` (`municipality_code`, `certificate`). Use `POST /v1/invoices/calculate` to check before issuing.

> Changing `taxRegime`, `simpleNational` or `specialRegime` with `PATCH` on the same day the company was created returns `409` (`ERROR_CONFLICT`, message `profile_validity_conflict`), because an approved profile is not rewritten. For a dated change use `PUT /v1/companies/:id/fiscal-profile` with `validFrom`. Service profiles (`/v1/companies/:id/service-tax-profiles`) are optional and become required when the regime needs IBS/CBS or configured ISS: the calculation returns `FISCAL_CLASSIFICATION_REQUIRED` with the missing fields.

### POST /v1/companies

Scopes: full_access. Success: 201 Created.

Registers a company.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| legalName | string | yes | Legal name, up to 200 characters, not empty after trim. |
| taxId | string | yes | Valid CNPJ; normalized before the duplicate check. |
| taxRegime | string | yes | `MEI` or `Simples Nacional`. Corvo serves only these two regimes: any other value returns `422` `ERROR_TAX_REGIME_NOT_SUPPORTED`. |
| tradeName | string | no | Up to 200 characters. |
| municipalReg | string or null | no | Optional, and nonblank when sent. It is stored but **not sent on the invoice** unless `sendMunicipalReg` is `true`. `null` clears it (and turns `sendMunicipalReg` off). |
| sendMunicipalReg | boolean | no | Default `false`. Send the municipal registration in the DPS only if the city registered this company in the national registry and the tax authority requires it; otherwise the invoice is rejected (E0120). |
| municipalityCode | string | yes | Exactly 7 digits (IBGE), required in test and live mode. Used as the issuer municipality and default service location. |
| defaultServiceCode | string | no | Exactly 6 digits (cTribNac); default for new invoices. Without it, provide `service.code` when issuing. |
| simpleNational | boolean | no | If omitted, follows the regime (`true` for MEI and Simples Nacional). |
| specialRegime | string | no | One of `"0"`–`"6"` (regEspTrib, RTC v1.01): 0 None, 1 Cooperative Act, 2 Estimate, 3 Municipal Microenterprise, 4 Notary or Registrar, 5 Self-employed Professional, 6 Professional Partnership. |
| simplesRate | string | no | Required for `Simples Nacional`, ignored for `MEI`. Effective total rate (%) of your DAS, the one shown in the PGDAS-D, e.g. `"6.54"` (0 to 100, at most 2 decimals). It goes on every invoice (`pTotTribSN`). Corvo does not compute the DAS. |
| simplesIssRate | string | no | Optional, `Simples Nacional` only. Effective ISS rate (%) of your bracket (1.80 to 5.00), needed only when a customer withholds ISS. Ignored for `MEI`. |
| address | object | no | `street` (200), `number` (20), `complement` (100), `district` (100), `city` (100), `state` (2) and `zip` (10), all optional strings. A filled-in state must be a valid UF and is normalized to uppercase. A filled-in zip must be 8 digits and is stored without punctuation. |

```bash
curl -X POST "$BASE_URL/companies" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "legalName": "Empresa Exemplo Ltda",
    "taxId": "11222333000181",
    "taxRegime": "Simples Nacional",
    "simplesRate": "6.54",
    "simpleNational": true,
    "municipalReg": "123456",
    "municipalityCode": "3550308",
    "defaultServiceCode": "010101",
    "address": {
      "street": "Rua Exemplo",
      "number": "100",
      "city": "São Paulo",
      "state": "SP",
      "zip": "01001000"
    }
  }'
```

Response 201 Created:

```json
{
  "data": {
    "id": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
    "legalName": "Empresa Exemplo Ltda",
    "taxId": "11222333000181",
    "taxRegime": "Simples Nacional",
    "municipalityCode": "3550308",
    "defaultServiceCode": "010101",
    "status": "pending_setup",
    "environment": "test",
    "createdAt": "2026-10-10T12:00:00.000Z"
  }
}
```

> A duplicate CNPJ in the same account/environment returns `409`. The CNPJ cannot be changed afterwards. In `live`, creation can fail on company limit or blocked plan (`422`).

> The input body uses `address`, but the response exposes flat fields: `addressStreet`, `addressNumber`, `addressCity`, `addressState`, `addressZip` etc. `status` is `pending_setup`, `ready` or `blocked`; `setupGaps` lists pending items (`municipality_code`, `certificate`).

### GET /v1/companies

Scopes: full_access, invoices_read_write. Success: 200 OK.

Lists the companies in the account/environment.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| limit | integer | no | Defaults to `50`; accepts integers from 1 to 1000 (an invalid value returns `400`). |
| cursor | string | no | `nextCursor` from the previous page, keeping the same filters. |

```bash
curl "$BASE_URL/companies?limit=50" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": [
    {
      "id": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
      "legalName": "Empresa Exemplo Ltda",
      "taxId": "11222333000181",
      "status": "ready",
      "environment": "test"
    }
  ],
  "pagination": {
    "limit": 50,
    "hasMore": true,
    "nextCursor": "eyJ2IjoxLCJjcmVhdGVkQXQiOiIyMDI2LTEwLTA5VDEyOjAwOjAwLjAwMDAwMFoiLCJpZCI6IjNmMWM4YTkwIn0"
  }
}
```

> Ordering is `createdAt DESC`, then `id DESC`. Continue with `pagination.nextCursor` until `hasMore: false`; there is no `total`.

### GET /v1/companies/:id

Scopes: full_access, invoices_read_write. Success: 200 OK.

Fetches a single company by id.

```bash
curl "$BASE_URL/companies/$COMPANY_ID" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "id": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
    "legalName": "Empresa Exemplo Ltda",
    "taxId": "11222333000181",
    "municipalReg": "123456",
    "taxRegime": "Simples Nacional",
    "status": "ready",
    "environment": "test",
    "setupGaps": []
  }
}
```

> A company that does not exist, was deleted, or belongs to another environment/account returns `404`. An `id` that is not a valid UUID returns `400` (`ERROR_BAD_REQUEST`).

### PATCH /v1/companies/:id

Scopes: full_access. Success: 200 OK.

Updates a company. Accepts the creation fields, all optional. Send `simplesRate` (and `simplesIssRate`, or `null` to remove it) to update the Simples rate, for example every month.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| legalName | string | no | Legal name, up to 200 characters, not empty after trim. |
| taxId | string | no | The CNPJ cannot be changed. Sending the current CNPJ is accepted and ignored; any other value returns `422`. To use another CNPJ, create a new company. |
| taxRegime | string | no | `MEI` or `Simples Nacional`. Corvo serves only these two regimes: any other value returns `422` `ERROR_TAX_REGIME_NOT_SUPPORTED`. |
| tradeName | string | no | Up to 200 characters. |
| municipalReg | string or null | no | Optional. Stored but not sent on the invoice unless `sendMunicipalReg` is `true`. `null` clears it. |
| municipalityCode | string | no | Exactly 7 digits when provided; omit to keep the existing value. Cannot be cleared. |
| defaultServiceCode | string or null | no | Exactly 6 digits when provided. Omit to keep; null clears the default. |
| simpleNational | boolean | no | Omit it to keep the current value. |
| specialRegime | string | no | One of `"0"`–`"6"` (regEspTrib, RTC v1.01), same codes as on creation. Empty string clears it; omit to keep the current value. |
| simplesRate | string | no | Omit it to keep the current value. Send a new value to update it (for example, each month). Ignored for `MEI`. |
| simplesIssRate | string or null | no | Same format as on creation. `null` removes it. |
| address | object or null | no | Same fields as on creation. `null` clears the address. |

```bash
curl -X PATCH "$BASE_URL/companies/$COMPANY_ID" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "tradeName": "Novo nome", "municipalReg": "987654" }'
```

Response 200 OK:

```json
{
  "data": {
    "id": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
    "tradeName": "Novo nome",
    "municipalReg": "987654",
    "status": "ready"
  }
}
```

> `municipalReg: null` clears municipal registration and `address: null` clears the address. Omit `defaultServiceCode` to keep it; `null` clears it; empty or invalid values are rejected. A supplied `municipalityCode` must have 7 digits and cannot be cleared. `environment` cannot be changed. May return `400` on validation, `404`, or `409` on a duplicate CNPJ.

### DELETE /v1/companies/:id

Scopes: full_access. Success: 200 OK.

Deletes a company (logical deletion).

```bash
curl -X DELETE "$BASE_URL/companies/$COMPANY_ID" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": null
}
```

> Returns `404` if the company is not found.

Source: https://www.corvo.tech/en/docs/companies

---

## Certificates

Upload and manage A1 (PKCS#12) certificates for issuance.

You can upload the A1 certificate through the dashboard (company page) or through the API with the endpoint below.

Permissions: `nfse.certificates.view` to list and `nfse.certificates.manage` to upload/revoke.

### POST /v1/companies/:companyId/certificates

Scopes: full_access. Success: 201 Created.

Uploads an A1 certificate (`.p12`/`.pfx`) for a company. The certificate is parsed, its validity is checked, and its CNPJ must match the company's.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| file | file | yes | PKCS#12 certificate (.p12/.pfx), max 50 × 1024 bytes. |
| password | string | yes | Non-empty, up to 100 characters. |

```bash
curl -X POST "$BASE_URL/companies/$COMPANY_ID/certificates" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -F 'file=@certificate.pfx' \
  -F 'password=CERT_PASSWORD'
```

Response 201 Created:

```json
{
  "data": {
    "id": "9a2b7c40-1d5e-4f6a-8b3c-5d7e9f0a2b41",
    "companyId": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
    "serialNumber": "3881234567",
    "issuer": "AC A1 Teste",
    "subject": "CNPJ: 11222333000181",
    "fingerprint": "AB:CD:EF:...",
    "validFrom": "2026-01-01T00:00:00.000Z",
    "validUntil": "2027-01-01T00:00:00.000Z",
    "status": "active",
    "createdAt": "2026-10-10T12:00:00.000Z"
  }
}
```

> Failures include `400` for missing file/password, `413` for size, and `422` for an expired certificate or a CNPJ that does not match the company. Parsing failures depend on the error produced by the parser; do not assume a single code for every invalid file.

> The API returns metadata only — never the password or the certificate content. Possible `status` values: `active`, `expired`, `revoked`.

### GET /v1/companies/:companyId/certificates

Scopes: full_access, invoices_read_write. Success: 200 OK.

Lists the certificates of a company.

```bash
curl "$BASE_URL/companies/$COMPANY_ID/certificates" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": [
    {
      "id": "9a2b7c40-1d5e-4f6a-8b3c-5d7e9f0a2b41",
      "companyId": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
      "serialNumber": "3881234567",
      "status": "active",
      "validUntil": "2027-01-01T00:00:00.000Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "hasMore": false,
    "nextCursor": null
  }
}
```

### DELETE /v1/companies/:companyId/certificates/:certId

Scopes: full_access. Success: 204 No Content.

Revokes a certificate and updates the company's readiness.

```bash
curl -X DELETE "$BASE_URL/companies/$COMPANY_ID/certificates/$CERT_ID" \
  -H "X-API-Key: $CORVO_API_KEY"
```

> No response body. Returns `404` if the certificate/company does not match the account, the environment or the path provided.

Source: https://www.corvo.tech/en/docs/certificates

---

## Invoices

Issue NFS-e, fetch status, download documents and request email delivery.

Permissions: `nfse.invoices.issue` to issue/request email; `nfse.invoices.view` for fetches, documents and signed URLs.

### POST /v1/invoices

Scopes: full_access, invoices_issue, invoices_read_write. Success: 202 Accepted.

Requests NFS-e issuance. Issuance is asynchronous: HTTP success means the request was registered/queued — it does not mean fiscal authorization. These examples use the CNPJ (`companyTaxId`) of a company registered with `municipalityCode` and `defaultServiceCode`. The issuer municipality always comes from the company.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| companyId | string UUID | no | Send this field or `companyTaxId`; if both exist, `companyId` takes precedence. |
| companyTaxId | string | no | CNPJ of a company already registered in the account/environment; punctuation optional. |
| externalId | string | no | Reference from the integrating system; does not replace the idempotency key. |
| customer | object | no | Optional: omit it or send `{}` for an invoice without tomador (the customer is left out of the DPS). When sent with any data, `taxId` is required (valid CPF or CNPJ, normalized); `name` is optional, `email` (optional; required when email sending is enabled; no email format validation in this DTO/domain) and `address` (optional: `street`, `city`, `state`, `zip`, `country` are optional strings; if you fill in city or state, fill in both; state must be valid). |
| service | object | yes | `code` is optional: without it the company `defaultServiceCode` is used and, if the company has none, `100901` (LC 116 item 10.09, representation of any nature); exactly 6 digits when provided. `municipalityCode` inherits the company municipality; when provided, exactly 7 digits and sets the service location. `description` is optional: when empty, the name of the service code is used. Empty, null or invalid values of the other fields do not use the defaults. |
| amount | number | yes | Value in reais, positive, up to 9999999999.99 with at most 2 decimals. |
| competenceDate | string ISO 8601 | yes | Valid competence date. Without `options.type` it cannot be in the future (`422` `ERROR_FUTURE_DATE`). With `SCHEDULE` or `RECURRING` it is the date of the first run, from tomorrow on (see Scheduled and recurring invoices). |
| discount | number | no | Unconditional discount in BRL, from 0 up to the invoice amount, at most 2 decimal places. |
| deduction | number | no | Deduction from the ISS base declared by the issuer, in BRL: greater than 0 and less than `amount` minus `discount`, at most 2 decimal places (`0` is the same as omitting it). Sent in the DPS as `vDedRed/vDR`, it reduces the ISS tax base. The invoice is still issued for the full amount. The issuer is responsible for the declared value; Corvo does not check whether the deduction is allowed. IBS/CBS is still calculated on the amount without the deduction. See ISS base deduction. |
| purchaseOrder | string | no | Purchase order or service order number the customer asked to see on the invoice, up to 60 characters on one line. Sent in the DPS as `serv/infoCompl/xPed` and printed on the PDF. It changes no tax. |
| notes | string | no | Free text printed on the invoice as complementary information, up to 2,000 characters (line breaks allowed). Sent in the DPS as `serv/infoCompl/xInfComp`. It changes no tax. A blank value is the same as omitting it. |
| email | boolean | no | Requests a notification; defaults to `false`. |
| options.email.send | boolean | no | When set, takes precedence over `email`. |
| options.type | string | no | `IMMEDIATE` (default), `SCHEDULE` or `RECURRING`. `SCHEDULE` and `RECURRING` create a schedule instead of issuing now; see Scheduled and recurring invoices. |
| options.recurrence.frequency | string | no | `WEEKLY`, `BIWEEKLY` or `MONTHLY`. Required with `RECURRING`; not allowed with the other types. |
| options.recurrence.endsOn | string YYYY-MM-DD | no | Last day the recurrence may run (inclusive). Without it, it runs until paused or cancelled. |

```bash
curl -X POST "$BASE_URL/invoices" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: pedido_123_emissao' \
  -d '{
    "companyTaxId": "11222333000181",
    "externalId": "pedido_123",
    "customer": {
      "name": "Cliente Exemplo",
      "taxId": "52998224725",
      "email": "cliente@example.com",
      "address": { "city": "São Paulo", "state": "SP" }
    },
    "service": {
      "description": "Prestação de serviço"
    },
    "amount": 150.50,
    "competenceDate": "2026-10-01",
    "options": { "email": { "send": true } }
  }'
```

Response 202 Accepted:

```json
{
  "data": {
    "id": "6c4d2e81-0a3b-4c5d-9e7f-1a2b3c4d5e6f",
    "companyId": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
    "environment": "test",
    "externalId": "pedido_123",
    "idempotencyKey": "pedido_123_emissao",
    "status": "queued",
    "amount": 150.5,
    "currency": "BRL",
    "competenceDate": "2026-10-01T00:00:00.000Z",
    "stage": "pending",
    "createdAt": "2026-10-10T12:00:00.000Z"
  }
}
```

> Send an `Idempotency-Key` header: with the same key, account and environment and equivalent content, the hash recovers the same invoice; different content returns `409` (`ERROR_IDEMPOTENCY_CONFLICT`). The hash is computed before fiscal normalization, with canonical JSON keys and the competence date. Do not change how fields are represented between retries: a CNPJ with and without punctuation can produce different hashes. Without a key there is no deduplication.

> Issuance is asynchronous — see the Async issuance guide. Track the invoice with `GET /v1/invoices/:id` or webhooks. The customer address is reduced to `city` and `state` in the snapshot; `street`, `zip` and `country` are not preserved — do not rely on them in the response.

### POST /v1/invoices/batches

Scopes: full_access, invoices_issue, invoices_read_write. Success: 202 Accepted.

Requests the issuance of **1 to 50 invoices in a single call**, for one company or for several. Each item has the same fields as `POST /v1/invoices` plus an optional `idempotencyKey`. Items are checked one by one: valid items are saved together in a single transaction, invalid items come back as `rejected` with the reason and are **not** saved. Issuance stays asynchronous, as in `POST /v1/invoices`.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| invoices | array | yes | List of 1 to 50 items. Each item takes the fields of `POST /v1/invoices` (`companyId` or `companyTaxId`, `service`, `amount`, `competenceDate`, optional `customer`, `discount`, `deduction`, `options`...). Items can belong to different companies of the account. Fewer than 1 or more than 50 items returns `400` `ERROR_VALIDATION` for the whole request. |
| invoices[].idempotencyKey | string | no | Idempotency key of the item (up to 255 characters). With the same key and the same content, repeating the batch returns the invoice already saved with `replayed: true` instead of issuing again. The `Idempotency-Key` header is not used by this route. |

```bash
curl -X POST "$BASE_URL/invoices/batches" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "invoices": [
      {
        "companyTaxId": "11222333000181",
        "idempotencyKey": "planilha-out-linha-2",
        "customer": { "name": "Cliente A", "taxId": "52998224725" },
        "service": { "description": "Consultoria" },
        "amount": 150.50,
        "competenceDate": "2026-10-01"
      },
      {
        "companyTaxId": "45723174000110",
        "idempotencyKey": "planilha-out-linha-3",
        "service": { "description": "Manutenção mensal" },
        "amount": 300,
        "competenceDate": "2026-10-01"
      }
    ]
  }'
```

Response 202 Accepted:

```json
{
  "data": {
    "total": 3,
    "accepted": 2,
    "rejected": 1,
    "results": [
      {
        "index": 0,
        "status": "accepted",
        "invoice": {
          "id": "6c4d2e81-0a3b-4c5d-9e7f-1a2b3c4d5e6f",
          "companyId": "3f1c8a90-6b2e-4d5a-9c11-8e2f0a7b4d11",
          "environment": "test",
          "idempotencyKey": "planilha-out-linha-2",
          "status": "queued",
          "amount": 150.5,
          "currency": "BRL",
          "competenceDate": "2026-10-01T00:00:00.000Z",
          "stage": "pending",
          "createdAt": "2026-10-10T12:00:00.000Z"
        }
      },
      {
        "index": 1,
        "status": "accepted",
        "replayed": true,
        "invoice": {
          "id": "0b7a1f52-3c4d-4e6f-8a9b-2c3d4e5f6a7b",
          "status": "queued",
          "idempotencyKey": "planilha-out-linha-3",
          "amount": 300
        }
      },
      {
        "index": 2,
        "status": "rejected",
        "error": {
          "code": "ERROR_VALIDATION",
          "message": "Request validation failed",
          "details": [
            { "field": "amount", "code": "ERROR_OUT_OF_RANGE", "message": "amount must be greater than 0" }
          ]
        }
      }
    ]
  }
}
```

> **All or nothing for the valid ones, never for the batch.** Every `accepted` item is saved in one single commit, with its credit reservation and its queue message. An invalid item (validation, company not found or not ready, missing certificate in `live`, plan limit) comes back `rejected` and is discarded without affecting the others. If something unexpected fails while saving, nothing at all is saved and you can repeat the same batch safely.

> **Reading the result.** `results` has one entry per item, in the order sent: use `index` to match each result to the row of your spreadsheet or to your own record. Fix only the `rejected` rows and send them again; the `accepted` ones are already saved. Always send an `idempotencyKey` per item (for example `file-row-7`): after a timeout, repeating the whole batch returns the saved ones as `replayed: true` and retries only the missing ones. A key repeated inside the same batch is rejected with `ERROR_DUPLICATE_IDEMPOTENCY_KEY_IN_BATCH`.

> In `live`, each accepted item reserves one credit, like `POST /v1/invoices`. When the monthly or daily limit is reached in the middle of the batch, the items that fit are saved and the rest come back `rejected` with `ERROR_MONTHLY_LIMIT_EXCEEDED`, `ERROR_DAILY_LIMIT_EXCEEDED` or `ERROR_PLAN_BLOCKED`. The route accepts up to 10 batches per minute per tenant (`429` with `Retry-After`). For AI agents, the MCP tool `nfse_issue_batch` has the same contract.

### POST /v1/invoices/calculate

Scopes: full_access, invoices_issue, invoices_read_write. Success: 200 OK.

Calculates the taxes of an invoice **without issuing it**: it stores no invoice, uses no credit, reserves no DPS number, schedules nothing and does not call Sefin. Use it to check the fiscal setup and show the amount to the customer before `POST /v1/invoices`.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| (corpo) | objeto | yes | Same body as `POST /v1/invoices` (company, `service`, `amount`, `competenceDate`, optional `customer`, `discount`, `deduction`). Requires the `nfse.invoices.issue` permission. It does not require a certificate or a ready company. |

```bash
curl -X POST "$BASE_URL/invoices/calculate" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "companyTaxId": "11222333000181",
    "service": { "code": "060101", "description": "Haircut" },
    "amount": 50,
    "competenceDate": "2026-10-13"
  }'
```

Response 200 OK:

```json
{
  "data": {
    "preEmission": true,
    "status": "ready",
    "disclaimer": "Pre-emission calculation. Values are not a fiscal document and may differ from the final validation by Sefin.",
    "competenceDate": "2026-10-13",
    "taxRegime": "MEI",
    "classification": {
      "serviceCode": "060101",
      "source": "official_catalog",
      "operationNature": "SERVICE",
      "nbsCode": null,
      "cst": null,
      "classCode": null,
      "serviceProfileId": null,
      "catalogValidated": false
    },
    "applicability": {
      "customerRequired": false,
      "strategy": "mei",
      "iss": {
        "status": "NOT_APPLICABLE",
        "reason": "ISS recolhido no DAS-MEI"
      },
      "federalWithholding": {
        "status": "NOT_APPLICABLE",
        "reason": "no federal withholding on payments to Simples Nacional/MEI optants (IN RFB 1.234/2012, art. 4, XI)"
      },
      "cbs": {
        "status": "NOT_APPLICABLE",
        "reason": "MEI não destaca IBS/CBS na fase de teste de 2026"
      },
      "ibs": {
        "status": "NOT_APPLICABLE",
        "reason": "MEI não destaca IBS/CBS na fase de teste de 2026"
      }
    },
    "taxes": {},
    "withholdings": [],
    "netReceivableAmount": "50.00",
    "collectionWaived": false,
    "calculation": {
      "source": "none",
      "calculatorVersion": null,
      "rulesVersion": "2026.10-r1",
      "legalReferences": [
        "Ato Conjunto RFB/CGIBS nº 4/2026; orientação CGNFS-e de 07/08/2026"
      ]
    },
    "warnings": [
      {
        "code": "CLASSIFICATION_NOT_CATALOG_VALIDATED",
        "message": "Service tax classification was not validated against the official catalog",
        "step": "ServiceTaxClassifier"
      }
    ],
    "pendingFields": [],
    "blocking": null,
    "trace": [
      {
        "step": "CompanyFiscalProfile",
        "status": "applied",
        "durationMs": 2.4
      },
      {
        "step": "ServiceTaxClassifier",
        "status": "applied",
        "durationMs": 7.1
      },
      {
        "step": "TaxApplicabilityResolver",
        "status": "applied",
        "durationMs": 0.3
      },
      {
        "step": "RtcTaxCalculator",
        "status": "skipped",
        "durationMs": 0.03,
        "reason": "MEI não destaca IBS/CBS na fase de teste de 2026"
      },
      {
        "step": "FiscalValidator",
        "status": "applied",
        "durationMs": 0.1
      }
    ]
  }
}
```

> `status: "ready"` means the fiscal data is complete and the calculation was done. It is a pre-emission estimate, not an authorization from Sefin. Amounts and rates are decimal strings. The response never returns the customer's name or CPF/CNPJ.

> A fiscal problem is not an HTTP error: it returns `200` with `status: "blocked"`, `blocking` (`code`, `message`, `step`) and `pendingFields[]` listing what is missing, for example `FISCAL_CLASSIFICATION_REQUIRED` or `TAX_RATE_NOT_FOUND`. Values already computed before the block stay in the response. Invalid input follows the normal envelope (`404` unknown company, `422` invalid field).

> `503` with `Retry-After` (seconds) when the tax calculator is unavailable: retry later, never estimate. The rate limit is the same as any authenticated endpoint (`429` with `Retry-After`). A future competence date is accepted only up to 15 days ahead.

### Scheduled and recurring invoices

Use `options.type: "SCHEDULE"` to issue an invoice once on a future date, or `options.type: "RECURRING"` to repeat it every week, every two weeks or every month. Neither issues now: they create a **schedule**, and the response is the schedule (`202`), not an invoice. `competenceDate` is the date of the first run: from tomorrow on and up to 15 days ahead (up to 31 days for `RECURRING`, so a monthly one can start today).

| Situation | Result |
| --- | --- |
| No `options.type` (or `IMMEDIATE`) and a future `competenceDate` | `422` with `ERROR_FUTURE_DATE` in `details[].code`. |
| `SCHEDULE` or `RECURRING` with a `competenceDate` from tomorrow on, within the limit (default 15 days ahead) | `202` with the schedule (`id`, `kind`, `status: active`, `next_run_on`). The invoice only exists when the schedule runs. |
| `SCHEDULE` or `RECURRING` with a `competenceDate` of today or in the past | `422` with `first_date_too_soon` in `details[].code`. To issue now, use `IMMEDIATE`. |
| `SCHEDULE` or `RECURRING` beyond the limit | `422` with `schedule_horizon_exceeded`. |
| `RECURRING` without `options.recurrence.frequency` | `422` with `required`. A `recurrence` with `SCHEDULE` or `IMMEDIATE` gives `422` with `not_allowed`. |
| `options.recurrence.endsOn` equal to or before the first date | `422` with `ends_before_start`. |
| More than 200 active schedules in the account | `422` with `ERROR_SCHEDULE_LIMIT`. |

```bash
curl -X POST "$BASE_URL/invoices" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "companyTaxId": "11222333000181",
    "service": { "description": "Monthly fee" },
    "amount": 150,
    "competenceDate": "2026-11-10",
    "options": {
      "type": "RECURRING",
      "recurrence": { "frequency": "MONTHLY", "endsOn": "2027-10-10" }
    }
  }'
```

```json
{
  "data": {
    "id": "8f6c2b1e-0d4a-4c43-9c1a-2d7f5e3b9a10",
    "kind": "recurring",
    "frequency": "MONTHLY",
    "status": "active",
    "pause_reason": null,
    "company_id": "5b0e7c5a-5d0b-4f45-8d6c-3a2a1e9d7f20",
    "anchor_on": "2026-11-10",
    "next_run_on": "2026-11-10",
    "ends_on": "2027-10-10",
    "attempts": 0,
    "last_run_on": null,
    "invoice": { "amount": 150, "service": { "description": "Monthly fee" } },
    "created_at": "2026-11-06T15:00:00.000Z"
  }
}
```

> Contract change: `SCHEDULE` used to return the invoice (with `scheduledFor`); it now returns the schedule. The `id` in the response is the schedule's, and the invoice shows up in `GET /v1/invoices` when the schedule runs. The credit is no longer reserved when you create it: it is used when the schedule runs. Invoices scheduled before the change are still issued normally. Schedules are not accepted in a batch (`POST /v1/invoices/batches`).

> Runs happen at 09:00 `America/Sao_Paulo`, Monday to Friday. A Saturday or Sunday date runs on Monday. The invoice takes the competence of the day it runs and uses the schedule's data at that moment. If a run cannot issue (for example, no notes available), it tries again on the next business day and you get an e-mail; after 3 failed attempts the schedule is paused and you get another e-mail. `POST /v1/schedules/:id/resume` continues from the next date, without catching up on what passed.

#### Manage schedules

| Method | Route | Description | Status |
| --- | --- | --- | --- |
| GET | `/v1/schedules` | List schedules (filters `status` and `companyId`) | 200 |
| GET | `/v1/schedules/:id` | Get a schedule | 200 |
| GET | `/v1/schedules/:id/runs` | Run history: due date, day it ran, result, issued invoice or error | 200 |
| PATCH | `/v1/schedules/:id` | Change `invoice`, `endsOn`, `frequency` or `anchorOn`; applies to the next runs | 200 |
| POST | `/v1/schedules/:id/pause` | Pause | 200 |
| POST | `/v1/schedules/:id/resume` | Resume a paused schedule | 200 |
| POST | `/v1/schedules/:id/cancel` | Cancel (final) | 200 |

A schedule has `id`, `kind` (`once` or `recurring`), `frequency`, `status` (`active`, `paused`, `completed`, `cancelled`), `pause_reason` (`customer` or `failures`), `company_id`, `anchor_on`, `next_run_on`, `ends_on`, `attempts` (failures in a row, 0 to 3), `last_run_on`, `invoice` (the body issued on each run) and `created_at`. Permissions: `nfse.invoices.view` to read and `nfse.invoices.issue` to create and change. A test key sees only test schedules, and a live key only live ones.

### Customer abroad

For a customer outside Brazil, send `customer.foreign` instead of the CPF or CNPJ. The invoice identifies the customer by its NIF (the tax id in its own country) and carries the address abroad.

| Field | Rule |
| --- | --- |
| `customer.name` | Required for a customer abroad. |
| `foreign.taxId` | Tax id in the customer's country (NIF), up to 40 characters. Send this field **or** `noTaxIdReason`, never both. |
| `foreign.noTaxIdReason` | When the customer has no tax id: `exempt` or `not_required`. |
| `foreign.country` | Two-letter country code (ISO 3166-1), other than `BR`. |
| `foreign.postalCode`, `city`, `region` | Postal code (up to 11), city and state, province or region (up to 60 each). Required. |
| `foreign.street`, `number`, `district` | Street (up to 255), number and district or neighbourhood (up to 60 each). The invoice layout requires all three. |
| `foreign.complement` | Optional, up to 156 characters. |
| Cannot be combined | `customer.taxId` and `customer.address` (the Brazilian address) answer `422` with `not_allowed`. |

```bash
curl -X POST "$BASE_URL/invoices" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: pedido_981_emissao" \
  -d '{
    "companyTaxId": "11222333000181",
    "service": { "description": "Software development" },
    "amount": 5000,
    "competenceDate": "2026-11-10",
    "customer": {
      "name": "Acme Inc.",
      "foreign": {
        "taxId": "12-3456789",
        "country": "US",
        "postalCode": "94105",
        "city": "San Francisco",
        "region": "CA",
        "street": "1 Market St",
        "number": "100",
        "district": "SoMa"
      }
    }
  }'
```

> Informing a customer abroad **does not declare a service export**: the invoice keeps the same tax treatment. Exports (with the country of the result and the foreign trade data) are not supported yet. Confirm the classification with your accountant.

> It applies to single invoices, batches, schedules and the MCP tool `nfse_issue` (field `customer.foreign`, in snake_case). In spreadsheets, use the optional customer-abroad columns (see Importing a spreadsheet). It is not added to saved customers.

### Substituting an invoice

`POST /v1/invoices/:id/substitute` issues a new invoice that replaces an **authorized** one. The Receita cancels the original in the same act that authorizes the substitute, so there is no gap without a valid invoice. The answer is `202` with the substitute in `queued`, with `substitutesInvoiceId` pointing at the original.

| Field | Rule |
| --- | --- |
| `description` | Required, 15 to 255 characters: why the invoice is being substituted. Sent in the DPS as `subst/xMotivo`. |
| `service.description` | Optional. New service description. |
| `purchaseOrder`, `notes` | Optional. Omitting keeps what the original had; an empty text removes it. |
| What does not change | Customer, competence date and amount stay as in the original. For MEI and Simples Nacional the Receita refuses a substitute that changes any of them (rule E0061). To correct those, cancel the invoice and issue another. |
| Original | Stays `authorized` until the Receita authorizes the substitute. Once it does, the original becomes `cancelled` and you receive `nfse.invoice.cancelled` with `substitutedBy`. If the Receita refuses, the original does not change and the substitute is `rejected`. |
| Credit | The substitute uses a credit, like any issued invoice. The credit of the original is not returned. |
| Errors | `409` `ERROR_INVOICE_NOT_SUBSTITUTABLE` when the invoice is not `authorized`; `404` when it does not exist. |

### POST /v1/invoices/:id/substitute

Scopes: full_access, invoices_issue, invoices_read_write. Success: 202 Accepted.

Issues a new invoice that replaces an `authorized` one. The original stays `authorized` until the Receita authorizes the substitute and only then becomes `cancelled`; if the Receita refuses, the original does not change. Customer, competence date and amount are copied from the original.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| description | string | yes | Required, 15 to 255 characters: why the invoice is being substituted (DPS `subst/xMotivo`). |
| service.description | string | no | New service description. |
| purchaseOrder | string | no | New purchase order. Omitting keeps the original; an empty text removes it. |
| notes | string | no | New notes. Omitting keeps the original; an empty text removes it. |

```bash
curl -X POST "$BASE_URL/invoices/$INVOICE_ID/substitute" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: pedido_981_substituicao" \
  -d '{
    "description": "Descricao do servico corrigida",
    "service": { "description": "Consultoria em tecnologia, outubro/2026" },
    "purchaseOrder": "PO-4521"
  }'
```

Response 202 Accepted:

```json
{
  "data": {
    "id": "9b2f4c1e-7a35-4d0f-8c21-5e6a1b3d7f90",
    "status": "queued",
    "substitutesInvoiceId": "6f1c0e2a-4b7d-4c1e-9a55-2b8f7c3d9e10",
    "substitutionDescription": "Descricao do servico corrigida",
    "amount": 1000,
    "serviceSnapshot": {
      "description": "Consultoria em tecnologia, outubro/2026",
      "code": "010601",
      "municipalityCode": "3550308",
      "purchaseOrder": "PO-4521"
    }
  }
}
```

> The deadline to substitute and some rules (for example, an invoice without an identified customer) are set by each municipality. Corvo does not know that deadline in advance: if the Receita refuses, the error code comes on the substitute invoice. Send `Idempotency-Key` to repeat the call without issuing two substitutes. On MCP, the tool is `nfse_substitute`.

### Saved customers

After an invoice with a customer is accepted, Corvo keeps the CPF or CNPJ, the name and the email of that customer. On the next invoice for the same document, send only `customer.taxId`: the `name` comes from the saved customer. What you send in the request always wins, and an invoice already issued never changes.

| Rule | Detail |
| --- | --- |
| Scope | One saved customer per document in each workspace and environment. `test` and `live` never mix. |
| What is filled | Only the `name`, and only when the request carries none. The saved email is not used to send the invoice. |
| Not saved yet | The invoice follows as before: without a `name`, the customer is issued as `Consumidor`. Send the name on the first invoice. |
| Updates | The saved name follows the latest invoice; a saved email is kept when the invoice carries no email. |
| Where it applies | Single invoices, batches, spreadsheets, schedules and recurrences, and the MCP tools. |
| Idempotency | The request hash is computed before the name is filled, so repeating the same call still returns the same invoice. |

### GET /v1/customers

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Lists the saved customers of the key's environment, most recently used first. `search` matches part of the name or the start of the CPF/CNPJ (punctuation is ignored).

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| search | string | no | Part of the name or start of the document. |
| limit | number | no | Items per page (default 50). |
| cursor | string | no | Cursor returned by the previous page. |

```bash
curl "$BASE_URL/customers?search=acme&limit=50" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": [
    {
      "taxId": "11222333000181",
      "name": "Acme Ltda",
      "email": "financeiro@acme.com.br",
      "lastUsedAt": "2026-11-10T12:00:00.000Z",
      "createdAt": "2026-11-01T12:00:00.000Z",
      "updatedAt": "2026-11-10T12:00:00.000Z"
    }
  ],
  "pagination": { "limit": 50, "hasMore": false, "nextCursor": null }
}
```

### GET /v1/customers/:taxId

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Gets a saved customer by CPF or CNPJ, with or without punctuation. Answers `404` when the document was never saved.

```bash
curl "$BASE_URL/customers/11222333000181" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "taxId": "11222333000181",
    "name": "Acme Ltda",
    "email": "financeiro@acme.com.br",
    "lastUsedAt": "2026-11-10T12:00:00.000Z",
    "createdAt": "2026-11-01T12:00:00.000Z",
    "updatedAt": "2026-11-10T12:00:00.000Z"
  }
}
```

### PATCH /v1/customers/:taxId

Scopes: full_access, invoices_issue, invoices_read_write. Success: 200 OK.

Corrects the `name` or the `email` of a saved customer. Send only what changes; `email: null` removes the email. The correction applies to the next invoices.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| name | string | no | New name, up to 300 characters. |
| email | string \| null | no | New email, or `null` to remove it. |

```bash
curl -X PATCH "$BASE_URL/customers/11222333000181" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"name":"Acme S.A."}'
```

Response 200 OK:

```json
{
  "data": {
    "taxId": "11222333000181",
    "name": "Acme S.A.",
    "email": "financeiro@acme.com.br",
    "lastUsedAt": "2026-11-10T12:00:00.000Z",
    "createdAt": "2026-11-01T12:00:00.000Z",
    "updatedAt": "2026-11-10T12:00:00.000Z"
  }
}
```

### DELETE /v1/customers/:taxId

Scopes: full_access, invoices_issue, invoices_read_write. Success: 200 OK.

Forgets the saved customer. Invoices already issued do not change, and the name is no longer filled in.

```bash
curl -X DELETE "$BASE_URL/customers/11222333000181" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": null
}
```

> Permissions: `nfse.invoices.view` to list and get; `nfse.invoices.issue` to correct and delete. An unknown customer answers `404`. On MCP: `customer_list`, `customer_update` and `customer_delete`.

### ISS base deduction

The issuer can declare in `deduction` an amount that the municipality's legislation allows to be deducted from the ISS tax base. The value is sent in the DPS as `vDedRed/vDR` and reduces the ISS base; the invoice is still issued for the full amount (`amount`).

| Field / tax | How it is handled |
| --- | --- |
| `amount` | Total amount of the invoice. |
| `deduction` | Amount to deduct from the ISS base. Greater than 0 and less than `amount` minus `discount`; `0` is the same as omitting it. |
| ISS | Base = `amount` − `discount` − `deduction`. |
| Federal withholdings | Base unchanged: `amount` − `discount`. |
| IBS/CBS | Calculated on the amount without the deduction. |
| Net receivable | Does not change with the deduction. |
| Validation errors | `422` with `out_of_range` (negative, or not less than `amount` minus `discount`) or `invalid_decimal_places` in `details[].code`, on `field: "deduction"`. |
| Response | The invoice echoes `deduction` when one was declared. |

```bash
curl -X POST "$BASE_URL/invoices" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order_123" \
  -d '{
    "companyTaxId": "11222333000181",
    "service": { "description": "Maintenance service" },
    "amount": 100,
    "deduction": 40,
    "competenceDate": "2026-10-20"
  }'
```

> The issuer declares the value and is responsible for it: Corvo issues what was reported, does not check whether the deduction is allowed for the service or the municipality, and does not replace your accountant. Acceptance of the deduction by the municipality and the national system has not been validated in Produção Restrita yet; if the invoice is rejected, the reason is in `lastErrorCode` and `lastErrorMessage`.

### Invoice schema

Each invoice has these fields:

| Fields | Type / notes |
| --- | --- |
| `id`, `companyId` | Identification strings. |
| `environment` | `test` or `live`. |
| `externalId`, `idempotencyKey` | String or null. |
| `status` | Enum described below. |
| `customerSnapshot` | `taxId`, `name`, `email?`, `address?: { city, state, country? }`. |
| `serviceSnapshot` | `description`, `code`, `municipalityCode`. |
| `taxSnapshot` | Fiscal information object. |
| `amount`, `currency`, `competenceDate` | Number in reais, currency and ISO 8601 date-time (the competence date at midnight UTC, e.g. `2026-10-01T00:00:00.000Z`). |
| `discount`, `deduction` | Optional numbers in reais: the unconditional discount and the issuer-declared deduction from the ISS base (see ISS base deduction). |
| `dpsId`, `dpsSeries`, `dpsNumber` | String/string/number or null. |
| `accessKey`, `nfseNumber` | String/number or null. |
| `fiscalProvider`, `fiscalSchemaVersion` | Strings. |
| `issuedAt`, `authorizedAt` | ISO date or null. |
| `emailSnapshot` | Optional object with `send`. |
| `lastErrorCode`, `lastErrorMessage`, `lastErrorProvider` | String or null. |
| `documentsReadyAt` | ISO date or null. |
| `lastEmailStatus`, `lastEmailSentAt` | `queued`, `sent`, `failed` or null; ISO date or null. |
| `documentsStatus` | Derived state: `pending` or `ready`. |
| `emailStatus` | Derived state: `queued`, `sent`, `failed` or null. |
| `stage` | Derived state: `pending`, `authorized`, `documents_ready`, `completed`, `failed`. |
| `scheduledFor` | ISO release date of a scheduled invoice, or null. |
| `cancellationReason`, `cancellationDescription` | Reason (`issue_error`, `service_not_provided` or `other`) and justification of the cancellation request, or null. |
| `cancelledAt` | ISO date when the invoice reached `cancelled`, or null. |
| `cancellationRequestedAt` | ISO date of a cancellation requested while the invoice was `processing`, or null. The invoice is cancelled at the Sefin as soon as it is authorized. |
| `createdAt`, `updatedAt` | ISO dates. |
| `documentKeyVersion` | Optional number, when present in the snapshot. |

`requestHash` is removed from serialization. The current response uses `documentsReadyAt`/`documentsStatus`, not the `documentsReady` boolean shown by a Swagger DTO. There is no `lastEmail` object in the current JSON — use the fields above. `stage: completed` can also occur with the email in `failed`; check `emailStatus` to know whether a send succeeded.

Fiscal statuses: `queued`, `processing`, `authorized`, `rejected`, `retry_pending`, `reconciliation_required`, `manual_review`, `failed`, `cancelling`, `cancelled`. Do not treat authorization as immediate availability of every document.

### GET /v1/invoices

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Lists invoices, newest first.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| companyId | string UUID | no | Filters by company. |
| status | string | no | One of the fiscal statuses above. |
| from | string ISO 8601 | no | Inclusive filter by competence date — not by `createdAt`. |
| to | string ISO 8601 | no | Inclusive filter by competence date — not by `createdAt`. |
| externalId | string | no | Exact match. |
| limit | integer | no | Integer between 1 and 1000; defaults to `50`. |
| cursor | string | no | `nextCursor` from the previous page, keeping the same filters. |

```bash
curl "$BASE_URL/invoices?status=authorized&limit=50" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": [
    {
      "id": "6c4d2e81-0a3b-4c5d-9e7f-1a2b3c4d5e6f",
      "status": "authorized",
      "amount": 150.5,
      "competenceDate": "2026-10-01T00:00:00.000Z",
      "createdAt": "2026-10-10T12:00:00.000Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "hasMore": true,
    "nextCursor": "eyJ2IjoxLCJjcmVhdGVkQXQiOiIyMDI2LTEwLTA5VDEyOjAwOjAwLjAwMDAwMFoiLCJpZCI6IjNmMWM4YTkwIn0"
  }
}
```

> Ordering is `createdAt DESC` with an ID tie-break. Continue with `pagination.nextCursor` until `hasMore: false`; newer inserts do not show up when continuing, and there is no `total`.

### GET /v1/invoices/:id

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Fetches a single invoice by id.

```bash
curl "$BASE_URL/invoices/$INVOICE_ID" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "id": "6c4d2e81-0a3b-4c5d-9e7f-1a2b3c4d5e6f",
    "status": "authorized",
    "stage": "documents_ready",
    "documentsStatus": "ready",
    "accessKey": "35260712345678900000350010000000011000000019",
    "nfseNumber": 123
  }
}
```

> Returns `404` if the invoice is not found in the account/environment. An `id` that is not a valid UUID returns `400` (`ERROR_BAD_REQUEST`).

### GET /v1/invoices/:id/xml

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Downloads the XML of an authorized invoice.

```bash
curl "$BASE_URL/invoices/$INVOICE_ID/xml" \
  -H "X-API-Key: $CORVO_API_KEY" --fail --output nfse.xml
```

> Returns raw XML with `Content-Type: application/xml` and `Content-Disposition: attachment; filename="nfse-<number-or-id>.xml"` — no JSON envelope.

> The invoice must be `authorized`, otherwise `404`. Availability also depends on document storage.

### GET /v1/invoices/:id/pdf

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Downloads the PDF of an authorized invoice.

```bash
curl "$BASE_URL/invoices/$INVOICE_ID/pdf" \
  -H "X-API-Key: $CORVO_API_KEY" --fail --output nota.pdf
```

> Returns PDF bytes with `Content-Type: application/pdf` and `Content-Disposition: inline; filename="nfse-<number-or-id>.pdf"` — no JSON envelope.

> The invoice must be `authorized`, otherwise `404`. Availability also depends on document storage.

### GET /v1/invoices/:id/events

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Fetches the status history of an invoice, oldest first. Paginated like any list (`limit`, `cursor`).

```bash
curl "$BASE_URL/invoices/$INVOICE_ID/events" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": [
    {
      "id": "e1d2c3b4-5a6f-4b7c-8d9e-0f1a2b3c4d5e",
      "invoiceId": "6c4d2e81-0a3b-4c5d-9e7f-1a2b3c4d5e6f",
      "fromStatus": "queued",
      "toStatus": "authorized",
      "reason": null,
      "createdAt": "2026-10-10T12:01:00.000Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "hasMore": false,
    "nextCursor": null
  }
}
```

> Fields: `id`, `invoiceId`, `fromStatus` (string or null), `toStatus`, `reason` (string or null), `createdAt`.

### POST /v1/invoices/:id/download-url

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Generates a short-lived signed URL for the invoice documents.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| format | string | yes | `"pdf"` or `"xml"`. |

```bash
curl -X POST "$BASE_URL/invoices/$INVOICE_ID/download-url" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "format": "pdf" }'
```

Response 200 OK:

```json
{
  "data": {
    "downloadUrl": "https://storage.example.com/documento-assinado",
    "expiresAt": "2026-10-10T15:00:00.000Z",
    "fileName": "nfse-123.pdf",
    "mimeType": "application/pdf"
  }
}
```

> The response comes with `Cache-Control: no-store`. The URL is valid for 3600 seconds at the storage. Use it directly and protect it as a temporary credential.

> The invoice must be authorized and have `documentsReadyAt`, otherwise `409`. Missing invoice: `404`. Storage unavailable: `503`.

### POST /v1/invoices/:id/email

Scopes: full_access, invoices_issue, invoices_read_write. Success: 202 Accepted.

Requests email delivery of the invoice to the address stored in `customerSnapshot.email`; no alternative recipient is accepted. The invoice must be authorized with documents ready.

```bash
curl -X POST "$BASE_URL/invoices/$INVOICE_ID/email" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Idempotency-Key: pedido_123_email'
```

Response 202 Accepted:

```json
{
  "data": {
    "emailId": "pedido_123_email",
    "status": "queued"
  }
}
```

> Optional `Idempotency-Key` header: 1–64 characters, letters, numbers, `_` and `-` only. Deduplication checks for the existence of this invoice/key job in the queue.

> `202` does not confirm delivery. On a repeat request the status may reflect the last state of the email. Errors: `404` invoice missing; `409` documents not ready; `422` customer without email or invalid idempotency key.

### POST /v1/invoices/:id/cancel

Scopes: full_access, invoices_issue, invoices_read_write. Success: 200 OK / 202 Accepted.

Cancels an invoice. A `queued` invoice (scheduled or not yet processed) is cancelled immediately; an `authorized` NFS-e moves to `cancelling` while event 101101 is sent to the Sefin. A `processing` invoice (being issued) registers the request: `202`, still `processing`, with `cancellationRequestedAt` set.

```bash
curl -X POST "$BASE_URL/invoices/$INVOICE_ID/cancel" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"reason":"issue_error","description":"Service amount was informed incorrectly"}'
```

Response 202 Accepted:

```json
{
  "data": {
    "id": "6f1c0e2a-4b7d-4c1e-9a55-2b8f7c3d9e10",
    "status": "cancelling",
    "stage": "completed",
    "cancellationReason": "issue_error",
    "cancellationDescription": "Service amount was informed incorrectly",
    "cancelledAt": null,
    "cancellationRequestedAt": null
  }
}
```

> `reason`: `issue_error`, `service_not_provided` or `other`. `description` is required (15–255 characters) for an authorized NFS-e and optional for a queued invoice. A `processing` invoice also requires `description`; once it is authorized it is cancelled automatically at the Sefin and the credit is not refunded, and if the emission ends `rejected` or `failed` the request is discarded and the reservation refunded as usual. Repeating the request for a `processing` (first request wins), `cancelling` or `cancelled` invoice returns its current state.

> `202` does not confirm the cancellation: wait for `nfse.invoice.cancelled` or `nfse.invoice.cancellation_rejected` (the invoice returns to `authorized` with `lastErrorCode`). Cancelling an issued NFS-e does not refund the credit; cancelling a queued invoice releases the live reservation. Errors: `404` invoice missing; `409` `ERROR_INVOICE_NOT_CANCELLABLE` (e.g. `retry_pending`, `reconciliation_required`, `manual_review`); `422` `ERROR_INVALID_CANCELLATION_REASON`. If another request already cancelled the invoice, the current state is returned.

Source: https://www.corvo.tech/en/docs/invoices

---

## Import spreadsheet

Issue invoices in bulk from a CSV or Excel spreadsheet: upload, review, issue and follow the counters, by API or MCP.

Issue hundreds of invoices from one spreadsheet. You upload a `.csv` or `.xlsx`, Corvo reads and checks every row in the background, you review the problems if you want, and then you issue everything. The same flow is available in the dashboard (Invoices, Import spreadsheet) and to assistants through MCP.

### How it works

- `POST /v1/imports` uploads the file and answers right away with the import id.
- Poll `GET /v1/imports/:id` until `status` is `ready`. Each row is checked on its own: a bad row never stops the others.
- Optional review: `GET /v1/imports/:id/rows?status=invalid` shows the problems, `PATCH /v1/imports/:id/rows/:line` fixes one, `GET /v1/imports/:id/errors.csv` downloads only the errors.
- `POST /v1/imports/:id/emit` issues the valid rows. Follow the counters until `status` is `done`.

### The spreadsheet

The first line is the header. Names are matched without caring about case or accents, in Portuguese or English (`valor` or `amount`). CSV may use `;` or `,` and UTF-8, UTF-16 or Windows encodings. Amounts accept `1.234,56`, `1234.56` and `R$ 1.234,56`; dates accept `dd/mm/aaaa` (also `7/11/2026`, `07-11-2026` and `07.11.2026`) and `aaaa-mm-dd`. Columns that match no name below are ignored and listed in `unknown_columns` of the import. Formulas are never run: only the stored value is read.

| Column | Required | What it is |
| --- | --- | --- |
| `cnpj_prestador` | if no company is chosen | CNPJ of the company that issues the row. |
| `tomador_documento` | no | Customer CPF or CNPJ, with or without punctuation. Leading zeros lost by Excel are restored. |
| `tomador_nome` | no | Customer name. |
| `tomador_email` | no | Customer e-mail, to send the invoice. |
| `descricao` | yes | Service description. |
| `valor` | yes | Amount in BRL, up to 2 decimals. |
| `codigo_servico` | no | National service code (6 digits). Empty uses the company default. |
| `data_competencia` | no | Competence date. Empty uses today (America/Sao_Paulo). |
| `pedido` | no | Purchase order or service order number printed on the invoice (up to 60 characters). |
| `observacoes` | no | Free text printed on the invoice as complementary information (up to 2,000 characters). |
| `tomador_nif`, `tomador_sem_nif` | no | Customer abroad: its tax id, or the reason it has none (`dispensado` or `nao exigido`). Used instead of `tomador_documento`. |
| `tomador_pais`, `tomador_codigo_postal`, `tomador_cidade`, `tomador_regiao`, `tomador_logradouro`, `tomador_numero`, `tomador_bairro`, `tomador_complemento` | for a customer abroad | Address abroad. The country is the two-letter code (for example `US`); all are required except the complement. These columns are not in the basic template. |

### Rules

| Rule | Detail |
| --- | --- |
| Limits | Up to 2,000 rows and 10 MB per file; `.csv` or `.xlsx` only. More rows fail the import with `ERROR_IMPORT_TOO_MANY_ROWS`. |
| Company | From the `cnpj_prestador` column or from `companyId`. A row with no company is `invalid` (`ERROR_IMPORT_COMPANY_REQUIRED`); a CNPJ different from the chosen company is `invalid` (`ERROR_IMPORT_COMPANY_MISMATCH`). |
| Environment | An import belongs to the environment of the key that created it: a `test` key only sees `test` imports, a `live` key only `live` ones. |
| Idempotency | Each line has its own key (`import:<id>:<line>`), so repeating `emit` or retrying a job never issues a line twice. |
| Not supported | `SCHEDULE` and `RECURRING` are not accepted inside a spreadsheet. |
| Permissions | Reading (`GET`) needs `invoices_view`; upload, fix, emit and discard need `invoices_issue`. |

### Status and counters

| status | Meaning |
| --- | --- |
| `processing` | The file is being read and every row checked. |
| `ready` | Read. You can review, fix and emit. |
| `emitting` | Issuing. Some invoices may still be waiting for the city. |
| `done` | Nothing is left in progress. Rows awaiting credits can still be issued again. |
| `failed` | The file could not be read (empty, too many rows or not a real spreadsheet), or the chosen company no longer exists (`ERROR_IMPORT_COMPANY_NOT_FOUND`); see `error_code`. |

`counters`: `total`, `valid`, `invalid`, `accepted` (saved and queued for issuing), `authorized` (the city already authorized), `awaiting_credits` (turned away for lack of credits: **not an error**), `failed` (invalid rows plus invoices the city refused), `pending` (still waiting or in progress), `valid_amount` and `awaiting_amount` in BRL. While issuing, `authorized_amount`, `pending_amount` and `failed_amount` show in BRL how much is already authorized, still in progress and refused (invalid rows never count, since they never went out).

### POST /v1/imports

Scopes: full_access, invoices_issue, invoices_read_write. Success: 202 Accepted.

Uploads a spreadsheet (`.csv` or `.xlsx`, up to 2,000 rows and 10 MB) as `multipart/form-data`. Reading is **asynchronous**: the answer is the import to follow, with `status: "processing"`. If the very same file was uploaded before for this company and environment, `duplicate_of` carries the earlier import (a warning, not a block).

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| file | file | yes | The `.csv` or `.xlsx` spreadsheet. |
| companyId | string (uuid) | no | Company that issues the rows without a CNPJ. A row with another company's CNPJ is rejected, so the wrong company never issues. |

```bash
curl -X POST "$BASE_URL/imports" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -F "file=@notas-novembro.csv" \
  -F "companyId=5b0e7c5a-5d0b-4f45-8d6c-3a2a1e9d7f20"
```

Response 202 Accepted: the import to follow:

```json
{ "data": { "id": "576905ae-1707-4848-9ed6-5a6e51800b74", "status": "processing", "duplicate_of": null } }
```

> The upload is limited to 10 requests per minute. A file over 10 MB answers `413` with `ERROR_IMPORT_FILE_TOO_LARGE`; another type answers `400` with `ERROR_IMPORT_FILE_INVALID`.

### GET /v1/imports

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Lists the recent imports of the environment, newest first, with their counters (at most 20). Useful to find an import again, for example one waiting for credits.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| limit | integer | no | 1 to 20, default `10`. |

```bash
curl "$BASE_URL/imports?limit=10" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK: a list of imports:

```json
{ "data": [ /* imports, like GET /v1/imports/:id */ ] }
```

### GET /v1/imports/:id

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

Status and counters of one import. Poll it while `status` is `processing` or `emitting`. While reading, `rows_expected` is how many rows the file has and `counters.total` how many are already checked.

```bash
curl "$BASE_URL/imports/576905ae-1707-4848-9ed6-5a6e51800b74" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK: the import with its counters:

```json
{
  "data": {
    "id": "576905ae-1707-4848-9ed6-5a6e51800b74",
    "status": "ready",
    "file_name": "notas-novembro.csv",
    "company_id": null,
    "error_code": null,
    "rows_expected": 300,
    "unknown_columns": [],
    "emit_started_at": null,
    "emit_finished_at": null,
    "created_at": "2026-11-07T13:05:21.000Z",
    "counters": {
      "total": 300,
      "valid": 297,
      "invalid": 3,
      "accepted": 0,
      "authorized": 0,
      "awaiting_credits": 0,
      "valid_amount": 718602.19,
      "awaiting_amount": 0,
      "failed": 3,
      "pending": 297,
      "authorized_amount": 0,
      "pending_amount": 718602.19,
      "failed_amount": 0
    }
  }
}
```

### GET /v1/imports/:id/rows

Scopes: full_access, invoices_view, invoices_read_write. Success: 200 OK.

The rows of an import, **one page at a time** (never the whole sheet). Filter by `status` to list only the rows with problems (`invalid`) and read the reason in `error_code` and `error_message`.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| status | string | no | `valid`, `invalid`, `queued`, `accepted` or `rejected`. |
| limit | integer | no | 1 to 200, default `50`; more answers `400`. |
| cursor | string | no | `nextCursor` of the previous page. |

```bash
curl "$BASE_URL/imports/576905ae-1707-4848-9ed6-5a6e51800b74/rows?status=invalid&limit=50" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK: a page of rows:

```json
{ "data": [
  {
    "line": 42,
    "data": {
      "amount": "abc",
      "competenceDate": "2026-11-07",
      "companyTaxId": "61469487000140",
      "customer": { "name": "Maria da Silva", "taxId": "52998224725" },
      "service": { "description": "Consultoria mensal" }
    },
    "status": "invalid",
    "error_code": "ERROR_VALIDATION",
    "error_message": "Request validation failed",
    "invoice_id": null
  }
], "pagination": { "limit": 50, "hasMore": false, "nextCursor": null } }
```

### PATCH /v1/imports/:id/rows/:line

Scopes: full_access, invoices_issue, invoices_read_write. Success: 200 OK.

Corrects one row and checks it again, only while the import is `ready`. Send the changed fields in `item`. `customer` and `service` are merged field by field, so editing the e-mail keeps the name. `companyId` and `companyTaxId` cannot be changed. The answer is the row, `valid` or still `invalid` with the reason. A row already queued for issuing answers `409` with `ERROR_IMPORT_STATE`.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| item | object | yes | Invoice fields to change: `amount`, `competenceDate`, `customer { name, taxId, email }`, `service { description, code }`. |

```bash
curl -X PATCH "$BASE_URL/imports/576905ae-1707-4848-9ed6-5a6e51800b74/rows/42" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{ "item": { "amount": 1500.5 } }'
```

Response 200 OK: the row, checked again:

```json
{ "data": {
  "line": 42,
  "data": {
    "amount": 1500.5,
    "competenceDate": "2026-11-07",
    "companyTaxId": "61469487000140",
    "customer": { "name": "Maria da Silva", "taxId": "52998224725" },
    "service": { "description": "Consultoria mensal" }
  },
  "status": "valid",
  "error_code": null,
  "error_message": null,
  "invoice_id": null
} }
```

### POST /v1/imports/:id/emit

Scopes: full_access, invoices_issue, invoices_read_write. Success: 202 Accepted.

Issues every valid row, in chunks of 50, with one idempotency key per line: calling it twice never issues twice. If the plan limit or the credits run out, the remaining rows are left as `awaiting_credits` (not errors). After topping up, **call it again**: only those rows are sent.

```bash
curl -X POST "$BASE_URL/imports/576905ae-1707-4848-9ed6-5a6e51800b74/emit" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 202 Accepted: the import, now emitting:

```json
{
  "data": {
    "id": "576905ae-1707-4848-9ed6-5a6e51800b74",
    "status": "emitting",
    "file_name": "notas-novembro.csv",
    "company_id": null,
    "error_code": null,
    "rows_expected": 300,
    "unknown_columns": [],
    "emit_started_at": null,
    "emit_finished_at": null,
    "created_at": "2026-11-07T13:05:21.000Z",
    "counters": {
      "total": 300,
      "valid": 297,
      "invalid": 3,
      "accepted": 0,
      "authorized": 0,
      "awaiting_credits": 0,
      "valid_amount": 718602.19,
      "awaiting_amount": 0,
      "failed": 3,
      "pending": 297,
      "authorized_amount": 0,
      "pending_amount": 718602.19,
      "failed_amount": 0
    }
  }
}
```

#### Other routes

| Method | Route | Description | Status |
| --- | --- | --- | --- |
| DELETE | `/v1/imports/:id` | Discards an import that was not emitted (nothing is issued). | 204 |
| GET | `/v1/imports/template` | Downloads the spreadsheet template (CSV). | 200 |
| GET | `/v1/imports/:id/errors.csv` | Downloads only the rows that need attention, streamed. Rows that only wait for credits are left out. | 200 |

### When credits run out

Running out of credits is not a failure of the spreadsheet. Issuing stops, the rows that were not sent are kept as `awaiting_credits` (`ERROR_MONTHLY_LIMIT_EXCEEDED`, `ERROR_INSUFFICIENT_CREDITS` and similar codes on the rows) and nothing is lost. Top up your credits and call `POST /v1/imports/:id/emit` again: only those rows are sent, with the same keys. You can find the import later with `GET /v1/imports`.

> In `test`, issuing does not use credits, so this is the way to try a spreadsheet before the real one. Use real CPFs and CNPJs in `live`: the city checks them against the tax registry and refuses invented ones.

### Through MCP

Assistants can run the same flow with the tools `import_create`, `import_list`, `import_get`, `import_rows`, `import_fix_row`, `import_emit` and `import_discard` (see the MCP page). A spreadsheet sent through MCP is text inside the message: CSV in `content` (or an `.xlsx` in `content_base64`), up to 1 MB; bigger files go through `POST /v1/imports`.

Source: https://www.corvo.tech/en/docs/imports

---

## Webhooks

Register webhook configurations and inspect deliveries.

Permissions: `webhooks.view` for fetches; `webhooks.manage` for registration, deletion, test and retry.

### GET /v1/webhooks

Scopes: full_access, invoices_read_write. Success: 200 OK.

Lists the webhook configurations of the account.

```bash
curl "$BASE_URL/webhooks" -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": [
    {
      "id": "7b8c9d0e-1f2a-4b3c-8d5e-6f7a8b9c0d1e",
      "url": "https://integracao.example.com/webhooks/corvo",
      "events": [
        "nfse.invoice.authorized"
      ],
      "active": true,
      "createdAt": "2026-10-10T12:00:00.000Z",
      "updatedAt": "2026-10-10T12:00:00.000Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "hasMore": false,
    "nextCursor": null
  }
}
```

> The listing never returns `secret`.

### POST /v1/webhooks

Scopes: full_access. Success: 201 Created.

Registers a webhook configuration.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| url | string | yes | Must use HTTP or HTTPS and must not point to private/loopback/link-local hosts. |
| events | string[] | yes | Non-empty array containing only accepted public events (list below). |

```bash
curl -X POST "$BASE_URL/webhooks" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://integracao.example.com/webhooks/corvo",
    "events": [
      "nfse.invoice.authorized",
      "nfse.invoice.documents_ready",
      "nfse.invoice.email_sent",
      "nfse.invoice.email_failed"
    ]
  }'
```

Response 201 Created:

```json
{
  "data": {
    "id": "7b8c9d0e-1f2a-4b3c-8d5e-6f7a8b9c0d1e",
    "url": "https://integracao.example.com/webhooks/corvo",
    "events": [
      "nfse.invoice.authorized"
    ],
    "active": true,
    "secret": "whsec_...",
    "createdAt": "2026-10-10T12:00:00.000Z",
    "updatedAt": "2026-10-10T12:00:00.000Z"
  }
}
```

> Store the secret at creation time — it never comes back in the listing. `active` starts as `true`.

### Subscribed events

- `nfse.invoice.authorized`
- `nfse.invoice.rejected`
- `nfse.invoice.failed`
- `nfse.invoice.reconciliation_required`
- `nfse.invoice.manual_review`
- `nfse.invoice.documents_ready`
- `nfse.invoice.email_sent`
- `nfse.invoice.email_failed`
- `nfse.invoice.fiscal_discrepancy`
- `nfse.invoice.cancelled`
- `nfse.invoice.cancellation_rejected`

> `webhook.test` is used by the test route and cannot be included in the subscription array. Accepting an event at registration does not guarantee that every failure path of the current processing emits it; do not rely solely on `failed`/`reconciliation_required` without fetching the invoice.

### DELETE /v1/webhooks/:id

Scopes: full_access. Success: 200 OK.

Deletes a webhook configuration.

```bash
curl -X DELETE "$BASE_URL/webhooks/$WEBHOOK_ID" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "deleted": true
  }
}
```

> Returns `404` if the configuration is not present in the account.

### POST /v1/webhooks/:id/test

Scopes: full_access. Success: 200 OK.

Sends a `webhook.test` event — always with environment `test` — to the registered URL.

```bash
curl -X POST "$BASE_URL/webhooks/$WEBHOOK_ID/test" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "sent": true
  }
}
```

> `{ "sent": true }` is returned when your endpoint answers `2xx`. Otherwise the response is still `200` with `{ "sent": false, "statusCode": 405, "error": "..." }` (`statusCode` is `null` if the endpoint could not be reached). A failed test attempt does not schedule the normal retries.

### GET /v1/webhooks/deliveries

Scopes: full_access, invoices_read_write. Success: 200 OK.

Lists webhook deliveries, newest first.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| hours | number | no | Window in hours (default `24`); it stays fixed on following pages. |
| limit | integer | no | Defaults to `50`; accepts integers from 1 to 1000 (an invalid value returns `400`). |
| cursor | string | no | `nextCursor` from the previous page, keeping the same filters. |
| environment | string | no | `test` or `live`. |

```bash
curl "$BASE_URL/webhooks/deliveries?hours=24&limit=50" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": [
    {
      "id": "c1d2e3f4-5a6b-4c7d-8e9f-0a1b2c3d4e5f",
      "webhookConfigId": "7b8c9d0e-1f2a-4b3c-8d5e-6f7a8b9c0d1e",
      "eventType": "nfse.invoice.authorized",
      "environment": "test",
      "url": "https://integracao.example.com/webhooks/corvo",
      "statusCode": 200,
      "status": "sent",
      "durationMs": 120,
      "retryCount": 0,
      "createdAt": "2026-10-10T12:00:05.000Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "hasMore": true,
    "nextCursor": "eyJ2IjoxLCJjcmVhdGVkQXQiOiIyMDI2LTEwLTA5VDEyOjAwOjAwLjAwMDAwMFoiLCJpZCI6IjNmMWM4YTkwIn0"
  }
}
```

> Fields include `id`, `webhookConfigId`, `eventType`, `environment`, `url`, `payload?`, `statusCode?`, `responseBody?`, `errorMessage?`, `status`, `durationMs?`, `retryCount`, `nextRetryAt?`, `lastError?`, `createdAt`. Delivery `status` values: `pending`, `sent`, `delayed`, `failed`, `manual_retry`. Without `?environment`, the listing may return both environments of the account.

### GET /v1/webhooks/deliveries/stats

Scopes: full_access, invoices_read_write. Success: 200 OK.

Fetches delivery statistics for the recent window.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| hours | number | no | Defaults to `24`. |
| environment | string | no | `test` or `live`. |

```bash
curl "$BASE_URL/webhooks/deliveries/stats?hours=24" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "total": 10,
    "sent": 7,
    "failed": 1,
    "pending": 1,
    "delayed": 1
  }
}
```

> The current implementation computes over up to 1000 recent deliveries. `manual_retry` counts toward `total` but has no counter of its own; the sum of the four counters can be smaller than `total`.

### POST /v1/webhooks/deliveries/:id/retry

Scopes: full_access. Success: 200 OK.

Schedules a new delivery attempt for a failed delivery.

```bash
curl -X POST "$BASE_URL/webhooks/deliveries/$DELIVERY_ID/retry" \
  -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "retried": true
  }
}
```

> Schedules the delivery with `status: manual_retry` and resets its counter — it does not mean the receiver already got the event. Returns `404` for a delivery missing from the account.

Source: https://www.corvo.tech/en/docs/webhooks

---

## Billing & quotas

Plan, consumption, availability and plan changes.

Fetches require `billing.view`; changes require `billing.manage`. All operations use `full_access`.

### GET /v1/billing/plan

Scopes: full_access. Success: 200 OK.

Fetches the current plan and its consumption.

```bash
curl "$BASE_URL/billing/plan" -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "plan": {
      "slug": "solo",
      "name": "Solo",
      "monthly_allowance": 100,
      "daily_limit": null,
      "max_active_companies": 999999,
      "monthly_price_cents": 5990
    },
    "usage": {
      "hard_limit": 100,
      "avulso_balance": 0,
      "credits_used": 10,
      "credits_reserved": 2,
      "credits_remaining": 188,
      "monthly_allowance": 200,
      "daily_usage": 3,
      "daily_limit": null,
      "active_companies": 1,
      "max_active_companies": 999999,
      "period_start": "2026-10-01T00:00:00.000Z",
      "period_end": "2026-10-31T23:59:59.000Z"
    },
    "subscription": {
      "status": "active",
      "paid_until": "2026-10-31T23:59:59.000Z",
      "cancel_at_period_end": false,
      "scheduled_plan": null,
      "blocked": false
    }
  }
}
```

> Values are illustrative. This route uses snake_case, unlike `billing/usage`. If no plan is found after resolution: `404`.

### GET /v1/billing/usage

Scopes: full_access. Success: 200 OK.

Fetches quota availability for issuance.

```bash
curl "$BASE_URL/billing/usage" -H "X-API-Key: $CORVO_API_KEY"
```

Response 200 OK:

```json
{
  "data": {
    "canEmit": true,
    "creditsRemaining": 188,
    "creditsUsed": 10,
    "creditsReserved": 2,
    "monthlyAllowance": 200,
    "dailyUsage": 3,
    "dailyLimit": null,
    "activeCompanies": 1,
    "maxActiveCompanies": 10,
    "periodStart": "2026-10-01T00:00:00.000Z",
    "periodEnd": "2026-10-31T23:59:59.000Z"
  }
}
```

> QuotaStatus: `canEmit` (boolean), `reason?`, `creditsRemaining`, `creditsUsed`, `creditsReserved`, `monthlyAllowance`, `dailyUsage`, `dailyLimit` (number or null), `activeCompanies`, `maxActiveCompanies`, `periodStart`, `periodEnd` (dates or null). Defined `reason` values: `no_credits`, `daily_limit_exceeded`, `company_limit_exceeded`, `plan_blocked`. The current check derives `canEmit` from credits, the daily limit and plan activity — it is not a guarantee that a company's fiscal data/certificate is ready. Quota fetches can initialize the default plan and refresh an expired period.

### POST /v1/billing/upgrade

Scopes: dashboard. Success: 200 OK.

Schedules the switch to the target plan on the subscription.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| plan_slug | string | yes | Slug of the target plan, e.g. `"equipe"`. |

```bash
curl -X POST "$BASE_URL/billing/upgrade" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "plan_slug": "equipe" }'
```

Response 200 OK:

```json
{
  "data": {
    "scheduled_plan": "equipe",
    "effective_at": "2026-11-01T00:00:00.000Z"
  }
}
```

> Dashboard-only route: API keys have no access (`403`). Requires an active subscription (`409` otherwise) and returns `scheduled_plan` and `effective_at`; checkout and the billing portal also live in the dashboard.

### POST /v1/billing/downgrade

Scopes: dashboard. Success: 200 OK.

Schedules a plan change for the end of the period.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| plan_slug | string | yes | Slug of the target plan, e.g. `"solo"`. |

```bash
curl -X POST "$BASE_URL/billing/downgrade" \
  -H "X-API-Key: $CORVO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "plan_slug": "solo" }'
```

Response 200 OK:

```json
{
  "data": {
    "scheduled_plan": "solo",
    "effective_at": "2026-11-01T00:00:00.000Z"
  }
}
```

> Dashboard-only route: API keys have no access (`403`). Requires an active subscription (`409` otherwise) and returns `scheduled_plan` and `effective_at`; checkout and the billing portal also live in the dashboard.

### Public plan catalog

These three routes need no API key or session: use them to show prices on your own site or to size a plan. Amounts are in cents (`...Cents`) and the only cycle is `monthly`; any other `cycle` returns `400`.

### GET /v1/plans

Scopes: public. Success: 200 OK.

Lists the plans with their monthly price and allowance.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| cycle | string | no | `monthly` (default) or `annual`. |
| limit | integer | no | Defaults to `50`; integer from 1 to 1000. |
| cursor | string | no | `nextCursor` from the previous page. |

```bash
curl "$BASE_URL/plans"
```

Response 200 OK:

```json
{
  "data": [
    {
      "slug": "solo",
      "name": "Solo",
      "monthlyAllowance": 100,
      "basePriceCents": 5990,
      "monthlyEquivalentCents": 5990,
      "chargeTotalCents": 5990,
      "currency": "BRL"
    }
  ],
  "pagination": {
    "limit": 50,
    "hasMore": false,
    "nextCursor": null
  }
}
```

> Ordered from the smallest to the largest allowance. `monthlyAllowance` is the number of included credits, `perCreditOverageCents` the price of each credit above it and `monthlyTotalCents` the monthly price. This is the pricing view; `GET /v1/credits/plans` returns the plan limits and features instead.

### GET /v1/plans/:slug

Scopes: public. Success: 200 OK.

Fetches the price of one plan.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| cycle | string | no | `monthly` (default) or `annual`. |

```bash
curl "$BASE_URL/plans/growth"
```

Response 200 OK:

```json
{
  "data": {
    "slug": "equipe",
    "name": "Equipe",
    "monthlyAllowance": 250,
    "basePriceCents": 11990,
    "monthlyEquivalentCents": 11990,
    "chargeTotalCents": 11990,
    "currency": "BRL"
  }
}
```

> `slug` is `solo`, `equipe`, `empresa` or `escala`. An unknown plan returns `404`.

### GET /v1/plans/recommend

Scopes: public. Success: 200 OK.

Cheapest way to cover N notes a month: a plan, a plan plus single notes, or single notes only.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| notes | integer | yes | Notes per month, a whole number from 1 to 1000000. |
| cycle | string | no | `monthly` (default) or `annual` (30% off, paid once a year). |

```bash
curl "$BASE_URL/plans/recommend?notes=250"
```

Response 200 OK:

```json
{
  "data": {
    "notes": 250,
    "cycle": "monthly",
    "option": { "planSlug": "equipe", "avulsoUnits": 0, "totalCents": 11990 },
    "alternatives": [
      { "planSlug": "empresa", "avulsoUnits": 0, "totalCents": 23990 }
    ],
    "currency": "BRL"
  }
}
```

> `planSlug: null` means no plan, single notes only. `totalCents` is the cost per month in the chosen cycle. Single notes cost R$ 0,99 and are sold in lots of at least 3, so `avulsoUnits` is `0` or at least `3`. There is no overage billing. An invalid `notes` returns `400`.

Source: https://www.corvo.tech/en/docs/billing

---

## Async issuance

How issuance processing, tracking and idempotent retries work.

`POST /v1/invoices` responds immediately: a `202` with the invoice in an early status (`queued`, then `processing`/`pending`) means the request was registered and queued — not that the fiscal authority authorized it. Actual processing is asynchronous.

### Tracking

- Poll `GET /v1/invoices/:id` and follow `status`/`stage` until `authorized` (or a terminal failure).
- Fetch the transition history with `GET /v1/invoices/:id/events`.
- Subscribe to webhooks (`nfse.invoice.authorized`, `nfse.invoice.documents_ready`, etc.) to avoid polling.
- Check `GET /v1/billing/usage` (`canEmit`) before issuing again.

> Fiscal statuses: `queued`, `processing`, `authorized`, `rejected`, `retry_pending`, `reconciliation_required`, `manual_review`, `failed`, `cancelling`, `cancelled`. Do not treat authorization as immediate availability of every document — wait for `documentsStatus: "ready"` before generating URLs and requesting emails.

### Idempotency-Key

The `Idempotency-Key` header is optional on issuance and email requests, but recommended — it makes retries safe. Use a stable key per business operation (e.g. the order id in your system) and keep the same key and the same payload on every retry.

The same key, account and environment with content equivalent to the computed hash recovers the same invoice; different content returns `409` (`ERROR_IDEMPOTENCY_CONFLICT`). The hash is computed before fiscal normalization, with canonical JSON keys and the competence date — do not change how fields are represented between retries (a CNPJ with and without punctuation can produce different hashes).

> Without the header there is no deduplication — a naive retry after a timeout can emit the same NFS-e twice.

```js
const key = `pedido_${pedidoId}_emissao`; // stable per business operation

async function issueWithRetry(buildBody, attempts = 3) {
  for (let i = 0; i < attempts; i++) {
    const res = await fetch(`${BASE_URL}/invoices`, {
      method: "POST",
      headers: {
        "X-API-Key": process.env.CORVO_API_KEY,
        "Content-Type": "application/json",
        "Idempotency-Key": key,
      },
      body: JSON.stringify(buildBody()),
    });
    if (res.status === 409) {
      // ERROR_IDEMPOTENCY_CONFLICT — payload differs; fix the data, don't retry
      throw new Error("Idempotency conflict: payload changed between retries");
    }
    if (res.status < 500) return res.json(); // success or client error — no retry
    await new Promise((r) => setTimeout(r, 2000 * 2 ** i)); // backoff on 5xx
  }
  throw new Error("Issuance request failed after retries");
}
```

> Retry with backoff only on `429`/`503`, with the same payload and the same `Idempotency-Key`. Do not repeat validation errors without fixing the data.

Source: https://www.corvo.tech/en/docs/async-issuance

---

## Pagination

Opaque cursor pagination on every list endpoint.

Every listing returns `{ "data": [...], "pagination": { "limit", "hasMore", "nextCursor" } }`. There is no `page`, `pageSize`, `offset` or `total`.

### How to paginate

- First call: `GET /v1/companies?limit=50`. `limit` accepts integers from 1 to 1000 (default `50`); invalid values return `400` with `ERROR_INVALID_LIMIT`, never silently truncated.
- Next pages: send `cursor=<nextCursor>` keeping exactly the same filters. You may change `limit` between pages.
- At the end, `hasMore` is `false` and `nextCursor` is `null`. An empty list returns `data: []`.
- The cursor is opaque and versioned: do not edit, build or reuse it on another collection, tenant or filter (`400` with `ERROR_INVALID_CURSOR`).
- Reads use current data with no snapshot between requests: items inserted later do not show up when continuing a descending listing, and a cursor keeps working if its record is deleted.

```js
async function listAllCompanies() {
  const all = [];
  let cursor;

  do {
    const url = new URL(`${BASE_URL}/companies`);
    url.searchParams.set("limit", "100");
    if (cursor) url.searchParams.set("cursor", cursor);

    const res = await fetch(url, {
      headers: { "X-API-Key": process.env.CORVO_API_KEY },
    });
    const { data, pagination } = await res.json();
    all.push(...data);
    cursor = pagination.hasMore ? pagination.nextCursor : undefined;
  } while (cursor);

  return all;
}
```

> For webhook deliveries (`GET /v1/webhooks/deliveries`) the `hours` window stays fixed on the following pages. Invoice events are ascending; plans keep the commercial order; the other listings are descending by creation date.

Source: https://www.corvo.tech/en/docs/pagination

---

## Receiving webhooks

Outbound request format, event types, retries and signature verification.

Corvo sends a JSON POST to your registered URL. Respond with HTTP 2xx within 10 seconds; enqueue slow work in your receiver.

### Request format

- Method: `POST`.
- Headers: `Content-Type: application/json`, `X-Corvo-Signature: sha256=<hex>`.
- Body: a JSON envelope with `id`, `type`, `environment`, `createdAt` and `data`.

```json
{
  "id": "evt_identifier",
  "type": "nfse.invoice.authorized",
  "environment": "test",
  "createdAt": "2026-10-10T14:00:00.000Z",
  "data": {
    "invoiceId": "INVOICE_UUID",
    "companyId": "COMPANY_UUID",
    "environment": "test",
    "status": "authorized",
    "documentsStatus": "pending",
    "emailStatus": null,
    "stage": "authorized",
    "accessKey": "ACCESS_KEY",
    "nfseNumber": 123
  }
}
```

`data` varies by event; in the fiscal flow it includes the invoice's identification and state. Authorization adds `accessKey`/`nfseNumber`, rejection adds `errorCode`/`errorMessage`, manual review adds `reason`, ready documents add `accessKey`/`nfseNumber`/`documentsReadyAt`, and a sent email adds `sentAt`. The test event carries `{ "message": "This is a test webhook event" }`.

### Event types

| Event type | When |
| --- | --- |
| `nfse.invoice.authorized` | The invoice was authorized; adds `accessKey`/`nfseNumber`. |
| `nfse.invoice.rejected` | Authorization was rejected; adds `errorCode`/`errorMessage`. |
| `nfse.invoice.failed` | Processing failed. |
| `nfse.invoice.reconciliation_required` | Reconciliation is required. |
| `nfse.invoice.manual_review` | Manual review is required; adds `reason`. |
| `nfse.invoice.documents_ready` | Documents are ready; adds `accessKey`/`nfseNumber`/`documentsReadyAt`. |
| `nfse.invoice.email_sent` | The notification email was sent; adds `sentAt`. |
| `nfse.invoice.email_failed` | The notification email failed. |
| `nfse.invoice.fiscal_discrepancy` | `invoiceId`, `status` and `differences[]` (`field`, `local`, `authorized`, `delta`, `kind`): difference between Corvo's calculation and the authorized NFS-e, above R$ 0.01 per tax. The authorized XML is not changed. |
| `nfse.invoice.cancelled` | The invoice was cancelled; adds `reason`. |
| `nfse.invoice.cancellation_rejected` | The Sefin refused the cancellation; the invoice is `authorized` again; adds `errorCode` and `errorMessage`. |
| `webhook.test` | Sent by the test route; carries `{ "message": "This is a test webhook event" }`. |

> Accepting an event at registration does not guarantee that every failure path of the current processing emits it; do not rely solely on `failed`/`reconciliation_required` without fetching the invoice. `webhook.test` cannot be subscribed.

### Signature verification

The signature is the HMAC-SHA256 of the sent JSON body with the configuration's `secret`, in hex. Verify the raw received body bytes — do not parse and stringify before verifying.

```js
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyWebhook(rawBody, signatureHeader, secret) {
  if (typeof signatureHeader !== "string") return false;
  const match = /^sha256=([a-f0-9]{64})$/.exec(signatureHeader);
  if (!match) return false;
  const received = Buffer.from(match[1], "hex");
  const expected = createHmac("sha256", secret).update(rawBody).digest();
  return timingSafeEqual(received, expected);
}
```

> Always compare in constant time (`timingSafeEqual`) and verify against the raw body bytes.

### Retries and delivery semantics

- The outbox makes up to 5 attempts, with intervals after a failure of 60 seconds, 160 seconds, 15 minutes and 30 minutes; execution depends on the worker.
- Retries preserve the original payload — deduplicate by the event `id`.
- The receiver may get the same event again; the current signature has no separate verification timestamp, so deduplication on the receiver is required.
- Do not assume a global delivery order.

> Respond `2xx` quickly and process asynchronously: the 10-second window applies to the HTTP response, not to the work itself.

Source: https://www.corvo.tech/en/docs/receiving-webhooks

---

## Integration checklist

From the first test key to going live.

- 1. Get a `test` key with the right scope. Registering companies/certificates requires `full_access`; an `invoices_read_write` key can issue once the registration exists.
- 2. Register or fetch the company in the corresponding environment (`POST /v1/companies`, `GET /v1/companies/:id`).
- 3. In `live`, upload a valid A1 certificate matching the CNPJ (`POST /v1/companies/:companyId/certificates`). The municipal registration is optional.
- 4. Check readiness with `GET /v1/companies/:id` — `status` must be `ready` and `setupGaps` empty.
- 5. Issue the first invoices in `test` with a stable `Idempotency-Key` and store `data.id`.
- 6. Register a webhook (`POST /v1/webhooks`) and confirm delivery with `POST /v1/webhooks/:id/test`.
- 7. Track status via `GET /v1/invoices/:id` or signed webhooks; generate download URLs and request email only after documents are ready — check `emailStatus` separately.

> Going live requires an active certificate matching the CNPJ and credits/quota available (`GET /v1/billing/usage` — `canEmit` must be `true`).

Source: https://www.corvo.tech/en/docs/integration-checklist

---

## Payment integrations

Connect Woovi, AbacatePay or Stripe and issue the NFS-e automatically for every confirmed payment.

Connect your payment platform account to Corvo. When a payment is confirmed, Corvo issues the NFS-e through the same path as the API: it checks the company and certificate, uses one plan credit and sends the invoice to the city.

### How it works

- In the Corvo dashboard, open Integrations, choose the platform and connect your account. Copy the webhook URL shown during setup.
- Register that address in the payment platform dashboard. The platform then notifies Corvo for every payment.
- Corvo checks the notice's authentication, stores the event and answers right away. Processing happens in the background.
- If the payment is confirmed and a service rule exists, the invoice is issued. The competence date is the confirmation date (São Paulo time zone).
- The same payment never produces two invoices, even if the platform sends the notice again.

### By platform

#### Woovi

- There is no credential to provide. Corvo generates an authentication token shown when you create the connection. Copy and save this token. The `test` environment uses the Woovi sandbox and `live` uses the production account.
- In Woovi, create a webhook with the connection `webhookUrl` and the paid charge event (`OPENPIX:CHARGE_COMPLETED`). Under HTTP headers, add an `Authorization` header with the `webhookToken` in the Value field.
- The invoice customer is the charge customer, never whoever paid the Pix.
- Each charge becomes one invoice, identified by its `correlationID`. The service description on the invoice is the charge `comment`; without one, the company default is used.
- Refunds: also select `PIX_TRANSACTION_REFUND_SENT_CONFIRMED` in the webhook. Corvo links the refund to the sale by the Pix `endToEndId`. A partial refund is ignored.

#### AbacatePay

- Credential: `apiKey`, an AbacatePay API v2 key (Integration > API > + New key) with the `CUSTOMER:READ` and `PRODUCT:READ` permissions. Corvo generates the `webhookSecret` and shows the full webhook URL when you create the connection. Copy and save that address.
- In AbacatePay, create a webhook: paste the `webhookUrl` in the URL field and secret shown when creating the connection in the Secret field, and select `checkout.completed` and `transparent.completed`. Corvo accepts the Standard Webhooks signature (`webhook-id`, `webhook-timestamp`, `webhook-signature`) and the legacy format (`?webhookSecret=`).
- The event `devMode` must match the connection environment: test events issue no invoice on a `live` connection, and the other way around.
- The webhook carries the CPF/CNPJ masked, so Corvo looks the customer up on AbacatePay with your key and uses the full document. If the customer has no document, the sale stays pending (`customer_tax_id_missing`), or is issued without a customer if the rule has `allowAnonymousCustomer`.
- A rule's `externalProductId` is the checkout item `id`. The service description on the invoice is the product name (Corvo looks it up with your key); without the `PRODUCT:READ` permission, the company default is used.
- Refunds: also select `checkout.refunded` and `transparent.refunded` in the webhook. Without automatic cancellation, a refund or dispute after the invoice opens the `refund_after_invoice` pendency and the invoice is not cancelled.

### Sales that need attention

When a sale cannot become an invoice automatically, check its pending status and reason in the integration sales list in the Corvo dashboard.

| blockReason | What to do |
| --- | --- |
| `customer_tax_id_missing` | The platform did not send a full CPF/CNPJ. Complete the customer details on the sale and retry issuing from the dashboard. |
| `no_rule` / `ambiguous_rule` | Create or adjust the rules, then retry from the dashboard. |
| `invoice_rejected` | Fiscal validation refused the request. The message names the field; fix it and retry from the dashboard. |
| `quota_exceeded` | No credits or plan limit reached. After fixing it, retry from the dashboard. |
| `connection_inactive` | The connection is paused or needs to be authorized again. Reactivate it and retry from the dashboard. |
| `company_not_ready` | The company is not ready or the certificate is missing, expired or invalid. Fix the registration and retry from the dashboard. |
| `before_active_from` | The payment happened before the connection start date. No invoice is issued. |
| `refunded` / `disputed` | The payment was refunded or disputed before the invoice. No invoice is issued. |
| `refund_after_invoice` | A refund or dispute arrived after the invoice and automatic cancellation is off. The invoice stays authorized. To cancel it, request cancellation from the invoice page; for future refunds, enable automatic cancellation in the integration settings (a dispute never cancels). |
| `cancel_requested` | Nothing to do: Corvo asked for the invoice to be cancelled (reason "Cancelado por reembolso"). Follow the result on the invoice page. |
| `cancel_failed` | The cancellation could not be requested (for example, the invoice is in a state that does not allow it). Check the invoice and, if it can be cancelled, retry from the dashboard. |

> By default a refund or dispute does not cancel the invoice. To cancel on a refund, enable automatic refund cancellation in the integration settings: Corvo asks for the cancellation with the reason "Cancelado por reembolso" (the invoice credit is not returned). A dispute never cancels. To cancel manually, request cancellation from the invoice page.

> The environment (`test` or `live`) is set on the connection. If the platform reports that an event belongs to another environment, Corvo drops it and issues no invoice.

### Using the API

Everything the dashboard does for payment integrations is also available by API, with an API key (`X-API-Key`).

| Method | Route | Description |
| --- | --- | --- |
| GET | `/v1/integrations/providers` | Available platforms and the credential fields of each |
| POST | `/v1/integrations/connections` | Create a connection |
| GET | `/v1/integrations/connections` | List connections |
| GET | `/v1/integrations/connections/:id` | Get a connection |
| POST | `/v1/integrations/connections/:id/validate` | Check the credentials and identify the account |
| POST | `/v1/integrations/connections/:id/activate` | Start issuing automatically |
| POST | `/v1/integrations/connections/:id/pause` | Stop issuing; events are still stored |
| POST | `/v1/integrations/connections/:id/disconnect` | Disconnect for good |
| GET | `/v1/integrations/connections/:id/rules` | Get the service rules |
| PUT | `/v1/integrations/connections/:id/rules` | Replace the service rules |
| GET | `/v1/integrations/connections/:id/events` | Events received |
| GET | `/v1/integrations/connections/:id/operations` | Sales and the invoice status of each |
| PATCH | `/v1/integrations/operations/:id/customer` | Fill in the customer of a pending sale |
| POST | `/v1/integrations/operations/:id/retry` | Try to issue again |
| POST | `/v1/integrations/inbound/:publicId` | Address the payment platform calls (public, authenticated by the connector) |

> The management routes require `integrations.view` (read) or `integrations.manage` (create, activate, change rules). `full_access` API keys have both.

```bash
curl -X POST "$BASE_URL/v1/integrations/connections"   -H "X-API-Key: $CORVO_API_KEY"   -H "Content-Type: application/json"   -d '{
    "provider": "woovi",
    "companyId": "<company id>",
    "environment": "test",
    "credentials": {},
    "activeFrom": "2026-11-01T00:00:00Z"
  }'
```

```bash
curl -X PUT "$BASE_URL/v1/integrations/connections/$CONNECTION_ID/rules"   -H "X-API-Key: $CORVO_API_KEY"   -H "Content-Type: application/json"   -d '{ "rules": [ { "service": { "code": "010101", "description": "Consulting" }, "sendEmail": true } ] }'

curl -X POST "$BASE_URL/v1/integrations/connections/$CONNECTION_ID/validate" -H "X-API-Key: $CORVO_API_KEY"
curl -X POST "$BASE_URL/v1/integrations/connections/$CONNECTION_ID/activate" -H "X-API-Key: $CORVO_API_KEY"
```

A rule without `externalProductId` applies to any product. To give a product a different service, send another rule with its `externalProductId`. Payments made before `activeFrom` are ignored.

A sale that could not become an invoice shows up in `GET /v1/integrations/connections/:id/operations` with `fiscalStatus` and `blockReason` (see the table above). Fix it with `PATCH /v1/integrations/operations/:id/customer` or by adjusting the rules, then call `POST /v1/integrations/operations/:id/retry`. To cancel an invoice after a refund, use `POST /v1/invoices/:id/cancel`.

Source: https://www.corvo.tech/en/docs/payment-integrations

---

## Municipalities on the national standard

Official list of Brazilian municipalities on the national NFS-e environment, searchable by name, state or IBGE code.

Corvo issues the NFS-e through the Receita Federal's national environment, so it matters how your company's municipality is on the national standard. The list below comes from the official table of the NFS-e Portal and already carries the 7-digit IBGE code the API asks for in `municipalityCode`.

### How to read the status

| Status | What it means | Municipalities |
| --- | --- | --- |
| Emissor Nacional | The municipality adopted the national issuer: the invoice is born in the national standard. | 3,495 |
| National environment only | The municipality joined and shares its invoices with the national environment, but keeps its own issuer. For taxpayers in general, issuing stays in the city hall's system. MEI and Simples Nacional issue through the national issuer by federal rule (MEI since 2023; ME and EPP from November 1, 2026). | 2,050 |
| Agreement not active | The municipality is registered, but the agreement is not active yet. | 26 |

> This list shows each municipality's status on the national standard. It does not guarantee that every invoice is accepted: the Receita decides when it receives the invoice. The API call is the same in every municipality; what changes is what the Receita accepts for that municipality.

### Search a municipality

The full list of municipalities, with search, is on the documentation page. The table by state below summarizes each state.

### By state

| State | Municipalities | Emissor Nacional | National environment only | Agreement not active |
| --- | --- | --- | --- | --- |
| AC | 22 | 11 | 11 | 0 |
| AL | 102 | 72 | 30 | 0 |
| AM | 62 | 40 | 21 | 1 |
| AP | 16 | 11 | 4 | 1 |
| BA | 417 | 187 | 229 | 1 |
| CE | 184 | 87 | 97 | 0 |
| DF | 1 | 1 | 0 | 0 |
| ES | 78 | 36 | 42 | 0 |
| GO | 246 | 133 | 113 | 0 |
| MA | 217 | 111 | 93 | 13 |
| MG | 853 | 611 | 242 | 0 |
| MS | 79 | 66 | 13 | 0 |
| MT | 142 | 114 | 28 | 0 |
| PA | 144 | 116 | 27 | 1 |
| PB | 223 | 73 | 150 | 0 |
| PE | 185 | 74 | 111 | 0 |
| PI | 224 | 130 | 89 | 5 |
| PR | 399 | 239 | 159 | 1 |
| RJ | 92 | 54 | 38 | 0 |
| RN | 167 | 85 | 82 | 0 |
| RO | 52 | 39 | 13 | 0 |
| RR | 15 | 9 | 6 | 0 |
| RS | 497 | 356 | 140 | 1 |
| SC | 295 | 253 | 42 | 0 |
| SE | 75 | 39 | 34 | 2 |
| SP | 645 | 493 | 152 | 0 |
| TO | 139 | 55 | 84 | 0 |

### Source and updates

Source: Receita Federal, NFS-e Portal, Monitoramento das Adesões page (spreadsheet of November 10, 2026). The IBGE code comes from the IBGE list of municipalities. The Receita updates the table as municipalities join, and this page is updated from it. If they differ, the official table prevails: https://www.gov.br/nfse/pt-br/municipios/monitoramento-adesoes

Source: https://www.corvo.tech/en/docs/municipalities

---

## AI agents (MCP)

Connect Claude Code, Claude Desktop, Cursor, VS Code, Codex and Windsurf to Corvo with OAuth.

The Corvo MCP server lets AI agents (Claude Code, Cursor and other MCP clients) issue and query NFS-e on behalf of a user, without you writing an integration. The agent connects with OAuth: it opens the browser, you sign in to Corvo, pick the workspace and approve. No API key is copied.

### Connect an agent

Use the server URL below. It also appears in the dashboard under AI agents, with ready-to-copy commands.

```bash
claude mcp add --transport http corvo https://api.corvo.tech/mcp
```

```json
{
  "mcpServers": {
    "corvo": {
      "url": "https://api.corvo.tech/mcp"
    }
  }
}
```

```json
{
  "servers": {
    "corvo": {
      "type": "http",
      "url": "https://api.corvo.tech/mcp"
    }
  }
}
```

```text
[mcp_servers.corvo]
url = "https://api.corvo.tech/mcp"
```

```json
{
  "mcpServers": {
    "corvo": {
      "serverUrl": "https://api.corvo.tech/mcp"
    }
  }
}
```

#### Claude Desktop

- Open Settings → Connectors.
- Click Add custom connector, enter a name (Corvo) and paste the server URL.
- Click Connect and approve access in the browser.
- URL: `https://api.corvo.tech/mcp`

> Not yet verified with Corvo's OAuth: the VS Code, Codex, Windsurf and Claude Desktop formats follow each client's public documentation and the dashboard. If one does not connect, use the dashboard (AI agents) and tell us.

```text
List my companies on Corvo and issue a test NFS-e of R$ 100.
```

- Add the server to the agent with the URL `https://api.corvo.tech/mcp`.
- The agent opens the browser on the Corvo approval screen. If you are not signed in, sign in first; you then return to the approval.
- Pick the workspace and click Allow (or Deny).
- Go back to the agent. It now has the Corvo tools.

> When you approve, you choose the connection environment: `test` (invoices with no fiscal value) or `live` (real invoices, using credits). Each connection stays in one environment; to switch, reconnect the agent. Start with test.

### Permissions

| Scope | What it allows | Roles that can grant it |
| --- | --- | --- |
| `nfse:read` | Query, list and download the PDF of invoices | admin, developer, billing |
| `nfse:write` | Issue invoices | admin, developer |

A member can only approve scopes that their own role in the workspace allows. A workspace where your role does not cover the request appears disabled on the approval screen.

### Tools

| Tool | Scope | Main input | Output |
| --- | --- | --- | --- |
| `nfse_issue` | `nfse:write` | `company_tax_id` (CNPJ) or `company_id`, `amount` (or `services [{description, quantity, unit_price}]`), `customer? {tax_id, name?, email?}` or `customer {name, foreign {tax_id \| no_tax_id_reason, country, postal_code, city, region, street, number, district}}` for a customer abroad (`tax_id` required when the customer is in Brazil), `description?`, `discount?`, `deduction?` (ISS base deduction declared by the issuer), `purchase_order?` (purchase order number, up to 60 characters), `notes?` (free text printed on the invoice), `competence_date?` (default: today), `emission_type?` (`IMMEDIATE`/`SCHEDULE`/`RECURRING`), `recurrence_frequency?` (`WEEKLY`/`BIWEEKLY`/`MONTHLY`, required with `RECURRING`), `recurrence_ends_on?`, `send_email?`, `service_code?`, `external_id?`, `idempotency_key?` | `{ invoice_id, access_key, status }`; with `SCHEDULE` or `RECURRING`, `{ schedule_id, kind, frequency, status, next_run_on, ends_on }` |
| `schedule_list` | `nfse:read` | `status?`, `company_id?`, `limit?`, `offset?` | `{ schedules [...], total, limit, offset }` |
| `schedule_get` | `nfse:read` | `schedule_id` | the schedule |
| `schedule_runs` | `nfse:read` | `schedule_id`, `limit?`, `offset?` | `{ runs [{ occurrence_on, ran_on, attempt, outcome, invoice_id?, error_code?, error_message? }], total }` |
| `schedule_update` | `nfse:write` | `schedule_id` and what changes: `amount?`, `description?`, `purchase_order?`, `notes?` (an empty text removes it), `customer?`, `send_email?`, `ends_on?` (or `null`), `frequency?`, `first_date?` | the schedule |
| `schedule_pause` | `nfse:write` | `schedule_id` | the schedule |
| `schedule_resume` | `nfse:write` | `schedule_id` | the schedule |
| `schedule_cancel` | `nfse:write` | `schedule_id` | the schedule |
| `import_create` | `nfse:write` | `content` (CSV) or `content_base64` (.xlsx), `file_name?`, `company_id?`; up to 1 MB and 2,000 rows | `{ id, status, duplicate_of }`; reading is asynchronous |
| `import_list` | `nfse:read` | `limit?` (1 to 20) | `{ imports [...] }` with counters, newest first |
| `import_get` | `nfse:read` | `import_id` | the import: `status`, `rows_expected`, `counters` (`valid_amount`, `awaiting_credits`...) |
| `import_rows` | `nfse:read` | `import_id`, `status?`, `cursor?`, `limit?` (up to 200) | `{ rows [{ line, data, status, error_code, error_message, invoice_id }], next_cursor, has_more }` |
| `import_fix_row` | `nfse:write` | `import_id`, `line`, `item` | the row, checked again (`valid`, or `invalid` with the reason) |
| `import_emit` | `nfse:write` | `import_id` | the import, `emitting`; call again after topping up credits to send only the `awaiting_credits` rows |
| `import_discard` | `nfse:write` | `import_id` | `{ import_id, discarded: true }` |
| `company_list` | `nfse:read` | `tax_id?` (CNPJ), `limit?`, `cursor?` | `{ companies [{ id, legal_name, tax_id, status, tax_regime, setup_gaps, ready_to_issue }], next_cursor }` |
| `nfse_issue_batch` | `nfse:write` | `invoices` (1 to 50 items, each with the same fields as `nfse_issue`, including `company_tax_id` or `company_id` and `idempotency_key`) | `{ total, accepted, rejected, results [{ index, status, replayed?, invoice_id?, access_key?, invoice_status?, error? }] }`; invalid items are rejected in place and the valid ones are saved together |
| `company_get` | `nfse:read` | `tax_id` (CNPJ) | `{ company }` or `{ company: null }` |
| `company_create` | `nfse:write` | `legal_name`, `tax_id`, `tax_regime`, `municipality_code`, `simples_rate` (required for Simples Nacional), `simples_iss_rate?` and optional fiscal data | `{ id, legal_name, tax_id, status }`; certificates remain API-only |
| `nfse_calculate` | `nfse:read` | `company_tax_id` or `company_id`, `amount`, optional `discount`, `deduction` and fiscal data | Calculation result; no issue, credit reservation or DPS |
| `billing_usage` | `nfse:read` | No parameters | `QuotaStatus` with `canEmit`, allowance and usage |
| `nfse_cancel` | `nfse:write` | `invoice_id`, `reason` (`issue_error`, `service_not_provided` or `other`), `description?` (15–255 characters, required for an authorized NFS-e or one being issued) | `{ invoice_id, status, cancelled_at }` (`cancelled`, `cancelling`, or `processing` with the request recorded) |
| `nfse_substitute` | `nfse:write` | `invoice_id`, `description` (15–255 characters), `service_description?`, `purchase_order?`, `notes?` (an empty text removes it) | `{ invoice_id, status, substitutes_invoice_id }` (the substitute, in `queued`). Customer, competence date and amount do not change |
| `customer_list` | `nfse:read` | `search?` (part of the name or start of the document), `limit?` (1 to 100, default 20), `offset?` | `{ customers: [{ tax_id, name, email, last_used_at }], total, limit, offset }` |
| `customer_update` | `nfse:write` | `tax_id` and what changes: `name?`, `email?` (`null` removes it) | `{ tax_id, name, email, last_used_at }` |
| `customer_delete` | `nfse:write` | `tax_id` | `{ tax_id, deleted: true }` |
| `nfse_query` | `nfse:read` | `access_key` | `{ access_key, status, nfse_number, authorized_at, last_error }` |
| `nfse_list` | `nfse:read` | `status?`, `limit?`, `cursor?` | `{ invoices, next_cursor }` |
| `nfse_download_pdf` | `nfse:read` | `access_key` (authorized invoice) | `{ access_key, pdf_base64 }` |
| `nfse_get_download_url` | `nfse:read` | `access_key`, `format` (`pdf` or `xml`; authorized invoice) | `{ download_url, expires_at, file_name, mime_type }` (signed URL, valid for one hour) |

The simplest call is `company_tax_id` plus `amount`: the customer is optional (omit it for an invoice without tomador; if you send one, `tax_id` is required), the competence date defaults to today, the service code comes from the company or falls back to `100901` (LC 116 item 10.09) and the description from the service code. Use `company_get` for one CNPJ and `billing_usage` before issuing. A1 certificates are not exposed over MCP and must be uploaded through the API only. Tool failures come back as a result with `isError: true` and the message as text, so the agent can read and fix them.

### See usage and revoke

- In the dashboard, open AI agents → Connected apps: you see each agent, the workspace, the permissions, the last use and how many calls and invoices it made.
- Click Revoke to cut access immediately. The agent has to be approved again to come back.
- Workspace admins see and can revoke every member's connections; other members see only their own.
- Reconnecting the same agent reuses the connection and revokes the previous session.

Source: https://www.corvo.tech/en/docs/mcp

---

## Build with AI (llms.txt)

Give llms.txt to your coding agent and let it implement the Corvo integration.

Corvo publishes its documentation in a format built for AI coding agents. Give the address to your agent (Claude Code, Cursor, Codex, Copilot and others) and it reads the API and writes the integration in your project, following the same rules as this documentation.

### What to give the agent

| File | Address | Use |
| --- | --- | --- |
| `llms.txt` | `https://www.corvo.tech/llms.txt` | Short index with the key facts and a link to every documentation page. The agent opens only what it needs. |
| `llms-full.txt` | `https://www.corvo.tech/llms-full.txt` | The whole documentation in one Markdown file (English): endpoints, fields, examples and errors. Best when the agent should implement everything in one pass. |

### Ready-to-use prompt

Copy it, fill in the part in brackets and paste it into your agent. It points to `llms-full.txt` and sets the rules that matter: test environment, key outside the code, idempotency and asynchronous issuance.

```text
Read https://www.corvo.tech/llms-full.txt (the Corvo NFS-e API documentation) and integrate invoice issuance into this project.

My stack and where invoices are created: [describe your language/framework and the place in the code where an order or sale becomes an invoice].

Follow these rules:
- Use the test environment. Read the key from the CORVO_API_KEY environment variable (it starts with corvo_test_). Never write a key in code, in tests or in commits.
- Register the company once with POST /v1/companies (taxId, taxRegime, municipalityCode) and keep its id.
- Before issuing, call POST /v1/invoices/calculate and show the taxes when it makes sense.
- Issue with POST /v1/invoices and send an Idempotency-Key built from my own order id, so a retry never creates a second invoice.
- Issuance is asynchronous: save the invoice id, and update the status from the nfse.invoice.authorized and nfse.invoice.rejected webhooks (verify the signature) or by polling GET /v1/invoices/:id.
- Handle the documented errors (validation, 409, 429 with Retry-After) and never log customer documents.
- Write tests with mocked HTTP. Do not call the live environment.

When you finish, list the files you changed and what I still need to configure (webhook URL, environment variables).
```

### In each tool

- Claude Code, Codex and other terminal agents: paste the prompt. They fetch the address themselves.
- Cursor: add `https://www.corvo.tech/llms-full.txt` as a documentation source (Settings → Indexing & Docs), then mention it in the chat, or paste the prompt.
- VS Code, Windsurf and chat apps: paste the prompt; if the tool cannot open addresses, download `llms-full.txt` and attach the file to the conversation.

> Never paste a `live` key into a prompt or a chat. Keep `corvo_test_...` in an environment variable, review the generated code before going live (company data, service code and tax regime are yours to confirm) and only then switch the key.

### Write the code, or operate directly

This page is for an agent that writes the integration into your repository. If you want the agent to issue and query invoices itself, in a conversation, connect it to the MCP server instead: see AI agents (MCP). Both can be used together.

Source: https://www.corvo.tech/en/docs/llms

---

# Como emitir nota fiscal de serviço (NFS-e): guia simples para MEI e Simples Nacional

> Para emitir a nota fiscal de serviço (NFS-e), você usa o sistema nacional do governo ou um emissor, como a Corvo. No portal, o MEI entra com a conta gov.br e preenche os dados a cada nota. Na Corvo, você cadastra a empresa uma vez e depois emite pelo painel, por planilha, por agenda ou conversando com um assistente de IA.

Prestou o serviço, o cliente pagou e falta a nota. Aqui estão as regras básicas e as formas de emitir, com cada termo explicado na primeira vez que aparece.

## O que é a NFS-e

A **NFS-e** é a nota fiscal de serviço eletrônica. É o documento que comprova que você prestou um serviço (uma aula, uma consultoria, um corte de cabelo, uma manutenção, um projeto de design) e que o imposto dessa prestação foi declarado.

Quem vende **produto** emite outra nota, a NF-e. É outro assunto, e a Corvo não emite esse tipo de nota.

Antes, cada prefeitura tinha o próprio sistema de nota. Hoje existe um sistema único do governo, o **Emissor Nacional**, e a nota emitida nele é a NFS-e “no padrão nacional”.

## Quem precisa emitir no padrão nacional

- **MEI:** a emissão pelo padrão nacional é obrigatória desde 1º de setembro de 2023 para quem presta serviço a outra empresa (CNPJ). Para cliente pessoa física, a nota segue opcional.
- **Microempresa (ME) e empresa de pequeno porte (EPP) do Simples Nacional:** obrigatória desde 1º de novembro de 2026. Explicamos em [NFS-e do Simples Nacional: o que mudou em novembro de 2026](/pt/blog/simples-nacional-nfse-nacional-novembro-2026).

> Regras fiscais mudam. Confirme com o seu contador e na [página oficial do governo sobre a NFS-e](https://www.gov.br/pt-br/servicos/emitir-nota-fiscal-de-servico-eletronica) antes de decidir.

## Três jeitos de emitir a nota

| Jeito | Como funciona | Bom para |
| --- | --- | --- |
| Portal do governo | Você entra e preenche um formulário a cada nota. O MEI entra com a conta gov.br (nível prata ou ouro), sem certificado digital. | Quem emite poucas notas por mês. |
| Emissor, como a Corvo | Você cadastra a empresa uma vez e emite pelo painel, por planilha, por agenda ou conversando com um assistente de IA. | Quem emite todo mês, para vários clientes ou para mais de uma empresa. |
| Contador | Você passa os dados e ele emite a nota. | Quem prefere não mexer com isso. |

## Como começar na Corvo, passo a passo

1. Crie a conta. É grátis e não pede cartão de crédito.
2. **Cadastre a empresa:** razão social, CNPJ, se é MEI ou Simples Nacional e o município. Antes de emitir notas de verdade, o painel também pede a **inscrição municipal** da empresa.
3. Emita uma nota de teste. Ela não tem valor fiscal, não precisa de certificado e não custa nada. Serve para você conhecer o painel sem medo de errar.
4. **Envie o certificado digital A1 da empresa** para emitir notas de verdade. Não sabe o que é isso? Veja o [guia do certificado digital A1](/pt/blog/certificado-digital-a1-o-que-e-quando-precisa).
5. Emita a nota real. A primeira é grátis.

## O que a Corvo faz por você

- Mostra os tributos da nota **antes** de emitir, para você ver o valor líquido.
- Entrega a nota pronta, com PDF e XML, e pode enviá-la por e-mail ao seu cliente.
- Deixa você emitir várias notas de uma vez por [planilha](/pt/blog/emitir-varias-notas-fiscais-com-planilha) e repetir a nota todo mês com a [agenda](/pt/blog/nota-fiscal-todo-mes-agendada).
- Guarda o certificado da empresa criptografado.

A Corvo **não** emite nota de produto (NF-e), não atende empresas fora do MEI e do Simples Nacional e não gera a guia do DAS.

## E se eu não entendo de imposto?

Você não precisa entender. O MEI não informa alíquota nenhuma. A ME e a EPP informam uma vez, ao cadastrar a empresa, a alíquota efetiva do Simples Nacional, que é o número que o seu contador já conhece. O resto, a Corvo calcula antes de emitir.

Quem quiser integrar a emissão ao próprio sistema pode ver os detalhes na [documentação da API](/pt/docs). Para quem só quer emitir a nota, o painel resolve.

## Perguntas frequentes

### O MEI precisa de certificado digital para emitir nota de serviço?

No portal do governo, não: o MEI entra com a conta gov.br em nível prata ou ouro. Para emitir pela Corvo uma nota de verdade, a empresa precisa do certificado digital A1. No ambiente de teste, não precisa de nenhum.

### Posso testar antes de emitir uma nota de verdade?

Pode. O ambiente de teste é grátis e as notas emitidas nele não têm valor fiscal. Use para conhecer o painel e conferir os dados antes de emitir de verdade.

### A Corvo emite nota de produto?

Não. A Corvo emite só NFS-e, a nota de serviço. Nota de produto (NF-e) e nota de varejo (NFC-e) não fazem parte do que ela oferece.

### Quanto custa emitir a primeira nota?

A primeira nota é grátis, sem cartão de crédito. O ambiente de teste também é sempre grátis. Os planos e o preço das notas seguintes ficam na seção de preços do site.

### Preciso saber a alíquota do Simples Nacional?

Só se a empresa for ME ou EPP: você informa a alíquota efetiva uma vez, ao cadastrar a empresa, e seu contador sabe qual é. O MEI não informa alíquota.

Fonte: https://www.corvo.tech/pt/blog/como-emitir-nota-fiscal-de-servico-nfse · atualizado em 2026-11-10

---

# Nota fiscal de serviço do Simples Nacional: o que mudou em 1º de novembro de 2026

> Desde 1º de novembro de 2026, microempresas (ME) e empresas de pequeno porte (EPP) do Simples Nacional devem emitir a nota fiscal de serviço no padrão nacional, conforme a Resolução CGSN nº 191/2026. Na prática: confira como você emite hoje, converse com o contador e escolha como emitir no sistema nacional.

Se a sua empresa é do Simples Nacional e emite nota de serviço pelo site da prefeitura, a forma de emitir mudou. Este texto explica o que aconteceu e o que fazer.

## O que mudou

A **NFS-e padrão nacional** é a nota de serviço emitida no sistema único do governo (o Emissor Nacional), em vez de no sistema de cada prefeitura. Para as empresas do Simples Nacional que são **ME ou EPP**, esse caminho passou a ser obrigatório em **1º de novembro de 2026**.

Se você é **MEI**, nada de novo: o MEI já emitia no padrão nacional desde 1º de setembro de 2023, quando presta serviço a outra empresa. Veja o básico em [Como emitir nota fiscal de serviço](/pt/blog/como-emitir-nota-fiscal-de-servico-nfse).

## A data mudou durante o ano

Se você ouviu falar de **setembro**, não errou: a Resolução CGSN nº 189/2026 previa essa data. Depois, a Resolução CGSN nº 191/2026, de 4 de agosto de 2026, a substituiu e fixou **1º de novembro**. A [Fenacon](https://fenacon.org.br/noticias/simples-nacional-nfs-e-nacional-sera-obrigatoria-para-me-e-epp-a-partir-de-1o-de-novembro-de-2026/) resume a mudança.

> Alguns textos antigos na internet ainda citam setembro. Na dúvida, confirme a data e a sua situação com o contador. Este guia explica a regra; ele não substitui a orientação de quem cuida da contabilidade da sua empresa.

## O que fazer agora

1. Confirme que sua empresa é ME ou EPP optante do Simples Nacional. Seu contador ou o seu comprovante de opção mostra isso.
2. Veja como você emite hoje. Se é pelo site da prefeitura, vale perguntar ao contador como a sua cidade ficou com a mudança.
3. **Escolha como emitir no sistema nacional:** pelo portal do governo, pelo contador ou por um emissor como a Corvo.
4. Teste antes de emitir de verdade. Na Corvo, o ambiente de teste é grátis e não tem valor fiscal.
5. **Separe o certificado digital A1 da empresa**, se for emitir por um emissor. O [guia do certificado A1](/pt/blog/certificado-digital-a1-o-que-e-quando-precisa) explica o que é.

## Como a Corvo ajuda

A Corvo emite a NFS-e no padrão nacional para empresas **MEI e do Simples Nacional**. Para a ME e a EPP, o cadastro tem uma particularidade: você informa a **alíquota efetiva** do Simples Nacional da empresa, o número que aparece no extrato do PGDAS-D e que o seu contador conhece. Ela vai em todas as notas, e a Corvo calcula os tributos antes de emitir.

Antes de começar, confira se o seu município está coberto na [página de cobertura por município](/pt/docs/municipalities). A Corvo **não** gera a guia do DAS.

## Se a nota der problema

Se uma nota não for autorizada, ela fica com o status **rejeitada** ou **em revisão**, e você vê isso no painel. Não adianta reemitir sem entender o motivo: corrija o que o painel indicar, ou fale com o suporte. Emitir de novo às cegas pode gerar duas notas para o mesmo serviço.

## Perguntas frequentes

### A partir de quando a NFS-e nacional é obrigatória para o Simples Nacional?

Para microempresas (ME) e empresas de pequeno porte (EPP) do Simples Nacional, desde 1º de novembro de 2026, pela Resolução CGSN nº 191/2026. Confirme a sua situação com o contador.

### O MEI também mudou em novembro de 2026?

Não. O MEI já emitia no padrão nacional desde 1º de setembro de 2023, quando presta serviço a outra empresa. Para cliente pessoa física, a nota segue opcional.

### Preciso trocar de sistema?

Depende de onde você emite hoje. Se emite pelo site da prefeitura, a emissão agora é no sistema nacional, pelo portal do governo, pelo contador ou por um emissor como a Corvo.

### A Corvo atende empresas do Simples Nacional?

Sim. A Corvo emite NFS-e para MEI e para empresas do Simples Nacional. Ela não atende outros regimes e não emite nota de produto.

### Quem informa a alíquota do Simples Nacional?

A ME ou a EPP informa a alíquota efetiva uma vez, ao cadastrar a empresa. É o número do extrato do PGDAS-D, que o contador conhece. O MEI não informa alíquota.

Fonte: https://www.corvo.tech/pt/blog/simples-nacional-nfse-nacional-novembro-2026 · atualizado em 2026-11-10

---

# Certificado digital A1: o que é, quando você precisa e como guardar com segurança

> O certificado digital A1 é um arquivo que funciona como o “RG digital” do CNPJ da empresa. Para emitir nota pelo portal do governo, o MEI não precisa dele: basta a conta gov.br em nível prata ou ouro. Para emitir notas de verdade por um emissor como a Corvo, o A1 da empresa é necessário. Nos testes, não.

Certificado digital soa como burocracia, mas o conceito é simples e, em geral, você só lida com ele quando precisa renovar.

## O que é o certificado A1

É um **arquivo** (normalmente com final `.pfx` ou `.p12`) que prova que quem está emitindo a nota é mesmo a empresa. Funciona como o RG digital do CNPJ: ele assina a nota em nome da empresa.

Ele é vendido por uma autoridade certificadora credenciada e tem **prazo de validade**, geralmente de um ano. Depois disso, é preciso renovar. Existe também o certificado A3, que fica em um cartão ou token; para emitir por um sistema, o que vale é o A1, que é o arquivo.

## Quando você precisa dele

| Situação | Precisa do A1? |
| --- | --- |
| MEI emitindo no portal do governo | Não. Entra com a conta gov.br em nível prata ou ouro, ligada ao CNPJ. |
| Emitindo notas de verdade pela Corvo | Sim. O A1 do CNPJ da empresa é necessário para assinar as notas. |
| Testando na Corvo | Não. O ambiente de teste não usa certificado e as notas não têm valor fiscal. |

> Para o portal do governo, as regras de acesso podem mudar. Confira na [página oficial da NFS-e](https://www.gov.br/pt-br/servicos/emitir-nota-fiscal-de-servico-eletronica) e com o seu contador.

## Como enviar o certificado para a Corvo

1. Tenha o arquivo do certificado A1 da empresa e a **senha** dele, que você definiu na compra.
2. Entre no painel da Corvo e abra a página da empresa que vai emitir.
3. Clique em **Enviar certificado**, escolha o arquivo (.p12 ou .pfx, de até 50 KB) e informe a senha. A senha é usada só nesse envio.
4. Depois disso, a empresa pode emitir notas reais.

Se ainda não tem a empresa cadastrada, comece pelo [guia de como emitir nota fiscal de serviço](/pt/blog/como-emitir-nota-fiscal-de-servico-nfse).

## Como guardar com segurança

O certificado é a assinatura da sua empresa. Quem tem o arquivo e a senha pode assinar em seu nome. Por isso:

- Não mande o certificado por WhatsApp, e-mail ou chat. Envie somente pelo painel de quem vai usá-lo.
- **Não compartilhe a senha** junto com o arquivo.
- **Guarde uma cópia** em um lugar seguro, como o gerenciador de senhas ou um disco protegido.
- **Anote a data de validade** e renove antes de vencer, para não ficar sem poder emitir.
- **Nunca cole o arquivo ou a senha em conversa com assistente de IA.**

Na Corvo, o certificado fica **criptografado**. Mesmo assim, o cuidado é seu na hora de enviar e guardar.

## Meu certificado venceu. E agora?

Compre ou renove o certificado A1 com a autoridade certificadora e envie o novo arquivo pelo painel. Enquanto o certificado estiver vencido, a empresa não consegue emitir notas reais. O ambiente de teste continua funcionando.

## Perguntas frequentes

### O que é certificado digital A1?

É um arquivo que funciona como o RG digital do CNPJ da empresa e assina as notas em nome dela. Costuma ter final .pfx ou .p12 e validade de cerca de um ano.

### O MEI precisa de certificado digital para emitir nota de serviço?

No portal do governo, não: basta a conta gov.br em nível prata ou ouro. Para emitir notas reais por um emissor como a Corvo, a empresa precisa do certificado A1.

### Preciso do certificado para testar a Corvo?

Não. O ambiente de teste não usa certificado, é grátis e as notas não têm valor fiscal. Você só precisa do A1 para emitir notas de verdade.

### Posso mandar o certificado por e-mail ou WhatsApp?

Não é recomendado. Quem tem o arquivo e a senha pode assinar em nome da empresa. Envie apenas pelo painel de quem vai usar o certificado e não compartilhe a senha.

### O que acontece quando o certificado vence?

A empresa fica sem poder emitir notas reais até você enviar um certificado novo. Renove antes do vencimento e envie o novo arquivo pelo painel.

Fonte: https://www.corvo.tech/pt/blog/certificado-digital-a1-o-que-e-quando-precisa · atualizado em 2026-11-10

---

# Como emitir várias notas fiscais de uma vez usando uma planilha

> Na Corvo, você pode emitir várias notas de serviço de uma vez enviando uma planilha em Excel (.xlsx) ou CSV, com até 2.000 linhas. A Corvo confere cada linha e mostra quais estão prontas e quais têm erro. Você corrige o que precisar e clica para emitir todas as notas prontas de uma só vez.

Quem presta o mesmo tipo de serviço para muita gente, como uma clínica, uma escola, um profissional que atende empresas ou um estúdio, conhece o fim do mês: uma lista de clientes e o mesmo formulário preenchido dezenas de vezes. A planilha troca isso por um envio só.

## O que você precisa

- **Uma conta na Corvo** com a empresa emissora já cadastrada. Se ainda não fez isso, veja o [guia de como emitir nota fiscal de serviço](/pt/blog/como-emitir-nota-fiscal-de-servico-nfse).
- **Uma planilha** em Excel (.xlsx) ou CSV, com até **2.000 linhas** e **10 MB**.
- **Os dados de cada nota:** quem é o cliente (tomador), qual foi o serviço e o valor.

## Passo a passo

1. No painel, na área de notas, clique em **Importar planilha**.
2. Clique em **Baixar modelo**. É uma planilha já com as colunas certas, para você só preencher.
3. Preencha uma linha para cada nota e salve o arquivo.
4. Escolha a **empresa que emite**. Se a sua planilha tem uma coluna com o CNPJ, a Corvo usa a empresa indicada em cada linha.
5. Envie a planilha. A Corvo **lê o arquivo** e **confere cada linha**. Leva só alguns segundos.
6. Veja o resumo: quantas linhas estão **prontas** e quantas têm **erro**. Use o filtro **Com erro** para ver só as que precisam de ajuste.
7. Corrija o que for preciso e clique em **Emitir** as notas prontas. O botão mostra quantas notas serão emitidas e o valor total.

> Faça o primeiro teste no **ambiente de teste**, com poucas linhas. As notas de teste não têm valor fiscal, não usam as notas do seu plano e você vê como a importação funciona sem risco. Na hora de emitir de verdade, use CPF e CNPJ **reais**: a prefeitura confere os dados no cadastro e recusa os inventados.

## A Corvo avisa antes de emitir

Você não emite no escuro. Depois do envio, a Corvo mostra a lista de linhas com o cliente, o serviço, o valor e a situação (**Pronta** ou **Corrigir**). Se alguma coluna da planilha não for reconhecida, ela avisa quais foram ignoradas. Se você enviar a mesma planilha duas vezes, ela também avisa, para evitar notas em dobro por descuido.

Uma linha com o CNPJ de outra empresa que não a escolhida é recusada. Dá para **baixar só os erros** em um arquivo, corrigir e enviar de novo. Se as notas do seu plano acabarem no meio da emissão, as que faltam ficam **aguardando créditos** até você resolver.

## Quando a planilha é a melhor opção

| Situação | Melhor jeito |
| --- | --- |
| Muitos clientes diferentes no mesmo mês | Planilha |
| O mesmo cliente e o mesmo valor, todo mês | [Agenda de nota recorrente](/pt/blog/nota-fiscal-todo-mes-agendada) |
| Uma nota avulsa agora | Emitir pelo painel |

Se o seu sistema de vendas já tem os dados, um programador pode ligar tudo direto à Corvo por API. Os detalhes estão na [documentação](/pt/docs/invoices). Mas, para a maioria dos casos, a planilha resolve sem escrever código.

## Perguntas frequentes

### Quantas notas posso emitir de uma vez pela planilha?

A planilha pode ter até 2.000 linhas e 10 MB. Se tiver mais, divida em arquivos menores.

### Que tipo de arquivo a Corvo aceita?

CSV ou Excel (.xlsx). No painel, há um modelo para baixar, já com as colunas certas.

### E se algumas linhas tiverem erro?

A Corvo mostra quais linhas estão prontas e quais têm erro. Você corrige as que tiverem erro e emite as notas prontas. Também dá para baixar só os erros em um arquivo.

### Posso testar a importação sem emitir notas de verdade?

Sim. No ambiente de teste as notas não têm valor fiscal. É a melhor forma de conhecer o processo antes de emitir de verdade.

### Corro o risco de emitir a mesma nota duas vezes?

A Corvo avisa quando você envia a mesma planilha de novo. Se foi de propósito, é só seguir; se foi sem querer, descarte a importação.

Fonte: https://www.corvo.tech/pt/blog/emitir-varias-notas-fiscais-com-planilha · atualizado em 2026-11-10

---

# Nota fiscal todo mês para o mesmo cliente: como agendar e esquecer

> Na Corvo, você cria uma agenda com a empresa, o valor, a descrição do serviço e o cliente, e escolhe se a nota é única ou recorrente (semanal, quinzenal ou mensal). A nota é emitida sozinha, às 9h (horário de Brasília), em dia útil. Você pode pausar, editar ou cancelar a agenda quando quiser.

Mensalidades, contratos de manutenção, assessorias, planos de acompanhamento: quando o serviço é o mesmo e o cliente também, repetir o formulário da nota todo mês é tempo perdido. A agenda existe para esse caso.

## Como funciona

Você cria uma **agenda** com os dados da nota uma única vez. Depois, a Corvo emite a nota nas datas combinadas. Há dois tipos:

- **Única:** a nota é emitida uma vez, numa data futura. Boa para um serviço que você já sabe que vai prestar.
- **Recorrente:** a nota se repete toda semana, a cada duas semanas (quinzenal) ou todo mês.

A agenda serve bem para mensalidades, contratos de manutenção, assessorias e planos de acompanhamento: tudo que se repete com o mesmo cliente, o mesmo serviço e o mesmo valor.

## Passo a passo

1. No painel, abra **Agendadas e recorrentes** e clique em **Nova agenda**.
2. Escolha a **empresa** que emite e o **tipo** (única ou recorrente).
3. Se for recorrente, escolha a **frequência**: semanal, quinzenal ou mensal.
4. Informe a **data da primeira execução**. Ela precisa ser de amanhã em diante.
5. Se quiser, defina o **último dia**. Sem ele, a agenda continua até você pausar ou cancelar.
6. Preencha o **valor**, a **descrição do serviço** e os dados do **cliente**.
7. Marque **Enviar a nota por e-mail ao cliente**, se quiser que ele receba a nota automaticamente.
8. Clique em **Criar agenda**.

## Quando a nota é emitida

As notas são emitidas às **9h, no horário de Brasília**, em **dias úteis**. Se a data cair em um sábado ou domingo, a nota é emitida na segunda-feira. A nota leva a data do dia em que foi emitida.

## E se der algum problema?

Se a Corvo não conseguir emitir (por exemplo, porque as notas do plano acabaram), ela tenta de novo no dia útil seguinte e avisa você por e-mail. Depois de **3 tentativas que falharam**, a agenda é **pausada** e você recebe outro e-mail. Resolva a causa e clique em **Retomar**: a agenda continua a partir da próxima data, sem recuperar as notas que ficaram para trás.

## Mudou o valor ou o cliente?

Clique em **Editar** na agenda. As mudanças valem para as **próximas** notas. As notas que já foram emitidas não mudam. Se o contrato acabou, use **Cancelar**: o cancelamento é definitivo, e as notas já emitidas continuam valendo. Para recomeçar, você cria uma nova agenda.

> Confira os dados da agenda antes de criar, principalmente o valor e a descrição do serviço. Em caso de dúvida sobre a descrição correta, pergunte ao seu contador.

## Quando a agenda não é a melhor saída

Se cada cliente tem um valor diferente a cada mês, a [planilha](/pt/blog/emitir-varias-notas-fiscais-com-planilha) costuma ser mais prática. E, para a primeira nota, vale seguir o [guia básico de emissão](/pt/blog/como-emitir-nota-fiscal-de-servico-nfse).

## Perguntas frequentes

### A nota fiscal recorrente é emitida em que horário?

Às 9h, no horário de Brasília, em dias úteis. Se a data cair no fim de semana, a nota é emitida na segunda-feira.

### Posso agendar uma nota para uma data só?

Sim. Escolha o tipo Única e a data. A nota é emitida uma vez, na data indicada, a partir de amanhã.

### O cliente recebe a nota automaticamente?

Se você marcar a opção de enviar a nota por e-mail ao cliente e informar o e-mail dele, sim. O cliente é opcional na agenda.

### O que acontece se a emissão falhar?

A Corvo tenta de novo no próximo dia útil e avisa você por e-mail. Depois de 3 falhas seguidas, a agenda é pausada. Resolva a causa e use Retomar.

### Posso mudar o valor de uma agenda que já está ativa?

Pode, com Editar. A mudança vale para as próximas notas, e as que já foram emitidas não mudam.

Fonte: https://www.corvo.tech/pt/blog/nota-fiscal-todo-mes-agendada · atualizado em 2026-11-10

---

# Emitir nota fiscal conversando com a inteligência artificial (Claude)

> Você conecta o Claude à Corvo uma vez, entra na sua conta e aprova o acesso. Depois, pede a nota em uma conversa, por exemplo: “emita uma nota de R$ 300 para este cliente”. O Claude mostra os dados, você confere e confirma. Comece pelo ambiente de teste, onde as notas não têm valor fiscal.

A Corvo funciona com assistentes de inteligência artificial como o Claude: você escreve “emita a nota desse serviço”, o assistente prepara os dados e você confirma. A nota sai pela sua conta, com a sua empresa.

## O que o assistente consegue fazer

- Encontrar as **empresas** da sua conta.
- **Emitir** uma nota de serviço.
- **Consultar** o status de uma nota e listar as suas notas.
- **Baixar o PDF** de uma nota autorizada.

Ele só faz o que você permitir ao aprovar o acesso. Você pode liberar apenas a consulta, ou também a emissão.

## Como conectar o Claude à Corvo

1. No Claude Desktop, abra **Configurações** e depois **Conectores**.
2. Clique em **Adicionar conector personalizado**, dê o nome **Corvo** e cole este endereço: `https://api.corvo.tech/mcp`.
3. Clique em **Conectar**. O navegador abre na Corvo.
4. Entre na sua conta, escolha o **workspace** e o **ambiente** e clique em **Permitir**.
5. Volte ao Claude: as ferramentas da Corvo já estão disponíveis.

> Ao aprovar, você escolhe o ambiente: **teste** (notas sem valor fiscal) ou **produção** (notas reais, que usam as notas do seu plano). Cada conexão fica em um ambiente. Para trocar, reconecte. Comece sempre pelo teste.

A Corvo documenta a conexão com Claude Code, Claude Desktop, Cursor, VS Code, Codex e Windsurf. Se algum não conectar, use o painel e avise o suporte. Quem programa encontra os detalhes técnicos na [página de agentes de IA da documentação](/pt/docs/mcp).

## Um primeiro pedido seguro

Conecte no ambiente de teste e escreva algo simples:

```text
Liste minhas empresas na Corvo e emita uma NFS-e de teste de R$ 100.
```

A emissão não é instantânea: a nota começa **na fila** e depois é autorizada. Se pedir para consultar de novo em instantes, o Claude mostra o resultado.

Depois do teste, você pode usar a conversa também para o dia a dia. Alguns pedidos que fazem sentido: “quais notas eu emiti este mês?”, “a nota do cliente tal já foi autorizada?” e “baixe o PDF da última nota”.

## Como emitir com segurança

- Peça para conferir antes. Escreva: “antes de emitir, me mostre os dados da nota e espere eu confirmar”.
- **Confira você mesmo** os dados da empresa, o código do serviço e o regime tributário. O assistente não sabe isso melhor que você ou o seu contador.
- **Nunca envie o certificado digital nem senhas** na conversa. O certificado se envia só pelo painel da Corvo. Veja o [guia do certificado A1](/pt/blog/certificado-digital-a1-o-que-e-quando-precisa).
- **Use produção só para notas reais**, depois de testar.
- Dê só a permissão necessária. Se você só quer consultar, não libere a emissão.

## Conversa, painel ou planilha?

| Situação | Melhor jeito |
| --- | --- |
| Uma nota rápida, no meio do dia | Conversa com o assistente ou painel |
| Muitos clientes no fim do mês | [Planilha](/pt/blog/emitir-varias-notas-fiscais-com-planilha) |
| O mesmo cliente todo mês | [Agenda](/pt/blog/nota-fiscal-todo-mes-agendada) |

## Perguntas frequentes

### Dá para emitir nota fiscal conversando com uma IA?

Sim. Você conecta um assistente como o Claude à Corvo, aprova o acesso e pede a nota em uma conversa. Ele mostra os dados, e você confere e confirma antes de emitir.

### Preciso enviar minha senha ou certificado para a IA?

Não, e não deve. A conexão é feita por login e aprovação no navegador. O certificado digital se envia só pelo painel da Corvo.

### A IA pode emitir nota de verdade sem eu perceber?

Só se você conectar no ambiente de produção e liberar a permissão de emitir. No ambiente de teste, as notas não têm valor fiscal. Peça sempre para ela mostrar os dados e esperar a sua confirmação.

### Quais assistentes funcionam com a Corvo?

A Corvo documenta a conexão com Claude Code, Claude Desktop, Cursor, VS Code, Codex e Windsurf. Se algum não conectar, use o painel e avise o suporte.

### Preciso saber programar para conectar?

Não. No Claude Desktop, a conexão é feita pelas configurações, colando o endereço da Corvo e aprovando o acesso no navegador.

Fonte: https://www.corvo.tech/pt/blog/emitir-nota-fiscal-com-claude · atualizado em 2026-11-10
