stackin-io / stackin-php-sdk
Official PHP SDK for the stackin fiscal document API — issue, consult, cancel NF-e and NFS-e.
Requires
- php: >=8.1
- guzzlehttp/guzzle: ^7.8
Requires (Dev)
- phpstan/phpstan: ^1.11
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^3.9
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Integrate once. Issue everywhere.
stackin
Official PHP SDK for fiscal document issuance — 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 class, Invoice — issue()/consult()/cancel()/reissue()/correct()/invalidate()/pdf()/received()/manifest(), 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.
// More than one unit — the note's line is 2 x 120.00 = 240.00 new Product(description: 'Teclado', quantity: 2.0, unitPrice: 120.00, unit: 'UN'); // Legacy: amount alone still means the line's gross total new Product(description: 'Servico', amount: 150.00, quantity: 3.0);
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.0, amount: 150.00
After: quantity: 3.0, unitPrice: 50.00
Nothing has to migrate. amount keeps the meaning it always had and is
not deprecated in this release.
Install
composer require stackin-io/stackin-php-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. Defaults to https://sdk.stackin.io.
use Stackin\Address; use Stackin\Br\Product; use Stackin\DocumentType; use Stackin\Invoice; $invoice = new Invoice(apiKey: 'COMPANY_API_KEY'); $result = $invoice->issue( DocumentType::NFE, 'Buyer Company Ltd', '11222333000181', [ new Product( description: 'Rosa Holambra Vermelha', unitPrice: 112.44, ncm: '06031100', cfop: '5102', ), ], new Address( street: 'Rua das Palmeiras', number: '100', neighborhood: 'Centro', city: 'Florianopolis', state: 'SC', zipCode: '88010000', cityCode: '4205407', ), ); $status = $invoice->consult('ACCESS_KEY...', DocumentType::NFSE); $invoice->cancel('ACCESS_KEY...', DocumentType::NFSE, 'Typo'); // The authorizer's PDF, as raw bytes. NFS-e only; the XML stays the // legally valid document, and a 502 here means the authorizer is down. file_put_contents( 'nota.pdf', $invoice->pdf('ACCESS_KEY...', DocumentType::NFSE), );
The recipient Address passed to issue() is 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 throws 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 = bin2hex(random_bytes(16)); $result = $invoice->issue( DocumentType::NFSE, 'Maria Silva', '12345678909', [new Product(description: 'Consultoria', unitPrice: 1500.00)], idempotencyKey: $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 = $invoice->correct( '35240912345678000199550010000000011000000017', DocumentType::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 = $invoice->invalidate( '1', 10, 12, '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.
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. The authorizer caps how many times a CNPJ may ask for its distribution per day, so collecting runs on a schedule on the API side and a page refresh cannot spend that allowance.
use Stackin\\Manifestation; $page = $client->received(limit: 20); echo $page['total']; $client->manifest($accessKey, Manifestation::CIENCIA); $client->manifest( $accessKey, Manifestation::OPERACAO_NAO_REALIZADA, '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.
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.
use Stackin\FiscalReference; use Stackin\Taxpayer; $ref = new FiscalReference(apiKey: '...'); // country 'BR' by default $ref->ncm->get('84716052'); // one code $ref->ncm->search('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('teclado'); // every kind at once (new Taxpayer(apiKey: '...'))->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.
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, null 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()andpdf()draw from. Onesearch()page beats Nget()calls. - Ordering is fixed (kind, then code, ascending). Unlike
history(),search()takes no$sortBy/$orderBy. - A 404 from
Taxpayerdoes 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.
Errors
Stackin\Errors\ApiError— the API responded with a non-2xx status (statusCode/detailproperties) — a 401 here meansapi_keyis missing, wrong, or was rotated.Stackin\Errors\ConnectionFailedError— the API didn't respond (network/DNS/timeout).Stackin\Errors\InvoiceError—issue()'s items is empty, missingncm/cfopon an item for NFE, or a missing/incomplete recipientAddresson 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 scripts in examples/nfe/ and examples/nfse/ — one script per field variant, from the bare minimum to every field filled. examples/consult_invoice.php, examples/cancel_invoice.php, and examples/reissue_invoice.php cover the operations that act on an already-issued document. examples/lookup_fiscal_reference.php and examples/lookup_taxpayer.php cover the two read-only clients.
Commit convention lives in CONTRIBUTING.md, not here.