stackin

package module
v0.28.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 15 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Integrate once. Issue everywhere.

Go Go Reference License

API Reference · Go SDK guide


stackin

Go SDK for issuing, consulting and cancelling electronic invoices — a handful of business fields, nothing about certificates, XML, XSD, signing or SOAP. The API resolves all of that from the issuer's own configuration, identified by api_key.

One struct, Invoice — Issue()/Consult()/Cancel()/Reissue()/Correct()/Invalidate()/Pdf()/History()/Submissions()/Received()/SyncReceived()/Manifest()/Usage()/Readiness()/Rejection()/Stats()/Classify()/Invalidations(), nothing else to instantiate. Each line item is a br.Product — Description/Amount apply to any document type, NCM/CFOP (plus everything else on Product: CEST, tax groups, presumed credits...) are Brazil-specific and required per item for NFE, ignored for NFSE.

What a line item is worth

UnitPrice 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 that they agree.

price := 120.00

// More than one unit — the note's line is 2 x 120.00 = 240.00
br.Product{Description: "Teclado", Quantity: 2, UnitPrice: &price, Unit: "UN"}

// Legacy: Amount alone still means the line's gross total
br.Product{Description: "Servico", Quantity: 3, Amount: 150.00}

Amounts that do not add up are refused before the authorizer sees them, with a 422 naming the line and both numbers (ITEM_TOTAL_MISMATCH).

Migrating
Before:  Quantity: 3, Amount: 150.00
After:   Quantity: 3, UnitPrice: &price   // price := 50.00

Nothing has to migrate. Amount keeps the meaning it always had and is not deprecated in this release.

Install

go get github.com/stackin-io/stackin-go-sdk

Usage

Get an api_key from the stackin dashboard — select the issuing company, then Settings → API key (context sdk). One key per issuing company, shown once at creation. The API resolves the issuer (CNPJ, state, address, certificate, environment) entirely from it; nothing about the issuer is ever passed on a call.

package main

import (
	"fmt"

	stackin "github.com/stackin-io/stackin-go-sdk"
	"github.com/stackin-io/stackin-go-sdk/br"
)

func main() {
	client := stackin.NewInvoice(stackin.WithAPIKey("COMPANY_API_KEY"))

	invoice, err := client.Issue(stackin.IssueRequest{
		DocumentType: stackin.NFSE,
		ClientName:   "John Doe",
		TaxID:        "00000000000",
		Items: []br.Product{
			{Description: "Software development", UnitPrice: ptr(5000.00)},
		},
	})

	status, err := client.Consult("ACCESS_KEY...", stackin.NFSE)
	_, err = client.Cancel("ACCESS_KEY...", stackin.NFSE, "Typo")

	ncm, cfop := "84713012", "5102"
	invoice, err = client.Issue(stackin.IssueRequest{
		DocumentType: stackin.NFE,
		ClientName:   "Buyer Company Ltd",
		TaxID:        "11111111111111",
		Items: []br.Product{
			{Description: "Test product", Amount: 100.00, NCM: &ncm, CFOP: &cfop},
		},
		RecipientAddress: &stackin.Address{
			Street:       "Avenida Atlantica",
			Number:       "500",
			Neighborhood: "Copacabana",
			City:         "Rio de Janeiro",
			State:        "RJ",
			ZipCode:      "22010000",
		},
		ExternalReference: "order-1234",
	})
	// The PDF, as raw bytes, drawn by the API from the authorized XML: the
	// DANFE for an NF-e, the DANFSe for an NFS-e. The XML stays the legally
	// valid document.
	document, err := client.Pdf("ACCESS_KEY...", stackin.NFSE)
	err = os.WriteFile("nota.pdf", document, 0o644)

	_ = status
	fmt.Println(invoice, err)
}

ExternalReference is your own id for the document — an order number, a ticket. It is sent as external_reference (left out when empty), stored as sent (at most 255 characters), returned on every read and webhook, and History(stackin.HistoryQuery{ExternalReference: "order-1234"}) finds the document by it (exact match).

RecipientAddress is an Address — the buyer's address, required for NFE. On NFE Street, Number, Neighborhood, City, State and ZipCode are required: it becomes enderDest on the wire and the SEFAZ rejects a partial one. CityCode (the 7-digit IBGE municipality code) may be left out — the API resolves it from City and State, and answers CITY_NOT_FOUND (422) when it cannot; send it yourself when the name is ambiguous. State is also what resolves idDest — a buyer in another state is emitted as an interstate operation automatically. On NFSE it is the tomador's address: optional, except when any item has TaxRetained (the tomador withholds the ISSQN), where it is required with every field except CityCode. A missing or incomplete NFE address, or a missing or incomplete one on an NFSE with a retained item, returns an *InvoiceError locally, before the request goes out.

Discount, emission date, purpose and buyers abroad

Optional since API v0.8–v0.9. Each is left out of the body when unset, so a call that does not use them sends exactly what it sent before.

issuedAt := time.Date(2026, 11, 14, 9, 30, 0, 0, time.FixedZone("BRT", -3*60*60))
discount := 25.00

invoice, err := client.Issue(stackin.IssueRequest{
	DocumentType:     stackin.NFE,
	ClientName:       "Buyer Company Ltd",
	TaxID:            "11111111111111",
	Items:            items,
	RecipientAddress: address,
	Discount:         &discount,
	IssuedAt:         &issuedAt,
	Purpose:          stackin.PurposeReturn,
	Direction:        stackin.DirectionIn,
	ReferencedKeys:   []string{"35261111111111111111550010000000011000000010"},
})
Field Sent as What it is
Discount *float64 discount (decimal string) A discount on the whole document, in BRL, zero or more. The API spreads it over the lines.
IssuedAt *time.Time issued_at The emission moment, RFC 3339 in the offset of the time.Time's own Location (2026-11-14T09:30:00-03:00; UTC goes out as Z). NF-e: at most 30 days back and 5 minutes ahead; NFS-e: never ahead. Defaults to now.
Purpose purpose NF-e only: PurposeNormal (the default), PurposeComplementary, PurposeAdjustment or PurposeReturn.
Direction direction NF-e only: DirectionOut (the default) or DirectionIn, an incoming NF-e the company issues itself, such as a sale returned by the buyer.
ReferencedKeys []string referenced_keys NF-e only: the 44-character access keys of the NF-e, NFC-e or CF-e this one refers to. Required for PurposeComplementary and, but for a few CFOPs, PurposeReturn.
ForeignID string foreign_id The document of a buyer abroad (idEstrangeiro, 5 to 20 characters).
Export *Export export Where the goods leave Brazil: ExitState (a Brazilian state, never EX), Place and an optional DispatchPlace. Required for an outgoing NF-e to a buyer abroad.

A buyer abroad is a RecipientAddress with State: stackin.AbroadState ("EX"), NF-e only. ZipCode and CityCode may be left out; CountryCode (the BACEN code, 1 to 4 digits, never 1058) is required and CountryName names it. TaxID is left empty and the SDK does not send it:

invoice, err = client.Issue(stackin.IssueRequest{
	DocumentType: stackin.NFE,
	ClientName:   "Globex Corporation",
	ForeignID:    "P1234567",
	Items:        items,
	RecipientAddress: &stackin.Address{
		Street: "Fifth Avenue", Number: "350", Neighborhood: "Midtown",
		City: "New York", State: stackin.AbroadState,
		CountryCode: "2496", CountryName: "Estados Unidos",
	},
	Export: &stackin.Export{ExitState: "SP", Place: "Porto de Santos"},
})

The SDK does not check the BACEN code's check digit: the official table has countries whose digit does not close.

An item on a fuel CFOP carries the fuel group (comb) as br.Fuel, sent under the item's fuel key. AnpCode (cProdANP, 9 digits), AnpDescription and ConsumerState are required; GlpPercent, NaturalGasNationalPercent, NaturalGasImportedPercent, StartingValue, Codif, TemperatureQuantity and BiodieselPercent are sent only when set. The groups it does not cover (CIDE, encerrante, origComb) still go through ExtraGroups["comb"] — one or the other, never both.

biodiesel := 14.0
item := br.Product{
	Description: "Oleo diesel B S10", Amount: 6200.00, NCM: &ncm, CFOP: &cfop,
	Fuel: &br.Fuel{
		AnpCode: "820101034", AnpDescription: "OLEO DIESEL B S10",
		ConsumerState: "SP", BiodieselPercent: &biodiesel,
	},
}

An item's IBS/CBS group (Reforma Tributária) is br.IbsCbs, sent under the item's br.ibs_cbs key. Every field except CST and Classification (cClassTrib) is sent only when set.

  • On an NF-e send RateState, RateCity and RateFederal (percent, 0–100), plus Base, ReductionIbs and ReductionCbs when they apply. ReductionIbs is the IBS pRedAliq (state and municipality) and ReductionCbs the CBS pRedAliq, both in percent: the cClassTrib's pRedIBS and pRedCBS in the official classification table. The API asks for the reductions on CST 011, 200 and 515 and refuses them on any other.
  • On an NFS-e send only CST, Classification and OperationIndicator (cIndOp, 6 digits). The API mandates OperationIndicator on a production NFS-e and refuses the rates there. An ME/EPP also needs SimplesApuracaoIbsCbs 3 on the company (Company.Update, below) for the NFS-e group.

Which fields each document type takes is the API's rule, not the SDK's: the SDK sends what is set and the API answers by name.

reduction := 60.0
state, city, federal := 0.1, 0.0, 0.9
nfeItem := br.Product{
	Description: "Medicamento", Amount: 100.00, NCM: &ncm, CFOP: &cfop,
	IbsCbs: &br.IbsCbs{
		CST: "200", Classification: "200009",
		RateState: &state, RateCity: &city, RateFederal: &federal,
		ReductionIbs: &reduction, ReductionCbs: &reduction,
	},
}

indicator := "100301"
nfseItem := br.Product{
	Description: "Consultoria", Amount: 100.00,
	IbsCbs: &br.IbsCbs{CST: "000", Classification: "000001", OperationIndicator: &indicator},
}

Breaking since v0.23.0: RateState, RateCity and RateFederal are *float64, like ReductionIbs, so a group can leave them out (an NFS-e) and still send a real 0 (an NF-e with RateCity 0). A float64 field cannot say both. Existing code that assigned a value must take its address:

Before:  IbsCbs{RateState: 0.1, RateCity: 0, RateFederal: 0.9}
After:   state, city, federal := 0.1, 0.0, 0.9
         IbsCbs{RateState: &state, RateCity: &city, RateFederal: &federal}

NF-e sale terms (all optional, NF-e only, sent only when set): Presence ("0"-"5", "9"), Intermediary, Transport, Payments and Change. Product.NetWeight and GrossWeight are one unit's kg. Pointers (TransportVolume.Quantity *int, the weights and Change *float64) let a real 0 go out; Payment.Amount is always sent. A nil Transport.Volumes is left out and an empty non-nil one is sent as []. The SDK checks only the code sets of Presence and FreightMode, a two-digit Method, Description on method "99", weights of at least 0 (volume weights at most 3 decimal places, Payment.Amount and Change at most 2), 1 to 100 payments (an empty non-nil Payments is refused) and a 2-60 character Intermediary.Identifier; the fiscal rules are the API's. Reissue takes none of them: it reuses the stored terms, and SaleTermsOf(detail) reads them back.

zero := 0.0
inv.Issue(stackin.IssueRequest{ /* ... */
	Presence:     "2",
	Intermediary: &stackin.Intermediary{TaxID: "11222333000181", Identifier: "loja-1"},
	Transport:    &stackin.Transport{FreightMode: "1", Volumes: []stackin.TransportVolume{{Species: "CAIXA", NetWeight: &zero}}},
	Payments:     []stackin.Payment{{Method: "17", Amount: 100}},
	Change:       &zero,
})

Catalog items take NetWeight, GrossWeight, IbsCbsCST, IbsCbsClass and NBS (ItemFields and ItemChanges). Catalog weights are checked for at least 0 and at most 6 decimal places. ItemChanges.ClearNetWeight and ClearGrossWeight send null to clear a weight.

Contingency — NF-e only: true sends the document through the UF's contingency authorizer (SVC-AN or SVC-RS, tpEmis 6/7) for when its own is down. Left false, nothing is sent:

inv.Issue(stackin.IssueRequest{ /* ... */ Contingency: true})

The fiscal rules about these fields — the emission window, which purpose needs a referenced key, an export group on a note to Brazil — are the API's, and it answers them by name.

NBS code on an NFS-e

br.Product.NBS is the NBS code of the service (cNBS), nine digits or dotted (1.1502.10.00). It sits on the line beside ServiceCode, NFS-e only, and is left out when empty. The API requires it on a line that carries IbsCbs (422 NBS_REQUIRED) and refuses an unknown code (422 NBS_UNKNOWN); both come back as the ordinary *APIError. Catalog items take it too: ItemFields.NBS and ItemChanges.NBS (pointing at "" clears it).

inv.Issue(stackin.IssueRequest{
	DocumentType: stackin.NFSE,
	// ...
	Items: []br.Product{{Description: "Consultoria", UnitPrice: ptr(1500.00), ServiceCode: ptr("17.01"), NBS: "1.1502.10.00"}},
})

FiscalReference.NBSSuggestions (GET /service-codes/{service_code}/nbs) lists the NBS codes NFS-e Anexo VIII pairs with a service code, in any form ServiceCode takes (1.07, 01.07.00, 010700). Each row also carries the OperationIndicator (cIndOp) and IbsCbsClassification (cClassTrib) the annex pairs with that NBS. They are suggestions only: nothing is written into a document unless you send them as Product.NBS and on Product.IbsCbs. A code the route cannot read is an *APIError 422.

reference := stackin.NewFiscalReference(stackin.WithAPIKey(os.Getenv("STACKIN_API_KEY")))
found, err := reference.NBSSuggestions("1.07")
for _, row := range found.Suggestions {
	fmt.Println(row.NBS, *row.OperationIndicator, *row.IbsCbsClassification)
}
NFS-e fields of the DPS

All optional, NFS-e only (the API refuses them on an NF-e), and left out of the request when unset. Decimals are float64 and go out as decimal strings; dates are time.Time and go out as YYYY-MM-DD.

  • On a line (br.Product): NBS, ConditionalDiscount (BRL, above 0), MunicipalServiceCode (3 digits; refused for an MEI) and InternalCode (up to 20 letters or digits). IbsCbs also takes PersonalUse, Government, ReferencedNfse, Recipient, RealEstate, MovableGoods, RegularTaxation, Deferral and PresumedCredit.
  • On the request: RecipientMunicipalRegistration (up to 15 letters or digits, masks dropped), ForeignIDMissingReason (1 or 2) and, on RecipientAddress, Complement and, for a tomador abroad, CountryISO2, PostalCode and Province.
  • IssueRequest.Nfse (*br.NfseDetails): ApproximateTaxes, CompetenceDate, ServiceCityCode or ServiceCountryCode, Iss, Federal, Deductions, Substitution, Construction, Event, References, Provider (NfseProvider: Caepf of 14 digits, Phone, Email), RecipientCaepf (14 digits), Intermediary and ForeignTrade. A deduction document also takes OtherDfe (Key up to 50 characters, Description) as one of its identifications; the API reads it on the homologation layout only.
inv.Issue(stackin.IssueRequest{
	DocumentType: stackin.NFSE,
	// ...
	Nfse: &br.NfseDetails{
		CompetenceDate:  time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC),
		ServiceCityCode: "3550308",
		ApproximateTaxes: &br.ApproximateTaxes{
			FederalPercent: ptr(13.45), StatePercent: ptr(0.0), MunicipalPercent: ptr(2.0),
		},
		Iss: &br.IssDetails{Rate: ptr(2.5), Retention: "tomador"},
	},
})

The API refuses some groups for an MEI: Deductions (DEDUCTIONS_NOT_FOR_MEI), Federal (FEDERAL_TAXES_NOT_FOR_MEI), Iss.Rate, a retention and MunicipalServiceCode. An NFS-e takes one line: more than one is a 422 NFSE_SINGLE_ITEM. Findings the API lets through come back in the warnings of the result: APPROXIMATE_TAXES_MISSING, IBS_CBS_RECOMMENDED, RECIPIENT_COMPLEMENT_OMITTED, CONSTRUCTION_RECOMMENDED, EVENT_RECOMMENDED and FOREIGN_TRADE_RECOMMENDED. The invoice detail returns the stored nfse and substituted_by_invoice_id.

The company's own defaults are FiscalFields.ApproximateTaxSimplesPercent, ApproximateTaxFederalPercent, ApproximateTaxStatePercent, ApproximateTaxMunicipalPercent, IssRate, MunicipalRegistration and SpecialTaxRegime (see Fixing the issuer); a group sent in Nfse overrides them for that document.

Activity warnings on issue

Issue returns the same result map as before with a warnings key added: always present, a []any of map[string]any with code, message and field (nil when the finding has no field), empty when there is none. The codes are MEI_ACTIVITY_NOT_ALLOWED, ACTIVITY_NOT_REGISTERED and MEI_NO_ICMS_ACTIVITY. The document is issued either way, unless the owner turned on BlockActivityMismatch (see Fixing the issuer).

result, err := inv.Issue(req)
for _, w := range result["warnings"].([]any) {
	fmt.Println(w.(map[string]any)["code"])
}

IssueRequest.AcceptLanguage (pt-BR, en or es; the API falls back to English) localizes the warning messages of Issue and Validate. It is sent as the Accept-Language header only, never in the body, and omitted when empty.

Checked before the request goes out

Issue() refuses, with an *InvoiceError and no network call, anything the authorizer is certain to reject:

  • NCM, when set, must be the full 8 digits, or 00 for a service line. Any other 2-digit chapter is not accepted: the SEFAZ rejects it with 777.
  • Barcode (cEAN), when set, must be SEM GTIN or a GTIN of 8, 12, 13 or 14 digits, and a GTIN's GS1 check digit must be right (a mistyped digit is caught here instead of by the SEFAZ).
  • RecopiNumber (nRECOPI), when set, must be the 20-digit RECOPI number; the SDK checks its two modulo-11 check digits (MOC §8.5) before sending.
  • On NFE, an item's Description (xProd) is at most 120 characters. NFSE descriptions are not bound by it.
  • Discount, when set, is zero or more; IssuedAt, when set, is not the zero time.Time; Purpose and Direction, when set, are one of their constants.
  • An item's Fuel needs AnpCode, AnpDescription and ConsumerState, and is refused beside ExtraGroups["comb"].
  • On NFE, a RecipientAddress with State EX (a buyer abroad) needs CountryCode instead of ZipCode.
  • RecipientAddress.Street and Neighborhood, when set, need at least 2 characters after trimming, on either document type.
  • On NFE, every free-text field sent — ClientName, each item's Description, Unit, PurchaseOrder, PurchaseOrderItem and Observations, the Fuel group's text fields, every RecipientAddress field, ForeignID and every Export field — is checked for characters the NF-e cannot carry. Anything the NF-e cannot carry (emoji, CJK, Cyrillic…) is refused, and the error names the field and the character. Accented Portuguese and anything else in ISO-8859-1 (latin1) is fine; tabs and line breaks are collapsed into a space, and typographic quotes, dashes, ellipsis, bullet, € and ™ are converted by the API (‘ ’ ‚ to ', “ ” „ to ", – — − and • to -, … to ..., € to EUR, ™ to TM). The SDK sends them unchanged. NFSE is not checked.
  • On NFSE, every Nfse group, the new IbsCbs groups and the new line and recipient fields are checked for the shapes the API fixes (patterns, lengths, enumerations, ranges and decimal places, and the groups that take exactly one of several members); the error names the path. What depends on the company, the service code or the environment is the API's and comes back by name.
  • On NFSE, an item with TaxRetained: ptr(true) needs a RecipientAddress with Street, Number, Neighborhood, City, State and ZipCode (CityCode optional): the ISSQN is retained by the tomador, and the city authorizer refuses the document without their address (E0237).

Retrying safely

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 number burned, and undoing it means cancelling, which has a deadline.

Pass an idempotency key to make the retry safe:

key := uuid.NewString()

result, err := inv.Issue(stackin.IssueRequest{
	DocumentType:   stackin.NFSE,
	ClientName:     "Maria Silva",
	TaxID:          "12345678909",
	Items:          []br.Product{{Description: "Consultoria", UnitPrice: ptr(1500.00)}},
	IdempotencyKey: key,
})

Reissue takes it as a call option instead, since it has no request struct:

result, err := inv.Reissue("<invoice-id>", stackin.WithIdempotencyKey(key))

Retry with the same key and the same body and you get the first response back, replayed — no second document, no credit consumed. Reissue takes the same argument.

Situation What the API does
New key issues normally, records the response
Same key, same body replays the recorded response
Same key, different body API error 422
Same key, first call still running API error 409
Previous attempt failed key is released — the retry issues
Key older than 24 hours treated as new

Generate the key yourself and keep it for as long as you might retry — one UUID per business event, not per HTTP call. The SDK never generates one, because a key minted per call would protect nothing, and because two genuinely separate invoices for the same customer and amount on the same day are a normal thing to issue.

Correcting a document

Some mistakes don't need a cancellation. A wrong product name, wrong transport details, a typo in the extra information — a CC-e (carta de correção) fixes those, and it is free: no new credit, no burned series number, no reissue.

result, err := inv.Correct(
	"35240912345678000199550010000000011000000017",
	stackin.NFE,
	"Transportadora corrigida para Rapido Ltda",
)

The correction text is 15 to 1000 characters, and the access key must be an NF-e access key (44 characters) — both checked locally before the call. Any other key, an NFS-e's 50-digit one included, returns an *InvoiceError: NFS-e has no correction letter, so cancel and reissue instead.

What a CC-e cannot fix: anything that changes the tax owed (base, rate, price, quantity, totals), the buyer or the seller, or the issue date. Those still mean cancelling and reissuing. The API sends the legally fixed wording that says exactly this, attached to every correction.

The original document does not change — the CC-e is an event attached to it, and the authorized XML stays as it was. A document accepts at most 20 of them, and they are numbered for you.

NF-e only. NFS-e has no correction letter. The key already says which one it is, so a key that is not an NF-e access key is refused locally with an *InvoiceError. What only the API can know stays an *APIError with status 409: an NF-e-shaped key sent with stackin.NFSE, or a key for a document the API does not hold. The NF-e key is 44 characters: digits, except positions 7 to 18, which may carry the uppercase letters of an alphanumeric CNPJ.

Invalidating unused numbers

NF-e numbering is sequential and the SEFAZ expects it to have no gaps. A number gets reserved the moment issuing starts, so a submission that fails afterwards — a rejection, a timeout — leaves a hole in the series. Reporting that range is how you close it.

result, err := inv.Invalidate(stackin.InvalidationRequest{
	Series:      "1",
	NumberStart: 10,
	NumberEnd:   12,
	Reason:      "Numeracao reservada e nao utilizada por falha no ERP",
})

The reason is 15 to 255 characters and the range is inclusive; both are checked locally, as is number_end not being below number_start.

A number that already reached the authorizer can't be invalidated. The API checks its own records first and answers 409 naming the offending numbers, without a round trip — and the authorizer checks again for what we can't see from here.

NF-e only, and it takes no access key: there is no document to point at.

Ranges already reported are listed, a page at a time, with the SEFAZ status and protocol of each — read it before reporting the same range twice:

page, err := inv.Invalidations(stackin.PageQuery{Limit: 20})

Before the first document, and after a refusal

ready, err := inv.Readiness()          // GET /company
if ready["ready"] == false {
	fmt.Println(ready["missing"])       // certificate, certificate_expired, certificate_unreadable, address, state_registration, plan
	fmt.Println(ready["by_document_type"], ready["fix_url"])
}

why, err := inv.Rejection(invoiceID)   // a rejected document, by its local id
fmt.Println(why["code"], why["explanation"], why["steps"], why["suggested"])

stats, err := inv.Stats(7)             // totals, by type and status, this week against the last

Readiness() says whether the company can issue right now and, when it cannot, what is missing, plus the certificate's expiry, the tax regime (CRT) and the default série per document type. by_document_type says it per nfe/nfse, with the address fields at fault; fix_url is the dashboard screen for the first blocker; suggested_fiscal_fields is what the CNPJ registry suggests, never applied. Rejection() reads the authorizer's answer (Submissions() has it raw) in plain words, with the field to fix and, when there is one, a suggested value; a document that is not rejected is an *APIError 409. Stats() takes days from 1 to 365, checked locally; 0 sends nothing and the API answers for 30.

Fixing the issuer

Company.Update() (PATCH /company) fixes what Readiness() reports missing and answers the same fields, plus the stored address and fiscal_fields:

company := stackin.NewCompany(stackin.WithAPIKey(os.Getenv("STACKIN_API_KEY")))

result, err := company.Update(stackin.CompanyUpdate{
	Address: &stackin.CompanyAddress{
		Street:           "Av. Paulista",
		Number:           "1000",
		Neighborhood:     "Bela Vista",
		MunicipalityCode: "3550308", // 7-digit IBGE code, in the company's state
		ZipCode:          "01310-100",
	},
	FiscalFields: &stackin.FiscalFields{TaxRegime: "1", SimplesNacional: "3"}, // owner only
})
fmt.Println(result["ready"], result["missing"])

Only what is set is sent. There is no complement, and the state changes only in the dashboard. MunicipalityName is derived from the code when left out. The municipality code (7 digits), the CEP (8 digits, mask stripped) and the TaxRegime (1–4), SimplesNacional and SimplesApuracao (1–3) and SimplesApuracaoIbsCbs (1 or 3) codes are checked locally. The FiscalFields percentages (two decimals, a comma accepted), MunicipalRegistration and SpecialTaxRegime are checked locally too, and pointing one at "" clears it. FiscalFields are the company owner's alone: anyone else gets an *APIError 403. An OAuth credential needs company:write (*InsufficientPermissionError without it). A 503 means the IBGE table could not be read: nothing was written, retry after Retry-After.

CompanyUpdate.BlockActivityMismatch (*bool, owner only, anyone else gets an *APIError 403) makes the API refuse an issuance with MEI_ACTIVITY_NOT_ALLOWED or ACTIVITY_NOT_REGISTERED as a 422 instead of a warning. It is sent only when set, so ptr(false) turns it off:

block := true
company.Update(stackin.CompanyUpdate{BlockActivityMismatch: &block})

Suggesting a classification

suggestion, err := inv.Classify(stackin.ClassifyRequest{
	Description:    "Cerveja artesanal IPA 500ml",
	DocumentType:   stackin.NFE,
	RecipientState: "SP",
	Answers:        map[string]any{"purpose": "resale"}, // optional, from missing_information
})
best := suggestion["primary_candidate"] // ncm, cfop, cst/csosn, cest, confidence

A suggestion, never a decision. Every code in a candidate is read from the published tables, but the NCM and CFOP decide the tax owed: show it, have someone confirm it, and only then put it on an item. missing_information lists what would settle it; answer through Answers and ask again. Description is 3 to 500 characters, checked locally.

Documents issued against you

Everything above serves the issuer. These two serve the recipient: what suppliers billed to this CNPJ, and the formal answer to it.

Reading the list never calls the SEFAZ. Collecting runs on a schedule on the API side, every six hours, and SyncReceived() asks for it now. After a read that finds nothing more the SEFAZ makes the CNPJ wait an hour; a sync inside that wait comes back as a *stackin.RateLimitedError with Code DISTRIBUTION_COOLDOWN, RetryAt and RetryAfter (seconds).

The first 50 received documents a month are included in every plan; each one after that takes R$ 0,05 from the account credit. Some existing accounts are exempt, and Usage().ReceivedFree says whether this one is.

sync, err := client.SyncReceived()
var limited *stackin.RateLimitedError
if errors.As(err, &limited) {
    fmt.Println("next read allowed at", limited.RetryAt)
} else if err != nil {
    log.Fatal(err)
} else {
    fmt.Println(sync.Stored, "new documents")
}

page, err := client.Received(20, 0)
if err != nil {
    log.Fatal(err)
}
fmt.Println(page["total"])

if _, err := client.Manifest(accessKey, stackin.Ciencia, ""); err != nil {
    log.Fatal(err)
}
_, err = client.Manifest(
    accessKey,
    stackin.OperacaoNaoRealizada,
    "Mercadoria nunca chegou ao endereco",
)

Before you answer a document the SEFAZ sends only a summary (resNFe): access key, issuer, amount, date. The full document (nfeProc) arrives after a manifestation, and the schema field on each row says which one you hold.

The four answers are 210200 Confirmação da Operação, 210210 Ciência da Operação, 210220 Desconhecimento da Operação and 210240 Operação não Realizada. Only the last one takes a reason, and it requires one — both rules are checked locally, before the request goes out, because a round trip to be told a fixed rule is a round trip wasted.

What was issued, and the plan behind it

History lists what this company issued, newest first. ExternalReference finds the documents issued with exactly that reference, and Fields: "summary" returns a lighter item per invoice.

page, err := client.History(stackin.HistoryQuery{
	ExternalReference: "order-1234",
	Fields:            "summary",
	Limit:             20,
})

usage, err := client.Usage() // GET /api/v1/company/usage
fmt.Println(usage.PlanName, usage.UsedInvoices, "/", usage.IncludedInvoices)
fmt.Println(usage.UsedReceived, "/", usage.IncludedReceived, "received, free:", usage.ReceivedFree)
fmt.Println("credit (cents):", usage.CreditBalance)

Usage() returns a *stackin.Usage: PlanName, PlanSlug, IncludedInvoices, UsedInvoices, OveragePriceCents (nil when the plan has no overage), IncludedReceived, UsedReceived, ReceivedPriceCents, ReceivedFree, CurrentPeriodStart, CurrentPeriodEnd (nil when open-ended), CreditBalance (cents) and CompaniesOnAccount. The numbers are the paying account's, shared by every company it holds.

Saved clients

The company keeps the recipients it issues to. A successful issuance saves a new recipient on its own; Clients reads and edits them, and IssueRequest.ClientID issues to one without retyping it.

clients := stackin.NewClients(stackin.WithAPIKey("..."))

page, err := clients.List(stackin.ClientQuery{Search: "acme", Limit: 20}) // active ones, by name
inactive := false
clients.List(stackin.ClientQuery{IsActive: &inactive})                  // the deactivated ones

acme, err := clients.Create(stackin.ClientFields{Name: "ACME Ltda", TaxID: "11.222.333/0001-81"})
var exists *stackin.ClientAlreadyExistsError
if errors.As(err, &exists) {
	acme, err = clients.Get(exists.ClientID) // it was there already
}
id := acme["id"].(string)

phone, empty := "+5511999999999", ""
clients.Update(id, stackin.ClientChanges{Phone: &phone, Notes: &empty}) // "" clears
clients.Deactivate(id)                                                  // kept, hidden from List
clients.Reactivate(id)

stackin.NewInvoice(stackin.WithAPIKey("...")).Issue(stackin.IssueRequest{
	DocumentType: stackin.NFSE,
	ClientID:     id, // name, tax id, address from it
	Items:        items,
})
  • List filters by Search (part of the name, the tax id masked or not, or the foreign id), Source (manual, issued, issuance) and IsActive (nil lists the active clients, as the API does), and pages with Limit/Offset. SortBy takes name, last_used_at, created_at or uses_count.
  • Update sends only the fields set in ClientChanges: a nil pointer is left alone, one pointing at "" clears the field, Address replaces the whole address and ClearAddress removes it. The API checks the client as a whole, so clearing a Brazilian client's tax id is refused like a create without one.
  • On Issue, the client fills whichever of ClientName, TaxID, ForeignID and RecipientAddress are empty; the ones set win, and the empty ones are left out of the request. The client's e-mail and phone likewise fill ClientEmail and ClientPhone when empty. With ClientID the address checks apply only to a RecipientAddress that is set: the API checks the merged request. A deactivated client is refused there with a *stackin.ClientInactiveError (422) until it is reactivated.
  • UpdateClient: true rewrites an existing client with that request's recipient data. Left false, the issuance only counts one more use of it.
  • ClientEmail and ClientPhone (8 to 15 digits, optional leading +) are saved on the client created after a successful issuance, or on an existing one only with UpdateClient: true, and only the ones sent. They are also kept on the invoice and sent again on a reissue (which does not touch the client), and written into the fiscal document: NF-e dest/email (up to 60 characters) and dest/enderDest/fone (digits only, up to 14, only with a RecipientAddress); NFS-e toma/email (up to 80) and toma/fone (up to 20 digits). The phone goes out digits only, area code first; a +55 is dropped unless the recipient is abroad. A value the layout cannot carry (too long, an e-mail with characters beyond Latin-1) is left out of the document and the issuance goes on.
  • Reading needs invoice:read; creating, editing and deactivating need invoice:issue. WithCompany and ForCompany work here as on Invoice.
Reading the XML of a received document
xml, err := client.ReceivedXML(accessKey)
if err != nil {
    log.Fatal(err)
}
os.WriteFile(accessKey+".xml", xml, 0o644)

ReceivedXML returns the procNFe as raw bytes. A document held only as a summary answers 409 with Code RECEIVED_XML_NOT_AVAILABLE until it is manifested; 402 is a *PaymentRequiredError with Code RECEIVED_PAYMENT_REQUIRED. Downloading is never billed.

Webhooks

Webhooks registers where the company's events are delivered: invoice.authorized, invoice.rejected, invoice.cancelled, invoice.corrected, received_invoice.stored and received_invoice.full_document (stackin.WebhookEvents). An endpoint receives the events of the credential's own environment only.

hooks := stackin.NewWebhooks(stackin.WithAPIKey("..."))

endpoint, err := hooks.Create(stackin.WebhookEndpoint{
	URL:    "https://shop.example/stackin",
	Secret: os.Getenv("STACKIN_WEBHOOK_SECRET"),                 // 16 to 255 characters
	Events: []string{"invoice.authorized", "invoice.rejected"}, // nil: every event
})
hooks.List()                                   // a plain list; secrets are never returned
hooks.Deliveries(stackin.PageQuery{Limit: 20}) // every attempt: status, attempts, last_error
hooks.Delete(endpoint["id"].(string))          // stops delivery, keeps the history

The secret signs every delivery and is not returned again, so keep it. An https:// URL, the secret's length and the event names are checked locally; the API also refuses a URL that points at a private network. On an OAuth credential every call needs webhook:manage. WithCompany and ForCompany work here as on Invoice.

Items catalog

The company keeps the products and services it sells in one catalog, told apart by Kind (product for an NF-e, service for an NFS-e). Items reads and edits it, and br.Product.ItemID issues a line from one without retyping it.

items := stackin.NewItems(stackin.WithAPIKey("..."))

page, err := items.List(stackin.ItemQuery{Kind: "product", Search: "cafe", Limit: 20}) // active ones, by description

// Upsert by ExternalReference (or Code): created is true for a 201, false for a 200.
// UnitPrice and ISSRetained are pointers: nil is not sent, &zero / &no are.
price := 18.9
coffee, created, err := items.Upsert(stackin.ItemFields{
	Kind: "product", Description: "Cafe torrado 500g", Code: "CAF-500",
	UnitPrice: &price, Unit: "UN", ExternalReference: "ns-variant-1", Source: "nuvemshop",
	NCM: "09012100", CFOP: "5102",
})
var exists *stackin.ItemAlreadyExistsError
if errors.As(err, &exists) {
	coffee, err = items.Get(exists.ItemID) // the code belongs to another item
}
id := coffee["id"].(string)

notes, empty := "fresh", ""
items.Update(id, stackin.ItemChanges{Notes: &notes, Unit: &empty}) // "" clears
items.Deactivate(id)                                               // kept, hidden from List
items.Reactivate(id)

stackin.NewInvoice(stackin.WithAPIKey("...")).Issue(stackin.IssueRequest{
	DocumentType: stackin.NFE,
	ClientID:     clientID,
	Items:        []br.Product{{ItemID: id, Quantity: 2}}, // description, price, unit and fiscal codes from it
})
  • List filters by Kind, Search (part of the description, code or external reference; digits also match the NCM and GTIN), Source (manual, import, nuvemshop, invoice) and IsActive (nil lists the active items, as the API does), and pages with Limit/Offset. SortBy takes description, code, unit_price, last_used_at, created_at or uses_count.
  • Upsert is the public POST /items (ItemFields.UnitPrice *float64 and ISSRetained *bool are pointers, so a price of 0 and iss_retained: false can be sent while nil is left out; the price goes out as a decimal string, and UnitPriceText: "18.9000000001" (up to 10 places, checked) keeps every digit a float would round. ItemChanges has the same UnitPriceText *string, "" clearing the price): it updates the company's item with the same ExternalReference (or the same Code when none is sent) with the fields sent, and keeps its source and active flag; otherwise it creates one. Sending the same fields twice never makes two items. Source is used only when it creates. Create is the same call without the created flag (kept for parity with Clients).
  • Update sends only the fields set in ItemChanges: a nil pointer is left alone and a text pointing at "" clears the field. ISSRetained *bool tells false from unset. The API checks the item as a whole, so turning a product into a service while it still has an NCM is refused (422).
  • Deactivate is DELETE /items/{id} (204, no body). A deactivated item still holds its code and is refused on Issue until Reactivate.
  • On Issue, a line with ItemID may leave Description empty: it is left out of the request and the catalog fills it, with Unit, Barcode, NCM, CFOP, CEST, Tax, ServiceCode, TaxRetained and the price (when neither Amount nor UnitPrice is set). A field set on the line wins. With ItemID, the SDK does not default Unit to UN, sends tax_retained only when TaxRetained is set (it is a *bool, so ptr(false) turns off a retention the item has) and does not require NCM/CFOP locally on an NF-e: the API checks the filled line. An item whose tax situation needs an ICMS base and rate is refused (*ItemTaxRequiredError) unless the line sends its own Tax.
  • Reading needs invoice:read; creating, editing and deactivating need invoice:issue. WithCompany and ForCompany work here as on Invoice. Responses are plain maps, as on Clients.

Several companies on one credential

An API key is one company and needs nothing here: with no company set, requests are exactly what they were before. A credential authorized for several companies (an OAuth connection) has to say which one each call acts on, by the company id or its CNPJ (punctuation is ignored). It goes out as the X-Stackin-Company header on every request, lookups included.

client := stackin.NewInvoice(
	stackin.WithAPIKey(token),
	stackin.WithCompany("00.000.000/0001-91"),
)

// One call on another company; client itself is unchanged.
client.ForCompany("6f1c2b8e-...").Consult("ACCESS_KEY...", stackin.NFE)

// Which companies this credential reaches, and what it may do on each.
access, err := client.Companies() // GET /api/v1/me/companies
for _, company := range access.Companies {
	fmt.Println(company.CompanyID, company.Name, company.TaxID, company.Permissions)
}

Companies() returns an *AuthorizedCompanies (Environment, Companies []AuthorizedCompany). An API key lists as its one company with every permission.

Three answers come back typed, and none of them is worth repeating unchanged:

Error When
*stackin.CompanyRequiredError 422 company_required: the credential covers several companies and the call named none. Companies lists them.
*stackin.CompanyNotInScopeError 403 company_not_in_scope: the company named is not covered. Companies lists the ones that are.
*stackin.InsufficientPermissionError 403 INSUFFICIENT_PERMISSION: the company is covered but the permission is missing. Description reads needs X, has Y, company=<id>.

Each wraps the *APIError it used to be, so errors.As(err, &apiErr) keeps working; a plain type assertion to *APIError does not match them.

Looking up a code, or who a CNPJ belongs to

Two more clients, for the tables an issuer reads while filling a document. Neither writes anything.

ref := stackin.NewFiscalReference(stackin.WithAPIKey("..."))   // country BR by default

ref.NCM.Get("84716052")                                        // one code
ref.NCM.Search(stackin.SearchQuery{Term: "teclado", Limit: 5}) // a page of matches
ref.CFOP.Get("5102")
ref.Kinds()                                                    // what this country has
ref.Kind("ibs_cbs_class").Get("000001")                        // any kind, named or not
ref.Search(stackin.SearchQuery{Term: "teclado"})               // every kind at once

stackin.NewTaxpayer(stackin.WithAPIKey("...")).Get("00000000000191")

CFOP, NCM, CEST, CST, CSOSN, IssService, IcmsFuel and IbsCbsClass have accessors. Kind(name) reaches anything else, including a classification published after this release — ask Kinds() rather than trusting this list.

Cities(name, CityQuery{State, Country}) lists the municipalities whose name starts with name, at most 20, each with its IBGE code — issuing resolves CityCode by itself, so this is for a name that matches more than one:

ref.Cities("santa rita", stackin.CityQuery{State: "SP"}) // [{country: BR, code: ..., name: ..., state: SP}]

CalculateIbsCbs(IbsCbsCalculationRequest) simulates the IBS and CBS of 1 to 990 items (POST /ibs-cbs/calculate, scope invoice:read). It needs no company, issues nothing and stores nothing:

amount, city := 100.0, 0.0
calc, err := ref.CalculateIbsCbs(stackin.IbsCbsCalculationRequest{
	DocumentType:  "nfe", // nfe (default), nfce or nfse: only picks the model the cClassTrib is checked for
	OperationDate: "2026-03-10",
	Items: []stackin.IbsCbsCalculationItem{
		{CST: "000", Classification: "000001", Amount: &amount}, // Amount or Base is required
	},
	Rates: &stackin.IbsCbsRates{RateCity: &city}, // optional; an item's own rate wins
})
fmt.Println(calc.Total.Ibs, calc.Total.Cbs, calc.Items[0].RatesSource)

Only what is set is sent. Left out, the official 2026 rates apply to a 2026 date (CBS 0.9%, IBS UF 0.1%, IBS Mun 0%); for any other year the API refuses the call with IBS_CBS_RATES_REQUIRED (an *APIError 422). The item count, the CST (3 digits) and Classification (6 digits) patterns, Amount/Base greater than zero, rates and reductions between 0 and 100 and the OperationDate format are checked locally. The result is typed (IbsCbsCalculation, IbsCbsCalculatedItem, IbsCbsIndicators, IbsCbsAppliedRates, IbsCbsAmounts) and keeps every amount and rate as the decimal string the API sends. The amounts are the NF-e's: the simulation does not compute an NFS-e's, which the Sefin Nacional does.

metadata comes back as the API sends it and differs per kind: utrib on an NCM, ncm_code on a CEST, tax_type on a CST, nil on an ISS service.

Three things worth knowing before you loop:

  • These share the invoice read allowance — 600 calls a minute per key, the same bucket Consult, History, Received and Pdf draw from. One Search page beats N Get calls.
  • Ordering is fixed (kind, then code, ascending). Unlike History, SearchQuery has no SortBy/OrderBy.
  • A 404 from Taxpayer does not mean the company does not exist. That registry reloads monthly, so a recently registered CNPJ is simply not in it yet. Do not build a validation rule on it.

Taxpayer has one method and keeps one: the registry holds the names and addresses of real people, so there is no search over it, by design.

Dry run and DPS lookup

Validate takes the same IssueRequest as Issue and runs the API's checks without transmitting, numbering or charging. A document that would be refused is a result, not an error:

result, err := client.Validate(req)
if err != nil {
    log.Fatal(err)
}
if !result.Valid {
    for _, f := range result.Errors {
        fmt.Println(f.Code, f.Field, f.Message)
    }
}
for _, w := range result.Warnings {
    fmt.Println(w.Code, w.Field, w.Message)
}

Any other refusal (malformed body, unknown client or item, credentials, rate limit) comes back as the error Issue would return.

ConsultByDPS reads an NFS-e by the DPS id, the DocumentID of an OUTCOME_UNKNOWN error, and answers like Consult (it may carry status: "cancelled"). The API answers 400 when the id is not this company's and 404 when the authority holds no note for it, meaning nothing was issued.

note, err := client.ConsultByDPS(apiErr.DocumentID)

Errors

  • *stackin.APIError — the API responded with a non-2xx status (StatusCode, Detail) — a 401 here means api_key is missing, wrong, or was rotated. Every error above wraps one, and it also carries what the body says about the failure, zero when absent: Code (a rule code, an authority cStat or CONNECTION_FAILED/OUTCOME_UNKNOWN), Field (the request path of the offending value), Retryable (*bool, nil when the API did not say), DocumentID (the DPS id of an OUTCOME_UNKNOWN NFS-e, for ConsultByDPS), SefazRejection, Expected and Received. Detail is the message, not the raw JSON, when the body has one.
  • *stackin.CompanyRequiredError, *stackin.CompanyNotInScopeError, *stackin.InsufficientPermissionError — the company or permission answers described under Several companies on one credential. Each wraps an *APIError.
  • *stackin.ClientAlreadyExistsError — 409 CLIENT_EXISTS: Clients.Create or Update with a tax id or foreign id the company already has on another client. ClientID names that client. It wraps an *APIError.
  • *stackin.PaymentRequiredError — any 402: the plan's allowance is spent and neither an overage price nor the account credit covers the call; Detail says why. It wraps an *APIError.
  • *stackin.RateLimitedError — any 429. RetryAfter is the Retry-After header in seconds (derived from RetryAt when the header is missing); Code and RetryAt are set when the body carries them (DISTRIBUTION_COOLDOWN on SyncReceived). It wraps an *APIError.
  • *stackin.ClientInactiveError — 422 CLIENT_INACTIVE: the saved client ClientID is deactivated; reactivate it first. It wraps an *APIError.
  • *stackin.ClientNotFoundError — 404 CLIENT_NOT_FOUND: no saved client of this company has that id. It wraps an *APIError.
  • *stackin.ItemAlreadyExistsError — 409 ITEM_EXISTS: Items.Create, Upsert or Update with a code (or external reference) the company already has on another item, active or not. ItemID names it and Field says which. It wraps an *APIError.
  • *stackin.ItemNotFoundError — 404 ITEM_NOT_FOUND: no item of this company has that id. It wraps an *APIError.
  • *stackin.ItemInactiveError, *stackin.ItemKindMismatchError, *stackin.ItemTaxRequiredError, *stackin.ItemTaxRegimeMismatchError — the 422 answers of Issue for a line with ItemID: the item is deactivated (ITEM_INACTIVE), is a service on an NF-e or a product on an NFS-e (ITEM_KIND_MISMATCH), has a tax situation that needs the line's own Tax (ITEM_TAX_REQUIRED), or has a CST/CSOSN that does not fit the company's tax regime (a CSOSN is for Simples Nacional, a CST for the rest) or an export CFOP (ITEM_TAX_REGIME_MISMATCH). ItemID names the item and, on the last three, Index the line. Each wraps an *APIError.
  • *stackin.ConnectionFailedError — the API didn't respond (network/DNS/timeout).
  • *stackin.InvoiceError — Issue()'s Items is empty, missing NCM/CFOP on an item for NFE, a missing/incomplete RecipientAddress on NFE, or any other check listed under Checked before the request goes out. Also Stats() with days outside 1–365, Classify() with a Description outside 3–500 characters, a DocumentType other than NFE/NFSE or a RecipientState that is not two letters, FiscalReference.Cities() with a name outside 2–100 characters or a State that is not two letters, Webhooks.Create() with a URL that is not https://, a secret outside 16–255 characters or an event name not in WebhookEvents, and an invoice or endpoint id that is empty, . or .. (ids are escaped as one path segment).

Building the full fiscal document (issuer data, service code, tax groups, schema-accurate XML) is the API's job — configured once per company, not passed on every call.

Examples

Runnable end-to-end programs in examples/nfe/ and examples/nfse/ — one program per field variant, from the bare minimum to every field filled. examples/consult_invoice/, examples/cancel_invoice/, and examples/reissue_invoice/ cover the operations that act on an already-issued document. examples/lookup_fiscal_reference/ and examples/lookup_taxpayer/ cover the two read-only clients.

Documentation

Overview

Package stackin is the official Go SDK for the stackin fiscal document API — issue, consult, and cancel Brazilian NF-e and NFS-e electronic invoices with a single API key, no certificates or XML handling required.

See https://docs.stackin.io for the REST API reference and https://docs.stackin.io/blog/go-sdk for the Go SDK guide.

Index

Constants

View Source
const AbroadState = "EX"

AbroadState is the State of a buyer abroad on an NF-e. Such an address may leave ZipCode and CityCode out and names its country with CountryCode (BACEN code) and CountryName instead.

View Source
const DefaultBaseURL = "https://sdk.stackin.io"

Variables

View Source
var Kinds = []string{
	"cfop",
	"ncm",
	"cest",
	"cst",
	"csosn",
	"iss_service",
	"icms_fuel",
	"ibs_cbs_class",
}

Kinds are the classifications with a named accessor on FiscalReference. It is not the whole truth and is not meant to be: ask Kinds() for what the API actually has, because a classification published after this release is reachable through Kind() with no release at all.

View Source
var WebhookEvents = []string{
	"invoice.authorized",
	"invoice.rejected",
	"invoice.cancelled",
	"invoice.corrected",
	"received_invoice.stored",
	"received_invoice.full_document",
}

WebhookEvents are the event names an endpoint can subscribe to.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode     int
	Detail         string
	Code           string
	Field          string
	Retryable      *bool
	DocumentID     string
	SefazRejection string
	Expected       string
	Received       string
	// contains filtered or unexported fields
}

APIError is any non-2xx answer. Detail is the human message. Code, Field, Retryable, DocumentID, SefazRejection, Expected and Received are filled from the body when it carries them and are zero (nil for Retryable) otherwise. A nil Retryable means the API did not say.

func (*APIError) Error

func (e *APIError) Error() string

type Address

type Address struct {
	State        string `json:"state,omitempty"`
	CityCode     string `json:"city_code,omitempty"`
	Street       string `json:"street,omitempty"`
	Number       string `json:"number,omitempty"`
	Neighborhood string `json:"neighborhood,omitempty"`
	City         string `json:"city,omitempty"`
	ZipCode      string `json:"zip_code,omitempty"`
	CountryCode  string `json:"country_code,omitempty"`
	CountryName  string `json:"country_name,omitempty"`
	// Complement is the apartment, suite or block, written as xCpl. A
	// complement too long for the layout is left out by the API with the
	// warning RECIPIENT_COMPLEMENT_OMITTED.
	Complement string `json:"complement,omitempty"`
	// CountryISO2 is the ISO 3166 alpha-2 code of an NFS-e tomador abroad
	// (State EX), never BR; PostalCode and Province complete its address.
	// NFS-e only.
	CountryISO2 string `json:"country_iso2,omitempty"`
	PostalCode  string `json:"postal_code,omitempty"`
	Province    string `json:"province,omitempty"`
}

type AuthorizedCompanies added in v0.15.0

type AuthorizedCompanies struct {
	Environment string              `json:"environment"`
	Companies   []AuthorizedCompany `json:"companies"`
}

AuthorizedCompanies is every company a credential covers, in one environment.

type AuthorizedCompany added in v0.15.0

type AuthorizedCompany struct {
	CompanyID   string   `json:"company_id"`
	Name        string   `json:"name"`
	TaxID       string   `json:"tax_id"`
	Permissions []string `json:"permissions"`
}

AuthorizedCompany is one company a credential may act on, and the permissions it holds there.

type CityQuery added in v0.19.0

type CityQuery struct {
	// State is one UF, two letters.
	State string
	// Country overrides the client's own, ISO 3166-1 alpha-2.
	Country string
}

CityQuery narrows a city lookup. Both fields are optional.

type ClassifyRequest added in v0.19.0

type ClassifyRequest struct {
	// Description is the item as the shop names it, 3 to 500 characters.
	Description string
	// DocumentType is NFE or NFSE. Required.
	DocumentType DocumentType
	// RecipientState is the buyer's UF, two letters. Omitted when empty.
	RecipientState string
	// Answers settle what the last suggestion listed in
	// missing_information: operation_scope, purpose, contains_alcohol,
	// service_city_code, tax_retained. Omitted when empty.
	Answers map[string]any
}

ClassifyRequest is one item's description and the context that changes its codes.

type ClientAlreadyExistsError added in v0.17.0

type ClientAlreadyExistsError struct {
	APIError
	Message  string
	ClientID string
}

ClientAlreadyExistsError is the API's 409 CLIENT_EXISTS: the company already has a client with this tax id or foreign id. ClientID names it, to read or reactivate instead of searching for it. errors.As still finds the *APIError inside.

func (*ClientAlreadyExistsError) Unwrap added in v0.17.0

func (e *ClientAlreadyExistsError) Unwrap() error

type ClientChanges added in v0.17.0

type ClientChanges struct {
	Name                  *string
	TaxID                 *string
	ForeignID             *string
	StateRegistration     *string
	MunicipalRegistration *string
	Email                 *string
	Phone                 *string
	Address               *Address
	ClearAddress          bool
	Notes                 *string
	// IsActive pointing at true brings a deactivated client back; see
	// Reactivate.
	IsActive *bool
}

ClientChanges is what Update changes. A nil field is not sent; a field pointing at "" is sent as null, which clears it. Address replaces the whole address; ClearAddress removes it.

type ClientFields added in v0.17.0

type ClientFields struct {
	Name                  string   `json:"name"`
	TaxID                 string   `json:"tax_id,omitempty"`
	ForeignID             string   `json:"foreign_id,omitempty"`
	StateRegistration     string   `json:"state_registration,omitempty"`
	MunicipalRegistration string   `json:"municipal_registration,omitempty"`
	Email                 string   `json:"email,omitempty"`
	Phone                 string   `json:"phone,omitempty"`
	Address               *Address `json:"address,omitempty"`
	Notes                 string   `json:"notes,omitempty"`
}

ClientFields is a client as Create takes it. TaxID is required except for a buyer abroad (Address.State EX), who has a ForeignID instead. Empty fields are left out of the request.

type ClientInactiveError added in v0.18.0

type ClientInactiveError struct {
	APIError
	Message  string
	ClientID string
}

ClientInactiveError is the API's 422 CLIENT_INACTIVE: the saved client named by ClientID is deactivated. Reactivate it, or issue without it. errors.As still finds the *APIError inside.

func (*ClientInactiveError) Unwrap added in v0.18.0

func (e *ClientInactiveError) Unwrap() error

type ClientNotFoundError added in v0.18.0

type ClientNotFoundError struct {
	APIError
	Message  string
	ClientID string
}

ClientNotFoundError is the API's 404 CLIENT_NOT_FOUND: no saved client of this company has that id. errors.As still finds the *APIError inside.

func (*ClientNotFoundError) Unwrap added in v0.18.0

func (e *ClientNotFoundError) Unwrap() error

type ClientQuery added in v0.17.0

type ClientQuery struct {
	// Search matches part of the name, the tax id (masked or not) or the
	// foreign id.
	Search string
	// Source is manual, issued or issuance.
	Source string
	// IsActive left nil lists the active clients, as the API does;
	// pointing at false lists the deactivated ones.
	IsActive *bool
	Limit    int
	Offset   int
	// SortBy takes name, last_used_at, created_at or uses_count.
	SortBy  string
	OrderBy string
}

ClientQuery narrows the client listing. Every field is optional; the zero value asks for the first page of active clients, by name.

type Clients added in v0.17.0

type Clients struct {
	// contains filtered or unexported fields
}

Clients reads and edits the company's saved clients: the recipients it issues to again. A successful issuance saves a new recipient on its own, and IssueRequest.ClientID issues to a saved one.

It is company data, like everything on Invoice: WithCompany and ForCompany pick the company. Reading needs invoice:read; creating, editing and deactivating need invoice:issue. The rules on a client's fields are the issuance's own and they are the API's: a refusal comes back as an *APIError 422.

func NewClients added in v0.17.0

func NewClients(opts ...Option) *Clients

func (*Clients) Create added in v0.17.0

func (c *Clients) Create(fields ClientFields) (map[string]any, error)

Create saves a client by hand. A TaxID or ForeignID the company already holds is a *ClientAlreadyExistsError, whose ClientID names it.

func (*Clients) Deactivate added in v0.17.0

func (c *Clients) Deactivate(clientID string) error

Deactivate deactivates a client. It is kept, left out of List by default and refused on issue until Reactivate brings it back.

func (*Clients) ForCompany added in v0.17.0

func (c *Clients) ForCompany(company string) *Clients

ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.

func (*Clients) Get added in v0.17.0

func (c *Clients) Get(clientID string) (map[string]any, error)

Get returns one client, deactivated or not. Another company's client is a 404.

func (*Clients) List added in v0.17.0

func (c *Clients) List(query ClientQuery) (map[string]any, error)

List returns a page of the company's clients.

func (*Clients) Reactivate added in v0.17.0

func (c *Clients) Reactivate(clientID string) (map[string]any, error)

Reactivate brings a deactivated client back, and returns it.

func (*Clients) Update added in v0.17.0

func (c *Clients) Update(clientID string, changes ClientChanges) (map[string]any, error)

Update changes only the fields set in changes. The API checks the client as a whole, so clearing a Brazilian client's tax id is refused like a create without one; taking another client's tax id is a *ClientAlreadyExistsError.

type Company added in v0.20.0

type Company struct {
	// contains filtered or unexported fields
}

Company fixes the issuer itself: its address and, for the owner, its fiscal fields (PATCH /company). It fixes what Invoice.Readiness reports missing; reading stays Readiness.

It is company data: WithCompany and ForCompany pick the company. On an OAuth credential Update needs company:write; an API key acts for the member who created it.

func NewCompany added in v0.20.0

func NewCompany(opts ...Option) *Company

func (*Company) ForCompany added in v0.20.0

func (c *Company) ForCompany(company string) *Company

ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.

func (*Company) Update added in v0.20.0

func (c *Company) Update(update CompanyUpdate) (map[string]any, error)

Update fixes the issuer's address and, for the owner, its fiscal fields, and answers what GET /company does — ready, missing, by_document_type, fix_url, ... — plus the stored address and fiscal_fields, so no second call is needed.

A municipality the IBGE table cannot be read for right now is an *APIError 503 with Retry-After: nothing was written. A member limited to homologation, or a non-owner sending FiscalFields, is an *APIError 403.

type CompanyAddress added in v0.20.0

type CompanyAddress struct {
	Street       string `json:"street,omitempty"`
	Number       string `json:"number,omitempty"`
	Neighborhood string `json:"neighborhood,omitempty"`
	// MunicipalityCode is the 7-digit IBGE code of a city in the company's
	// state. MunicipalityName is derived from it when left out.
	MunicipalityCode string `json:"municipality_code,omitempty"`
	// MunicipalityName is resolved to its code when sent alone, and must be
	// the code's city when both are sent.
	MunicipalityName string `json:"municipality_name,omitempty"`
	// ZipCode is the 8-digit CEP; a mask (01310-100) is stripped.
	ZipCode string `json:"zip_code,omitempty"`
}

CompanyAddress is the issuer address Update may fix. There is no complement, and the state changes only in the dashboard: it decides the authorizer. Empty fields are left out.

type CompanyNotInScopeError added in v0.15.0

type CompanyNotInScopeError struct {
	APIError
	Description string
	Companies   []AuthorizedCompany
}

CompanyNotInScopeError is the API's 403 company_not_in_scope: the company named is not one this credential covers. Companies lists the ones it does. Retrying the same request cannot succeed. errors.As still finds the *APIError inside.

func (*CompanyNotInScopeError) Unwrap added in v0.15.0

func (e *CompanyNotInScopeError) Unwrap() error

type CompanyRequiredError added in v0.15.0

type CompanyRequiredError struct {
	APIError
	Description string
	Companies   []AuthorizedCompany
}

CompanyRequiredError is the API's 422 company_required: the credential covers several companies and the request named none. Companies lists them; name one with WithCompany or ForCompany. Retrying the same request cannot succeed. errors.As still finds the *APIError inside.

func (*CompanyRequiredError) Unwrap added in v0.15.0

func (e *CompanyRequiredError) Unwrap() error

type CompanyUpdate added in v0.20.0

type CompanyUpdate struct {
	Address *CompanyAddress
	// FiscalFields are the company owner's alone: anyone else gets an
	// *APIError 403, even when the address in the same call would pass.
	FiscalFields          *FiscalFields
	BlockActivityMismatch *bool
}

CompanyUpdate is what Update sends. A nil group, or one with nothing set, is left out; an empty CompanyUpdate changes nothing and answers the company as it is.

type ConnectionFailedError

type ConnectionFailedError struct {
	Message string
}

func (*ConnectionFailedError) Error

func (e *ConnectionFailedError) Error() string

type Direction added in v0.14.0

type Direction string

Direction is whether an NF-e is outgoing or an incoming one the company issues itself (tpNF). The API defaults to DirectionOut when it is left out.

const (
	DirectionOut Direction = "out"
	DirectionIn  Direction = "in"
)

type DocumentType

type DocumentType string
const (
	NFE  DocumentType = "nfe"
	NFSE DocumentType = "nfse"
)

type Environment

type Environment string
const (
	Local      Environment = "local"
	Test       Environment = "test"
	Production Environment = "production"
)

type Export added in v0.14.0

type Export struct {
	ExitState     string `json:"exit_state"`
	Place         string `json:"place"`
	DispatchPlace string `json:"dispatch_place,omitempty"`
}

Export is where the goods of an NF-e to a buyer abroad leave Brazil (the exporta group): ExitState is a Brazilian state (UFSaidaPais, never EX), Place the place of shipment or border crossing (xLocExporta) and DispatchPlace the optional customs facility of dispatch (xLocDespacho).

type FiscalFields added in v0.20.0

type FiscalFields struct {
	// TaxRegime is the CRT: 1 Simples, 2 Simples excesso, 3 normal, 4 MEI.
	TaxRegime string `json:"tax_regime,omitempty"`
	// SimplesNacional is the NFS-e opSimpNac: 1 no, 2 MEI, 3 ME/EPP.
	SimplesNacional string `json:"simples_nacional,omitempty"`
	// SimplesApuracao is the NFS-e regApTribSN for ME/EPP, 1 to 3.
	SimplesApuracao string `json:"simples_apuracao,omitempty"`
	// SimplesApuracaoIbsCbs is the apuração of the IBS/CBS for an ME/EPP,
	// 1 or 3; 3 is what the NFS-e IBS/CBS group needs.
	SimplesApuracaoIbsCbs string `json:"simples_apuracao_ibs_cbs,omitempty"`
	// StateRegistration is the inscrição estadual (IE), or ISENTO.
	StateRegistration string `json:"state_registration,omitempty"`
	// ServiceCode is the default cTribNac, e.g. 1.07 or 01.07.00.
	ServiceCode string `json:"service_code,omitempty"`

	// The fields below are pointers: nil leaves the setting alone and a
	// pointer to "" clears it.
	//
	// The ApproximateTax* settings are the Lei 12.741 percentages (DPS
	// totTrib), two decimals: the Simples one 0 to 99.99, the others 0 to
	// 100. IssRate is the ISSQN rate in percent, above 0 and at most 5.
	// MunicipalRegistration is the provider's inscrição municipal, up to 15
	// letters or digits. SpecialTaxRegime is regEspTrib: 0, 1, 2, 3, 4, 5, 6
	// or 9.
	ApproximateTaxSimplesPercent   *string `json:"approximate_tax_simples_percent,omitempty"`
	ApproximateTaxFederalPercent   *string `json:"approximate_tax_federal_percent,omitempty"`
	ApproximateTaxStatePercent     *string `json:"approximate_tax_state_percent,omitempty"`
	ApproximateTaxMunicipalPercent *string `json:"approximate_tax_municipal_percent,omitempty"`
	IssRate                        *string `json:"iss_rate,omitempty"`
	MunicipalRegistration          *string `json:"municipal_registration,omitempty"`
	SpecialTaxRegime               *string `json:"special_tax_regime,omitempty"`
}

FiscalFields are the fiscal fields the owner may set. Empty fields are left out.

type FiscalReference added in v0.10.0

type FiscalReference struct {
	CFOP        *Kind
	NCM         *Kind
	CEST        *Kind
	CST         *Kind
	CSOSN       *Kind
	IssService  *Kind
	IcmsFuel    *Kind
	IbsCbsClass *Kind
	// contains filtered or unexported fields
}

FiscalReference reads the published classification tables. Nothing here is the company's own data and nothing here is writable.

func NewFiscalReference added in v0.10.0

func NewFiscalReference(opts ...Option) *FiscalReference

func (*FiscalReference) CalculateIbsCbs added in v0.23.0

func (r *FiscalReference) CalculateIbsCbs(request IbsCbsCalculationRequest) (*IbsCbsCalculation, error)

CalculateIbsCbs simulates the IBS and CBS of up to 990 items (POST /ibs-cbs/calculate). The amounts are the NF-e's: the simulation does not compute an NFS-e's, which the Sefin Nacional does. It needs no company and writes nothing. A refusal by the API, such as IBS_CBS_RATES_REQUIRED, is an *APIError with its code and field.

func (*FiscalReference) Cities added in v0.19.0

func (r *FiscalReference) Cities(name string, query CityQuery) ([]map[string]any, error)

Cities lists the municipalities whose name starts with name, with their code. Each row is {country, code, name, state}; for Brazil code is the 7-digit IBGE code an Address's CityCode takes. Issuing resolves it from City and State by itself, so this is for the name that matches more than one. The API answers at most 20 rows.

func (*FiscalReference) Kind added in v0.10.0

func (r *FiscalReference) Kind(name string, country ...string) *Kind

Kind reaches any classification by name, including one with no accessor on this struct.

func (*FiscalReference) Kinds added in v0.10.0

func (r *FiscalReference) Kinds(country ...string) ([]string, error)

Kinds asks which classifications this country has rows for. The only honest answer to "what else is there" — a hard-coded list goes stale the next time the ETL grows one.

func (*FiscalReference) NBSSuggestions added in v0.27.0

func (r *FiscalReference) NBSSuggestions(serviceCode string) (*NBSSuggestions, error)

NBSSuggestions suggests the NBS codes Anexo VIII correlates with a service code, in any form Product.ServiceCode takes: "1.07", "01.07.00" or "010700". Only its LC 116 subitem decides the answer. Nothing here is written into a document: send a suggestion as Product.NBS and its OperationIndicator and IbsCbsClassification on Product.IbsCbs. A code the route cannot read is an *APIError 422.

func (*FiscalReference) Search added in v0.10.0

func (r *FiscalReference) Search(query SearchQuery) (map[string]any, error)

Search spans every classification at once, which no accessor can express. It is the most expensive call the endpoint accepts: the whole country's tables, not one of them.

type HistoryQuery added in v0.5.0

type HistoryQuery struct {
	DocumentType DocumentType
	Status       string
	Limit        int
	Offset       int
	SortBy       string
	OrderBy      string

	// ExternalReference finds the documents issued with exactly this
	// IssueRequest.ExternalReference.
	ExternalReference string

	// Fields set to "summary" returns a lighter item per invoice.
	Fields string
}

HistoryQuery filters the issuance history. Every field is optional; the zero value asks for the newest page with the API's own defaults.

type IbsCbsAmounts added in v0.23.0

type IbsCbsAmounts struct {
	Base             string `json:"base"`
	IbsState         string `json:"ibs_state"`
	IbsCity          string `json:"ibs_city"`
	Ibs              string `json:"ibs"`
	Cbs              string `json:"cbs"`
	DeferredIbsState string `json:"deferred_ibs_state"`
	DeferredIbsCity  string `json:"deferred_ibs_city"`
	DeferredCbs      string `json:"deferred_cbs"`
}

IbsCbsAmounts are money values as the API sends them, decimal strings such as "1.00", so nothing is rounded through a float.

type IbsCbsAppliedRates added in v0.23.0

type IbsCbsAppliedRates struct {
	RateState   string `json:"rate_state"`
	RateCity    string `json:"rate_city"`
	RateFederal string `json:"rate_federal"`
}

IbsCbsAppliedRates are rates in percent, as decimal strings.

type IbsCbsCalculatedItem added in v0.23.0

type IbsCbsCalculatedItem struct {
	CST            string              `json:"cst"`
	Classification string              `json:"classification"`
	Indicators     IbsCbsIndicators    `json:"indicators"`
	HasGroup       bool                `json:"has_group"`
	Rates          *IbsCbsAppliedRates `json:"rates"`
	RatesSource    *string             `json:"rates_source"`
	ReductionIbs   *string             `json:"reduction_ibs"`
	ReductionCbs   *string             `json:"reduction_cbs"`
	EffectiveRates *IbsCbsAppliedRates `json:"effective_rates"`
	Deferral       *string             `json:"deferral"`
	Amounts        IbsCbsAmounts       `json:"amounts"`
}

IbsCbsCalculatedItem is one simulated item. RatesSource is "caller" or "official_2026"; Rates and EffectiveRates are nil when the item has none.

type IbsCbsCalculation added in v0.23.0

type IbsCbsCalculation struct {
	Simulated     bool                   `json:"simulated"`
	Notice        string                 `json:"notice"`
	DocumentType  string                 `json:"document_type"`
	OperationDate string                 `json:"operation_date"`
	Items         []IbsCbsCalculatedItem `json:"items"`
	Total         IbsCbsAmounts          `json:"total"`
}

IbsCbsCalculation is the simulation. Simulated is always true: nothing is issued or stored.

type IbsCbsCalculationItem added in v0.23.0

type IbsCbsCalculationItem struct {
	CST            string
	Classification string
	Amount         *float64
	Base           *float64
	RateState      *float64
	RateCity       *float64
	RateFederal    *float64
	ReductionIbs   *float64
	ReductionCbs   *float64
}

IbsCbsCalculationItem is one item of the simulation. CST (3 digits) and Classification (cClassTrib, 6 digits) are required, and so is Amount or Base. Fields left nil are not sent.

type IbsCbsCalculationRequest added in v0.23.0

type IbsCbsCalculationRequest struct {
	DocumentType  string
	OperationDate string
	Rates         *IbsCbsRates
	Items         []IbsCbsCalculationItem
}

IbsCbsCalculationRequest is what CalculateIbsCbs sends. OperationDate is YYYY-MM-DD and required. DocumentType is "nfe" (the default when empty), "nfce" or "nfse": it only picks the model the cClassTrib is checked for.

type IbsCbsIndicators added in v0.23.0

type IbsCbsIndicators struct {
	Group     *int `json:"group"`
	Reduction *int `json:"reduction"`
	Deferral  *int `json:"deferral"`
}

IbsCbsIndicators are the cClassTrib's group, reduction and deferral indicators; nil when the classification does not carry one.

type IbsCbsRates added in v0.23.0

type IbsCbsRates struct {
	RateState   *float64
	RateCity    *float64
	RateFederal *float64
}

IbsCbsRates are the caller's rates for the whole simulation, in percent (0 to 100): pIBSUF, pIBSMun and pCBS. Each is sent only when set, and an item's own rate wins over it. A nil IbsCbsCalculationRequest.Rates in 2026 makes the official 2026 rates apply (CBS 0.9%, IBS UF 0.1%, IBS Mun 0%); outside 2026 the API refuses it with IBS_CBS_RATES_REQUIRED.

type InsufficientPermissionError added in v0.15.0

type InsufficientPermissionError struct {
	APIError
	Description string
}

InsufficientPermissionError is the API's 403 INSUFFICIENT_PERMISSION: the credential reaches the company but lacks the permission the call needs. Description reads "needs X, has Y, company=<id>". Retrying the same request cannot succeed. errors.As still finds the *APIError inside.

func (*InsufficientPermissionError) Unwrap added in v0.15.0

func (e *InsufficientPermissionError) Unwrap() error

type Intermediary added in v0.25.0

type Intermediary struct {
	TaxID      string `json:"tax_id"`
	Identifier string `json:"identifier"`
}

Intermediary is the marketplace or platform an NF-e sale went through (infIntermed). TaxID is its CNPJ and Identifier the seller's user name or profile id there.

type InvalidationRequest added in v0.2.0

type InvalidationRequest struct {
	Series      string
	NumberStart int
	NumberEnd   int
	Reason      string
}

type Invoice

type Invoice struct {
	// contains filtered or unexported fields
}

func NewInvoice

func NewInvoice(opts ...Option) *Invoice

func (*Invoice) Cancel

func (inv *Invoice) Cancel(accessKey string, documentType DocumentType, reason string, opts ...RequestOption) (map[string]any, error)

Cancel voids an authorized document. Pass WithIdempotencyKey to make a retry safe: repeating the same key with the same body replays the first answer instead of cancelling twice. This is the one irreversible operation here, with a legal window and no undo.

func (*Invoice) Classify added in v0.19.0

func (inv *Invoice) Classify(req ClassifyRequest) (map[string]any, error)

Classify suggests a fiscal classification for one item's description.

A suggestion, never a decision: primary_candidate and alternative_candidates carry the NCM, CFOP, CST/CSOSN, CEST or service code, each read from the published tables, with a confidence, and missing_information lists what would settle it (pass those back in Answers). Someone confirms it before it goes on an item; the codes decide the tax owed.

func (*Invoice) Companies added in v0.15.0

func (inv *Invoice) Companies() (*AuthorizedCompanies, error)

Companies lists the companies this credential reaches, with the permissions it holds on each: the ids WithCompany and ForCompany accept. An API key lists as its one company with every permission.

func (*Invoice) Consult

func (inv *Invoice) Consult(accessKey string, documentType DocumentType) (map[string]any, error)

func (*Invoice) ConsultByDPS added in v0.24.0

func (inv *Invoice) ConsultByDPS(dpsID string) (map[string]any, error)

ConsultByDPS reads an NFS-e by the DPS id the authority was sent, the document_id of an OUTCOME_UNKNOWN error. It answers like Consult and may carry status "cancelled". The API answers 400 when the id is not this company's and 404 when the authority holds no note for it, meaning nothing was issued.

func (*Invoice) Correct added in v0.2.0

func (inv *Invoice) Correct(accessKey string, documentType DocumentType, correction string) (map[string]any, error)

Correct files a correction letter (CC-e). NF-e only: a key that is not an NF-e access key is refused before the call. A well-formed key sent with NFSE, or one for a document the API does not hold, is answered 409 by the API and comes back as an *APIError.

func (*Invoice) ForCompany added in v0.15.0

func (inv *Invoice) ForCompany(company string) *Invoice

ForCompany returns a copy of the client bound to another company, for the calls chained on it: inv.ForCompany("00.000.000/0001-91").Issue(req). The receiver is left as it was and the copy shares its HTTP client. An empty company sends no header at all.

func (*Invoice) History added in v0.5.0

func (inv *Invoice) History(query HistoryQuery) (map[string]any, error)

History lists what this company issued, newest first.

The counterpart of Received: that one lists what was issued against the company, this one what the company issued.

func (*Invoice) Invalidate added in v0.2.0

func (inv *Invoice) Invalidate(req InvalidationRequest) (map[string]any, error)

func (*Invoice) Invalidations added in v0.19.0

func (inv *Invoice) Invalidations(query PageQuery) (map[string]any, error)

Invalidations lists the numbering ranges this company already invalidated, a page. Each row carries the range, the reason, the SEFAZ status and its protocol. Read it before Invalidate to avoid reporting the same range twice.

func (*Invoice) Issue

func (inv *Invoice) Issue(req IssueRequest) (map[string]any, error)

func (*Invoice) Manifest added in v0.3.1

func (inv *Invoice) Manifest(accessKey string, manifestation Manifestation, reason string) (map[string]any, error)

Manifest files the recipient's formal answer to a received document.

Only OperacaoNaoRealizada takes a reason, and it requires one. Both are fixed rules, checked here rather than spending a round trip to be told.

func (*Invoice) Pdf added in v0.3.0

func (inv *Invoice) Pdf(accessKey string, documentType DocumentType) ([]byte, error)

Pdf returns the printable rendering of an authorized document, as raw bytes — the only method that does not return a parsed object. The API draws it itself from the authorized XML: the DANFE for an NF-e, the DANFSe for an NFS-e. The XML stays the legally valid document.

func (*Invoice) Readiness added in v0.19.0

func (inv *Invoice) Readiness() (map[string]any, error)

Readiness says whether the company can issue right now, and if not, why (GET /company).

ready is true when at least one document type can be issued; when false, missing names why: certificate, certificate_expired, certificate_unreadable, address, state_registration (NF-e) or plan. by_document_type breaks it down per nfe/nfse (ready, missing, warnings, each issue a code plus, for address, the fields at fault) and fix_url is the dashboard screen for the first blocker (nil when nothing blocks). Also has_certificate, certificate_expires_at, tax_regime (CRT), state, default_series per document type and suggested_fiscal_fields, what the CNPJ registry suggests where it differs — never applied. The map keeps whatever the API adds. Company.Update fixes the address and fiscal fields. Ask before a first document instead of failing it.

func (*Invoice) Received added in v0.3.1

func (inv *Invoice) Received(limit, offset int) (map[string]any, error)

Received lists documents other companies issued against this one.

Reads what the API already collected; it does not call the authorizer. Collecting runs on a schedule there, every six hours, and SyncReceived asks for it now. After a read that finds nothing more the SEFAZ makes the CNPJ wait an hour before the next one.

The first 50 received documents a month are included in every plan; each one after that takes R$ 0,05 from the account credit. Some accounts are exempt: Usage().ReceivedFree tells.

func (*Invoice) ReceivedXML added in v0.24.0

func (inv *Invoice) ReceivedXML(accessKey string) ([]byte, error)

ReceivedXML returns the full XML (procNFe) of a received document as raw bytes. A document held only as a summary answers 409 with code RECEIVED_XML_NOT_AVAILABLE until it is manifested; 402 is a *PaymentRequiredError. Downloading is never billed.

func (*Invoice) Reissue added in v0.2.0

func (inv *Invoice) Reissue(invoiceID string, opts ...RequestOption) (map[string]any, error)

func (*Invoice) Rejection added in v0.19.0

func (inv *Invoice) Rejection(invoiceID string) (map[string]any, error)

Rejection explains why a rejected document was refused, and what to change. Submissions has the authorizer's own answer; this reads it for someone who does not speak SEFAZ: code, message, explanation, steps, the field to fix and, when there is one, a suggested value. It takes the invoiceID, like Submissions. A document that is not rejected is an *APIError 409.

func (*Invoice) Stats added in v0.19.0

func (inv *Invoice) Stats(days int) (map[string]any, error)

Stats counts this company's documents, and the last days of them.

total, by_document_type and by_status cover every document; current_period/previous_period compare the last days (1 to 365) with the ones before, and daily_series has one row per day. Zero days sends nothing and the API answers for 30.

func (*Invoice) Submissions added in v0.6.0

func (inv *Invoice) Submissions(invoiceID string) ([]map[string]any, error)

Submissions returns every attempt made for one invoice, with what the authorizer answered to each.

Consult gives the status; this gives the reason. It takes the invoiceID, like Reissue and unlike everything else, because a rejected document has no access key to look it up by.

func (*Invoice) SyncReceived added in v0.18.0

func (inv *Invoice) SyncReceived() (*SyncResult, error)

SyncReceived asks the SEFAZ now for the documents issued against this company since the last read, instead of waiting for the scheduled collection, which runs every six hours. After a read that finds nothing more the SEFAZ makes the CNPJ wait an hour; a call inside that wait is a *RateLimitedError with Code DISTRIBUTION_COOLDOWN, RetryAt and RetryAfter.

func (*Invoice) Usage added in v0.18.0

func (inv *Invoice) Usage() (*Usage, error)

Usage reads the plan behind this company and how much of it the current period has used (GET /company/usage).

func (*Invoice) Validate added in v0.24.0

func (inv *Invoice) Validate(req IssueRequest) (*ValidationResult, error)

Validate dry-runs an issuance: the same request as Issue, checked by the API without transmitting, numbering or charging. The rules failing is a result with Valid false, not an error; any other refusal (malformed body, unknown client or item, credentials, rate limit) is returned as the error Issue would return.

type InvoiceError

type InvoiceError struct {
	Message string
}

func (*InvoiceError) Error

func (e *InvoiceError) Error() string

type IssueRequest

type IssueRequest struct {
	DocumentType     DocumentType
	ClientName       string
	TaxID            string
	Items            []br.Product
	RecipientAddress *Address
	Series           string
	Number           string

	// ExternalReference is the caller's own id for the document, an order
	// number say. The API stores it as sent (at most 255 characters) and
	// returns it on every read and webhook. Omitted when empty.
	ExternalReference string

	// IdempotencyKey makes a retry safe: the same key with the same body
	// replays the first response instead of issuing a second document.
	// Keys live 24 hours. Never generated for you — only the caller knows
	// which two requests are meant to be the same one.
	IdempotencyKey string

	AcceptLanguage string `json:"-"`

	// Discount is a discount on the whole document, in BRL, zero or more.
	// The API spreads it over the lines. Omitted when nil.
	Discount *float64

	// IssuedAt is the emission moment (dhEmi), sent as RFC 3339 in the
	// offset of its own Location. NF-e: at most 30 days back and 5 minutes
	// ahead; NFS-e: never ahead. The API defaults it to now. Omitted when
	// nil.
	IssuedAt *time.Time

	// Purpose is why the NF-e is issued; Direction whether it is outgoing
	// or incoming. NF-e only, omitted when empty.
	Purpose   Purpose
	Direction Direction

	// ReferencedKeys are the 44-character access keys of the NF-e, NFC-e
	// or CF-e this NF-e refers to: required for PurposeComplementary and,
	// but for a few CFOPs, PurposeReturn. NF-e only, omitted when empty.
	ReferencedKeys []string

	// ForeignID identifies a buyer abroad (idEstrangeiro, 5 to 20
	// characters), for an NF-e whose RecipientAddress.State is EX. TaxID
	// is then left out. Omitted when empty.
	ForeignID string

	// Export is where the goods leave Brazil, required for an outgoing
	// NF-e to a buyer abroad. Omitted when nil.
	Export *Export

	// ClientID names a saved client of the company (see Clients). Its
	// name, tax id, foreign id and address fill whichever of ClientName,
	// TaxID, ForeignID and RecipientAddress are left empty; the ones set
	// win, and the empty ones are left out of the request. Its e-mail and
	// phone likewise fill ClientEmail and ClientPhone when empty. The address
	// checks then apply only to a RecipientAddress that is set: the API
	// checks the merged request. Omitted when empty.
	ClientID string

	// Presence is indPres, how the buyer took part: 0, 1, 2, 3, 4, 5 or 9.
	// NF-e only, omitted when empty.
	Presence string

	// Intermediary is the marketplace or platform the sale went through.
	// NF-e only, omitted when nil.
	Intermediary *Intermediary

	// Transport is the freight mode and the volumes. NF-e only, omitted
	// when nil.
	Transport *Transport

	// Payments are the detPag entries, 1 to 100 (an empty non-nil slice is refused); Amount and Change take at most 2 decimal places. NF-e only, omitted when
	// empty.
	Payments []Payment

	// Change is vTroco in BRL, what the payments exceed the total by. A
	// pointer so a 0 can be sent. NF-e only, omitted when nil.
	Change *float64

	// Contingency sends an NF-e through the UF's contingency authorizer
	// (SVC-AN or SVC-RS, tpEmis 6/7) for when its own is down. Sent only
	// when true.
	Contingency bool

	// UpdateClient rewrites an existing client with this request's
	// recipient data after a successful issuance; a new recipient is
	// saved as a client either way. Sent only when true.
	UpdateClient bool

	// ClientEmail is the recipient's e-mail, saved on the Stackin client
	// created after a successful issuance, or on an existing one only with
	// UpdateClient. It is also kept on the invoice and sent again on a
	// reissue (which does not touch the client), and written into the
	// fiscal document: NF-e dest/email (up to 60 characters), NFS-e
	// toma/email (up to 80). A value the layout cannot carry (too long,
	// characters beyond Latin-1) is left out of the document and the
	// issuance goes on. Omitted when empty.
	ClientEmail string

	// ClientPhone is the recipient's phone, 8 to 15 digits with an optional
	// leading + (the API drops spaces, dots, dashes and parentheses). Saved
	// on the client like ClientEmail, and written into the fiscal document:
	// NF-e dest/enderDest/fone (digits only, up to 14, only with a
	// RecipientAddress), NFS-e toma/fone (up to 20 digits). Digits only,
	// area code first; a +55 is dropped unless the recipient is abroad. A
	// value the layout cannot carry is left out of the document. Omitted
	// when empty.
	ClientPhone string

	// RecipientMunicipalRegistration is the tomador's inscrição municipal
	// (toma/IM), up to 15 letters or digits with masks dropped. NFS-e only.
	// Omitted when empty.
	RecipientMunicipalRegistration string

	// ForeignIDMissingReason is cNaoNIF, for an NFS-e tomador abroad without
	// a ForeignID: 1 exempt from a NIF, 2 the country does not require one.
	// Omitted when nil.
	ForeignIDMissingReason *int

	// Nfse holds the NFS-e document-level fields beyond the lines. NFS-e
	// only, omitted when nil.
	Nfse *br.NfseDetails
}

type ItemAlreadyExistsError added in v0.21.0

type ItemAlreadyExistsError struct {
	APIError
	Message string
	ItemID  string
	Field   string
}

ItemAlreadyExistsError is the API's 409 ITEM_EXISTS: the company already has an item with this code or external reference (a deactivated item still holds its code). ItemID names it and Field is "code" or "external_reference". errors.As still finds the *APIError inside.

func (*ItemAlreadyExistsError) Unwrap added in v0.21.0

func (e *ItemAlreadyExistsError) Unwrap() error

type ItemChanges added in v0.21.0

type ItemChanges struct {
	Kind        *string
	Description *string
	Code        *string
	// UnitPrice is sent as a decimal string. UnitPriceText (up to 10
	// places) wins over it and keeps every digit; pointing it at "" clears
	// the price.
	UnitPrice         *float64
	UnitPriceText     *string
	Unit              *string
	ExternalReference *string
	Notes             *string
	NCM               *string
	CFOP              *string
	TaxSituation      *string
	Origin            *string
	CEST              *string
	GTIN              *string
	ServiceCode       *string
	NBS               *string
	ISSRetained       *bool
	NetWeight         *float64
	GrossWeight       *float64
	// ClearNetWeight and ClearGrossWeight send null, clearing the weight;
	// a NetWeight or GrossWeight set alongside wins.
	ClearNetWeight   bool
	ClearGrossWeight bool
	IbsCbsCST        *string
	IbsCbsClass      *string
	// IsActive pointing at true brings a deactivated item back; see
	// Reactivate.
	IsActive *bool
}

ItemChanges is what Update changes. A nil field is not sent; a text field pointing at "" is sent as null, which clears it. The API checks the item as a whole, so changing Kind while a field of the old kind is still set is a 422.

type ItemFields added in v0.21.0

type ItemFields struct {
	Kind        string `json:"kind"`
	Description string `json:"description"`
	Code        string `json:"code,omitempty"`
	// UnitPrice is a pointer so a price of 0 can be sent, and goes out as a
	// decimal string. UnitPriceText (such as "18.9000000001", up to 10
	// places) wins over it and keeps every digit a float64 would round.
	UnitPrice         *float64 `json:"-"`
	UnitPriceText     string   `json:"-"`
	Unit              string   `json:"unit,omitempty"`
	ExternalReference string   `json:"external_reference,omitempty"`
	Notes             string   `json:"notes,omitempty"`
	// Source is how the item came to be (manual, import, nuvemshop or
	// invoice). Upsert only, and only when it creates; the API defaults it
	// to manual.
	Source       string `json:"source,omitempty"`
	NCM          string `json:"ncm,omitempty"`
	CFOP         string `json:"cfop,omitempty"`
	TaxSituation string `json:"tax_situation,omitempty"`
	Origin       string `json:"origin,omitempty"`
	CEST         string `json:"cest,omitempty"`
	GTIN         string `json:"gtin,omitempty"`
	ServiceCode  string `json:"service_code,omitempty"`
	NBS          string `json:"nbs,omitempty"`
	ISSRetained  *bool  `json:"iss_retained,omitempty"`
	// NetWeight and GrossWeight are one unit's weight in kg (a product);
	// pointers so a real 0 can be sent.
	NetWeight   *float64 `json:"net_weight,omitempty"`
	GrossWeight *float64 `json:"gross_weight,omitempty"`
	// IbsCbsCST (3 digits) and IbsCbsClass (cClassTrib, 6 digits) go
	// together; the API checks them.
	IbsCbsCST   string `json:"ibs_cbs_cst,omitempty"`
	IbsCbsClass string `json:"ibs_cbs_class,omitempty"`
}

ItemFields is an item as Create and Upsert take it. Kind and Description are required. The NCM, CFOP, TaxSituation, Origin, CEST and GTIN fields belong to a product and ServiceCode and ISSRetained to a service; the other kind's is a 422. Empty text fields and nil pointers are left out of the request; UnitPrice and ISSRetained are pointers so a price of 0 and ISSRetained false (turning retention off) can be sent.

func (ItemFields) MarshalJSON added in v0.21.0

func (f ItemFields) MarshalJSON() ([]byte, error)

MarshalJSON writes the unit price as a decimal string.

type ItemInactiveError added in v0.21.0

type ItemInactiveError struct {
	APIError
	Message string
	ItemID  string
}

ItemInactiveError is the API's 422 ITEM_INACTIVE: the catalog item named by ItemID is deactivated. Reactivate it, or issue without it. errors.As still finds the *APIError inside.

func (*ItemInactiveError) Unwrap added in v0.21.0

func (e *ItemInactiveError) Unwrap() error

type ItemKindMismatchError added in v0.21.0

type ItemKindMismatchError struct {
	APIError
	Message string
	ItemID  string
	Index   int
}

ItemKindMismatchError is the API's 422 ITEM_KIND_MISMATCH: a service item on an NF-e or a product item on an NFS-e. Index is the line. errors.As still finds the *APIError inside.

func (*ItemKindMismatchError) Unwrap added in v0.21.0

func (e *ItemKindMismatchError) Unwrap() error

type ItemNotFoundError added in v0.21.0

type ItemNotFoundError struct {
	APIError
	Message string
	ItemID  string
}

ItemNotFoundError is the API's 404 ITEM_NOT_FOUND: no item of this company has that id, also the answer for another company's item. errors.As still finds the *APIError inside.

func (*ItemNotFoundError) Unwrap added in v0.21.0

func (e *ItemNotFoundError) Unwrap() error

type ItemQuery added in v0.21.0

type ItemQuery struct {
	// Kind is product or service.
	Kind string
	// Search matches part of the description, code or external reference;
	// digits also match the NCM and the GTIN.
	Search string
	// Source is manual, import, nuvemshop or invoice.
	Source string
	// IsActive left nil lists the active items, as the API does; pointing
	// at false lists the deactivated ones.
	IsActive *bool
	Limit    int
	Offset   int
	// SortBy takes description, code, unit_price, last_used_at,
	// created_at or uses_count.
	SortBy  string
	OrderBy string
}

ItemQuery narrows the item listing. Every field is optional; the zero value asks for the first page of active items, by description.

type ItemTaxRegimeMismatchError added in v0.21.0

type ItemTaxRegimeMismatchError struct {
	APIError
	Message string
	ItemID  string
	Index   int
}

ItemTaxRegimeMismatchError is the API's 422 ITEM_TAX_REGIME_MISMATCH: the item's CST/CSOSN does not fit the company's tax regime (a CSOSN is for Simples Nacional, a CST for the rest), or is not allowed on an export CFOP. Send the line's own Tax, or fix the item. Index is the line. errors.As still finds the *APIError inside.

func (*ItemTaxRegimeMismatchError) Unwrap added in v0.21.0

func (e *ItemTaxRegimeMismatchError) Unwrap() error

type ItemTaxRequiredError added in v0.21.0

type ItemTaxRequiredError struct {
	APIError
	Message string
	ItemID  string
	Index   int
}

ItemTaxRequiredError is the API's 422 ITEM_TAX_REQUIRED: the item's tax situation needs an ICMS base and rate the catalog does not keep, so the line at Index must send its own tax. errors.As still finds the *APIError inside.

func (*ItemTaxRequiredError) Unwrap added in v0.21.0

func (e *ItemTaxRequiredError) Unwrap() error

type Items added in v0.21.0

type Items struct {
	// contains filtered or unexported fields
}

Items reads and edits the company's catalog of products and services, and Product.ItemID issues a line from one. The catalog is one table told apart by Kind: "product" for goods (NF-e) and "service" for services (NFS-e).

It is company data, like everything on Invoice: WithCompany and ForCompany pick the company. Reading needs invoice:read; creating, editing and deactivating need invoice:issue. The rules on an item's fields are the API's: a refusal comes back as an *APIError 422.

func NewItems added in v0.21.0

func NewItems(opts ...Option) *Items

func (*Items) Create added in v0.21.0

func (i *Items) Create(fields ItemFields) (map[string]any, error)

Create is Upsert without the created flag.

func (*Items) Deactivate added in v0.21.0

func (i *Items) Deactivate(itemID string) error

Deactivate deactivates an item. It is kept, still holds its code, is left out of List by default and refused on issue until Reactivate brings it back. The API answers 204 with no body.

func (*Items) ForCompany added in v0.21.0

func (i *Items) ForCompany(company string) *Items

ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.

func (*Items) Get added in v0.21.0

func (i *Items) Get(itemID string) (map[string]any, error)

Get returns one item, deactivated or not. Another company's item is a 404 (*ItemNotFoundError).

func (*Items) List added in v0.21.0

func (i *Items) List(query ItemQuery) (map[string]any, error)

List returns a page of the company's items.

func (*Items) Reactivate added in v0.21.0

func (i *Items) Reactivate(itemID string) (map[string]any, error)

Reactivate brings a deactivated item back, and returns it.

func (*Items) Update added in v0.21.0

func (i *Items) Update(itemID string, changes ItemChanges) (map[string]any, error)

Update changes only the fields set in changes. The API checks the item as a whole; taking a code another item holds is a *ItemAlreadyExistsError.

func (*Items) Upsert added in v0.21.0

func (i *Items) Upsert(fields ItemFields) (item map[string]any, created bool, err error)

Upsert saves an item by its ExternalReference, or by its Code when no reference is sent: the company's matching item is updated with the fields sent (it keeps its source and its active flag), otherwise a new one is created. created is true for the API's 201 and false for its 200, so sending the same fields twice never makes two items. A Code the company holds on another item is a *ItemAlreadyExistsError.

type Kind added in v0.10.0

type Kind struct {
	Name    string
	Country string
	// contains filtered or unexported fields
}

Kind is one classification, bound to a country.

func (*Kind) Get added in v0.10.0

func (k *Kind) Get(code string, country ...string) (map[string]any, error)

Get returns one code. A code that does not exist is a 404, which arrives as *APIError — there is no separate not-found type.

func (*Kind) Search added in v0.10.0

func (k *Kind) Search(query SearchQuery) (map[string]any, error)

Search returns a page of this classification, filtered by the query's term when it has one. An empty term is no term: the route rejects search="" with a 422, and sending it would invent a failure the caller cannot read.

type Manifestation added in v0.3.1

type Manifestation string

Manifestation is the recipient's answer to a document issued against it.

const (
	Confirmacao          Manifestation = "210200"
	Ciencia              Manifestation = "210210"
	Desconhecimento      Manifestation = "210220"
	OperacaoNaoRealizada Manifestation = "210240"
)

type NBSSuggestion added in v0.27.0

type NBSSuggestion struct {
	NBS                  string  `json:"nbs"`
	Description          *string `json:"description"`
	OperationIndicator   *string `json:"operation_indicator"`
	IbsCbsClassification *string `json:"ibs_cbs_classification"`
	ClassificationName   *string `json:"classification_name"`
}

NBSSuggestion is one row of NFS-e Anexo VIII for a service code: an NBS with the cIndOp and cClassTrib the annex pairs with it. Description, OperationIndicator, IbsCbsClassification and ClassificationName are nil when the annex lists none.

type NBSSuggestions added in v0.27.0

type NBSSuggestions struct {
	ServiceCode string          `json:"service_code"`
	Suggestions []NBSSuggestion `json:"suggestions"`
	Source      ReferenceSource `json:"source"`
}

NBSSuggestions is what the NBS route answers: ServiceCode is the six-digit cTribNac and Suggestions every NBS, cIndOp and cClassTrib combination the annex lists for its subitem, empty when it lists none.

type Option

type Option func(*transport)

func WithAPIKey

func WithAPIKey(apiKey string) Option

func WithBaseURL

func WithBaseURL(baseURL string) Option

func WithCompany added in v0.15.0

func WithCompany(company string) Option

WithCompany names the company every request acts on, by its id (UUID) or its CNPJ, punctuated or not. It is sent as the X-Stackin-Company header. Only a credential covering several companies needs it; an API key is one company already. Left empty, nothing is sent.

func WithCountry added in v0.10.0

func WithCountry(country string) Option

WithCountry sets the ISO 3166-1 alpha-2 code FiscalReference and Taxpayer look codes up under. Defaults to BR.

func WithEnvironment

func WithEnvironment(env Environment) Option

func WithTimeout

func WithTimeout(timeout time.Duration) Option

type PageQuery added in v0.19.0

type PageQuery struct {
	Limit   int
	Offset  int
	SortBy  string
	OrderBy string
}

PageQuery is the API's pagination for a listing. Every field is optional; a zero value is left out and the API's own default applies.

type Payment added in v0.25.0

type Payment struct {
	Method      string
	Amount      float64
	Description string
	Card        *PaymentCard
}

Payment is one detPag. Method is the national tPag code, such as "01" or "17"; Amount is in BRL and is always sent, so a 0 (method "90") goes out. Description is required for method "99" and sent only then.

func (Payment) MarshalJSON added in v0.25.0

func (p Payment) MarshalJSON() ([]byte, error)

func (*Payment) UnmarshalJSON added in v0.25.0

func (p *Payment) UnmarshalJSON(data []byte) error

type PaymentCard added in v0.25.0

type PaymentCard struct {
	Integration   string `json:"integration"`
	TaxID         string `json:"tax_id,omitempty"`
	Brand         string `json:"brand,omitempty"`
	Authorization string `json:"authorization,omitempty"`
}

PaymentCard is the electronic payment's processor and authorization (card). Integration is 1 (integrated with the seller's system) or 2.

type PaymentRequiredError added in v0.18.0

type PaymentRequiredError struct {
	APIError
}

PaymentRequiredError is any 402: the plan's allowance is spent and neither an overage price nor the account credit covers the call. Detail says why. errors.As still finds the *APIError inside.

func (*PaymentRequiredError) Unwrap added in v0.18.0

func (e *PaymentRequiredError) Unwrap() error

type Purpose added in v0.14.0

type Purpose string

Purpose is why an NF-e is issued (finNFe). The API defaults to PurposeNormal when it is left out.

const (
	PurposeNormal        Purpose = "normal"
	PurposeComplementary Purpose = "complementary"
	PurposeAdjustment    Purpose = "adjustment"
	PurposeReturn        Purpose = "return"
)

type RateLimitedError added in v0.18.0

type RateLimitedError struct {
	APIError
	Code       string
	RetryAfter int
	RetryAt    *time.Time
}

RateLimitedError is any 429. RetryAfter is the Retry-After header in seconds; without the header it is derived from RetryAt, and zero when neither is there. RetryAt and Code come from the body when it carries them: DISTRIBUTION_COOLDOWN is the SEFAZ's one-hour wait after a received-invoices read that found nothing more. errors.As still finds the *APIError inside.

func (*RateLimitedError) Unwrap added in v0.18.0

func (e *RateLimitedError) Unwrap() error

type ReferenceSource added in v0.27.0

type ReferenceSource struct {
	Path string  `json:"path"`
	Date *string `json:"date"`
}

ReferenceSource is the official file the reference rows were loaded from.

type RequestOption added in v0.2.0

type RequestOption func(*requestConfig)

RequestOption tunes a single call, as opposed to Option, which tunes the client.

func WithIdempotencyKey added in v0.2.0

func WithIdempotencyKey(key string) RequestOption

WithIdempotencyKey attaches an Idempotency-Key to one call. See IssueRequest.IdempotencyKey for what the API does with it.

type SaleTerms added in v0.25.0

type SaleTerms struct {
	Presence     *string       `json:"presence"`
	Intermediary *Intermediary `json:"intermediary"`
	Transport    *Transport    `json:"transport"`
	Payments     []Payment     `json:"payments"`
	Change       *float64      `json:"-"`
}

SaleTerms are the NF-e sale terms an invoice was issued with, as the invoice detail returns them. Every field is nil or empty when the issuance did not send it. Change is in BRL.

func SaleTermsOf added in v0.25.0

func SaleTermsOf(detail map[string]any) (*SaleTerms, error)

SaleTermsOf reads the stored sale terms out of an invoice detail, as returned by the API: presence, intermediary, transport, payments and change at the top level of the object (or of its "result"). Fields the detail does not carry stay nil.

func (*SaleTerms) UnmarshalJSON added in v0.25.0

func (s *SaleTerms) UnmarshalJSON(data []byte) error

type SearchQuery added in v0.10.0

type SearchQuery struct {
	Term    string
	Country string
	Limit   int
	Offset  int
}

SearchQuery narrows a classification listing.

There is no SortBy or OrderBy: the route accepts both and discards them, so rows always come back ordered by kind then code. History on Invoice does honour them, which is why the difference is spelled out here rather than left to be discovered.

type SyncResult added in v0.18.0

type SyncResult struct {
	Stored     int
	Pages      int
	LastNSU    string
	MaxNSU     *string
	NextSyncAt *time.Time
}

SyncResult is what one read of the SEFAZ distribution brought back. NextSyncAt is set when the SEFAZ had nothing more to deliver: no read is allowed before it.

func (*SyncResult) UnmarshalJSON added in v0.18.0

func (s *SyncResult) UnmarshalJSON(raw []byte) error

type Taxpayer added in v0.10.0

type Taxpayer struct {
	// contains filtered or unexported fields
}

Taxpayer reads the taxpayer registry, one tax id at a time.

One method, and it stays one method. The registry names and addresses real people and companies: an exact lookup answers the question an issuer has — who is this CNPJ I am about to invoice — and answers nothing else. A prefix or wildcard search over the same table is a bulk export wearing the costume of a query. Do not add one, not for parity with FiscalReference, not "just by name", not "just within one state".

func NewTaxpayer added in v0.10.0

func NewTaxpayer(opts ...Option) *Taxpayer

func (*Taxpayer) Get added in v0.10.0

func (t *Taxpayer) Get(taxID string, country ...string) (map[string]any, error)

Get returns one taxpayer, by exact tax id.

A 404 arrives as *APIError and does not mean the taxpayer does not exist: the registry reloads monthly, so a company registered in the last few weeks is simply not in it yet. Never build a validation rule on top of it.

type Transport added in v0.25.0

type Transport struct {
	FreightMode string
	Volumes     []TransportVolume
}

Transport is the freight mode (modFrete) and the volumes carried. Volumes left nil lets the API derive one from the lines' weights; an empty non-nil slice is sent as [] and writes none.

func (Transport) MarshalJSON added in v0.25.0

func (t Transport) MarshalJSON() ([]byte, error)

func (*Transport) UnmarshalJSON added in v0.25.0

func (t *Transport) UnmarshalJSON(data []byte) error

type TransportVolume added in v0.25.0

type TransportVolume struct {
	Quantity    *int     `json:"quantity,omitempty"`
	Species     string   `json:"species,omitempty"`
	Brand       string   `json:"brand,omitempty"`
	Numbering   string   `json:"numbering,omitempty"`
	NetWeight   *float64 `json:"net_weight,omitempty"`
	GrossWeight *float64 `json:"gross_weight,omitempty"`
}

TransportVolume is one transp/vol group. Every field is optional and sent only when set; the pointers let a real 0 go out. Weights are in kg with at most 3 decimal places.

func (*TransportVolume) UnmarshalJSON added in v0.25.0

func (v *TransportVolume) UnmarshalJSON(data []byte) error

type Usage added in v0.18.0

type Usage struct {
	PlanName           string
	PlanSlug           string
	IncludedInvoices   int
	UsedInvoices       int
	OveragePriceCents  *int
	IncludedReceived   int
	UsedReceived       int
	ReceivedPriceCents int
	ReceivedFree       bool
	CurrentPeriodStart time.Time
	CurrentPeriodEnd   *time.Time
	CreditBalance      int
	CompaniesOnAccount int
}

Usage is the plan behind the company and how much of it the current period has used. The numbers are the paying account's, shared by every company it holds; CompaniesOnAccount says whether that sharing is real. Prices and CreditBalance are in cents.

Received invoices: the first IncludedReceived a month come with every plan, then each costs ReceivedPriceCents from the account credit. ReceivedFree is true for the accounts exempt from that charge.

func (*Usage) UnmarshalJSON added in v0.18.0

func (u *Usage) UnmarshalJSON(raw []byte) error

type ValidationFinding added in v0.24.0

type ValidationFinding struct {
	Code           string `json:"code"`
	Field          string `json:"field"`
	Message        string `json:"message"`
	SefazRejection string `json:"sefaz_rejection"`
	Expected       string `json:"expected"`
	Received       string `json:"received"`
	FixURL         string `json:"fix_url"`
}

ValidationFinding is one refusal or blocker found by Validate. Field is the request path of the offending value, empty for a blocker of the company itself.

type ValidationResult added in v0.24.0

type ValidationResult struct {
	Valid    bool                `json:"valid"`
	Errors   []ValidationFinding `json:"errors"`
	Warnings []ValidationWarning `json:"warnings"`
}

ValidationResult is what Validate answers. Valid is false when Errors is not empty.

type ValidationWarning added in v0.24.0

type ValidationWarning struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Field   string `json:"field"`
}

ValidationWarning is a default the issuance would declare for the company.

type WebhookEndpoint added in v0.19.0

type WebhookEndpoint struct {
	// URL must be https://, at most 500 characters. The API also refuses
	// one that points at a private network.
	URL string
	// Secret signs every delivery, 16 to 255 characters. It is never
	// returned again, so keep it.
	Secret string
	// Events narrows what is sent, from WebhookEvents. Left nil, the
	// endpoint receives every event.
	Events []string
}

WebhookEndpoint is an endpoint as Create takes it.

type Webhooks added in v0.19.0

type Webhooks struct {
	// contains filtered or unexported fields
}

Webhooks manages where the company's events are delivered (/webhooks).

It is company data: WithCompany and ForCompany pick the company. An endpoint receives the events of the credential's own environment only. On an OAuth credential every call needs webhook:manage; an API key has it.

func NewWebhooks added in v0.19.0

func NewWebhooks(opts ...Option) *Webhooks

func (*Webhooks) Create added in v0.19.0

func (w *Webhooks) Create(endpoint WebhookEndpoint) (map[string]any, error)

Create registers an HTTPS endpoint for this company's events.

func (*Webhooks) Delete added in v0.19.0

func (w *Webhooks) Delete(endpointID string) error

Delete stops delivery to one endpoint, keeping what was already sent. An id this company does not have is an *APIError 404.

func (*Webhooks) Deliveries added in v0.19.0

func (w *Webhooks) Deliveries(query PageQuery) (map[string]any, error)

Deliveries lists every delivery attempt in the credential's environment, a page. Each row has the event, its status, attempts, the endpoint's response_status, last_error and when it was delivered or will be tried again.

func (*Webhooks) ForCompany added in v0.19.0

func (w *Webhooks) ForCompany(company string) *Webhooks

ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.

func (*Webhooks) List added in v0.19.0

func (w *Webhooks) List() ([]map[string]any, error)

List returns this company's endpoints in the credential's environment. A plain list, not a page. Secrets are never returned.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL