stackin

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 10 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(), 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.

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", Amount: 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",
			CityCode:     "3304557",
		},
	})
	_ = status
	fmt.Println(invoice, err)
}

RecipientAddress is an Address — the buyer's address, required for NFE and ignored for NFSE. Every field is required, CityCode (the 7-digit IBGE municipality code) included: it becomes enderDest on the wire and the SEFAZ rejects a partial one. State is also what resolves idDest — a buyer in another state is emitted as an interstate operation automatically. A missing or incomplete address returns an *InvoiceError locally, before the request goes out.

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", Amount: 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, checked locally before the call.

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, and asking for one returns a 409.

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.

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.
  • *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, or a missing/incomplete RecipientAddress on NFE.

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.

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 DefaultBaseURL = "https://sdk.stackin.io"

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Detail     string
}

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"`
}

type ConnectionFailedError

type ConnectionFailedError struct {
	Message string
}

func (*ConnectionFailedError) Error

func (e *ConnectionFailedError) Error() string

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 InvalidationRequest added in v0.2.0

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

type Invoice

type Invoice struct {
	BaseURL string
	APIKey  string
	Timeout time.Duration
	// 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) (map[string]any, error)

func (*Invoice) Consult

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

func (*Invoice) Correct added in v0.2.0

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

func (*Invoice) Invalidate added in v0.2.0

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

func (*Invoice) Issue

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

func (*Invoice) Pdf added in v0.3.0

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

Pdf returns the authorizer's own rendering of an authorized document, as raw bytes — the only method that does not return a parsed object. The XML is the legally valid document; this is a convenience, and the authorizer's endpoint for it is unstable, so an APIError with status 502 means the authorizer is unavailable, not that the invoice is wrong. NFS-e only.

func (*Invoice) Reissue added in v0.2.0

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

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

	// 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
}

type Option

type Option func(*Invoice)

func WithAPIKey

func WithAPIKey(apiKey string) Option

func WithBaseURL

func WithBaseURL(baseURL string) Option

func WithEnvironment

func WithEnvironment(env Environment) Option

func WithTimeout

func WithTimeout(timeout time.Duration) Option

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.

Directories

Path Synopsis
examples
cancel_invoice command
consult_invoice command
nfe/basic command
Only what NFE requires: description, amount, ncm, cfop.
Only what NFE requires: description, amount, ncm, cfop.
nfe/full command
Every field on Product filled in at once.
Every field on Product filled in at once.
nfe/icms_isento command
CSOSN 400 — MEI/Simples equivalent of the exempt ICMS40.
CSOSN 400 — MEI/Simples equivalent of the exempt ICMS40.
nfe/imported command
An imported item, tracked by its Ficha de Conteudo de Importacao.
An imported item, tracked by its Ficha de Conteudo de Importacao.
nfe/interstate_with_icms_dest command
Interstate sale, partilha do ICMS — CSOSN 900 (MEI/Simples).
Interstate sale, partilha do ICMS — CSOSN 900 (MEI/Simples).
nfe/scale_manufactured command
Relevant-scale manufacturing indicator and its manufacturer CNPJ.
Relevant-scale manufacturing indicator and its manufacturer CNPJ.
nfe/taxed_icms command
CSOSN 102 (no credit) — MEI/Simples equivalent of ICMS00.
CSOSN 102 (no credit) — MEI/Simples equivalent of ICMS00.
nfe/used_asset command
A used movable asset being resold.
A used movable asset being resold.
nfe/with_barcode command
A real GTIN/EAN instead of the "SEM GTIN" default.
A real GTIN/EAN instead of the "SEM GTIN" default.
nfe/with_extra_charges command
Freight, insurance, discount, and other expenses on the item.
Freight, insurance, discount, and other expenses on the item.
nfe/with_purchase_order command
Linked to the buyer's purchase order and item number.
Linked to the buyer's purchase order and item number.
nfe/with_quantity command
Multiple units at a per-unit price.
Multiple units at a per-unit price.
nfe/with_tax_benefit command
ICMS-ST item with a state tax benefit and presumed credit.
ICMS-ST item with a state tax benefit and presumed credit.
nfse/basic command
Only description/amount — service_code falls back to the company's fiscal profile.
Only description/amount — service_code falls back to the company's fiscal profile.
nfse/full command
Every optional field set at once.
Every optional field set at once.
nfse/with_discount command
An unconditional discount applied to the service value.
An unconditional discount applied to the service value.
nfse/with_observations command
A free-text note attached to the service.
A free-text note attached to the service.
nfse/with_service_code command
Explicit service_code, overriding the company default (1.06).
Explicit service_code, overriding the company default (1.06).
nfse/with_tax_retained command
ISSQN retained by the tomador — rejected (E0583) if the issuer is MEI.
ISSQN retained by the tomador — rejected (E0583) if the issuer is MEI.
reissue_invoice command

Jump to

Keyboard shortcuts

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