TF Fiscal

Tax Calculation

POST/api/tax/calculate

Calculate taxes

Takes the facts of the transaction (nature, purpose, recipient, NCM, amounts and date) and returns, per line item, the CFOP, the CST / CSOSN and the bases, rates and amounts of ICMS, ICMS-ST, DIFAL / FCP, IPI, PIS / COFINS and IBS / CBS, using the NF-e XML tag names. The ERP does not send rates or a tax scenario: when data is missing or a rule is ambiguous, the item comes back with a pending issue and no rate is assumed.

The call only calculates: nothing is stored and SEFAZ is not queried; issuing stays at /api/invoice/create. The issuer (CNPJ, state and tax regime) comes from the company registered for the token, and an emitente object sent in the body is ignored. Parameters are sent in the body as JSON.

Required headers

tokenstringstringToken of the issuing company; its CNPJ, state and tax regime are read from its registration. Always send it in this header: it is the one used in the signature
signstringstringMD5 signature: md5(token + "/api/tax/calculate" + body without line breaks + timestamp), in lowercase hexadecimal (32 characters)
timestampstringstringUnix timestamp in seconds, accepted with a tolerance of 5 minutes (before or after the server clock)

Body

data_operacaostringstringTransaction date, YYYY-MM-DD.
natureza*stringstringvenda (sale), devolucao (return), transferencia (transfer), bonificacao (bonus goods), amostra_gratis (free sample) or baixa_estoque (stock write-off)
finalidadestringstringWhat the recipient will do with the goods: revenda (resale), industrializacao (manufacturing), uso_consumo (use or consumption) or ativo_imobilizado (fixed assets).
regime_federalstringstringreal or presumido.
destinatario*objectobjectRecipient of the transaction
itens*arrayarrayLine items; the response follows the same order
nota_originalobjectobjectPurchase invoice being returned.
detalhadobooleanbooleantrue returns the full response, with descriptions, the legal basis of each rule, warnings and the versions of the tables used.
equiparado_ipibooleanbooleantrue when the issuer is treated as a manufacturer for IPI for a reason other than own production or direct import (for example, an equated wholesaler).
transferencia_tributadabooleanbooleantrue taxes ICMS on transfers between establishments (LC 87/1996, art. 12, § 5).
amostra_isencao_requisitosbooleanbooleantrue when the free sample meets the ICMS exemption requirements.
desconta_icms_pis_cofinsbooleanbooleanDeducts ICMS (and DIFAL, in sales to non-taxpayers) from the PIS / COFINS base (Supreme Court Tema 69; Superior Court of Justice Tema 1372).
desconta_icms_pis_cofins_ibs_cbsbooleanbooleanIBS / CBS base by the official RFB formula: deducts ICMS, FCP, DIFAL and destination-state FCP and, in 2026, PIS and COFINS.
difal_desconta_icms_interbooleanbooleanDIFAL base: removes the interstate ICMS before rebuilding the base.
difal_base_por_dentrobooleanbooleanTax-inclusive DIFAL base (the "double base" of state law).

 * Required field. Each item needs valor_total or quantidade + valor_unitario. Numbers use a decimal point and no thousands separator: text that is not a number (for example "1.234,56") returns the pending item valor_invalido, and a discount larger than the item value returns desconto_maior_que_valor.

Filling rules

finalidade is required:

  • on sales, bonus goods or samples to a contribuinte or isento recipient, because it drives ST, final consumer and DIFAL. For non-taxpayers the transaction is always to a final consumer;
  • on every return, because it drives the CFOP. In that case the purpose of the original purchase applies, sent in nota_original.finalidade_compra.

Without indicador_ie, the indicator is inferred as follows:

  • numeric IE: taxpayer;
  • IE ISENTO: exempt;
  • CPF only: non-taxpayer;
  • CNPJ without IE: pending issue. The registration status can be checked with /api/consulta/destinatario.

IPI follows the item, and the same rule decides whether the item is from a manufacturer or importer for single-phase PIS / COFINS:

  • own production: levied, per TIPI;
  • origin 1 or 6 (direct import): levied, because the importer is treated as a manufacturer;
  • domestic goods bought from third parties: not levied (CST 53), unless equiparado_ipi is sent.

Response

The default response carries only what goes into the NF-e XML, using the tag names. A tax group is omitted when the tax does not apply, for example PIS and COFINS from 2027. The example below is the actual response to this page's payload example: NCM 8471.30.12 is subject to ICMS-ST on sales for resale in RJ (CEST 21.028.00), hence CFOP 6403 and CST 10.

{
  "success": true,
  "message": "成功",
  "data": {
    "status": "determinado",
    "pendencias": [],
    "itens": [
      {
        "nItem": 1,
        "status": "determinado",
        "CFOP": "6403",
        "NCM": "84713012",
        "CEST": "21.028.00",
        "ICMS": { "orig": 0, "CST": "10", "modBC": 3, "vBC": 1020.0, "pICMS": 12.0, "vICMS": 122.4,
                  "modBCST": 4, "pMVAST": 42.55, "vBCST": 1454.01, "pICMSST": 20.0, "vICMSST": 168.4,
                  "vBCFCPST": 1454.01, "pFCPST": 2.0, "vFCPST": 29.08 },
        "IPI": { "CST": "53" },
        "PIS": { "CST": "01", "vBC": 1020.0, "pPIS": 1.65, "vPIS": 16.83 },
        "COFINS": { "CST": "01", "vBC": 1020.0, "pCOFINS": 7.6, "vCOFINS": 77.52 },
        "IBSCBS": {
          "CST": "000",
          "cClassTrib": "000001",
          "gIBSCBS": {
            "vBC": 1020.0,
            "gIBSUF": { "pIBSUF": 0.1, "vIBSUF": 1.02 },
            "gIBSMun": { "pIBSMun": 0.0, "vIBSMun": 0.0 },
            "vIBS": 1.02,
            "gCBS": { "pCBS": 0.9, "vCBS": 9.18 }
          }
        },
        "pendencias": []
      }
    ],
    "total": {
      "ICMSTot": { "vBC": 1020.0, "vICMS": 122.4, "vFCP": 0.0, "vICMSUFDest": 0.0, "vFCPUFDest": 0.0,
                   "vBCST": 1454.01, "vST": 168.4, "vFCPST": 29.08, "vIPI": 0.0, "vPIS": 16.83, "vCOFINS": 77.52 },
      "IBSCBSTot": { "vBCIBSCBS": 1020.0, "vIBS": 1.02, "vCBS": 9.18 }
    }
  }
}

Response fields

statusstringstringdeterminado (determined), parcial (partial) or pendente (pending); the worst status among the items
pendenciasarrayarrayPending issues of the transaction: codigo (stable, for the integrator to handle) and mensagem (for display). With a transaction-level pending issue, itens comes back empty and there is no total; an item's pending issue is in itens[].pendencias
itensarrayarrayOne element per item sent, in the same order
itens[].IPI/PIS/COFINSobjectobjectCST and, when tax is due, vBC, rate (pIPI, pPIS, pCOFINS) and amount (vIPI, vPIS, vCOFINS)
totalobjectobjectICMSTot and IBSCBSTot, using the NF-e total tag names

Status

  • determinado: every tax and code was resolved from the tables;
  • parcial: everything was resolved, but a point needs review (missing MVA for the CEST, conditional state benefit, free sample that may be exempt, transfer without transferencia_tributada, valor_total different from quantity × unit price); the warnings are in itens[].avisos;
  • pendente: data or rules are missing for a safe determination. Do not issue the invoice with this result.

Transaction-level pending issue (for example, regime_federal_ausente or indicador_ie_ausente): it is in pendencias, and itens comes back empty, with no total:

{
  "success": true,
  "message": "成功",
  "data": {
    "status": "pendente",
    "pendencias": [
      { "codigo": "regime_federal_ausente", "mensagem": "..." }
    ],
    "itens": []
  }
}

Pending issue of an item (for example, ncm_inexistente): the overall status is pendente, the top-level pendencias comes back empty and the pending issue is on the item, which may come back without a CFOP and without the tax groups. Always check both places:

{
  "success": true,
  "message": "成功",
  "data": {
    "status": "pendente",
    "pendencias": [],
    "itens": [
      {
        "nItem": 1,
        "status": "pendente",
        "NCM": "99999999",
        "pendencias": [
          { "codigo": "ncm_inexistente", "mensagem": "NCM 99999999 não existe na tabela NCM vigente: confira a classificação fiscal do produto." }
        ]
      }
    ],
    "total": { ... }
  }
}

Detailed response

With "detalhado": true, the response carries the identified scenario, each tax with its rule, source and legal basis, the warnings of every item and the versions of the tables used (TIPI, ICMS matrix, cClassTrib etc.). Use it for audit and review; the default response is enough to fill the XML.

What is determined

TopicBehaviour
ICMSState internal rate, interstate matrix, 4% for imports and the state's unconditional benefits. Conditional benefits are only flagged. Simples Nacional: CSOSN 101 / 102; CSOSN 101 only with pCredSN, on sales to taxpayers for resale or manufacturing (MEI: never 101)
ICMS-STBy CEST and the MVA table. Only for taxpayers who will resell; not applied to final consumers, to manufacturing or to interstate transfers to non-retailers
DIFAL / FCPInterstate sales to non-taxpayers (EC 87/2015). For taxpayers buying for use or consumption, the recipient pays it (the warning difal_destinatario_contribuinte only appears in the detailed response). Simples Nacional issuer (CRT 1 and 4): no DIFAL on the invoice
IPIPer TIPI, on own production and direct imports. Resale of domestic goods: CST 53. Simples Nacional, when the item would bear IPI (own production or direct import): CST 99 (CRT 1, 2 and 4: IPI stays in the DAS even above the sub-limit); on resale, CST 53 as in the normal regime
PIS / COFINSBy regime (cumulative or non-cumulative) and the EFD-Contribuições tables: single-phase, zero rate etc. Transactions without revenue (return, transfer, bonus, sample): CST 49. Simples Nacional (CRT 1, 2 and 4): CST 99, no amounts
IBS / CBScClassTrib by the rules of LC 214/2025; without a rule, sales and returns use 000001 (full taxation). Transfers, bonus goods and free samples get CST 410 (non-levy: 410002, 410001 and 410003), with no base or amounts; a stock write-off without a rule is pending (natureza_sem_regra_ibs_cbs). Simples Nacional issuer: no IBSCBS group in 2026. In 2026 the test-year rate applies (CBS 0.9%, state IBS 0.1%, municipal IBS 0). From 2027 the rate comes from the ibs_cbs_aliquota table; with no rate registered for the year, the item is pending (ibs_cbs_aliquota_ausente). PIS / COFINS cease to exist in 2027
CFOPBy nature, destination, own or third-party production, ST and purpose; checked against the official CFOP table
TransferICMS not levied (ADC 49; LC 204/2023): CST 41 (Simples: CSOSN 400), and the item comes back parcial with the warning transferencia_nao_incidencia. transferencia_tributada taxes it
ReturnMirrors the CST and rates of the original invoice and determines the return CFOP. Original invoice with CSOSN, issuer under the regular regime: CST 90 with the original rate or the credit taken (p_cred_sn). CST 20 / 70 require p_red_bc; CST 10, 30 and 70 require the calculated ST (otherwise, pending item devolucao_st_sem_calculo); CST 30, 40, 41, 50 and 60 carry no own ICMS. IPI is only itemized when the issuer is an IPI taxpayer for the item; returned IPI (vIPIDevol) is not calculated. Under the Simples, a CSOSN that does not fit a return becomes 900

Stock write-off

  • Nature baixa_estoque: loss, theft, spoilage, deterioration or scrap without sale (selling scrap is venda). CFOP 5927, intrastate; the recipient is the issuer itself and can be omitted.
  • Output without debit: ICMS CST 90, IPI CST 99 when the item carries IPI (resale of domestic goods: CST 53), PIS/COFINS CST 49. The item returns the estorno group (icms, ipi, pis, cofins, forma_icms) with the credito_entrada credits to reverse (LC 87/1996, art. 21, IV; RIPI, art. 254, V; Law 10.833/2003, art. 3, §13 — PIS/COFINS only under lucro real).
  • The ICMS reversal method follows the state rule: destaque (ICMS itemized on the invoice) or apuracao (no itemization). Without a registered rule for the state, pending item estorno_baixa_sem_regra.
  • IBS/CBS: without a classification rule for the nature, the item is pending (natureza_sem_regra_ibs_cbs).

Limitations

  • exports (EX): the CFOP is returned with a pending issue; taxation is not determined;
  • services (ISS) are not determined;
  • IBS / CBS with special mechanics (fixed rate, deferral, suspension, single-phase, presumed credit) is returned as pending;
  • returned IPI (vIPIDevol, a return made by someone who is not an IPI taxpayer) is not calculated;
  • the recipient's registration status is not checked automatically.

Common errors

MessageCause
Missing sign headerHTTP 400, as plain text: the sign header was not sent
Erro de assinatura / 签名错误HTTP 401: the sign does not match. Compute it with the token from the header, the path /api/tax/calculate, the same body sent (without line breaks) and the timestamp, in lowercase hexadecimal
TimeStamp ausente nos Headers / Headers 中缺少 TimeStampHTTP 401: the timestamp header is missing
Formato do TimeStamp inválido / TimeStamp 格式错误HTTP 401: the timestamp is not a number
Diferença do timestamp muito grande / 时间戳误差太大HTTP 401: the timestamp differs from the server clock by more than 5 minutes (or was sent in milliseconds)
Informe o token / 请传入tokenThe token header was not sent
token inválido / token错误The token does not exist
Aplicação desativada / 应用已停用The token's application is disabled
Rate limit exceeded, please slow downThe token's limit of calls per second was exceeded: wait and retry
Empresa não cadastrada para este token / 该token未关联公司The token is not linked to a registered company. Use the issuing company's token
One or more validation errors occurred.HTTP 400, JSON with title and errors: the body is not a JSON object (for example, an array) or is malformed
Corpo da requisição inválido: envie um objeto JSON / 请求体无效,请传入 JSON 对象The body arrived but could not be read as a JSON object (rare; the common case is the previous row)
Falha na determinação tributária. Tente novamente mais tarde. / 税务判定失败,请稍后重试Internal calculation failure; the request can be retried later

Examples

# sign = md5(token + path + body + timestamp)
# Template generated from the endpoint path; replace the placeholders
curl -X POST "https://api.tffiscal.com/api/tax/calculate" \
  -H "Content-Type: application/json" \
  -H "token: $TOKEN" \
  -H "timestamp: $TIMESTAMP" \
  -H "sign: $SIGN" \
  -d @body.json