SDKs
One class, six methods
An
Invoiceclient withissue(),consult(),cancel(),reissue(),correct()andinvalidate()— nothing else to instantiate.Typed models
Each item is a typed
Product, with Brazil-specific fiscal fields validated client-side before the request leaves.Same contract in every language
Python, Go, Node and PHP follow the same API contract, checked in CI on every change — methods, errors and resources behave identically, so switching languages doesn't mean relearning stackin.
Just getting started?
Create a free account, generate an SDK key and issue your first document in homologation — free and unlimited, no card.
pip install stackin-python-sdkOne dependency, with no third-party SDK underneath.
Copy a prompt for your AI
Paste it into your editor's assistant chat — Claude Code, Cursor, Copilot, Codex or ChatGPT. Each prompt tells the agent what to do, what to check and what never to do with your key.
- Install the SDKDetects the project's language, installs the official SDK and makes a first call in homologation.Copy promptCopy prompt: Install the SDK
Show the prompt
You are my coding assistant. Install Stackin's official SDK (Brazilian NF-e and NFS-e invoices) in this project and make a first call in homologation. 1. Detect the project's language from its files (pyproject.toml/requirements.txt, package.json, go.mod, composer.json) and use the package manager it already uses: - Python: pip install stackin-python-sdk (the package imports as stackin) - Node: npm install @stackin-io/stackin-node-sdk - Go: go get github.com/stackin-io/stackin-go-sdk - PHP: composer require stackin-io/stackin-php-sdk 2. Read https://docs.stackin.io/en/sdks#installation and https://docs.stackin.io/en/sdks#authentication. The key is an SDK key generated at https://app.stackin.io; the environment is fixed on the key, so use a homologation key. 3. Create the client in one place in the code, reading the key from the STACKIN_API_KEY environment variable. Add the variable to .env.example (with no value) and confirm .env is in .gitignore. 4. Make one read call to prove the connection (listing the invoice history, for example) and show me the result. On a 401, check the key is an SDK key and not an API key (https://docs.stackin.io/en/sdks#errors). Never: - write the key into code, a log or a commit; - issue any invoice unless I ask, and never in production without my explicit confirmation; - switch the language or the package manager the project already uses./prompts/en/install-sdk.md - Build the integrationIssuing from your own domain objects, with idempotency, webhooks, rejections and tests.Copy promptCopy prompt: Build the integration
Show the prompt
You are my coding assistant. Build invoice issuing through Stackin into this project (NFS-e for services, NF-e for goods), in homologation. 1. Read the code and tell me where a billable sale or service comes from and who the recipient is. Propose where the integration lives (one module/service) before writing it. 2. Use the official SDK (https://docs.stackin.io/en/sdks) or the HTTP API (https://docs.stackin.io/en/api). Create the client once, with the key in STACKIN_API_KEY. 3. Build the issue call from the domain objects: https://docs.stackin.io/en/api#issue-invoice and https://docs.stackin.io/en/api#item-values. Do not make up an NCM, CFOP or service code — read it from the product record or ask me. 4. Send one idempotency key per business event (the order id, for example), stored with the order: https://docs.stackin.io/en/api#idempotency. Repeating the call must never produce a second invoice. 5. Store the returned id and access key. Follow the outcome by webhook (https://docs.stackin.io/en/api#webhooks), checking Stackin-Signature and ignoring a repeated Stackin-Delivery-Id; consult the status (https://docs.stackin.io/en/api#consult-invoice) only as a fallback. 6. Treat a rejection as a business state: store the reason, show it to the user and allow a reissue after the fix (https://docs.stackin.io/en/api#errors, https://docs.stackin.io/en/api#reissue-invoice). 7. Write tests with a mocked client and an optional integration test against homologation. Never: - expose the key in code, logs or commits; - issue in production, or switch the key to production, without my explicit confirmation; - retry an issue call without the same idempotency key./prompts/en/integration.md - Fix an errorDiagnoses authentication, validation, tax-authority rejections, certificates and rate limits, and proposes the fix.Copy promptCopy prompt: Fix an error
Show the prompt
You are my coding assistant. Help me diagnose a problem with Stackin (Brazilian NF-e and NFS-e invoices) in this project. 1. Ask for the exact error message, the HTTP status, the operation and the document type. Do not guess before that. 2. Check the environment without exposing the key: does STACKIN_API_KEY exist? Is it an API key (api.stackin.io) or an SDK key (sdk.stackin.io)? Homologation or production? 3. Classify by status, using https://docs.stackin.io/en/api#errors: - 401: key missing, expired, or created for the other host. - 403: the connection does not cover the company, or the permission/OAuth scope is missing (INSUFFICIENT_PERMISSION, https://docs.stackin.io/en/mcp#scopes). - 400: the issuer's setup — certificate, address or fiscal fields at https://app.stackin.io. - 422: company_required (the connection covers several companies and the call names none, https://docs.stackin.io/en/api#companies), an invalid field, or a SEFAZ/municipal rejection with the error block. For the authority's code and what to change, use explain_rejection over MCP, GET /invoices/{invoice_id}/rejection over the API, or rejection(invoice_id) in the Python SDK; the other SDKs do not have the method yet, so call the HTTP route. The submission history (get_invoice_submissions, https://docs.stackin.io/en/api#invoice-submissions) is only the raw data, for when the explanation is not enough. - 429: wait Retry-After and repeat with the same idempotency key (https://docs.stackin.io/en/api#rate-limits). - 502/503: the authority did not answer; check error.retryable. 4. Propose the smallest fix, explain why, and apply it only after I agree. Never: - print or commit the key; - reissue, cancel or issue again in production without my explicit confirmation — first check the invoice was not already authorized; - turn off webhook signature checks to "make it work"./prompts/en/troubleshoot.md
Authentication
The SDK authenticates with an SDK key — pass it once when creating the client, the library handles every request after that. You never construct a URL or set a header yourself.
Getting an SDK key
- 1Sign up and log in at .
- 2Create a company — this is required before a key.
- 3In the dashboard, with the company selected, go to Management → Integrations → API keys, leaving the context on
sdk. No certificate is needed at this step — the key can be created and used right away; the certificate is only required later, at issuance. - 4Name the key and choose its environment —
homologationorproduction. Both are required at creation, and the environment is fixed for the key’s whole lifetime. - 5Copy the key immediately — it's shown , at creation time, and can't be retrieved again. Losing it means revoking it and creating a new one.
from stackin import Invoice
client = Invoice(api_key="$STACKIN_API_KEY")A company holds up to 3 keys at a time, in any mix of context (sdk/api) and environment (homologation/production) — revoking one frees a slot.
A missing or invalid token gets a 401 — see below.
Environments
Every SDK key is created for exactly one environment — or or — chosen when you generate it in the dashboard, and fixed for that key's lifetime. There's no environment field in SDK calls: the key you authenticate with decides where the document goes.
Free and unlimited — it's the real SEFAZ/ADN test environment, not a mock — so integrate and test fully before switching to production. The recipient goes through the same rules as production: for an NF-e the SEFAZ accepts the test CNPJ 99999999000191; for an NFS-e the ADN checks the tomador against the Receita registry — the CNPJ (E0190) and the CPF (E0206 invalid check digits, E0207 not registered) — so use an active CNPJ or a real, registered CPF.
For real documents. Make sure everything works in homologation before switching.
A company can hold keys for both environments at once (up to 3 total).
Several companies
An API key belongs to one company and needs nothing here — calls made with it work exactly as before. An OAuth credential, the kind an app receives through the consent screen, may cover several companies, each with its own permissions, all in one environment.
Name the company with company — on the client, for every call, or on a single call, which overrides the client's. It takes the UUID or the CNPJ/CPF, punctuation ignored, and goes out as the X-Stackin-Company header. Left unset, nothing is sent. In Go the client option is WithCompany and a single call goes through ForCompany.
companies() (Companies() in Go) lists what the credential covers and what it may do in each. The refusals below come back as typed errors that are still an APIError; none is worth retrying unchanged.
from stackin import Invoice
client = Invoice(api_key=access_token, company="11.222.333/0001-81")
client.history()
listing = client.companies()
for company in listing["companies"]:
print(company["company_id"], company["tax_id"], company["permissions"])
client.history(company=listing["companies"][1]["company_id"])- company
- string | optionalthe company a call acts on, by UUID or CNPJ/CPF. Set on the client it applies to every call; set on a call it overrides the client's.
- companies()
- methodthe companies the credential covers, each with company_id, name, tax_id and permissions.
- CompanyRequiredError
- APIError 422the credential covers several companies and the call named none. The answer lists them.
- CompanyNotInScopeError
- APIError 403the company named is not one the credential covers. The answer lists the ones it does.
- InsufficientPermissionError
- APIError 403the credential covers the company but not this operation there. The description reads
needs X, has Y, company=<id>. - APIError 422
- company_ambiguousthe tax id names more than one company the credential covers. Name it by its UUID instead.
Idempotency
Issuing is the one call you must not repeat blindly. If the response is lost — a timeout, a dropped connection — the document may well have been authorized, and a second attempt issues a second fiscal document: another credit, another series number burned, and undoing it means cancelling, which has a deadline.
Pass idempotency_key (named per each language's convention) to make the retry safe. Repeat with the same key and the same body and you get the first response back — no second document, no credit consumed. Available on issue and reissue.
Generate the key yourself — one UUID per business event, not per HTTP request — and keep it for as long as you might retry. Keys live 24 hours; after that the same key is treated as new.
result = client.issue(
document_type=DocumentType.NFSE,
client_name="Maria Silva",
tax_id="12345678909",
items=[Product(description="Consultoria", unit_price=Decimal("1500.00"))],
idempotency_key=key,
)- idempotency_key
- string | optionalyour key, up to 255 characters. The SDK only forwards it as a header — it never generates or stores anything.
- replay
- same key, same bodysame key, same body: returns the recorded response without reprocessing.
- APIError 422
- same key, other bodysame key, different body. Reusing a key on another request is a client bug, not a retry.
- APIError 409
- still runningthe first call is still running. Consult before trying again.
Rate limits
Limits are per API key. Each company has its own count — one client's volume never spends another's allowance.
Issuing has a tighter limit than consulting, and consulting a tighter one than listing history. The more an operation depends on the SEFAZ, the fewer calls per minute it takes.
Going over raises APIError with status 429. The SDK does not expose the response headers, so wait a few seconds before trying again — and reuse the same idempotency key, so the retry can't produce a second document.
try:
result = client.issue(...)
except APIError as error:
if error.status_code == 429:
# Wait before calling again — reuse the same idempotency_key.
raise- issue / reissue
- 60 / minproduces a document and consumes credit.
- consult / cancel
- 120 / minreaches the SEFAZ, but produces no document.
- APIError 429
- over the limitwait, then repeat with the same idempotency key.
Errors
The SDKs translate each failure into a distinct type: APIError for whatever the API answered (carrying status and detail), ConnectionFailedError for a network failure before any response, and the language's own validation error for what's caught client-side, before the request leaves.
from stackin import APIError, ConnectionFailedError
try:
result = client.issue(...)
except ValueError as error:
# Caught before the request left — empty items, missing ncm/cfop,
# incomplete recipient_address on an NFE.
print(f"Invalid request: {error}")
except APIError as error:
# 4xx/5xx from the API. 422 AUTHORITY_REJECTED carries the authorizer's own message.
print(f"[{error.status_code}] {error.detail}")
except ConnectionFailedError as error:
print(f"Could not reach the API: {error}")| HTTP | Error | When |
|---|---|---|
| 400 | Invalid configuration | The issuer's configuration (certificate, address, fiscal fields) is missing or invalid. |
| 401 | Unauthorized | The Bearer token is missing, expired, invalid, or wasn't created for the host you're calling (api.stackin.io vs sdk.stackin.io). |
| 402 | Quota reached | The company's plan quota for production invoices was reached and the plan has no overage price (trial). |
| 404 | Not found | No document with that access key or invoice_id belongs to the company behind your key. |
| 409 | Operation conflict | The requested operation doesn't apply to that document_type (e.g. an nfse-only operation on an nfe). |
| 422 | Validation error | The request body failed validation — a required field is missing or malformed. |
| 422 | Rule refused | A rule checked before the SEFAZ refused the document. APIError carries status 422 and the detail the API answered, with the rule's code, field and message; nothing reached the authorizer. |
| 422 | Authorizer rejectedAuthorizer rejection | The SEFAZ or ADN received the request and refused its data. detail carries the authorizer's own code and message; the same request fails the same way. |
| 429 | Rate limited | Too many calls for this key in the current window. The Retry-After header says how many seconds to wait. |
| 501 | Not implemented | Signing for that document type/country isn't implemented on the server yet. |
| 502 | Authorizer unreachable | The authorizer could not be reached or failed on its side, or a step on ours did — no endpoint for that state, the PDF renderer. detail says which. |
| 503 | Authorizer paused | The SEFAZ said it is paused (108, 109) or throttled the company (656). The data is fine: try again later. |
Item values
unit_price is the price of one unit. amount is the gross total of the line's products, before discount, freight, insurance and other expenses.
Send either. Sending both asserts they agree: the API compares quantity x unit_price against amount and refuses the document before transmission if they differ by more than one cent. In the SDKs decimals travel as strings, so a ten-place unit price reaches the API exactly as typed.
Also refused: neither field (ITEM_AMOUNT_MISSING), values at or below zero, a discount larger than the gross amount (ITEM_DISCOUNT_EXCEEDS_GROSS) and precision the XML cannot carry (ITEM_PRECISION_UNSUPPORTED). Nothing has to migrate: amount keeps the meaning it always had.
from decimal import Decimal
# unit_price: what one unit costs — the line is 2 x 120.00 = 240.00
Product(description="Teclado", quantity=Decimal("2"), unit_price=Decimal("120.00"))
# amount: the line's gross total (the original contract)
Product(description="Teclado", quantity=Decimal("3"), amount=Decimal("50.00"))
# both, checked against each other before transmission
Product(
description="Teclado",
quantity=Decimal("2"),
unit_price=Decimal("120.00"),
amount=Decimal("240.00"),
)IBS/CBS — tax reform
The tax-reform group, per item. Required from 2026 for the regime normal. cst and classification (cClassTrib) are your fiscal decision; the API derives the amounts from the rates.
The three rates are percentages: rate_state (pIBSUF), rate_city (pIBSMun) and rate_federal (pCBS). base is optional — without it, the base is the item amount. An item without the group emits nothing, which is what an NF-e looked like before the reform.
In Go the three rates are *float64 since v0.23.0, so an NFS-e can leave them out and an NF-e can still send a real 0.
from stackin.br import IbsCbs, Product
Product(
description="Teclado",
quantity=Decimal("2"),
unit_price=Decimal("120.00"),
ncm="84716052",
cfop="5102",
ibs_cbs=IbsCbs(
cst="000",
classification="000001",
rate_state=0.1,
rate_city=0.0,
rate_federal=0.9,
),
)NFS-e
On an nfse, the item's ibs_cbs group takes cst, classification (cClassTrib) and operation_indicator (cIndOp, 6 digits, from the NFS-e Anexo VII table, such as 100301): operation_indicator in Python and Node, OperationIndicator in Go and operationIndicator in PHP. They go into the IBSCBS group of the DPS. The group is optional in 2026 (NT SE/CGNFS-e 004 v2.0, §1.1) and is sent only when the item carries it.
from decimal import Decimal
from stackin.br import IbsCbs, Product
Product(
description="Consultoria",
unit_price=Decimal("1000.00"),
nbs="115021000",
ibs_cbs=IbsCbs(
cst="000",
classification="000001",
operation_indicator="100301",
),
)The Sefin Nacional computes the NFS-e base, rates and amounts itself, so the base, the three rates and the reductions are refused on an nfse: the call fails with an API error of status 422. On an nfe the three rates are still required and the operation indicator is refused.
The operation indicator is mandatory in production (layout v1.01) and optional in homologation (NT 009 layout). Without it in production the call fails with 422 IBS_CBS_OPERATION_INDICATOR_REQUIRED. A real-estate indicator (020101, 020201 and 020301, and in homologation also 020202 and 020401) fails with IBS_CBS_REAL_ESTATE_REQUIRED, because the SDKs do not send the imovel group — unless the service is one of the civil-works subitems. A classification not allowed on an NFS-e (indNFSe 0 in the cClassTrib table) fails with 422 IBS_CBS_CLASS_NOT_ALLOWED.
Who may send the group depends on the layout of the environment. In production (layout v1.01) an MEI cannot send it: 422 IBS_CBS_NOT_FOR_MEI. An ME/EPP (simples_nacional 3) can only when the company fiscal field simples_apuracao_ibs_cbs is 3 (IBS and CBS at the regular regime, outside the DAS); with 1, the default, the call fails with 422 IBS_CBS_SIMPLES_IN_DAS. In homologation (NT 009 layout), for a competência from 2026-10-01 the layout lists the group as mandatory and every regime may send it. Company.update sets the field, for the company owner only, and the SDKs accept 1 or 3. The NFS-e layouts in force have no field for it, so it is not written into the DPS.
On an nfse the service's NBS code goes in the item's nbs (DPS cServ/cNBS; NBS in Go), nine digits or dotted (1.1502.10.00). It is required together with ibs_cbs: without it the call fails with 422 NBS_REQUIRED, and a code that is not on the NBS list (NFS-e Anexo B) fails with NBS_UNKNOWN. The SDKs send it as given and leave it out when unset. Catalog items take nbs too.
from stackin import Company
Company(api_key=api_key).update(
fiscal_fields={"simples_apuracao_ibs_cbs": "3"},
)The rest of the group is optional: personal_use (indFinal), government (tpOper, tpEnteGov), referenced_nfse (gRefNFSe), recipient (dest), real_estate (imovel), movable_goods (bensMoveis), regular_taxation (gTribRegular), deferral (gDif) and presumed_credit (cCredPres). The API checks each against the service code and the layout and refuses what the ADN would, with IBS_CBS_* codes. Some parts exist in only one layout: real_estate.city_code, lease, more than one unit, base_adjustments and movable_goods exist only in homologation (NT 009), and sent to production they are refused with IBS_CBS_FIELD_LAYOUT_UNSUPPORTED.
Item tax groups
ICMS, IPI, PIS and COFINS per item, through Tax. Each group has its class per CST/CSOSN — IcmsSn102 for Simples Nacional without a credit, PisNt and CofinsNt for untaxed, and so on.
stackin never infers taxation: which group applies is the issuer’s fiscal decision, and getting it wrong produces wrong tax, not a schema error. Without tax, the API sends the no-tax-due default for the issuer’s regime: ICMSSN102 with CSOSN 400 for Simples Nacional and MEI (CRT 1 and 4), ICMS40 with CST 41 for the others (CRT 2 and 3), and PIS/COFINS with CST 07. If the operation is taxed, send tax.
from stackin.br import CofinsNt, IcmsSn102, PisNt, Product, Tax
Product(
description="Teclado",
quantity=Decimal("2"),
unit_price=Decimal("120.00"),
ncm="84716052",
cfop="5102",
tax=Tax(icms=IcmsSn102(csosn="102"), pis=PisNt(cst="07"), cofins=CofinsNt(cst="07")),
)Invoices
Issue an invoice
Issues a new document. items[].product.br (ncm, cfop) is required for , ignored for , ignored for — a service has no tax classification code, so nfse only reads description and amount off each item.
The same call works for nfse — just change document_type.
The result of issue() carries warnings, always a list (empty when there are none) of code, message and field (null when the finding is about the company): result["warnings"] in Python and Go, result.warnings in Node, $result['warnings'] in PHP. The codes are MEI_ACTIVITY_NOT_ALLOWED, ACTIVITY_NOT_REGISTERED and MEI_NO_ICMS_ACTIVITY; they never stop the issuance unless the company turned on block_activity_mismatch, which Company.update sets (block_activity_mismatch in Python, BlockActivityMismatch in Go, blockActivityMismatch in Node and PHP; the company owner only). issue() and validate() take accept_language (AcceptLanguage in Go, acceptLanguage in Node and PHP): pt-BR, en or es, the language of the warning messages, sent as the Accept-Language header and never in the body. The warnings of validate() are the same findings.
from decimal import Decimal
from stackin import Address, DocumentType, Invoice
from stackin.br import Product
client = Invoice(api_key="$STACKIN_API_KEY")
result = client.issue(
document_type=DocumentType.NFE,
client_name="Buyer Company Ltd",
tax_id="11222333000181",
items=[
Product(
description="Rosa Holambra Vermelha",
unit_price=Decimal("112.44"),
ncm="06031100",
cfop="5102",
)
],
recipient_address=Address(
street="Rua das Flores",
number="1200",
neighborhood="Centro",
city="Joinville",
state="SC",
zip_code="89201100",
city_code="4209102",
),
)Consult an invoice
Looks up a document's current status directly at the authorizer by its access key. Requires as a query param.
result = client.consult(
document_type=DocumentType.NFE,
access_key="42260831112223330001815500000012341123456789",
)Cancel an invoice
Cancels a previously authorized document. must be at least 15 characters for nfe (the authorizer's xJust field requires it). Cancelling doesn't refund plan quota — the authorizer capacity was already spent on issuance.
result = client.cancel(
document_type=DocumentType.NFE,
access_key="42260831112223330001815500000012341123456789",
reason="Duplicate order, cancelled by the buyer within 24h",
)Reissue invoice
Retries a failed submission by the document's local `id` (not its access key — a rejected invoice doesn't have one). Useful for retrying after fixing a configuration problem or an authorizer outage. Consumes credit like a fresh issuance, since it's a new transmission.
result = client.reissue(
invoice_id="9f2c1e3a-4b5d-6e7f-8a9b-0c1d2e3f4a5b",
)Correct invoice
Corrects an already-authorized document with a correction letter (CC-e), without cancelling and reissuing — it consumes no credit and burns no series number. It covers mistakes that don't change the tax: a product name, transport details, extra information.
The text runs 15 to 1000 characters, checked by the SDK before the call. A CC-e cannot fix anything that changes the tax owed, the seller, the buyer, or the issue date — those still mean cancelling and reissuing. The original document doesn't change: the correction is attached to it. At most 20 per document, numbered for you. NF-e only; NFS-e raises APIError 409.
result = client.correct(
"35240912345678000199550010000000011000000017",
document_type=DocumentType.NFE,
correction="Transportadora corrigida para Rapido Ltda",
)Invalidate range
NF-e numbering is sequential and the SEFAZ expects it to have no gaps. The number is reserved the moment issuing starts, so a submission that fails afterwards — a rejection, a timeout — leaves a hole in the series. Invalidating the range is how that hole gets closed.
The reason runs 15 to 255 characters and the range is inclusive — the SDK checks both, and that the end isn't below the start, before the call. A number that already reached the SEFAZ can't be invalidated: that comes back as APIError 409 naming them. NF-e only, and no access key: there is no document to point at.
In AC, BA and SP there is nothing to invalidate. Since 2026-11-01 the Pedido de Inutilização no longer applies there (Ajuste SINIEF 40/26), and the SEFAZ turned the service off (NT 2023.002 v1.02). For an issuer in one of those states the call comes back as APIError 422 whose detail carries INVALIDATION_NOT_AVAILABLE_IN_UF, without reaching the SEFAZ: a gap in the numbering there needs no filing. If any other state answers that the service is off, it is APIError 422 whose detail names INVALIDATION_SERVICE_DISABLED, and repeating the call does not help.
result = client.invalidate(
series="1",
number_start=10,
number_end=12,
reason="Numeracao reservada e nao utilizada por falha no ERP",
)Document PDF
The printed representation the authorizer generates — DANFE for NF-e, DANFSe for NFS-e. Returns raw bytes, the only method that does not return an object: write it to a file or serve it directly.
The XML remains the legally valid document; the PDF is a convenience. The authorizer’s endpoint for it is unstable, so a 502 here means the authorizer is unavailable, not that the invoice is wrong.
pdf = client.pdf(access_key, document_type=DocumentType.NFSE)
with open("nota.pdf", "wb") as file:
file.write(pdf)History
What this company issued, newest first. It is the counterpart of received: that one lists what was issued against you, this one what you issued.
Filter by document_type and status (issued, rejected, cancelled), and page with limit and offset. The answer carries the standard pagination envelope.
page = client.history(
document_type=DocumentType.NFE,
status="issued",
limit=20,
offset=0,
)
for row in page["data"]:
print(row["access_key"], row["client_name"], row["amount"])Attempts
Every attempt made for one invoice and what came back from the authorizer. consult gives the status; this gives the reason — the rejection code and the XML that was sent.
It takes the invoice_id, not the access key: a rejected document never had one. This is how you find out that a rejection was, say, 972.
attempts = client.submissions(invoice["id"])
for attempt in attempts:
print(attempt["status"], attempt["detail"])Received invoices
Documents other companies issued against your tax id. It reads what the API already collected — it does not call the authorizer on the spot.
Collection runs on a schedule on the API side because the SEFAZ caps how many times a tax id may ask per day. Reading here does not spend that quota.
page = client.received(limit=20)
for document in page["data"]:
print(document["access_key"], document["issuer_name"], document["amount"])Manifestation
The recipient’s formal answer: confirmation, acknowledgement, unknown operation or operation not performed.
Only operation not performed takes a reason — and it requires one. The SDK checks that before leaving your machine, rather than spending a round trip to be told.
from stackin import Manifestation
client.manifest(access_key, manifestation=Manifestation.CONFIRMACAO)
client.manifest(
access_key,
manifestation=Manifestation.OPERACAO_NAO_REALIZADA,
reason="Mercadoria nao recebida",
)Clients
Each company keeps the recipients it issues to: one client list per company, the same one the dashboard shows. A client carries a name, a CPF/CNPJ (or a foreign_id, for a buyer abroad), state and municipal registrations, e-mail, phone, address and notes, plus source, uses_count and last_used_at, which say where it came from and how much it has been used. The list is company data: with a credential that covers several companies, it follows the chosen company, like the documents do.
Clients is a client of its own, built with the same key and the same options as Invoice, company included (in Go, NewClients, with WithCompany and ForCompany). list() returns the active clients by name, with search, source, is_active and the same paging as the history; get() reads one, active or not. Names follow each language: is_active is isActive in Node and PHP and IsActive in Go.
create() follows the issuance's rules (CPF/CNPJ check digits, foreign_id only for a buyer abroad), and a refusal comes back as an APIError 422. A CPF/CNPJ the company already has raises ClientAlreadyExistsError, carrying the existing client's client_id. update() sends only what was passed and a null value clears the field (in Go, a pointer to an empty string; in PHP, update() takes an array keyed by the API's field names). deactivate() takes the client out of the listing without erasing it; reactivate() brings it back.
On issue(), client_id fills the name, CPF/CNPJ, foreign_id and address left out; what is passed wins. With it, the SDK stops requiring those four, and the API checks the merged request. A deactivated client comes back as an APIError 422 until it is reactivated.
After an authorized issuance, the recipient is saved as a client when it is new, recognized by its CPF/CNPJ or, for a buyer abroad, by its foreign_id or its name. An existing client only gains one more use and a new last-used date; name, address and registration are rewritten only with update_client on. A rejected issuance saves and counts nothing, a replay with the same idempotency key counts no extra use, and a failure while saving the client never fails the issued document. A deactivated client is counted and stays deactivated.
from stackin import ClientAlreadyExistsError, Clients, DocumentType, Invoice
clients = Clients(api_key="$STACKIN_API_KEY")
page = clients.list(search="buyer", limit=20)
clients.list(is_active=False)
try:
buyer = clients.create(name="Buyer Company Ltd", tax_id="11.222.333/0001-81")
except ClientAlreadyExistsError as error:
buyer = clients.get(error.client_id)
clients.update(buyer["id"], phone="+5511999999999", notes=None)
clients.deactivate(buyer["id"])
clients.reactivate(buyer["id"])
Invoice(api_key="$STACKIN_API_KEY").issue(
document_type=DocumentType.NFSE,
client_id=buyer["id"],
items=[...],
)- Clients
- classaccess to the company's clients, with the same options as
Invoice. In Go,NewClients. - list()
- methoda page of clients, active by default, filtered by
search,sourceandis_active. - get()
- methodone client by id, active or not.
- create()
- methodsaves a client; a repeated CPF/CNPJ raises
ClientAlreadyExistsError. - update()
- methodchanges only what was passed; null clears,
addressreplaces the whole address. - deactivate()
- methoddeactivates without erasing; returns nothing.
- reactivate()
- methodreactivates and returns the client.
- client_id
- issue()the saved client that fills the recipient.
clientIdin Node and PHP,ClientIDin Go. - update_client
- issue()rewrites the existing client with this issuance's recipient.
updateClientin Node and PHP,UpdateClientin Go. - ClientAlreadyExistsError
- APIError 409the CPF/CNPJ or
foreign_idis already on another client of the company, active or not.client_id(clientId,ClientID) names it. - APIError 404
- CLIENT_NOT_FOUNDthe company has no client with that id. It is also the answer for another company's client.
- APIError 422
- CLIENT_INACTIVE
issue()with a deactivated client. Reactivate it before issuing.
IBS/CBS simulation
Simulates the IBS/CBS group an NF-e would carry for a set of items, without issuing anything. The response always has simulated: true and a notice: it is a simulation, not a fiscal document, and has no legal effect. Nothing is stored or sent to a tax authority.
FiscalReference runs it with an API key, or an OAuth token with the invoice:read scope, and needs no company. The call counts against the read rate limit.
The document type (nfe, nfce or nfse, default nfe) only picks the model the classification (cClassTrib) is checked against. The amounts are always the NF-e's: an NFS-e's are computed by the Sefin Nacional, not by Stackin, and the NFS-e issuance checks do not run here.
Pass the rates for every item, or on an item, which win over the shared ones. With no rates and an operation date in 2026, the official 2026 rates apply (CBS 0.9%, IBS UF 0.1%, IBS Mun 0%) and the item reports official_2026 as its rates source. Outside 2026 the rates are required, or the call fails with 422 IBS_CBS_RATES_REQUIRED. A CST without the gIBSCBS group (such as 400 or 410) needs no rate.
from stackin import FiscalReference
ref = FiscalReference(api_key=api_key)
result = ref.calculate_ibs_cbs(
[{"cst": "000", "classification": "000001", "amount": 200}],
operation_date="2026-05-10",
)
print(result.items[0].amounts.cbs, result.total.ibs)
result = ref.calculate_ibs_cbs(
[
{"cst": "000", "classification": "000001", "amount": 100},
{"cst": "410", "classification": "410001", "base": 80},
],
operation_date="2027-03-01",
document_type="nfe",
rates={"rate_state": 0.05, "rate_city": 0.05, "rate_federal": 8.8},
)- FiscalReference
- classBuilt with the API key, like the other reference lookups:
FiscalReference(api_key=...)in Python,new FiscalReference({ apiKey })in Node,NewFiscalReference(WithAPIKey(...))in Go andnew FiscalReference(apiKey: ...)in PHP. - calculateIbsCbs()
- methodPython
calculate_ibs_cbs(items, operation_date=, document_type=, rates=), NodecalculateIbsCbs({ items, operationDate, documentType, rates }), GoCalculateIbsCbs(IbsCbsCalculationRequest)and PHPcalculateIbsCbs($items, $operationDate, $documentType, $rates). The document type defaults tonfe. - items
- list1 to 990 entries, each with
cst,classification,amountorbase, plus optional rates and reductions. Python and PHP take typed items or arrays with snake_case keys, Node takes camelCase keys (rateState,reductionIbs) and Go takesIbsCbsCalculationItem, with pointers for what is optional. - IbsCbsCalculation
- resultTyped, with the API's decimal strings kept as they are, so nothing is rounded through a float:
simulated,notice, the items with theiramountsand rates source, and thetotal. Read it asresult.items[0].amounts.cbsin Python and Node,calc.Items[0].Amounts.Cbsin Go and$result->items[0]->amounts->cbsin PHP.
Errors
A refused cClassTrib or CST is an API error with status 422. Its detail carries the code and a field pointing into the request, such as items[0].classification. The checks are those of NF-e issuance.
- 422
- IBS_CBS_CLASS_CST_MISMATCHThe
classificationdoes not belong to thecst. - 422
- IBS_CBS_CLASS_NOT_IN_FORCEThe
classificationis not in force on theoperation_date. - 422
- IBS_CBS_CLASS_NOT_ALLOWEDThe
classificationis not allowed on thedocument_typesent. - 422
- IBS_CBS_REDUCTION_NOT_ALLOWEDA reduction was sent for a CST that does not take one.
- 422
- IBS_CBS_REDUCTION_REQUIREDThe CST needs a reduction and none was sent or found in the cClassTrib table.
- 422
- IBS_CBS_RATES_REQUIREDNo rates outside 2026, for a CST that carries the group.
detail.fieldnames the missing rate.