eFacture Connect API

Integrate Tunisian e-invoicing into your ERP in a few minutes. Send JSON, receive a signed TEIF v1.8.9 XML (XAdES) and a PDF with a QR code, ready to be submitted to Tunisie TradeNet.

Base URLAll requests use https://efacturetn.com/api/v1

First call in 30 seconds

Copy the command on the right into your terminal to test the API in sandbox mode. Replace ck_test_xxx with the test key of one of your clients, shown in the developer portal when the client is created (Accounts and clients). Your sk_dev_ developer key does not issue invoices.

You will get back a genuinely signed XML (sandbox environment) and a PDF, exactly as in live mode. No credit is consumed in test mode.

Authentication

The API uses API keys passed in the X-Api-Key header. Every request must include a valid key.

PrefixModeUsage
sk_dev_ Developer Your key, and the only one. It is used to manage your clients: create them, connect them, read their counters. It issues no invoice, and it carries no environment. Accounts opened before September 2026 keep their sk_test_ key, which remains valid.
ck_test_ Test Key of one of your clients. Real signature on the sandbox environment, test TTN submission, no credit consumed.
ck_live_ Live Key of the same client, in live mode. Real XAdES signature, actual TTN submission, 1 credit deducted per signature.
Never share your keyAPI keys give full access to your account. Store them as secrets (environment variables, secrets manager).

Accounts and clients

A developer account can manage several clients (one integration per end company). You create and configure your clients from your developer area, "My clients" section.

ConceptDescription
Keys per client Each client has its own pair of ck_test_ / ck_live_ keys (client key), separate from your sk_dev_ developer key, which is used for management. An issuing request is always attached to the client whose key you use. The developer key cannot issue invoices, whether or not you have attached clients: /einvoices/prepare, /einvoices/process and /einvoices/{id}/resubmit-ttn return 403 DEVELOPER_KEY_NOT_ALLOWED. Use the key of the client concerned. To issue on behalf of your own company, create a client for yourself (POST /api/v1/clients) and use its key: your tax ID (matricule fiscal) is accepted there even if it is also the one of your account.
Shared wallet Credits are purchased at the developer account level and shared among all your clients.
Cap per client You can set a credit cap per client. The client is blocked at its cap without affecting the others or the rest of the wallet. You track consumption per client.
Submission channel Each client submits to TTN by SOAP (synchronous) or SFTP (asynchronous), depending on the configuration of its TTN account. With SFTP, the invoice goes through the submitted_ttn status, and you read the validation with GET /einvoices/{id}.
Signing method Configured per client: server seal (automatic), USB token (local signature) or remote signature. No impact on the request format.
INSUFFICIENT_CREDITSThis error (402) is returned when the developer account wallet is empty OR when the credit cap of the client concerned has been reached.
The seller is your keyEach key belongs to a client whose tax ID was registered and validated in the full format required by TTN. The invoice is signed under that tax ID. seller.tax_id is therefore optional: if you omit it, we set the account's one. If you send it, we compare only the first 8 characters, those that identify the taxpayer. 1234567R and 1234567RAM000 are therefore equivalent, and the form you send does not matter: the full form of the account is what goes into the document. If the taxpayer is actually different, the request is rejected with SELLER_MISMATCH before any signature, so no credit is consumed.
Sending the same invoice again does not sign it twice If your connector did not receive our response in time and replays the call, you no longer pay twice. We compare the content of the invoice, not only its number, and we respond according to what that number already carries. The pdf_base64 you provide is not part of the comparison: a PDF regenerated on each send (its creation date changes) does not make the invoice a different invoice.
  • Same content, invoice already produced: we return the existing document, identical, with "replayed": true. No credit is consumed and nothing is resubmitted to TTN.
  • Different content on a number already accepted by TTN: rejected with INVOICE_NUMBER_ALREADY_ISSUED. A submitted number cannot carry two documents.
  • Number already used by the same issuer on another channel (the web platform, or another API key with the same tax ID): rejected with INVOICE_NUMBER_USED_BY_ISSUER, before any signature. TTN refuses that an issuer reuses a number that is in progress or accepted (business rule 8); a number whose document was rejected by TTN remains reusable.
  • Different content after a TTN rejection: the signature proceeds normally, and consumes a credit. The previous document is void, the number still belongs to you.
  • Same content, signature pending (DigiGo, USB token, E-Houwiya): we return the link already open, with "resumed": true and the same signing_url. Lost the link? Simply send the same invoice again to POST /einvoices/prepare, or read GET /einvoices/{signing_id}, which carries signing_url as long as the signature is pending. No second transaction is opened.
  • Different content while a signature is pending: rejected with INVOICE_IN_PROGRESS. error.details carries the signing_id, the signing_url of the open signature and can_prepare_again_at. That link signs the PREVIOUS version of the invoice, not the one you just sent: do not open it for the new version. Instead, tell the user that a signature of the previous version is open. Without a signature by then, the attempt is abandoned at that time (30 minutes after it was opened) and the number can be prepared again. To avoid waiting, cancel it: POST /einvoices/{signing_id}/cancel.
Two useful details. Transport fields (return_url, a correlation identifier) do not count in the comparison: changing them does not make your invoice a different document. The order of the lines does count, however, because it changes the submitted document. The sandbox follows exactly the same rule as live mode, and the two environments are separate: a test invoice never blocks a real number.

Test vs live

Moving a client to live mode requires no code change: in its ERP, simply replace its ck_test_xxx key with its ck_live_xxx key. The prefix decides the environment; there is no setting to change anywhere else.

Your clients are independent of one another: one can be in live mode while another stays in test mode. There is no global switch, and your developer key never changes.

Sandbox = real test environmentNo simulation: in test mode, unless the test bench has been opened for this client, signing and submission actually run on the TEST environments of the signing service and of TTN. The signing_url from /einvoices/prepare points to the real signing page (sandbox), where the signer signs with a test certificate. The client's sandbox signing account must therefore be configured.
CriterionTestLive
SignatureReal XAdES (sandbox environment)Real XAdES (live)
TTN submissionTTN test platformTTN production platform
Credits consumedNone1 per signature
Seal/CertificateRequired (sandbox)Required (live)

Test bench: integrate before having TTN access

The test bench is not test mode.Test mode (ck_test_ key) really signs and submits, on the test environments of the signing service and of TTN: this requires an El Fatoora account and a certificate. The test bench, on the other hand, simulates signing and TTN. It serves a single purpose: letting you write and fine-tune your integration while your client is waiting for its TTN access and its certificate, instead of waiting with them. Nothing is signed, nothing is submitted, and no document produced has legal value.

Obtaining an El Fatoora account and a certificate often takes several weeks. Without the test bench, no call succeeds before they arrive: you can neither test your screens, nor read our responses, nor prepare error handling. With the test bench, you deliver an integration that is already well tested, and the first real call succeeds the first time.

CriterionTest benchTest mode (ck_test_)Live (ck_live_)
What it is forWriting and fine-tuning your integrationAcceptance testing with the real chain, without legal valueIssuing the client's invoices
El Fatoora account and certificateNot requiredRequired (test environment)Required (live)
SignatureSimulatedReal (test environment)Real
TTN submissionSimulated, nothing sentTTN test platformTTN production platform
TTN referenceSIMULATION-AAAAMMJJ-XXXXXXXXTest TTN referenceOfficial TTN reference
Credits consumedNoneNone1 per signature
Legal valueNoneNoneYes

Getting it

The test bench is opened on request, client by client: write to support and name the client concerned. It applies only to calls made with that client's ck_test_ key. A ck_live_ key is never simulated, whatever the setting: a live invoice cannot come out of a simulation.

What changes in your code: nothing

Same addresses, same request bodies, same response fields, same error codes: POST /einvoices/process, POST /einvoices/prepare, GET /einvoices/{signing_id}, POST /einvoices/{signing_id}/resubmit-ttn and POST /einvoices/{signing_id}/cancel. The day your client's access arrives, we close the test bench: its ck_test_ key goes back to the real test mode, then you switch to its ck_live_ key. Not a single line of your code changes.

To tell that a response comes from the test bench, two markers are added, which existing code ignores without breaking anything:

  • the "simulation": true field in data;
  • the X-eFactureTN-Simulation: 1 HTTP header.

Do not make any business logic depend on these markers: they are there to display a "simulation" banner in your interface, not to follow a different path. Otherwise, your production code would never have been exercised.

What you receive

  • The same TEIF as in live mode: it comes out of our real generator. An error in your request body is therefore discovered on the test bench, not in live mode.
  • xml_base64: the TEIF with an Id="SigFrs" signature block built like the real one, but whose value is the word SIMULATION. No cryptographic verification will accept it.
  • pdf_base64: the live-mode PDF, crossed out on every page with the notice « SIMULATION - SANS VALEUR LÉGALE » ("simulation, no legal value").
  • The seal arrives later, as with TTN. The submission only returns the reference. About 20 seconds later, GET /einvoices/{signing_id} returns ttn.reference_confirmee: true, ttn.qr_png_base64 (QR marked SIMULATION) and xml_validettn_base64 (the document with RefTtnVal then the SigTTN signature, in TTN's order). If your code reads the QR in the submission response, it will not find it on the test bench, and it would not find it in live mode either: this is intended.

The signing page (DigiGo, USB token, E-Houwiya)

POST /einvoices/prepare returns a signing_url to a simulated signing page. Redirect your user there as you will in live mode:

  • the PIN code is always 0000, and no SMS is sent;
  • any other code displays « Code PIN incorrect » (incorrect PIN code); after 3 wrong codes, the signature is blocked;
  • the « Refuser de signer » (refuse to sign) button simulates the signer's refusal: the status changes to rejected with the code SIGNATURE_REFUSED;
  • after signing or refusing, the user comes back to your return_url, with efacture_invoice and signing_id, as in live mode. Then check the status with GET /einvoices/{signing_id}: the redirect brings the user back, it announces nothing;
  • the link works only once and expires after 30 minutes.

Exercising errors

Errors in your request are rejected as in live mode, with the same codes: an invalid body returns 422 VALIDATION_FAILED, a malformed tax ID is rejected as TTN would reject it. Also use POST /einvoices/validate, which is the same on the test bench and in live mode.

Failures you cannot trigger yourself are requested with the X-Simulation-Scenario header, on /process, /prepare or /resubmit-ttn. It applies only to the call that carries it: a resubmission without the header follows the normal path, which lets you play out the "TTN was unavailable, I resubmit" case.

curl -X POST https://efacturetn.com/api/v1/einvoices/process \
  -H "X-Api-Key: ck_test_xxxxxxxxxxxx" \
  -H "X-Simulation-Scenario: ttn_indisponible" \
  -H "Content-Type: application/json" \
  -d @facture.json
ValueWhat happensResponse
ttn_indisponibleTTN does not respond. The document is not at fault.signed_ttn_rejected, next_action: resubmit: resubmit it with /resubmit-ttn.
ttn_compte_desactiveTTN rejects: the client's El Fatoora account is disabled (SERV01).signed_ttn_rejected, next_action: resubmit.
ttn_rejet_contrl05TTN rejects: the authentication tax ID is not the issuer's (CONTRL05). The document is at fault.signed_ttn_rejected, next_action: resign: correct it then issue it again.
ttn_rejet_contrl02TTN rejects: non-compliant signature transform block (CONTRL02).signed_ttn_rejected, next_action: resign.
signature_echoueeSigning fails: nothing is signed or submitted.503 SIGNING_FAILED on /process. On the signing page, the status changes to rejected.

An unknown value is rejected with 422 INVALID_SIMULATION_SCENARIO, with the list of accepted values: silently ignoring it would make you believe you are exercising a case while you follow the normal path. On a key that is not on the test bench, the header is ignored.

Limits

  • No legal value. Never pass a PDF or an XML from the test bench on to an end client: it is not an invoice.
  • 300 invoices per 24-hour period and per client; beyond that: 429 SANDBOX_DAILY_LIMIT.
  • Sending the same number twice creates two invoices on the test bench, whereas in live mode the second send returns the first one (see Sending the same invoice again). Exercise this case in test mode or in live mode.
  • Test bench documents can only be read with the client's ck_test_ key, or with your developer key.

Signing modes

Four signing modes depending on your use case: Entreprise ID (SEAL server seal), DigiGo (PIN + OTP), USB token (local signature) and E-Houwiya (Mobile ID). You can switch on the fly with the method field (seal, digigo, usb or mobileid) in the request.

Entreprise ID (SEAL)DigiGoUSB tokenE-Houwiya
Synchronous?Yes (~5s)No (manual signature)No (local signature)No (smartphone)
InteractionNoneUser PIN + OTPUSB token on the signer's computerApproval on the signer's smartphone
method valuesealdigigousbmobileid
Endpoint (POST)/einvoices/process/einvoices/prepare/einvoices/prepare/einvoices/prepare
Use caseBack-office ERP, high volumesPersonal signature, small volumesYou already hold your certification keyNo hardware: the smartphone is enough
ResultDirectly in the responsePolling GET /einvoices/{id}Polling GET /einvoices/{id}Polling GET /einvoices/{id}

E-Houwiya (Mobile ID): the signer approves from their smartphone with their mobile digital identity. The option is enabled at the signing service for each account: ask us for it before the first try, otherwise the signing page does not offer it.

Error handling

The API uses standard HTTP codes and returns a normalized JSON payload. All errors have the same shape:

CodeHTTPDescription
AUTH_INVALID_KEY401Invalid, inactive or unauthorized API key
VALIDATION_FAILED422Missing required fields: see error.details
INVALID_JSON400Request body is not valid JSON
INSUFFICIENT_CREDITS402Wallet exhausted or client cap reached (live only)
SEAL_NOT_CONFIGURED412SEAL electronic seal not provisioned, or seal passphrase missing, for this client in the key's environment (sandbox or live). Set seal_passphrase_test / seal_passphrase_prod through the API or the portal.
BATCH_VALIDATION_FAILED422At least one invoice in the batch is invalid: nothing was sent. error.details.errors lists each invoice to correct (index, invoice_number, code, message).
BATCH_TOO_LARGE422More than 20 invoices in POST /einvoices/prepare-batch: split the batch.
BATCH_METHOD_NOT_SUPPORTED422A batch is signed with digigo or usb. For the server seal, sign each invoice with /einvoices/process.
BATCH_NOT_AVAILABLE422Batch signing is not available for this client's signing service: prepare each invoice with /einvoices/prepare.
PLAN_REQUIRED403Batch signing is included from the Jugurtha plan upward for a key attached to a company.
METHOD_REQUIRES_PREPARE422method is digigo, usb or mobileid (or it is the client's mode with no seal ready) on POST /einvoices/process, which only signs with the server seal. Send the invoice to POST /einvoices/prepare: it returns a signing_url.
SIGNER_NOT_CONFIGURED412This client's signing account has not yet been created in the key's environment (DigiGo, USB token, E-Houwiya). Create it from the developer portal, or with PATCH /api/v1/clients/{id} with "provision": "sandbox" or "production"
SIGNER_EMAIL_MISSING412Remote signature (digigo, mobileid) without signer_email set on the client. Set it (PATCH /api/v1/clients/{id} or portal) to the address of the signer's certificate
DEVELOPER_KEY_NOT_ALLOWED403Developer key (sk_) used on /einvoices/prepare, /process, /resubmit-ttn or /cancel: issuing must go through the key of the client concerned (ck_), including for your own company
SELLER_MISMATCH422The seller.tax_id sent designates another taxpayer than the key holder. Rejected before signing, so no credit is consumed: an invoice is signed under the account's tax ID, and TTN would reject a document whose issuer does not match the signer. Issue with the key of the client concerned, or correct the tax ID
INVOICE_NUMBER_ALREADY_ISSUED409This invoice number already carries a document accepted by TTN, and the content you send is different. A number submitted to TTN cannot carry two documents: issue a credit note, or use a new number. If you only wanted to resubmit the existing document, call POST /einvoices/{id}/resubmit-ttn, which costs no credit
INVOICE_NUMBER_USED_BY_ISSUER409This number is already carried by the same issuer (same tax ID) on another channel: the web platform, or another API key. TTN would reject the document (business rule 8). Send this invoice under a new number. Nothing is signed, no credit is consumed.
ALREADY_SIGNED / CANCEL_NOT_SUPPORTED / SIGNATURE_ALREADY_CLOSED409Responses of POST /einvoices/{signing_id}/cancel: see Cancel a signature
CANCEL_UNCONFIRMED502Cancellation not confirmed by the signing service: nothing is cancelled or charged, try again
INVOICE_IN_PROGRESS409Another request is signing this number right now, or a manual signature is open and not yet completed. The signing_id concerned is returned in error.details: query it with GET /einvoices/{id} rather than retrying, otherwise you would pay twice for the same invoice. For a manual signature, error.details.signing_url gives the open link: it signs the version already prepared, not content modified since. Sending the same invoice again to /einvoices/prepare does not produce this error: the link is returned to you ("resumed": true)
PERMISSION_DENIED403The signing_id queried belongs to another account. Only the owning client and its parent developer can query it
WRONG_ENVIRONMENT403Each key reads only its own environment. The document belongs to you, but it was issued in the other environment: a ck_test_ key only queries test documents, a ck_live_ key only live documents. The message says which key opens it. Your sk_dev_ developer key, on the other hand, sees both
NOT_SIGNED409TTN resubmission requested on an invoice with no signed document: nothing to resubmit
AWAITING_TTN409TTN resubmission requested while TTN has already accepted the submission: the confirmation is polled every 2 to 3 minutes, resubmitting would create a duplicate
SIGNATURE_EXPIRED-Carried by a rejected invoice: the signature was not completed within 7 days. No credit charged. Stop polling this signing_id and prepare the invoice again.
ALREADY_VALIDATED409TTN resubmission requested on an invoice already confirmed by TTN: the document is final
DEPOSIT_DELEGATED409This client's submission is handled by the signing service: it cannot be replayed through the API
RESIGN_REQUIRED409TTN resubmission requested while TTN rejected the document itself (next_action = resign): correct the invoice and issue it again
DOCUMENTS_PURGED409TTN resubmission requested on an invoice whose documents were erased at the end of the 90-day retention period: issue it again
TTN_DEPOSIT_FAILED502TTN rejected or did not respond to the submission: TTN's message is in error.message, the signed document is kept and can be resubmitted with POST /einvoices/{id}/resubmit-ttn
TTN_DEPOSIT_FAILED-Present in ttn.error of the einvoice object: the invoice is signed but the TTN submission failed (e.g. invalid TTN credentials). Correct the client's TTN configuration then issue the invoice again
TTN_CREDENTIALS_MISSING412The chosen submission channel (soap or sftp) puts the submission on our side, but the client's TTN credentials are not set. Rejected before signing: without them, the invoice would be signed and billed, then go nowhere. Set ttn.sandbox.login / ttn.sandbox.password (or ttn.prod.*). If this client has no TTN account of its own, use the delegated channel: the signing service then submits under its own account. The delegated channel is never affected by this error.
SIGNING_TOKEN_EXPIRED412The signing service token has expired and its automatic renewal failed. Retrying will return the same error: re-provision the client's signing account (PATCH /api/v1/clients/{id} with "provision": "sandbox" or "production"), then issue again. In test mode, error.details.refresh_error gives the reason the renewal failed
INVALID_METHOD422Unknown signing method: method is seal, digigo, usb or mobileid
SIGNER_UNAVAILABLE400This mode is not offered by the client's signing service (for example E-Houwiya): choose another one or contact us
SIGNER_CIRCUIT_OPEN503Signing service repeatedly failing: circuit breaker triggered. Retry in 30-60 sec
RATE_LIMIT429Requests-per-minute limit exceeded
SIGNING_FAILED503Technical failure of the signing service (timeout, provider 5xx, etc.)
USER_CANCELLED-(DigiGo) The end client cancelled the signature. Present in error of the einvoice object with status rejected

Debugging in test mode (ck_test_ keys)

In test mode only, SIGNING_FAILED errors return an error.details.debug field containing the underlying technical message, and GET /einvoices/{id} includes a debug block (signature state, possible verification error) as long as the invoice is in progress. These fields are never present in live mode (live keys), to avoid any information leak.

Example of a SIGNING_FAILED response in test mode
{
  "success": false,
  "data": null,
  "error": {
    "code": "SIGNING_FAILED",
    "message": "La signature électronique a échoué. Veuillez réessayer.",
    "details": {
      "debug": "HTTP 401 Unauthorized"
    }
  }
}

SIGNING_FAILED error resolution table

If you get a SIGNING_FAILED, check the content of error.details.debug below to identify the cause:

Message in debugLikely causeRecommended action
HTTP 401
or Unauthorized
The signing token configured for your account is invalid or expired. Contact support to have your signing token renewed.
HTTP 402
or Payment Required
Signing account with no credit or expired plan. Contact support to reactivate the service.
HTTP 403
or Forbidden
The organization associated with your account is not authorized for this endpoint. Check the method sent. Contact support if the problem persists.
HTTP 500 or HTTP 502
Bad Gateway
The signing service is temporarily unavailable or overloaded. Retry in 1 to 2 minutes. Implement a retry with exponential backoff on the client side.
HTTP 504
Gateway Timeout
The signing service is taking too long to respond. Retry immediately. If it recurs, contact support.
Connection timed out
or Could not resolve host
Network issue on the server side (often a route blocked by an outbound firewall). Retry in a few minutes. If it persists, alert support.
Idle timeout reached
or timed out after
The signing service takes more than 30 seconds to respond (server load). Retry after 1 minute. The seal mode is faster than digigo for high volumes.
Email signataire non configuré The signer's address is not set on the client record. Set signer_email (PATCH /api/v1/clients/{id} or portal) to the address of the signer's DigiGo or E-Houwiya certificate.
Passphrase manquante
or required for seal
The seal mode requires a passphrase configured for the client's environment (sandbox or live). Set seal_passphrase_test / seal_passphrase_prod through the API (PATCH /clients/{id}) or the portal, or switch to method: "digigo".
Invoice not found
or Locked invoice 50010
Attempt to re-sign an invoice already being signed. Retrieve the current state with GET /einvoices/{id}. If it is still pending, send the same invoice again to /einvoices/prepare to get its link back, or cancel it (POST /einvoices/{id}/cancel). If it is rejected, issue it again: the same number is accepted.
Invalid TEIF format
or XML validation error
The data sent does not comply with the TEIF v1.8.9 format. Check your data: tax ID with 13 characters for the issuer (7 digits + check letter + category + nature + 000, e.g. 1234567RAM000), 8 or 13 characters for the buyer, correct check letter in both cases, full seller address (street, city, postal code), VAT in [0, 7, 13, 19], required fields.
aucune transaction UUID retournée Abnormal response from the signing service. Retry. If it persists, contact support with your invoice_number.
Other message not listed Unlisted error, possibly a new one. Contact support with: the full debug, invoice_number, timestamp, and your API Client ID.
Best practices in live mode
  • Implement a retry with exponential backoff for 5xx errors and timeouts (3 attempts max: 1s, 3s, 10s)
  • Never automatically retry 4xx errors (except 429 RATE_LIMIT, after the indicated delay)
  • Keep the X-Request-Id header of each response: quote it to support, it lets them find your exact call

Validate a payload

POST /api/v1/einvoices/validate

Validates the payload structure without signing or submitting to TTN. Ideal for debugging your integration. No credit consumed, even in live mode.

Request body

The same body for /einvoices/validate, /einvoices/process and /einvoices/prepare. Below are the essentials; all optional fields (discounts, FODEC, currency, withholding tax, PDF notes…) are described in Invoice object, and an example with every field in Full example.

FieldTypeDescription
invoice_numberrequiredstringInvoice number on the ERP side. 30 characters at most, letters, digits, - and _ only, no period, no space and no /: see the format rules. Odoo's default format, INV/2026/09/0008, is rejected by TTN.
daterequireddate YYYY-MM-DDIssue date, never in the future.
sellerrequiredobjectname, address. tax_id optional: your key already carries it, and only its first 8 characters are compared if you send it.
buyerrequiredobjectname, and tax_id (Tunisian tax ID) or id_number (national ID card (CIN), foreign company number, with country).
itemsrequiredarrayAt least one line: description, quantity, unit_price (excl. VAT), vat_rate (0, 7, 13 or 19). See Invoice object.
typeoptionalenumfacture by default. For a credit note: credit_note and original_invoice_number, see Credit notes and debit notes.
pdf_base64optionalstringYour invoice PDF encoded in base64. Without it, we generate it. See Invoice PDF.

Response

The response carries two lists. errors: what would prevent issuing, and makes valid false. warnings: non-blocking alerts, which change neither valid nor the behavior of /einvoices/process and /einvoices/prepare. Show them to the user, for example in your "Check compliance" button.

{
  "success": true,
  "data": {
    "valid": true,
    "errors": [],
    "warnings": [
      "suspension.authorization_number : le numéro de l'attestation d'achat en suspension de TVA manque. C'est la pièce qui justifie la suspension en cas de contrôle."
    ]
  }
}

Warnings returned today, for a sale under VAT suspension (the API returns their text in French):

SituationWhy we warn you
Certificate number missingIt is the document that justifies the suspension in case of an audit.
Purchase order number missingThe purchase order reference accompanies the sale under suspension.
Unreadable date (date_from, date_to, order_date)A date outside the YYYY-MM-DD format is neither sent to TTN nor printed.
Validity period invertedThe start date is later than the end date.
Invoice dated outside the validity periodThe certificate does not cover the invoice date.
No VAT to suspendAll lines are at 0% or exempt: send the actual rate (vat_rate: 19), not exonerated: true.

Sign + submit (SEAL mode)

POST /api/v1/einvoices/process

Synchronous (~5 seconds). Automatic signing with a server electronic seal, immediate submission to TTN. The response directly contains the signed XML (base64), the PDF with QR code (base64) and the TTN reference. Key required: that of the client concerned (ck_); a developer key receives 403 DEVELOPER_KEY_NOT_ALLOWED.

Recommended use caseBack-office ERP, daily batch, high volumes. No user interaction.

Request body

The same body for /einvoices/validate, /einvoices/process and /einvoices/prepare. Below are the essentials; all optional fields (discounts, FODEC, currency, withholding tax, PDF notes…) are described in Invoice object, and an example with every field in Full example.

FieldTypeDescription
invoice_numberrequiredstringInvoice number on the ERP side. 30 characters at most, letters, digits, - and _ only, no period, no space and no /: see the format rules. Odoo's default format, INV/2026/09/0008, is rejected by TTN.
daterequireddate YYYY-MM-DDIssue date, never in the future.
sellerrequiredobjectname, address. tax_id optional: your key already carries it, and only its first 8 characters are compared if you send it.
buyerrequiredobjectname, and tax_id (Tunisian tax ID) or id_number (national ID card (CIN), foreign company number, with country).
itemsrequiredarrayAt least one line: description, quantity, unit_price (excl. VAT), vat_rate (0, 7, 13 or 19). See Invoice object.
typeoptionalenumfacture by default. For a credit note: credit_note and original_invoice_number, see Credit notes and debit notes.
pdf_base64optionalstringYour invoice PDF encoded in base64. Without it, we generate it. See Invoice PDF.

Response codes

HTTPMeaning
200Invoice signed and submitted. Full response.
412Seal not provisioned, or seal PIN code missing, for the key's environment. See SEAL_NOT_CONFIGURED.
422METHOD_REQUIRES_PREPARE: DigiGo, USB token or E-Houwiya requested here. Use POST /einvoices/prepare.
402Insufficient credits.
422Validation failed. See error.details.

Prepare a signature (DigiGo, USB token, E-Houwiya)

POST /api/v1/einvoices/prepare

This is the entry point for DigiGo, the USB token and E-Houwiya. POST /einvoices/process only signs with the server seal: sending "method": "digigo" or "usb" there returns 422 METHOD_REQUIRES_PREPARE.

Asynchronous. Generates the TEIF, creates a signing transaction and returns a signing_url to which you redirect the end client (remote signature or local USB token). The client signs, then is redirected to your return_url. Key required: that of the client concerned (ck_); a developer key receives 403 DEVELOPER_KEY_NOT_ALLOWED. The returned signing_id (format sg_...) is used for tracking with GET /einvoices/{signing_id}.

Retrieve the final result with:

  • Polling: GET /einvoices/{signing_id} until status: validated

Request body

The same body for /einvoices/validate, /einvoices/process and /einvoices/prepare. Below are the essentials; all optional fields (discounts, FODEC, currency, withholding tax, PDF notes…) are described in Invoice object, and an example with every field in Full example.

FieldTypeDescription
invoice_numberrequiredstringInvoice number on the ERP side. 30 characters at most, letters, digits, - and _ only, no period, no space and no /: see the format rules. Odoo's default format, INV/2026/09/0008, is rejected by TTN.
daterequireddate YYYY-MM-DDIssue date, never in the future.
sellerrequiredobjectname, address. tax_id optional: your key already carries it, and only its first 8 characters are compared if you send it.
buyerrequiredobjectname, and tax_id (Tunisian tax ID) or id_number (national ID card (CIN), foreign company number, with country).
itemsrequiredarrayAt least one line: description, quantity, unit_price (excl. VAT), vat_rate (0, 7, 13 or 19). See Invoice object.
typeoptionalenumfacture by default. For a credit note: credit_note and original_invoice_number, see Credit notes and debit notes.
pdf_base64optionalstringYour invoice PDF encoded in base64. Without it, we generate it. See Invoice PDF.

In addition, for a manual signature (DigiGo, USB token, E-Houwiya)

FieldTypeDescription
methodoptionalenum

Signing mode for this invoice.

Values
seal, digigo, usb, mobileid.
Default
The mode configured on the client.
Effect
seal signs immediately with the server seal, without signing_url. mobileid = E-Houwiya (Mobile ID).
Good to know
E-Houwiya is enabled at the signing service for each account: ask us for it before the first try, otherwise the signing page does not offer it.
return_urlrequired (digigo, usb, mobileid)HTTPS URL

Address in your ERP where the client returns after signing.

Example
"return_url": "https://erp.exemple.tn/factures/42"
Required
As soon as the signature goes through a browser: digigo, usb and mobileid. Only seal does without it, since nobody is in front of the screen.
Rejected (422)
Missing when it is required, or in http://: VALIDATION_FAILED.
Good to know
Your own query parameters are preserved.
Redirect security (read this) The return_url is used only to bring the user back into your interface. It is a browser redirect: never consider an invoice signed because the browser came back to this URL; it could be called directly. To confirm the real status, always use an authenticated server-to-server channel:
  • Polling: GET /einvoices/{signing_id} with your API key (X-Api-Key header).
To help you correlate the return, we automatically append ?efacture_invoice={invoice_number}&signing_id={signing_id} to your return_url. The signing_id (format sg_...) is the one to use with GET /einvoices/{signing_id}. Use these parameters only to find the invoice concerned, never as proof of signature.
Never assume where the signing_url leads It is an opaque address: redirect your user to it without parsing it. Depending on the signing service handling the account, it leads either directly to the signing page, or to a waiting page hosted on efacturetn.com that opens that page and then brings the user back to your return_url as soon as the signature is obtained. Some signing services honor no return address, and we fill that gap for you.
  • The contract does not change: you receive a signing_url, your user comes back to return_url. Changing signing service requires no change on your side.
  • So do not hard-code any domain, do not open this page in an iframe, and do not replay an expired signing_url: cancel the signature (POST /einvoices/{id}/cancel) then call POST /einvoices/prepare again, or wait for can_prepare_again_at. While it is pending, sending it again to /prepare returns the same link, without a second credit (see Sending the same invoice again).
  • If your user closes the page, nothing is lost: the signature is retrieved on our side in the background, and the invoice continues to its TTN submission as if the browser had come back. GET /einvoices/{signing_id} remains the source of truth. The browser return is a convenience, never the mechanism.

Prepare the signature of a batch (DigiGo, USB token)

POST /api/v1/einvoices/prepare-batch

Up to 20 invoices, a single code entered. All invoices go into a single signing transaction: your user opens a single signing_url and enters their DigiGo code, or their USB token code, only once. Each invoice keeps its own signature and receives its own signing_id, then tracked exactly like an invoice prepared alone (GET /einvoices/{signing_id}).

  • All or nothing before signing. Each invoice is checked as on /einvoices/prepare. A single invalid invoice, and nothing is sent: the 422 BATCH_VALIDATION_FAILED response lists in error.details.errors the index, the invoice_number, the code and the message of each invoice to correct.
  • Credits. The balance must cover the whole batch before sending. One credit is then charged per invoice actually signed, as for a single invoice.
  • Methods. digigo and usb only. The server seal signs each invoice immediately with /einvoices/process.
  • Plan. A key attached to a company requires the Jugurtha plan or higher (403 PLAN_REQUIRED otherwise).

Request body

FieldTypeDescription
invoicesrequiredarrayFrom 1 to 20 invoices, each in the format of /einvoices/prepare. invoice_number is mandatory there and must be unique within the batch: it is what links each invoice to its signature.
methodoptionalenumdigigo or usb. Default: the mode configured on the client.
return_urlrequiredHTTPS URLWhere to bring your user back after the batch is signed. We append ?efacture_batch={batch_id} to correlate the return, never as proof of signature.

Response

{
  "status": "pending_signature",
  "batch_id": "lot_8f3c...",
  "signing_url": "https://efacturetn.com/signature/...",
  "method": "digigo",
  "count": 2,
  "invoices": [
    {
      "invoice_number": "F2026-101",
      "signing_id": "sg_...",
      "tracking": "available"
    },
    {
      "invoice_number": "F2026-102",
      "signing_id": "sg_...",
      "tracking": "available"
    }
  ]
}

Redirect your user to signing_url, then track each signing_id with GET /einvoices/{signing_id}. One invoice of the batch may be signed while another is refused: read the status of each one.

Retrieve an e-invoice

GET /api/v1/einvoices/{id}

Returns the status and files of an e-invoice. Used mainly for polling after POST /einvoices/prepare. Only the owning client of the invoice and its parent developer can query it: any other key receives 403 PERMISSION_DENIED.

Each key reads only its own environment. A document issued in test mode is queried with ck_test_, a document issued in live mode with ck_live_; the other way round returns 403 WRONG_ENVIRONMENT, and the same applies to POST /einvoices/{id}/resubmit-ttn. This is not an ownership restriction, the document is indeed yours: it is a separation of environments, because a test key is distributed more widely than a live key and must not open your real tax documents. Your sk_dev_ developer key designates no environment and sees both, across all your clients.

Lifecycle

draft → teif_generated → pending_signature → signed → submitted_ttn → validated
                                                                                            ↘ rejected
StatusDescription
pending_signatureWaiting for the client to sign on signing_url
signedSignature received, TTN submission in progress
submitted_ttnSubmitted, waiting for TTN validation
validatedTTN accepted. xml_base64 and pdf_base64 are available. TTN's QR and the final reference arrive a few minutes later: see Final documents & QR.
rejectedCancelled or rejected: see the signature and ttn blocks to know which stage failed, and ttn.next_action to know what to do (see below)

Two stages described separately: signature and ttn

The status field is the overall summary of the cycle. A rejected can mean two very different things: signature refused, or invoice signed but TTN submission rejected. The response therefore contains two dedicated blocks:

{
  "status": "rejected",
  "signature": {
    "status": "signed",  // pending | signed | rejected
    "signed_xml_available": true
  },
  "ttn": {
    "status": "rejected",  // not_reached | submitted | validated | rejected
    "reference": null,
    "error": {
      "code": "TTN_DEPOSIT_FAILED",
      "message": "Erreur TTN: ..."
    }
  }
}
Scenariostatussignature.statusttn.status
Waiting for the signerpending_signaturependingnot_reached
Signature refused / cancelledrejectedrejectednot_reached
Signed, TTN submission rejectedrejectedsignedrejected + error
Signed, submitted (SFTP), TTN response pendingsubmitted_ttnsignedsubmitted
Validatedvalidatedsignedvalidated + reference

If the submission is rejected (ttn.status: rejected): the signed XML remains available; fix the cause (e.g. the client's TTN credentials) then issue the invoice again (new /prepare or /process). A rejection is final for this signing_id.

Polling strategyExponential backoff recommended: 5s, 10s, 20s, 30s, 60s... with a total timeout of 30 minutes. Stop polling as soon as status is rejected, or validated with reference_confirmee: true. A signature not completed within 7 days changes to rejected by itself (SIGNATURE_EXPIRED). The signing service is queried only once every 30 seconds per invoice: polling more often returns the same status. On return from signing: when your user comes back to your return_url, query GET /einvoices/{id} right away. We then query the signing service, and the signature is usually already recorded. If the status is still pending_signature, retry 30 seconds later. A return to your return_url does not by itself prove that the invoice is signed: only the status says so.

After a TTN rejection: resubmit or re-sign

When status = rejected and a signed document exists, the API tells you what to do, in ttn.next_action (GET), in next_action (responses of /process and /prepare with signed_ttn_rejected). Two values, no more: your module does not have to read TTN's text.

next_actionWhat it meansThe button to show
resubmitThe signed document is not at fault: TTN unavailable, timeout exceeded, client's TTN account nonexistent or disabled, certificate not declared. Once the cause is removed, the same file goes out again.Resubmit to TTN: POST /einvoices/{id}/resubmit-ttn, with no new signature, no credit.
resignThe document is at fault: schema violated (for example a malformed number), number already submitted, issuer different from the account. Resubmitting the same file would get the same answer, and the API refuses it (409 RESIGN_REQUIRED).Correct then issue again: new invoice, new signature (one credit in live mode). Check first with /einvoices/validate.
When in doubt, the API answers resubmit. A useless resubmission costs nothing, TTN says the same thing again and the document is kept. A useless re-signing costs a credit and a PIN entry for the signer. A signature can never be stuck back onto a corrected file: the slightest change to the document invalidates the signature, which is the very principle of electronic signatures.

Resubmit to TTN without re-signing

POST /api/v1/einvoices/{id}/resubmit-ttn

For the "Resubmit to TTN" button in your ERP. When the submission failed because TTN was unavailable, or was rejected for a cause external to the document, this call resubmits the signed document exactly as it was signed, with no new signature and without consuming any credit.

ItemValue
{id}The signing_id returned by /einvoices/prepare or /einvoices/process at issue time, the same as for GET /einvoices/{id}. One call per invoice: a client with several signed documents makes one call per identifier.
AuthenticationThe API key of the issuing client, ck_test_ or ck_live_. Never the sk_ developer key (403 DEVELOPER_KEY_NOT_ALLOWED). An identifier belonging to another account returns 403 PERMISSION_DENIED.
BodyEmpty.

When to use it

Invoice stateResponse
rejected with error.code = TTN_DEPOSIT_FAILED, TTN_REJECTED or SFTP_DEPOSIT_FAILED200: the signed file is resubmitted. The status changes to validated (provisional reference) or submitted_ttn, then the confirmation is read as usual with GET /einvoices/{id}.
pending_signature, no signed document409 NOT_SIGNED: nothing to resubmit, wait for the signature or run /prepare again.
validated or submitted_ttn, reference_confirmee = false409 AWAITING_TTN: TTN has already accepted the submission, resubmitting would create a duplicate. The confirmation is polled every 2 to 3 minutes.
reference_confirmee = true409 ALREADY_VALIDATED: the document is final.
Client whose submission is handled by the signing service409 DEPOSIT_DELEGATED: this submission cannot be replayed through the API; contact support with the signing_id.
rejected because TTN rejected the document (next_action = resign)409 RESIGN_REQUIRED: resubmitting the same file would get the same answer. Correct the invoice and issue it again.
TTN rejects or does not respond502 TTN_DEPOSIT_FAILED with TTN's message. The invoice stays rejected; you can retry later.

Response

{
  "success": true,
  "data": {
    "signing_id": "sg_146c4253ea74656dbedc5b57",
    "invoice_number": "FACT-2026-0012",
    "status": "validated",
    "ttn": {
      "status": "validated",
      "reference": "TTN-SOAP-1234567",
      "reference_confirmee": false
    },
    "ttn_reference": "TTN-SOAP-1234567",
    "resigned": false,
    "credits_consumed": 0,
    "message": "Document signé renvoyé chez TTN, sans nouvelle signature."
  },
  "error": null
}
What the button must not do: run /process or /prepare again for the same invoice. That would produce a second signed document, a second credit consumed, and two submissions for a single number. Resubmission is only shown when status = rejected and a signed document exists (signature.signed_xml_available = true).

Cancel a pending signature

POST /api/v1/einvoices/{signing_id}/cancel

Stops a signature opened by POST /einvoices/prepare (DigiGo, USB token, E-Houwiya) and not yet done. Key required: that of the client concerned, in the invoice's environment. No request body.

No credit is consumed by a cancellation, and an invoice cannot be charged twice: the credit is only taken when a real signature comes back. If your user signs at the very moment you cancel, we re-read the status at the signing service before responding: the invoice is then treated as signed, with a single credit, and the document is kept for you.

Responses

HTTPCodeMeaning
200-"status": "cancelled", "credits_consumed": 0. Nothing was signed. The invoice number can be prepared again immediately.
409ALREADY_SIGNEDToo late: the invoice was signed. It follows its normal course, one credit. Read it with GET /einvoices/{signing_id}; to cancel it in your accounts, issue a credit note.
409SIGNATURE_ALREADY_CLOSEDNothing to cancel: the attempt is already closed (refused, cancelled or abandoned). The number is free.
409CANCEL_NOT_SUPPORTEDThis client's signing service does not allow cancellation. Without a signature, the attempt is abandoned by itself at error.details.can_prepare_again_at (30 minutes after it was opened).
502CANCEL_UNCONFIRMEDThe cancellation could not be confirmed. Nothing is considered cancelled, nothing is charged: retry in a moment.

Credit notes and debit notes

A credit note is sent through the same endpoints as an invoice. Nothing separate: only two fields change in the body.

FieldValueRequired
type
alias: document_type
credit_note for a credit note, debit_note for a debit note.
Also accepted: avoir, creditnote, credit-note, note_debit, debit-note. Absent = invoice.
yes
original_invoice_number
alias: parent_invoice_number, facture_origine_numero
The number of the cancelled or corrected invoice. one of the two
original_ttn_reference
alias: facture_origine_ttn
The TTN reference of the original invoice, if you have it. one of the two
Amounts stay POSITIVE. Do not send negative quantities or prices: the type carries the meaning of the document, and the TEIF applies the sign itself. Negative lines on a credit_note would produce a document that cancels itself twice.
{
  "type": "credit_note",
  "original_invoice_number": "F-2026-0042",
  "invoice_number": "AV-2026-0007",
  "date": "2026-09-18",
  "seller": {
    "name": "MA SOCIETE",
    "tax_id": "1234567RBM000",
    "address": "Rue X",
    "city": "Tunis",
    "postal_code": "1000"
  },
  "buyer": {
    "name": "MON CLIENT",
    "tax_id": "7654321CBM000",
    "address": "Rue Y, Sfax"
  },
  "items": [
    {
      "description": "Retour marchandise",
      "quantity": 2,
      "unit_price": 150.000,
      "vat_rate": 19
    }
  ],
  "stamp_duty": false
}

Stamp duty and withholding tax on a credit note

They are never automatically copied from the original invoice: the API only knows the body you send. If your credit note must carry them, send them explicitly (stamp_duty, withholding tax fields). Otherwise, leave them out.

Final documents & QR code

An e-invoice produces four documents, and they do not all arrive at the same time. This is the most frequent source of confusion: do not confuse what you signed with what TTN validated.

FieldContentAvailableTo archive
xml_base64 The TEIF that you signed and that we submitted. As soon as it is signed no
xml_validettn_base64 The final document: the same one, plus the <RefTtnVal> block added by TTN (TTN reference, processing date, seal). After confirmation yes
ttn.qr_png_base64 TTN's QR alone, as a PNG image. After confirmation if you compose your own document
pdf_base64 Our PDF, with the QR already affixed. As soon as it is signed, updated on confirmation your choice

The QR cannot be fabricated

The QR of an El Fatoora invoice is the visible electronic seal (CEV). TTN produces it, as a PNG image, and it can be verified with the official tools. A QR rebuilt on your side will look the same but will fail verification: the fingerprint and the key it contains are computed by TTN.

So you have nothing to compute. Either you use our pdf_base64, or you affix ttn.qr_png_base64 as is on your own document, without re-encoding or retouching.

The QR arrives later

TTN fills the <RefTtnVal> block after the submission: this block is excluded from your signature, which is why TTN can write into it without invalidating it. We query TTN again to retrieve it: every 2 to 3 minutes during the first half hour, then less often (see below).

"ttn": {
  "status": "validated",
  "reference": "073620200053562920196810312",
  "reference_confirmee": true,          // false = submission acknowledgment, not yet the final reference
  "confirmed_at": "2026-09-01T14:32:07+00:00",
  "qr_png_base64": "iVBORw0KGgo..."     // null as long as reference_confirmee is false
}
The deciding fieldreference_confirmee tells you whether you hold the final document. As long as it is false, the reference carried is only a submission acknowledgment and the QR is not yet TTN's final one: do not print the invoice for your client.

How to retrieve the confirmation

Call GET /einvoices/{id} again until reference_confirmee changes to true. We are the ones querying TTN, not your call: a 2-minute interval is enough, shorter is useless. TTN usually confirms within a few minutes. If it has not done so after 30 minutes, we keep querying it every 15 minutes, then every hour after 6 hours, for 7 days: space out your calls the same way. Beyond that, contact us.

Two submission steps, not one

What you readWhat it means
status: submitted_ttnTTN accepted the submission but returned no identifier to us. The invoice is submitted, not yet confirmed. Keep polling.
status: validated, reference_confirmee: falseTTN returned an identifier on submission, the reference is provisional. Keep polling.
status: validated, reference_confirmee: trueThe reference is final: go and fetch the QR and the validated XML.

How long we keep these documents

90 days, and not one more. After that period, the four documents and the body of your request are erased from our servers, as well as the corresponding call and transaction logs. We keep the invoice row, that is its number, its dates, its status and its TTN reference: a signing_id therefore keeps responding, with the erasure date in documents_purged_at.

Why we erase. Two reasons, and neither is a service limitation:

  • Confidentiality. Your clients' invoices contain their amounts, their partners and their addresses. That is their business, not ours. Keeping forever what we no longer have a reason to keep would be a decision by default, and we prefer not to make it on their behalf.
  • Performance. A database that only grows ends up slowing everyone down, including your calls. Erasing what has served keeps our response times where they are.
ConsequenceWhat to do
GET /einvoices/{id} returns the XML and PDF fields as null, with documents_purged_at set.Nothing: your archives are the reference.
POST /einvoices/{id}/resubmit-ttn returns 409 DOCUMENTS_PURGED.Issue the invoice again from your ERP.
Archiving is up to you, with no exception. Download xml_validettn_base64 as soon as reference_confirmee changes to true, and keep it with the PDF in your system: it is the document that carries TTN's reference and seal. If you do not archive them on your side, you will not find them with us after 90 days. The period applies to all invoices, including those TTN never confirmed. Our 90 days are an operational safety net, not legal archiving.

If you prefer us to keep your archives

Archiving ten years of signed invoices, keeping them safe and knowing how to find them is not an integrator's job. We offer to do it for you, as an option, for each client you move to live mode.

What you getDetail
10-year retentionThe signed document, the document validated by TTN and the PDF, stored encrypted, instead of 90 days.
Access at any timeA dedicated key to retrieve your clients' archives whenever you need them, without going through our support.
PricePer client and per year, on top of the connection fee. The amount is shown in your developer portal, on the pricing page.

The option is ordered from your developer portal, client by client, when moving to live mode or at renewal.

A copy in your client's Google Drive

Your client wants to keep a copy of its invoices itself, in a space that belongs to it. We place for it, in a Google Drive account, one archive per validated e-invoice, without your integration having to call anything.

QuestionAnswer
What does each archive contain?One ZIP file per e-invoice: the signed document, the document validated by TTN, the PDF and a metadata file (number, dates, TTN reference).
Where is it stored?In an eFactureTN folder, then a subfolder per client, per year and per month.
When is it sent?Automatically, shortly after validation. With SOAP submission, after TTN's confirmation, so that the archive carries the final document.
Which Google account?The one you connect from the client's record in your portal. The same account can serve several of your clients: each one gets its own folder.
In what form?Decrypted, so that its recipient can read it, and sent over a secure connection (HTTPS). On our side, documents remain encrypted.
What if Google access is revoked or expires?Nothing is lost: archives wait, you are notified by email, and they go out again by themselves as soon as the account is reconnected.
What about invoices already issued?For each client, the portal offers to download the archives of a whole month.
PricePer client and per year, even if several clients share the same Google account. A bundled price applies when the copy is taken together with the 10-year archiving. The amounts are shown in your developer portal.
Once placed, the archive belongs to the Google account. Its retention, sharing and deletion are then up to its holder. If you also want us to keep our own copy for ten years, take both options together.

Credit balance

GET /api/v1/credits/balance

Returns the current credit balance, the total used and the total purchased.

Platform status

GET /api/v1/status

Returns the overall state of the platform. No authentication required, no credit consumed. Use it as a probe from your ERP or your monitoring.

The only public endpointIt does not require a key. Checks are automatic and hourly: this status is not entered by hand, it reflects the state actually measured.
curl https://efacturetn.com/api/v1/status

Response

{
  "success": true,
  "data": {
    "status": "operational",
    "version": "1.0.0",
    "teif_version": "1.8.9",
    "all_operational": true,
    "last_check": "17/07/2026 09:00"
  },
  "error": null
}

Fields

FieldTypeDescription
statusstringOverall state. Always that of the most degraded service: if a single component suffers, you see it here. Values: operational, degraded, partial_outage, major_outage, maintenance.
all_operationalboolShortcut: true only if all services are fully operational.
last_checkstringDate of the last automatic check.
versionstringAPI version.
teif_versionstringSupported TEIF version.

Availability per service

GET /api/v1/status/services

Service-by-service detail: status, measured latency and availability rate. Requires an API key. No credit consumed, in test as in live mode.

Parameters

FieldTypeDescription
daysoptionalintAvailability rate window, in days. Between 1 and 180. Default: 90.
curl "https://efacturetn.com/api/v1/status/services?days=30" \
  -H "X-Api-Key: ck_test_xxxxxxxxxxxx"

Response

{
  "success": true,
  "data": {
    "status": "degraded",
    "all_operational": false,
    "last_check": "17/07/2026 09:00",
    "uptime_window_days": 30,
    "services": [
      {
        "slug": "signature",
        "name": "Signature électronique",
        "description": "Service de signature",
        "status": "operational",
        "status_label": "Operationnel",
        "operational": true,
        "latency_ms": 214,
        "detail": null,
        "uptime_percent": 99.86
      },
      {
        "slug": "ttn_prod",
        "name": "TTN production (El Fatoora)",
        "description": "Envoi e-factures (production)",
        "status": "partial_outage",
        "status_label": "Panne partielle",
        "operational": false,
        "latency_ms": null,
        "detail": "Perturbations en cours",
        "uptime_percent": 98.40
      },
      {
        "slug": "ttn_sandbox",
        "name": "TTN sandbox (test)",
        "description": "Environnement de test",
        "status": "operational",
        "status_label": "Operationnel",
        "operational": true,
        "latency_ms": 187,
        "detail": null,
        "uptime_percent": 99.90
      }
    ]
  },
  "error": null
}

Fields of a service

FieldTypeDescription
slugstringStable identifier of the service. Use it in your code: the label may change, the slug does not. Values: platform, signature, ttn_prod, ttn_sandbox, api, tej, email.
statusstringSame values as the overall state.
operationalboolShortcut for status === "operational".
latency_msint / nullMeasured latency. Set only for services probed over the network, null otherwise.
detailstring / nullReason, set only when the service is not operational. null the rest of the time.
uptime_percentfloat / nullAvailability rate over the requested window. null as long as no history is available.

Example: pausing the sending queue when TTN goes down

$res = json_decode(file_get_contents('https://efacturetn.com/api/v1/status'), true);

if ($res['data']['status'] !== 'operational') {
    // Do not send now: resume the batch later
    $this->queue->pause('E-invoicing platform unavailable');
}
Good habitProbe at most once a minute. The status is recomputed every hour: querying more often will not tell you anything more and will use up your request quota.

Client management (API)

A developer account can manage its clients directly from its ERP, through the API. Each client has its own TTN configuration (sandbox and live), its signing method, its credit cap and its own API keys.

AuthenticationThese endpoints use your developer account key (not a client's key). They operate on your attached clients. A client key is refused (403).

Confidentiality of secrets

TTN and SFTP passwords are never returned in clear text. When read, they are masked with asterisks whose number matches the stored length (e.g. "password": "********"). You can write them (creation / update) but never read them back.

Fields of a client

FieldTypeDescription
namestringClient name (required at creation)
matriculestringTax ID (TTN identifier)
signer_methodstringseal (server seal), usb (local token), digigo (remote) or mobileid (E-Houwiya, smartphone)
signer_emailstringSigner's email: the address under which they hold their DigiGo or E-Houwiya certificate, the one declared to the certification authority. Any other address, even a valid one, shows « certificat introuvable pour l'email fourni » (certificate not found for the email provided) on the signing page. Required for digigo and mobileid (otherwise SIGNER_EMAIL_MISSING, HTTP 412), not needed for seal and usb. It is set on the client (here, or in the developer portal), not in the invoice: it is read and passed to the signing service at each signature.
seal_passphrase_teststringPassphrase of the sandbox electronic seal, required for the seal method in test mode. The sandbox seal and the live seal are two separate organizations, potentially with different passphrases. Masked when read.
seal_passphrase_prodstringPassphrase of the live electronic seal, required for the seal method in live mode. Masked when read.
usb_signing_tool_urlstringRead-only. Direct download link of the USB signing tool (Windows) to install on the signer's computer. Distribute it to your clients from your ERP.
submission_channelstringWho submits the invoice to TTN once signed. delegated (default): the signing service submits it itself, under its own TTN account: your client does not need an El Fatoora account of its own. soap: we submit through the client's TTN web service, the reference is known immediately. sftp: we place the signed XML in the in folder of its TTN account, and the response is picked up later in out: the invoice then stays submitted until the response is polled, with no reference. Any other value is rejected.
credit_capint / nullClient's credit cap. null = unlimited (within the limit of the wallet). If you have enabled automatic top-up in your portal, a client created without credit_cap follows it: its cap is raised automatically in steps, which credits.auto_recharge shows when read. Sending a credit_cap switches the client back to a manual cap.
ttn.sandbox / ttn.prodobjectlogin + password of the TTN account per environment
sftp.sandbox / sftp.prodobjecthost, port, username, password, in_dir, out_dir (SFTP channel)
provisionstringOptional (creation / update). sandbox, production or both: creates or updates the client's signing account, whatever its signing mode. The operation is idempotent (creation the first time, update afterward). The result, including any error message from the service, is returned in provisioning. Without provision, any PATCH automatically updates the environments already connected (company name, tax ID, TTN access). The signer's email, however, is not sent here: it goes with each signature.

When read, each client also returns its tracking data: credits (cap, used, remaining) and stats (total, validated, rejected). Enough to display a mini dashboard per client in your ERP.

Create a client

POST /api/v1/clients

Creates a client and returns its API keys (ck_test_ / ck_live_). These keys can be retrieved at any time with GET /clients/{id}. Add "provision": "sandbox" (or production / both) to create the client's signing account at the same time.

POST /api/v1/clients
X-Api-Key: sk_dev_YOUR_DEVELOPER_KEY
Content-Type: application/json

{
  "name": "Société ABC",
  "matricule": "1234567RAM000",
  "signer_method": "seal",
  "signer_email": "signataire@societe-abc.tn",
  "seal_passphrase_test": "123456",
  "seal_passphrase_prod": "987654",
  "submission_channel": "soap",
  "credit_cap": 500,
  "ttn": {
    "sandbox": {
      "login": "abc_test",
      "password": "secret1"
    },
    "prod": {
      "login": "abc_prod",
      "password": "secret2"
    }
  }
}

Response (201):

{
  "success": true,
  "data": {
    "id": "018f...-....",
    "name": "Société ABC",
    "matricule": "1234567RAM000",
    "signer_method": "seal",
    "signer_email": "signataire@societe-abc.tn",
    "seal_passphrase_test": "******",
    "seal_passphrase_prod": "******",
    "seal_org_uuid_test": null,
    "seal_org_uuid_prod": null,
    "usb_signing_tool_url": "https://efacturetn.com/downloads/...",
    "submission_channel": "soap",
    "active": true,
    "live_enabled": true,
    "credits": {
      "cap": 500,
      "used": 0,
      "remaining": 500,
      "auto_recharge": false
    },
    "stats": {
      "total": 0,
      "validated": 0,
      "rejected": 0
    },
    "ttn": {
      "sandbox": {
        "login": "abc_test",
        "password": "*******"
      },
      "prod": {
        "login": "abc_prod",
        "password": "*******"
      }
    },
    "sftp": {
      "sandbox": {
        "host": null,
        "port": null,
        "username": null,
        "password": null,
        "in_dir": null,
        "out_dir": null
      },
      "prod": {
        "host": null,
        "port": null,
        "username": null,
        "password": null,
        "in_dir": null,
        "out_dir": null
      }
    },
    "keys": {
      "test": "ck_test_...",
      "live": "ck_live_..."
    },
    "created_at": "2026-11-18T10:42:07+01:00"
  }
}

If you requested a provision, the response contains a provisioning block per environment:

"provisioning": {
  "sandbox": {
    "success": true,
    "message": "Compte de signature créé (environnement test)."
  },
  "production": {
    "success": false,
    "message": "L'organisation existe déjà chez le prestataire..."
  }
}

Creating the client succeeds even if provisioning fails: correct the access details then run it again with PATCH and provision. Then use the client's key (keys.live / keys.test) to issue its e-invoices through /einvoices/process or /einvoices/prepare.

List clients

GET /api/v1/clients

Returns all your clients (secrets masked) with their credits and statistics, plus the balance of your shared wallet.

{
  "success": true,
  "data": {
    "clients": [
      {
        "id": "...",
        "name": "Société ABC",
        "credits": {
          "cap": 500,
          "used": 180,
          "remaining": 320,
          "auto_recharge": true
        },
        "stats": {
          "total": 200,
          "validated": 190,
          "rejected": 10
        },
        ...
      }
    ],
    "wallet": {
      "balance": 4200,
      "total_purchased": 5000
    }
  }
}

Read a client

GET /api/v1/clients/{id}

Returns a client: configuration, credits, statistics and its API keys (keys.test / keys.live, ck_ prefix). TTN/SFTP passwords remain masked, but the client's API keys are returned in clear text so that you can retrieve them at any time.

Update a client

PATCH /api/v1/clients/{id}

Partial update: only the fields sent are modified. Send a TTN/SFTP password only to replace it; omit it to keep it. Add "provision" to recreate or update the signing account.

PATCH /api/v1/clients/018f...
X-Api-Key: sk_dev_YOUR_DEVELOPER_KEY

{
  "credit_cap": 800,
  "submission_channel": "sftp",
  "sftp": {
    "prod": {
      "host": "sftp.ttn.tn",
      "port": 22,
      "username": "abc",
      "password": "xxx",
      "in_dir": "/in",
      "out_dir": "/out"
    }
  }
}

Delete a client • Regenerate keys

DELETE /api/v1/clients/{id}

Deletes the client.

POST /api/v1/clients/{id}/keys

Regenerates the client's API keys (the old ones stop working immediately). The new keys are returned, and remain retrievable with GET /clients/{id}.

Rate limits

By default: 60 requests per minute per API key. Sliding window, atomic counting. Configurable on request for high volumes.

When exceeded: 429 RATE_LIMIT response. Implement an exponential backoff on the client side.

Invoice object

FieldTypeDescription
invoice_numberrequiredstring

Invoice number in your software.

Example
"invoice_number": "F-2026-0042"
Limit
30 characters at most: letters, digits, - and _ only, no period, no space, no /. See the format rules.
Rejected
Odoo's default format, INV/2026/09/0008, is rejected by TTN.
daterequireddateIssue date YYYY-MM-DD.
due_dateoptionaldateDue date.
typeoptionalenum

Nature of the document.

Values
facture (default), avoir, note_debit, honoraire, proforma.
Effect
A credit note produces a TEIF of type I-12 and must reference its original invoice (see below).
Other names
document_type
original_invoice_numbercredit notestring

Number of the original invoice of a credit note or a debit note.

Example
"original_invoice_number": "F-2026-0042"
Required
On a credit note or a debit note: without it, TTN cannot link the document.
With the reference
Add original_ttn_reference if you know the TTN reference of the original.
Other names
facture_origine_numero parent_invoice_number
delivery_dateoptionaldateDelivery date YYYY-MM-DD, when it differs from the issue date.
currencyoptionalstring

Invoice currency, as an ISO 4217 code.

Values
TND (default, 3 decimals), EUR or USD (2 decimals) for export.
Effect
In a foreign currency: no VAT, no stamp duty (export regime), the total incl. VAT equals the total excl. VAT. Amounts are kept as is, without conversion.
Rejected (422)
TTN only accepts these three currencies: any other (GBP, CHF...) is rejected with VALIDATION_FAILED, before signing and with no credit consumed.
exchange_rateoptionalnumber

For an invoice in EUR or USD: how many dinars for one unit of the currency.

Example
"exchange_rate": 3.385
Effect
TTN also requires the total incl. VAT in dinars (business rule 14): we add it to the document with your rate.
Default
Our rate of the day, if you do not send it.
Rejected (422)
An unreadable or negative rate, never silently replaced.
Other names
taux_de_change
seller.namerequiredstringSeller's company name.
seller.tax_idoptionalstring

Seller's tax ID. Optional: your key already carries it.

Effect
The account's tax ID is what goes into the document, in the full format required by TTN.
Comparison
If you send it, only the first 8 characters are compared: 1234567R and 1234567RAM000 are equivalent.
Rejected
A different taxpayer, with SELLER_MISMATCH, before signing.
seller.addressrequiredstringAddress (street). Also: address_line_2, governorate, country (default TN), phone, email.
seller.cityrequiredstringSeller's city. Required by TTN (business rule 5: supplier's address, city, postal code and country).
seller.postal_coderequiredstringSeller's postal code. Required by TTN, same rule.
seller.ribpublic sectorstring

Your 20-digit bank or postal account number.

Example
"rib": "12 345 6789012345678 90" (spaces allowed)
Required
When the buyer belongs to the public sector (business rule 13): it goes into the document.
Default
We look for it in bank_details.
Other names
bank_account
buyer.namerequiredstringCompany name / name of the client.
buyer.tax_idrequired*string

Client's Tunisian tax ID.

Example
"tax_id": "1234567RAM000" or "1234567R"
Form
8 or 13 characters, with a correct check letter: see the format rules.
Required
*It or buyer.id_number, never both.
Rejected (422)
A foreign number, with VALIDATION_FAILED: this field only accepts the Tunisian form. For a foreign client, use buyer.id_number.
buyer.id_numberrequired*string

Identification number, instead of the tax ID: the national ID card (CIN) of an individual or the company number of a foreign client.

Example
"id_number": "01234567" (CIN) or "FR40123456789" (EU VAT number)
Form
Tunisian client: exactly 8 digits. Foreign client (SIREN, SIRET, EU VAT number, NIF): 1 to 30 letters and digits.
Effect
Spaces and punctuation are removed before sending.
Other names
cin piece_identite passport
buyer.addressoptionalstringClient's address (street).
buyer.address_line_2optionalstringAdditional address line.
buyer.postal_codeoptionalstringPostal code.
buyer.cityoptionalstringCity.
buyer.governorateoptionalstringGovernorate.
buyer.countryoptionalstring

Client's country, as an ISO code. It decides the type of identifier sent to TTN: set it as soon as the client is not Tunisian.

Example
"country": "FR"
Default
TN.
Effect
With TN, an id_number is sent as a national identity card, which TTN's schema requires to be exactly 8 characters. With a foreign country, it is sent as a non-Tunisian tax identifier, in free form.
Pitfall
A 9-digit SIREN sent without a country would be rejected at submission, after signing.
buyer.public_entityoptionalboolean

true for the State, a local authority or a public institution.

Example
"public_entity": true or "type": "public"
Effect
TTN then requires (rules 11 to 13): buyer.tax_id, the buyer's full address (address, city, postal_code) and seller.rib.
Other names
secteur_public
buyer.phone / buyer.emailoptionalstringClient's phone / email.
items[].descriptionrequiredstringLine description. 255 characters at most.
items[].referenceoptionalstringItem reference, printed in the RÉFÉRENCE (reference) column. Alias: code, article_code.
items[].unitoptionalstringUnit of the line (piece, kg, jour, heure…). Alias: unite.
items[].quantityrequirednumberQuantity.
items[].unit_pricerequirednumberUnit price excl. VAT.
items[].vat_raterequired*enum

VAT rate of the line.

Values
0, 7, 13, 19.
Required
*Unless default_vat_rate (invoice) is set or the line is exonerated.
Rejected (422)
A missing rate: no value is assumed by default.
Currency
Ignored in a foreign currency: no VAT.
Other names
tva_rate tax_rate
items[].discount_percentoptionalnumberDiscount on the line, in % (0–100). The line's total excl. VAT is reduced accordingly, and VAT is computed on the amount excl. VAT after discount. Alias: remise, remise_percent, discount.
items[].line_total_htoptionalnumber

Line total excl. VAT as YOU computed it.

Example
"line_total_ht": 333.333
Effect
It replaces quantity × unit price, and both VAT and FODEC are derived from it. We take your amount: it is your invoice.
When
If your software rounds differently from us: your totals and ours stop diverging by a few millimes, without multiplying the decimals of the unit price.
Rejected (422)
Only a gap of more than 1% with our computation: a total incl. VAT sent instead of excl. VAT, or a misplaced decimal point. The message names the three amounts involved. No rounding difference blocks you.
Other names
total_ht montant_ht line_total
items[].exoneratedoptionalbooleanLine exempt from VAT (0% rate). Equivalent to vat_rate: 0. Alias: vat_exempt.
items[].fodecoptionalboolean

FODEC 1% on the line, for products subject to it.

Example
"fodec": true
Effect
Computed on the amount excl. VAT after discount, and the line VAT is computed on amount excl. VAT + FODEC (Tunisian rule).
Where
« FODEC (1%) » line in the PDF totals, tax I-162 in the TEIF.
Currency
Ignored in a foreign currency.
Other names
fodec_applicable is_fodec
items[].other_taxesoptionalarray

Other taxes on the line, apart from VAT, FODEC and stamp duty: consumption duty, tax on metal packaging, etc.

Example
[{ "code": "I-161", "rate": 25 }]: a rate in % of the line amount excl. VAT, after discount. Or [{ "code": "I-163", "amount": 1.5 }]: a fixed amount for the line. Never both.
Codes
TTN's I-16 code list: I-161 consumption duty, I-163 tax on metal packaging, I-164 environmental protection tax (TPE), I-165 FODET, I-166 tax on air conditioners, I-167 taxes on lamps and tubes, I-168 taxes on fruit and vegetables, I-169 taxes on fishery products, I-160 RB taxes and I-1603 for another tax, which then requires name.
VAT base
By default, the tax is included in it, like FODEC (article 6 of the VAT Code), except I-168, I-169 and I-160, which the code list says are not subject to VAT. in_vat_base (boolean) decides otherwise for a line: your accountant decides.
Effect
The tax is included in the total incl. VAT and is not reduced by the global discount. It has its own line in the PDF totals. In the TEIF, it is declared at invoice level (InvoiceTax), grouped by code and by rate, the fixed amount at rate 0.
Rejected (422)
A code already carried by a field (I-162 FODEC, I-1601 stamp duty, I-1602 VAT), with the field to use. More than ten taxes per line. An invoice in a foreign currency.
Other names
autres_taxes; taux montant libelle dans_base_tva
default_vat_rateoptionalenumDefault VAT rate of the invoice (0, 7, 13, 19), applied to lines without vat_rate. Avoids repeating the rate on each line.
global_discount_percentoptionalnumber

Discount on the whole invoice, as a percentage, applied after line discounts.

Example
"global_discount_percent": 10 takes 10% off the total excl. VAT
Effect
The amount excl. VAT goes down accordingly, VAT is recomputed. FODEC is not reduced: it remains computed on the amount excl. VAT before discount. « Remise globale X% » (global discount) line in the PDF totals.
Rejected (422)
A value outside 0 to 100: that is an amount, use global_discount_amount.
With the amount
Send one or the other. If both arrive, the percentage wins.
Other names
remise_globale_percent remise_globale_pct
global_discount_amountoptionalnumber

Discount on the whole invoice, as an amount, in the invoice currency.

Example
"global_discount_amount": 50 takes TND 50 off the total excl. VAT
Effect
The amount excl. VAT goes down by 50, VAT is recomputed. FODEC and the other taxes do not go down. Same effects as global_discount_percent, the amount being related to the lines' total excl. VAT, line discounts deducted.
Rejected (422)
If the discount exceeds the lines' total excl. VAT: the total would be negative.
With the %
Send one or the other. If both arrive, global_discount_percent wins.
Other names
remise_globale remise_globale_montant remise_montant
stamp_dutyoptionalboolean | numberStamp duty. Present by default (1.000 TND): set false to disable it, or a numeric amount to customize it. Alias: timbre, fiscal_stamp.
withholding_tax_rateoptionalnumberWithholding tax (e.g. 1.5, 3, 10, 15, 20). Base = total incl. VAT excluding stamp duty (excl. VAT + VAT). Amount deducted from the net amount payable.
suspensionoptionalobject

Sale under VAT suspension: VAT is computed but not invoiced, and the net amount payable equals the amount excl. VAT + stamp duty.

Example
{ "enabled": true, "authorization_number": "AUT-2026-777", "date_from": "2026-01-01", "date_to": "2026-12-31", "order_number": "BC-42", "order_date": "2026-01-15" }
TEIF
The line keeps its actual rate, the VAT due is 0 and the suspended amount goes in I-187. The authorization number goes as reference I-85 with its validity period, the purchase order as I-83 with its date, and the invoice carries the SpecialConditions notice « Vente en suspension de TVA » (sale under VAT suspension).
PDF
The suspended VAT is shown separately, below the totals, with the notices.
Pitfall
Do not send exonerated: true: that is an exemption, which declares a 0% rate.
Check
/einvoices/validate reports in warnings a missing certificate or purchase order, or a date that is unreadable or outside validity.
Other names
suspension_tva for a simple boolean; num_autorisation date_debut date_fin bon_commande
brand_coloroptionalstringBrand color of the generated PDF (hex, e.g. #1d4ed8). Default: #dc2626. Ignored if you provide pdf_base64. Other name: color.
payment_methodoptionalstringPayment method shown on the PDF (free text, e.g. Virement bancaire - RIB 12345678901234567890, Chèque, Espèces). Max 255 characters. Rendered on the generated PDF (mode B).
custom_noteoptionalobject

Free note placed wherever you want on the PDF: legal notices, conditions, a paragraph...

Example
{ "text": "Merci de votre confiance.", "position": "bottom_left" }
Positions
top_left, bottom_left (default), bottom_center, bottom_right.
Limit
text: 1000 characters.
Where
On the generated PDF (mode B).
invoice_objectoptionalstringSubject of the invoice, shown as « Objet : … » (e.g. Prestation de conseil - janvier 2026). Max 255 characters. Rendered on the generated PDF (mode B).
termsoptionalstring

General terms, payment terms or notices, in a « Conditions générales » (general terms) block of the PDF.

Example
"terms": "Paiement à 30 jours. Pénalité de 1,5%/mois en cas de retard."
Limit
1000 characters.
Where
On the generated PDF (mode B).
referencesoptionalstringFree reference shown as « Référence » (e.g. Bon de commande N° 1234 du 05/01/2026). Max 100 characters. Rendered on the generated PDF (mode B).
bank_detailsoptionalstringBank details shown as « Coordonnées bancaires : … » (e.g. RIB 12345678901234567890 - Banque XYZ). Max 255 characters. Rendered on the generated PDF (mode B).
pdf_base64optionalstringYour invoice PDF encoded in base64. See Invoice PDF.

Document format rules

These rules apply to the three entry points, POST /einvoices/validate, POST /einvoices/process and POST /einvoices/prepare, with the same messages. They reject before signing what TTN would reject after, when the credit has already been consumed. Do a dry run with /einvoices/validate: the call is free and returns the full list of errors in data.errors.

FieldRuleWhy
invoice_number1 to 30 characters, starts with a letter or a digit, then letters, digits, -, _. No period, no space, no /, no :. Accepted examples: FACT-2026-0012, INV-2026-09-0008, F202600002.TTN business rule 7: ^[A-Za-z0-9][A-Za-z0-9_-]{0,29}$. The period is no longer accepted (rules published by TTN in October 2026): FACT.2026.0012 is rejected. Odoo integrators: the default format INV/2026/09/0008 is signed and then rejected at submission. Send INV-2026-09-0008 or change the sequence, and keep the mapping on the invoice.
dateValid calendar date in YYYY-MM-DD format, not in the future (Tunisia time).The document is signed and timestamped on the day of the call; a later issue date is inconsistent.
due_dateOptional. Same format, never earlier than date.A due date before the issue date is an input error.
typeOptional, default facture. Accepted values: facture, invoice, credit_note, avoir, debit_note. Any other value is rejected.An unknown nature used to fall back silently on "facture": a misspelled credit note went out as an invoice.
original_invoice_numberRequired for credit_note and debit_note, same format rules as invoice_number.A credit note corrects a named document.
items[].quantityStrictly positive number, 3 decimals at most.The document keeps the quantity to three decimals: beyond that, the value would be truncated between your ERP and the signed document.
items[].unit_pricePositive or zero number, 6 decimals at most, 15 integer digits at most.The TEIF schema limits an amount to 15 integer digits; the price is kept to six decimals and printed to three.
items[].line_total_htOptional, positive or zero number. When sent, it prevails over quantity × price (see the rounding tolerance of the Invoice object).Your line amount excl. VAT is what must appear on the document, not our recomputation.
items[].vat_rate0, 7, 13 or 19, or default_vat_rate at document level, or exonerated: true on the line.A rate cannot be guessed.
items[].discount_percentOptional, from 0 to 100.
stamp_dutytrue, false, or a positive amount.
global_discount_percent / global_discount_amountFrom 0 to 100 for the percentage, positive amount for the amount.
seller.tax_idOptional: the key carries the seller. If sent, it must designate the same taxpayer (first 8 characters), otherwise SELLER_MISMATCH.The document is signed under the key's identity.
buyer.tax_idTunisian tax ID, long form (1234567RBM000) or short form (1234567R), nothing else: 8 or 13 characters. Otherwise, buyer.id_number.A foreign number placed here is rejected: this field only accepts the Tunisian form. The check letter is verified, as TTN does: sum of the 7 digits weighted from 7 to 1, modulo 23, position in ABCDEFGHJKLMNPQRSTVWXYZ. Example: 1234567 gives R. Lost leading zeros are restored (426108A becomes 0426108A).
seller.tax_idFull 13-character form, correct check letter, category A B D N P, nature C M N P E.Optional: the key carries the seller. An account tax ID with a wrong letter is rejected before signing.
seller.address, seller.city, seller.postal_codeAll three required.TTN business rule 5: the supplier's address is complete, or the document is rejected.
buyer.id_numberNational ID card (CIN) of a Tunisian individual: exactly 8 digits. Company number of a foreign client: 1 to 30 letters and digits.Send it alone, without buyer.tax_id, and with buyer.country.
These rules are the same for everyone. A document accepted by /validate is accepted by /process and /prepare; a document rejected would also be rejected by TTN. Do not work around a rejection by changing the message on the ERP side: correct the data.

Full example (all fields)

Reference payload gathering all supported fields: structured seller/client details (tax ID, address, city, postal code, governorate, country, phone, email), multi-rate VAT per line, default rate, exempt line, stamp duty, withholding tax and PDF color. This payload passes validation without error.

{ "method": "seal", "invoice_number": "F-2026-00042", "date": "2026-06-26", "due_date": "2026-07-26", "default_vat_rate": 19, "stamp_duty": true, "withholding_tax_rate": 1.5, "brand_color": "#1d4ed8", "payment_method": "Virement bancaire - RIB 12345678901234567890", "invoice_object": "Prestation de conseil - janvier 2026", "terms": "Paiement à 30 jours. Pénalité de 1,5%/mois en cas de retard (art. 5 CGV).", "references": "Bon de commande N° 1234 du 05/01/2026", "bank_details": "RIB 12345678901234567890 - Banque XYZ", "custom_note": { "text": "Facture soumise à la TVA. En cas de retard de paiement, une pénalité de 1,5% par mois sera appliquée (art. 5 des CGV).", "position": "bottom_left" }, "seller": { "name": "Mon Entreprise SARL", "tax_id": "1234567RBM000", "address": "Avenue Habib Bourguiba", "address_line_2": "Immeuble El Amen, 3e étage", "postal_code": "1000", "city": "Tunis", "governorate": "Tunis", "country": "TN", "phone": "71234567", "email": "contact@mon-entreprise.tn" }, "buyer": { "name": "Client Demo SARL", "tax_id": "7654321CBM000", "address": "Rue de la Liberté", "postal_code": "3000", "city": "Sfax", "governorate": "Sfax", "country": "TN", "phone": "74111222", "email": "facturation@client-demo.tn" }, "items": [ { "description": "Prestation de conseil", "quantity": 1, "unit_price": 1000.000, "vat_rate": 19 }, { "description": "Licence logicielle annuelle", "quantity": 2, "unit_price": 250.000, "vat_rate": 13 }, { "description": "Produit de première nécessité", "quantity": 5, "unit_price": 20.000, "vat_rate": 7 }, { "description": "Service à l'export", "quantity": 1, "unit_price": 500.000, "exonerated": true } ], "return_url": "https://votre-erp.tn/factures/retour" }

Notes:

  • method: seal for /einvoices/process (automatic signing), digigo, usb or mobileid for /einvoices/prepare (signing by the client).
  • Individual: replace buyer.tax_id with buyer.id_number (national ID card/passport) → the PDF shows « CIN » instead of « MF » (tax ID).
  • Foreign client: same field, buyer.id_number, and above all buyer.country. See the export example below.
  • default_vat_rate applies to lines without vat_rate; each line can override it (different VAT per line). A VAT summary per rate is generated automatically.
  • stamp_duty is present by default (1.000 TND): set false to remove it.
  • brand_color and the contact details are only used for rendering the generated PDF (mode B). In mode A (pdf_base64), your PDF is the reference.
  • Validate first with POST /einvoices/validate (0 credits): any missing/invalid field is returned in error.details.
  • Accepted field aliases (seller/client): name=nom/raison_sociale, tax_id=matricule_fiscal/mf, address=adresse/rue, postal_code=code_postal/cp, city=ville, governorate=gouvernorat, country=pays, phone=tel. address can also be an object { street, city, postal_code }.

VAT summary produced for this example:

RateBase excl. VATVAT amount
0% (exempt)500.0000.000
7%100.0007.000
13%500.00065.000
19%1,000.000190.000
TOTAL2,100.000262.000

Export invoice: a client with no Tunisian tax ID

A foreign client has no Tunisian tax ID, and its company number (SIREN, SIRET, EU VAT number, NIF) does not go in buyer.tax_id: that field only accepts the Tunisian form and rejects it. It goes in buyer.id_number, alone, with the client's country.

The country is not decorative, it determines the type of identifier. Left at its default value, the number is sent to TTN as a national identity card, for which TTN's schema requires exactly 8 characters. A SIREN has 9: the invoice would be signed, the credit charged, and the submission rejected afterward. With a foreign country, the number is sent as a non-Tunisian tax identifier, in free form.
{ "invoice_number": "F2026-0002", "type": "facture", "date": "2026-07-13", "currency": "EUR", "method": "seal", "seller": { "name": "Mon Entreprise SARL", "address": "Avenue Habib Bourguiba", "city": "Tunis", "postal_code": "1000", "country": "TN" }, "buyer": { "name": "Export Client SA", "id_number": "552 100 554", "address": "Rue de Paris", "postal_code": "75002", "city": "Paris", "country": "FR" }, "stamp_duty": false, "items": [ { "description": "Produit export", "quantity": 5, "unit_price": 200.00, "vat_rate": 0 } ] }

What export changes, and nothing else:

  • buyer.id_number carries the number, and buyer.tax_id is absent. Spaces are removed before sending: 552 100 554 becomes 552100554.
  • buyer.country carries the client's country code. It is what makes a number without the Tunisian form acceptable.
  • currency in a foreign currency: 2 decimals, no conversion, amounts are kept as is.
  • No VAT, no stamp duty: vat_rate: 0 on the lines, or exonerated: true, and stamp_duty: false.
  • The seller, however, does not change: it is always the holder of your key, and its full Tunisian tax ID goes into the document.

This case appears in full in your portal, as the second document of the TTN test set, ready to be sent as is.

Withholding tax (RS)

Withholding tax is the tax that the buyer withholds from the payment and pays to the State on behalf of the seller. It changes neither the amount excl. VAT, nor the VAT, nor the total incl. VAT: it only reduces the net amount payable.

  • Optional: send withholding_tax_rate only when there is a withholding. Omit the field (or set 0) to apply none; the « Retenue à la source » (withholding tax) line then does not appear and the net amount payable = total incl. VAT. No other indicator is required.
  • Calculation base = total incl. VAT excluding stamp duty (excl. VAT + VAT).
  • Common rates: 1.5 (purchases of goods/services > TND 1,000 incl. VAT), 3 (fees, actual-earnings regime), 10 (fees/rents/commissions), 15, 20…

Example 1: with withholding tax (1.5%)

{ "invoice_number": "F-2026-00051", "date": "2026-06-27", "stamp_duty": true, "withholding_tax_rate": 1.5, "seller": { "name": "Mon Entreprise SARL", "tax_id": "1234567RBM000", "address": "Avenue Habib Bourguiba", "city": "Tunis", "postal_code": "1000" }, "buyer": { "name": "Client Public", "tax_id": "7654321CBM000", "address": "Sfax" }, "items": [ { "description": "Location bus", "quantity": 1, "unit_price": 125.000, "vat_rate": 7 } ] }
LineAmountCalculation
Total excl. VAT125.0001 × 125.000
VAT (7%)8.7507% of the amount excl. VAT
Stamp duty1.000fixed
Total incl. VAT134.750excl. VAT + VAT + stamp duty
Withholding tax 1.5%− 2.0061.5% × (excl. VAT + VAT) = 1.5% × 133.750
NET AMOUNT PAYABLE132.744incl. VAT − withholding tax

Example 2: without withholding tax

Simply do not send withholding_tax_rate (or set 0):

{ "invoice_number": "F-2026-00052", "date": "2026-06-27", "stamp_duty": true, "seller": { "name": "Mon Entreprise SARL", "tax_id": "1234567RBM000", "address": "Avenue Habib Bourguiba", "city": "Tunis", "postal_code": "1000" }, "buyer": { "name": "Client Privé", "tax_id": "7654321CBM000", "address": "Sfax" }, "items": [ { "description": "Location bus", "quantity": 1, "unit_price": 125.000, "vat_rate": 7 } ] }
LineAmountCalculation
Total excl. VAT125.0001 × 125.000
VAT (7%)8.7507% of the amount excl. VAT
Stamp duty1.000fixed
NET AMOUNT PAYABLE (= total incl. VAT)134.750no withholding tax line shown

Your totals and ours: line_total_ht

By default, we compute the total of each line ourselves: quantity × unit price, discount deducted. In the vast majority of cases, this is exactly what you want and you have nothing to do.

When you need it

When your software arrives at a total slightly different from ours. This happens with unit prices with many decimals, and for two reasons that have nothing to do with a defect:

  • The precision kept. We keep six decimals on a unit price. A price such as 8.40336134454 is therefore stored as 8.403361. Over 7,006 units, these few millionths add up to about 3 millimes.
  • The order of rounding. Many programs round the total only once, at the end. We round each line and then add them up, because a printed line must be a real amount and the total must be the sum of what is printed. That accounts for another millime or two, sometimes in the other direction.

No additional precision removes the second point: it is not a matter of decimals, it is a convention. Hence this field: send us the amount you computed, and we print the same one.

How to use it

Add line_total_ht on the line, excluding taxes, discount already deducted. It replaces the quantity × price product; VAT and FODEC are then derived from it as usual.

{ "invoice_number": "F-2026-00700", "date": "2026-09-01", "stamp_duty": true, "seller": { "name": "Ma Société SARL", "tax_id": "1234567RAM000", "address": "Rue du Lac", "city": "Tunis", "postal_code": "1053" }, "buyer": { "name": "Client SA", "tax_id": "7654321CAM000" }, "items": [ { "description": "Bon d'achat", "quantity": 7006, "unit_price": 8.40336134454, "vat_rate": 19, "line_total_ht": 58873.950 } ] }

The only line added is line_total_ht. Everything else is your usual invoice.

Without the fieldWith the field
Line total excl. VAT 58,873.947
(7,006 × 8.403361)
Line total excl. VAT 58,873.950
(your amount, taken as is)

So that the INVOICE total is right too

The document's total excl. VAT is the sum of the lines you send. If your software rounds the total only once, the sum of your rounded lines may exceed your own total by one millime. In that case, carry the remainder over to one line, as your software already does to print your own document, and our two totals will be identical to the millime.

Full example, ready to send

A three-line invoice, with unit prices to eleven decimals: exactly the case that makes totals diverge. Each line carries its line_total_ht.

{ "method": "seal", "invoice_number": "F-2026-00700", "date": "2026-09-01", "due_date": "2026-10-01", "currency": "TND", "stamp_duty": true, "seller": { "name": "MA SOCIÉTÉ SARL", "tax_id": "1234567RAM000", "address": "Avenue Habib Bourguiba", "city": "Tunis", "postal_code": "1000" }, "buyer": { "name": "CLIENT SA", "tax_id": "7654321CAM000", "address": "Rue de la Liberté", "city": "Sfax", "postal_code": "3000" }, "items": [ { "description": "Bon d'achat 50 DT", "quantity": 7006, "unit_price": 8.40336134454, "vat_rate": 19, "line_total_ht": 58873.950 }, { "description": "Bon d'achat 25 DT", "quantity": 474, "unit_price": 4.20168067227, "vat_rate": 19, "line_total_ht": 1991.597 }, { "description": "Frais de gestion", "quantity": 42, "unit_price": 3.36134453782, "vat_rate": 19, "line_total_ht": 141.176 } ] }

What you get, and these are the amounts this request actually produces:

 With line_total_htWithout
Total excl. VAT61,006.72361,006.720
VAT 19%11,591.27711,591.277
Stamp duty1.0001.000
Net amount payable72,599.00072,598.997

With the field, the total is exactly that of your software. Here the VAT is right on both sides: it is the amount excl. VAT, and therefore the net amount payable, that carry the gap. Without it, a gap of three millimes, enough for an automatic accounting reconciliation to flag the invoice.

Here, the sum of the three lines lands exactly on your total. When that is not the case, carry the remainder over to one line, as explained just above.

What we check

We take your amount: it is your invoice, you are its issuer. We only reject a gap of more than 1% with our own computation, because no rounding produces that and the invoice goes signed to the tax administration. This safeguard catches the three real errors: an amount incl. VAT sent instead of excl. VAT (+19%), a misplaced decimal point (×10), a mismatched line. The rejection is a 422 that names the three amounts involved.

Two pitfalls to avoid

  • Send an amount EXCLUDING TAXES. The amount incl. VAT is the most frequent error, and it is rejected.
  • Do not send it « just in case ». If your totals already match ours, omit the field: the normal computation remains the rule, and one line less is one line that cannot diverge.

Invoice PDF

The PDF is the visual document presented to the signer and archived after signing (the signature QR is affixed to it automatically). Two modes are possible:

ModeWhenResult
A: You provide the PDF recommended You send the pdf_base64 field (your PDF already laid out: logo, colors, notices from your ERP). Your PDF is signed as is. Your document is the reference.
B: Automatic generation You omit pdf_base64. We generate a plain but valid PDF from the invoice data (seller, client, lines, totals). Without your logo.

Recommendation: if your ERP already produces PDF invoices, send them via pdf_base64 to keep your visual identity. Constraints:

  • Base64 encoding of the PDF's binary content (the data:application/pdf;base64, prefix is tolerated but optional).
  • Must be a valid PDF (starts with %PDF).
  • Maximum size: 10 MB (before encoding).
  • If the PDF provided is invalid or missing, mode B (generation) automatically takes over: no signing failure.

Error object

Normalized format for all errors:

{ "success": false, "data": null, "error": { "code": "VALIDATION_FAILED", "message": "Invoice validation failed.", "details": [ "seller.address is required.", "buyer.tax_id or buyer.id_number is required.", "item 1: vat_rate is required (set the line vat_rate, a document default_vat_rate, or \"exonerated\": true)." ] } }

A technical question? Contact the team or see the interactive Swagger reference.

Discuter sur WhatsApp