Invoices

Create simplified (B2C), standard (B2B), credit, and debit documents. Every create requires egs_unit_id and supports Idempotency-Key.

Clinic visits

A patient paying at the desk gets a simplified invoice. Each clinic or branch issues from its own EGS unit. Put the patient on buyer when you know who they are.

  • Saudi citizen, private healthcare at 0%: every exempt line is vat_category: "Z" and vat_exemption_code: "VATEX-SA-HEA", and buyer.id_scheme must be NAT with a 10-digit national ID starting with 1.
  • Non-Saudi patient at 15%: leave vat_category as S (or omit it). Buyer is optional; use IQA, PAS, or GCC when you want the ID on the invoice.
  • A service and a medicine on one invoice are two line items. Each line has its own category. A qualifying medicine can be Z with VATEX-SA-35; anything else on that visit stays S at 15%. If any line is VATEX-SA-HEA, the national ID is still required.
  • A refund is a credit note against the original UUID. Repeat the same categories, exemption codes, and buyer, and send a reason.

Before integrating endpoints, read Responses (200 / 202 / warnings) and Errors. Request shapes: API objects. Branch setup: Quickstart.

Hybrid submit

We sign and persist first, then call Fatoora inline. 200 = finished (reported / cleared). 202 = queued — poll GET or wait for webhooks. Details: Understanding responses.
Accepted with warnings (still HTTP 200) — do not resubmit
{
  "status": "reported",
  "zatca_compliant": false,
  "zatca_warning_count": 1,
  "zatca_warnings": [
    {
      "code": "BR-KSA-37",
      "message": "The seller address building number must contain 4 digits."
    }
  ],
  "resubmit": false
}

Which endpoint to call

One EGS unit can issue more than one document type. The URL selects the type. Send egs_unit_id on every create.

TypeEndpointUse it for
Simplified (B2C)POST /v1/invoices/simplifiedTax invoice reported to ZATCA. QR comes back on the response when signing succeeds. No buyer VAT.
Standard (B2B)POST /v1/invoices/standardTax invoice cleared with ZATCA. Buyer name, VAT, and Saudi address are required.
Credit notePOST /v1/invoices/credit-noteCorrection against an earlier invoice. Send original_invoice_uuid and a reason.
Debit notePOST /v1/invoices/debit-noteExtra charge against an earlier invoice. Same body as a credit note.
PrepaymentPOST /v1/invoices/prepaymentAdvance payment (ZATCA type 386). A later tax invoice can settle it with prepaid_invoices.

Line VAT category is per line: S standard 15%, Z zero-rated, E exempt, O out of scope. One invoice can mix them. Field list: line item.

Your own fields (metadata)

Optional on simplified, standard, credit note, debit note, and prepayment. Send an object of string keys and values. We store it and return it on create, list, GET, and invoice webhooks. It is not written into the ZATCA XML.

  • Up to 20 keys.
  • Each key starts with a letter and uses only letters, numbers, and underscore. Max 40 characters.
  • Each value is a string, max 500 characters.
  • loan_reference is max 255 characters. When set, the PDF header shows it as Loan: …. Other keys are not printed.
  • Numbers, lists, and nested objects are rejected.
  • Omit the field and the stored value is null.
Loan id and any other reference you want back on the invoice
{
  "metadata": {
    "loan_reference": "LN-2026-01482",
    "contract_id": "C-100"
  }
}

Endpoints

Jump to an operation — or use the nested links under Invoices in the left nav.

POST/v1/invoices/simplified#

Submit simplified (B2C) invoice

Creates a simplified tax invoice (B2C). Signs and persists first, then reports to ZATCA. Returns HTTP 200 when reported inline, or HTTP 202 when queued. Always includes QR code, pdf_url, and report_deadline when applicable. See /docs/responses for compliance fields.

Requires API Key (Bearer)Supports Idempotency-Key header

Request body

CreateSimplifiedInvoiceDto
AttributeTypePresenceDescription
egs_unit_idstringRequiredRequired. Active EGS unit ID for the issuing branch or POS device.
invoice_numberstringRequired—
invoice_datestringRequiredYYYY-MM-DD
invoice_timestringRequiredHH:mm:ss
sellerSellerDtoRequired—
buyerSimplifiedBuyerDtoOptionalPerson on the invoice (name, id_scheme, id_number). Required with id_scheme NAT when a line uses VATEX-SA-HEA or VATEX-SA-EDU (BUYER_NATIONAL_ID_REQUIRED). Omit for an anonymous standard-rated sale.
line_itemsLineItemDto[]Required—
metadataobjectOptionalYour own key-value data. Up to 20 keys. Keys start with a letter and use only letters, numbers, and underscore (max 40). Values are strings, max 500 characters. Stored and returned on create, list, GET, and invoice webhooks. Not written into the ZATCA XML. The loan_reference key is capped at 255 characters and printed on the PDF as Loan: …. Null when omitted.
prepaid_invoicesPrepaidInvoiceRefDto[]OptionalSettle previously cleared/reported prepayment invoices (type 386) on this tax invoice. Omit amount to apply remaining balance, capped at this invoice total.
currencystringOptionalDefault: SAR
Child object: SellerDto
AttributeTypePresenceDescription
namestringRequiredSeller legal name
name_arstringOptionalArabic name
vat_numberstringRequired15-digit VAT registration number (PartyTaxScheme CompanyID)
cr_numberstringOptionalCommercial Registration Number for PartyIdentification schemeID=CRN. Do not send the VAT number here. If omitted, company-profile cr_number is used; one of the two is required.
addressAddressDtoOptionalOptional when a Saudi address is on the company profile (invoice overrides profile per field). Otherwise MISSING_SELLER_ADDRESS.
Child object: AddressDto
AttributeTypePresenceDescription
streetstringRequiredStreet name
building_numberstringOptionalZATCA expects 4 digits for SA (BR-KSA-37). Omitted or invalid values pass through to Fatoora.
districtstringOptionalDistrict / CitySubdivisionName. Recommended for SA.
citystringRequired—
postal_codestringOptionalZATCA expects 5 digits for SA (BR-KSA-66). Invalid formats pass through to Fatoora.
countrystringRequiredISO code, e.g. "SA"
Child object: SimplifiedBuyerDto
AttributeTypePresenceDescription
namestringRequired—
name_arstringOptional—
id_scheme"NAT" | "IQA" | "GCC" | "PAS" | "OTH"RequiredNAT = Saudi national ID (10 digits, starts with 1). IQA = Iqama (10 digits, starts with 2). GCC, PAS, and OTH are other personal IDs. Not a VAT number.
id_numberstringRequiredValue for id_scheme. A bad shape returns INVALID_BUYER_ID.
Child object: LineItemDto
AttributeTypePresenceDescription
descriptionstringRequiredItem description
description_arstringOptional—
quantitynumberRequiredMin 0.0001
unit_pricenumberRequiredIn SAR
vat_category"S" | "Z" | "E" | "O"OptionalS = 15% standard; Z/E/O = 0%. Default S. For Z/E/O, send vat_exemption_code (ZATCA VATEX-SA-*); missing/wrong codes are validated by Fatoora (warnings/errors), not API validation errors.
vat_exemption_codestringOptionalRecommended when vat_category is Z, E, or O; code should match category (e.g. Z→VATEX-SA-32, Z→VATEX-SA-HEA for a Saudi patient's private healthcare, Z→VATEX-SA-35 for a qualifying medicine). VATEX-SA-HEA and VATEX-SA-EDU return 400 BUYER_NATIONAL_ID_REQUIRED unless the simplified buyer is id_scheme NAT. Other missing or wrong codes pass through to Fatoora.

Code examples

const res = await fetch('https://api.esnadapi.com/v1/invoices/simplified', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${apiKey}`,
    'Idempotency-Key': 'unique-key-123',
  },
  body: JSON.stringify({
    egs_unit_id: egsUnitId,
    invoice_number: 'INV-001',
    invoice_date: '2025-01-15',
    invoice_time: '14:30:00',
    seller: {
      name: 'Acme Ltd',
      vat_number: '300012345600003',
      cr_number: '1010010000',
      address: { street: 'King Fahd Rd', building_number: '1234', district: 'Al Olaya', city: 'Riyadh', postal_code: '12271', country: 'SA' },
    },
    line_items: [
      { description: 'Product A', quantity: 2, unit_price: 50.0 },
    ],
    metadata: { loan_reference: 'LN-2026-01482', contract_id: 'C-100' },
  }),
});
const invoice = await res.json();

Success response (200)

{
  "invoice_id": "uuid",
  "uuid": "invoice-uuid",
  "metadata": {
    "loan_reference": "LN-2026-01482",
    "contract_id": "C-100"
  },
  "status": "reported",
  "subtotal": 100,
  "vat": 15,
  "total": 115,
  "invoice_date_hijri": "1446-07-15",
  "qr_code": "base64-encoded-qr",
  "reported_at": "2025-01-15T10:05:00.000Z",
  "report_deadline": "2025-01-16T10:00:00.000Z",
  "pdf_url": "/v1/invoices/uuid/pdf",
  "zatca_warning_count": 0,
  "zatca_warnings": [],
  "zatca_compliant": true,
  "resubmit": true
}

Error responses

  • 400
    {
      "error": {
        "code": "EGS_UNIT_REQUIRED",
        "message": "egs_unit_id is required in the request body so the invoice is attributed to the correct EGS unit (branch/POS).",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "EGS_NOT_READY",
        "message": "EGS unit onboarding not complete",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "SELLER_VAT_MISMATCH",
        "message": "seller.vat_number must match the company profile VAT.",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "SELLER_CRN_REQUIRED",
        "message": "seller.cr_number (Commercial Registration Number) is required for ZATCA. Set it on the invoice seller object, or save cr_number on the company profile.",
        "retryable": false
      }
    }
POST/v1/invoices/standard#

Submit standard (B2B) invoice

Creates a standard tax invoice (B2B). Signs and persists first, then requests ZATCA clearance. Returns HTTP 200 when cleared inline, or HTTP 202 when queued. Do not deliver to the buyer until status is cleared. Includes signed_xml_url and pdf_url.

Requires API Key (Bearer)Supports Idempotency-Key header

Request body

CreateStandardInvoiceDto
AttributeTypePresenceDescription
egs_unit_idstringRequiredRequired. Active EGS unit ID for the issuing branch or POS device.
invoice_numberstringRequired—
invoice_datestringRequired—
invoice_timestringRequired—
sellerSellerDtoRequired—
buyerBuyerDtoRequiredRequired for B2B
line_itemsLineItemDto[]Required—
metadataobjectOptionalYour own key-value data. Up to 20 keys. Keys start with a letter and use only letters, numbers, and underscore (max 40). Values are strings, max 500 characters. Stored and returned on create, list, GET, and invoice webhooks. Not written into the ZATCA XML. The loan_reference key is capped at 255 characters and printed on the PDF as Loan: …. Null when omitted.
prepaid_invoicesPrepaidInvoiceRefDto[]OptionalSettle previously cleared/reported prepayment invoices (type 386) on this tax invoice. Omit amount to apply remaining balance, capped at this invoice total.
currencystringOptional—
Child object: SellerDto
AttributeTypePresenceDescription
namestringRequiredSeller legal name
name_arstringOptionalArabic name
vat_numberstringRequired15-digit VAT registration number (PartyTaxScheme CompanyID)
cr_numberstringOptionalCommercial Registration Number for PartyIdentification schemeID=CRN. Do not send the VAT number here. If omitted, company-profile cr_number is used; one of the two is required.
addressAddressDtoOptionalOptional when a Saudi address is on the company profile (invoice overrides profile per field). Otherwise MISSING_SELLER_ADDRESS.
Child object: AddressDto
AttributeTypePresenceDescription
streetstringRequiredStreet name
building_numberstringOptionalZATCA expects 4 digits for SA (BR-KSA-37). Omitted or invalid values pass through to Fatoora.
districtstringOptionalDistrict / CitySubdivisionName. Recommended for SA.
citystringRequired—
postal_codestringOptionalZATCA expects 5 digits for SA (BR-KSA-66). Invalid formats pass through to Fatoora.
countrystringRequiredISO code, e.g. "SA"
Child object: BuyerDto
AttributeTypePresenceDescription
namestringRequired—
name_arstringOptional—
vat_numberstringRequired—
cr_numberstringOptionalBuyer Commercial Registration Number (PartyIdentification schemeID=CRN). VAT goes in PartyTaxScheme.
addressBuyerAddressDtoRequired—
Child object: BuyerAddressDto
AttributeTypePresenceDescription
streetstringRequired—
building_numberstringOptionalZATCA expects 4 digits for SA (BR-KSA-37). Omitted or invalid values pass through to Fatoora.
districtstringOptionalDistrict / CitySubdivisionName. Recommended for SA.
citystringRequired—
postal_codestringOptionalZATCA expects 5 digits for SA (BR-KSA-66). Invalid formats pass through to Fatoora.
countrystringRequired—
Child object: LineItemDto
AttributeTypePresenceDescription
descriptionstringRequiredItem description
description_arstringOptional—
quantitynumberRequiredMin 0.0001
unit_pricenumberRequiredIn SAR
vat_category"S" | "Z" | "E" | "O"OptionalS = 15% standard; Z/E/O = 0%. Default S. For Z/E/O, send vat_exemption_code (ZATCA VATEX-SA-*); missing/wrong codes are validated by Fatoora (warnings/errors), not API validation errors.
vat_exemption_codestringOptionalRecommended when vat_category is Z, E, or O; code should match category (e.g. Z→VATEX-SA-32, Z→VATEX-SA-HEA for a Saudi patient's private healthcare, Z→VATEX-SA-35 for a qualifying medicine). VATEX-SA-HEA and VATEX-SA-EDU return 400 BUYER_NATIONAL_ID_REQUIRED unless the simplified buyer is id_scheme NAT. Other missing or wrong codes pass through to Fatoora.

Code examples

const res = await fetch('https://api.esnadapi.com/v1/invoices/standard', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${apiKey}`,
    'Idempotency-Key': 'unique-key-456',
  },
  body: JSON.stringify({
    egs_unit_id: egsUnitId,
    invoice_number: 'INV-002',
    invoice_date: '2025-01-15',
    invoice_time: '14:30:00',
    seller: {
      name: 'Acme Ltd',
      vat_number: '300012345600003',
      cr_number: '1010010000',
      address: { street: 'King Fahd Rd', building_number: '1234', district: 'Al Olaya', city: 'Riyadh', postal_code: '12271', country: 'SA' },
    },
    buyer: {
      name: 'Client Co',
      vat_number: '300098765400003',
      address: { street: 'Olaya St', building_number: '2322', district: 'Al Murabba', city: 'Riyadh', postal_code: '12271', country: 'SA' },
    },
    line_items: [
      { description: 'Service B', quantity: 1, unit_price: 115.0 },
    ],
  }),
});
const invoice = await res.json();

Success response (200)

{
  "invoice_id": "uuid",
  "uuid": "invoice-uuid",
  "metadata": {
    "loan_reference": "LN-2026-01482",
    "contract_id": "C-100"
  },
  "status": "cleared",
  "subtotal": 100,
  "vat": 15,
  "total": 115,
  "qr_code": null,
  "signed_xml_url": "/v1/invoices/uuid/xml",
  "pdf_url": "/v1/invoices/uuid/pdf",
  "cleared_at": "2025-01-15T10:05:00.000Z",
  "zatca_compliant": true,
  "zatca_warning_count": 0,
  "zatca_warnings": [],
  "resubmit": true
}

Error responses

  • 400
    {
      "error": {
        "code": "EGS_UNIT_NOT_FOUND",
        "message": "EGS unit not found",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "EGS_NOT_READY",
        "message": "EGS unit onboarding not complete",
        "retryable": false
      }
    }
POST/v1/invoices/credit-note#

Submit credit note

Creates a credit note referencing an original invoice. Required: original_invoice_uuid, reason, seller, line_items. If the original was B2B, buyer needs name, vat_number, and address. If the original was simplified and a line uses VATEX-SA-HEA or VATEX-SA-EDU, buyer needs name and id_scheme NAT. Credit note total must not exceed original invoice total. Same hybrid submit as other creates: HTTP 200 when reported/cleared inline, HTTP 202 when queued.

Requires API Key (Bearer)Supports Idempotency-Key header

Request body

CreateCreditNoteDto
AttributeTypePresenceDescription
egs_unit_idstringRequiredRequired. Active EGS unit ID for the issuing branch or POS device.
invoice_numberstringRequired—
invoice_datestringRequired—
invoice_timestringRequired—
original_invoice_uuidstringRequiredUUID of the original invoice
reasonstringRequired—
reason_arstringOptional—
sellerSellerDtoRequired—
buyerNoteBuyerDtoOptionalB2B original: name, vat_number, and address (BUYER_REQUIRED_FOR_B2B_NOTE). Simplified original: name, id_scheme, and id_number. NAT is required when a line uses VATEX-SA-HEA or VATEX-SA-EDU.
line_itemsLineItemDto[]Required—
metadataobjectOptionalYour own key-value data. Up to 20 keys. Keys start with a letter and use only letters, numbers, and underscore (max 40). Values are strings, max 500 characters. Stored and returned on create, list, GET, and invoice webhooks. Not written into the ZATCA XML. The loan_reference key is capped at 255 characters and printed on the PDF as Loan: …. Null when omitted.
currencystringOptional—
Child object: SellerDto
AttributeTypePresenceDescription
namestringRequiredSeller legal name
name_arstringOptionalArabic name
vat_numberstringRequired15-digit VAT registration number (PartyTaxScheme CompanyID)
cr_numberstringOptionalCommercial Registration Number for PartyIdentification schemeID=CRN. Do not send the VAT number here. If omitted, company-profile cr_number is used; one of the two is required.
addressAddressDtoOptionalOptional when a Saudi address is on the company profile (invoice overrides profile per field). Otherwise MISSING_SELLER_ADDRESS.
Child object: AddressDto
AttributeTypePresenceDescription
streetstringRequiredStreet name
building_numberstringOptionalZATCA expects 4 digits for SA (BR-KSA-37). Omitted or invalid values pass through to Fatoora.
districtstringOptionalDistrict / CitySubdivisionName. Recommended for SA.
citystringRequired—
postal_codestringOptionalZATCA expects 5 digits for SA (BR-KSA-66). Invalid formats pass through to Fatoora.
countrystringRequiredISO code, e.g. "SA"
Child object: BuyerDto
AttributeTypePresenceDescription
namestringRequired—
name_arstringOptional—
vat_numberstringRequired—
cr_numberstringOptionalBuyer Commercial Registration Number (PartyIdentification schemeID=CRN). VAT goes in PartyTaxScheme.
addressBuyerAddressDtoRequired—
Child object: SimplifiedBuyerDto
AttributeTypePresenceDescription
namestringRequired—
name_arstringOptional—
id_scheme"NAT" | "IQA" | "GCC" | "PAS" | "OTH"RequiredNAT = Saudi national ID (10 digits, starts with 1). IQA = Iqama (10 digits, starts with 2). GCC, PAS, and OTH are other personal IDs. Not a VAT number.
id_numberstringRequiredValue for id_scheme. A bad shape returns INVALID_BUYER_ID.
Child object: BuyerAddressDto
AttributeTypePresenceDescription
streetstringRequired—
building_numberstringOptionalZATCA expects 4 digits for SA (BR-KSA-37). Omitted or invalid values pass through to Fatoora.
districtstringOptionalDistrict / CitySubdivisionName. Recommended for SA.
citystringRequired—
postal_codestringOptionalZATCA expects 5 digits for SA (BR-KSA-66). Invalid formats pass through to Fatoora.
countrystringRequired—
Child object: LineItemDto
AttributeTypePresenceDescription
descriptionstringRequiredItem description
description_arstringOptional—
quantitynumberRequiredMin 0.0001
unit_pricenumberRequiredIn SAR
vat_category"S" | "Z" | "E" | "O"OptionalS = 15% standard; Z/E/O = 0%. Default S. For Z/E/O, send vat_exemption_code (ZATCA VATEX-SA-*); missing/wrong codes are validated by Fatoora (warnings/errors), not API validation errors.
vat_exemption_codestringOptionalRecommended when vat_category is Z, E, or O; code should match category (e.g. Z→VATEX-SA-32, Z→VATEX-SA-HEA for a Saudi patient's private healthcare, Z→VATEX-SA-35 for a qualifying medicine). VATEX-SA-HEA and VATEX-SA-EDU return 400 BUYER_NATIONAL_ID_REQUIRED unless the simplified buyer is id_scheme NAT. Other missing or wrong codes pass through to Fatoora.

Code examples

await fetch('https://api.esnadapi.com/v1/invoices/credit-note', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${apiKey}`,
    'Idempotency-Key': 'credit-001',
  },
  body: JSON.stringify({
    egs_unit_id: egsUnitId,
    invoice_number: 'CN-001',
    invoice_date: '2025-01-20',
    invoice_time: '11:00:00',
    original_invoice_uuid: 'original-invoice-uuid',
    reason: 'Goods returned',
    seller: { name: 'Acme Ltd', vat_number: '...', cr_number: '1010010000', address: { street: '...', building_number: '1234', district: '...', city: '...', postal_code: '...', country: 'SA' } },
    line_items: [{ description: 'Refund Item A', quantity: 1, unit_price: 57.5 }],
  }),
});

Success response (200)

{
  "invoice_id": "uuid",
  "uuid": "credit-note-uuid",
  "metadata": {
    "loan_reference": "LN-2026-01482",
    "contract_id": "C-100"
  },
  "status": "reported",
  "document_type": "credit_note",
  "subtotal": 50,
  "vat": 7.5,
  "total": 57.5,
  "reported_at": "2025-01-20T11:00:00.000Z",
  "cleared_at": null,
  "zatca_compliant": true,
  "zatca_warning_count": 0,
  "zatca_warnings": [],
  "resubmit": true
}

Error responses

  • 404
    {
      "error": {
        "code": "ORIGINAL_INVOICE_NOT_FOUND",
        "message": "Original invoice not found",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "ORIGINAL_INVOICE_NOT_READY",
        "message": "Original invoice must be reported or cleared",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "BUYER_REQUIRED_FOR_B2B_NOTE",
        "message": "Buyer required when original invoice was B2B",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "CREDIT_NOTE_TOTAL_EXCEEDS_ORIGINAL",
        "message": "Credit note total must not exceed original invoice total",
        "retryable": false
      }
    }
POST/v1/invoices/debit-note#

Submit debit note

Same request body as credit note. Creates a debit note referencing the original invoice. Same validation rules apply (original must be reported/cleared; buyer required for B2B; total must not exceed original). Hybrid submit: HTTP 200 when reported/cleared inline, HTTP 202 when queued.

Requires API Key (Bearer)Supports Idempotency-Key header

Request body

CreateDebitNoteDto
AttributeTypePresenceDescription
egs_unit_idstringRequiredRequired. Active EGS unit ID for the issuing branch or POS device.
invoice_numberstringRequired—
invoice_datestringRequired—
invoice_timestringRequired—
original_invoice_uuidstringRequired—
reasonstringRequired—
reason_arstringOptional—
sellerSellerDtoRequired—
buyerNoteBuyerDtoOptionalSame buyer rules as a credit note: company fields for a standard original, id_scheme and id_number for a simplified original.
line_itemsLineItemDto[]Required—
metadataobjectOptionalYour own key-value data. Up to 20 keys. Keys start with a letter and use only letters, numbers, and underscore (max 40). Values are strings, max 500 characters. Stored and returned on create, list, GET, and invoice webhooks. Not written into the ZATCA XML. The loan_reference key is capped at 255 characters and printed on the PDF as Loan: …. Null when omitted.
currencystringOptional—

Code examples

await fetch('https://api.esnadapi.com/v1/invoices/debit-note', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${apiKey}`,
    'Idempotency-Key': 'debit-001',
  },
  body: JSON.stringify({
    egs_unit_id: egsUnitId,
    invoice_number: 'DN-001',
    invoice_date: '2025-01-20',
    invoice_time: '12:00:00',
    original_invoice_uuid: 'original-invoice-uuid',
    reason: 'Additional charges',
    seller: { name: 'Acme Ltd', vat_number: '...', cr_number: '1010010000', address: { street: '...', building_number: '1234', district: '...', city: '...', postal_code: '...', country: 'SA' } },
    line_items: [{ description: 'Extra fee', quantity: 1, unit_price: 23.0 }],
  }),
});

Success response (200)

{
  "invoice_id": "uuid",
  "uuid": "debit-note-uuid",
  "metadata": {
    "loan_reference": "LN-2026-01482",
    "contract_id": "C-100"
  },
  "status": "reported",
  "document_type": "debit_note",
  "subtotal": 20,
  "vat": 3,
  "total": 23,
  "reported_at": "2025-01-20T12:00:00.000Z",
  "cleared_at": null,
  "zatca_compliant": true,
  "zatca_warning_count": 0,
  "zatca_warnings": [],
  "resubmit": true
}

Error responses

  • 404
    {
      "error": {
        "code": "ORIGINAL_INVOICE_NOT_FOUND",
        "message": "Original invoice not found",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "ORIGINAL_INVOICE_NOT_READY",
        "message": "Original invoice must be reported or cleared",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "BUYER_REQUIRED_FOR_B2B_NOTE",
        "message": "Buyer required when original invoice was B2B",
        "retryable": false
      }
    }
POST/v1/invoices/prepayment#

Submit prepayment invoice (ZATCA type 386)

Issues an advance/wallet-top-up tax invoice. invoice_type standard uses B2B clearance (buyer required); simplified uses B2C reporting with QR. Counts against the same monthly invoice quota. Later tax invoices settle this balance via prepaid_invoices.

Requires API Key (Bearer)Supports Idempotency-Key header

Request body

CreatePrepaymentInvoiceDto
AttributeTypePresenceDescription
egs_unit_idstringRequiredRequired. Active EGS unit ID for the issuing branch or POS device.
invoice_type"standard" | "simplified"Requiredstandard = B2B clearance; simplified = B2C reporting.
invoice_numberstringRequired—
invoice_datestringRequired—
invoice_timestringRequired—
sellerSellerDtoRequired—
buyerBuyerDtoOptionalRequired when invoice_type is standard.
line_itemsLineItemDto[]Required—
metadataobjectOptionalYour own key-value data. Up to 20 keys. Keys start with a letter and use only letters, numbers, and underscore (max 40). Values are strings, max 500 characters. Stored and returned on create, list, GET, and invoice webhooks. Not written into the ZATCA XML. The loan_reference key is capped at 255 characters and printed on the PDF as Loan: …. Null when omitted.
currencystringOptional—
Child object: SellerDto
AttributeTypePresenceDescription
namestringRequiredSeller legal name
name_arstringOptionalArabic name
vat_numberstringRequired15-digit VAT registration number (PartyTaxScheme CompanyID)
cr_numberstringOptionalCommercial Registration Number for PartyIdentification schemeID=CRN. Do not send the VAT number here. If omitted, company-profile cr_number is used; one of the two is required.
addressAddressDtoOptionalOptional when a Saudi address is on the company profile (invoice overrides profile per field). Otherwise MISSING_SELLER_ADDRESS.
Child object: AddressDto
AttributeTypePresenceDescription
streetstringRequiredStreet name
building_numberstringOptionalZATCA expects 4 digits for SA (BR-KSA-37). Omitted or invalid values pass through to Fatoora.
districtstringOptionalDistrict / CitySubdivisionName. Recommended for SA.
citystringRequired—
postal_codestringOptionalZATCA expects 5 digits for SA (BR-KSA-66). Invalid formats pass through to Fatoora.
countrystringRequiredISO code, e.g. "SA"
Child object: BuyerDto
AttributeTypePresenceDescription
namestringRequired—
name_arstringOptional—
vat_numberstringRequired—
cr_numberstringOptionalBuyer Commercial Registration Number (PartyIdentification schemeID=CRN). VAT goes in PartyTaxScheme.
addressBuyerAddressDtoRequired—
Child object: BuyerAddressDto
AttributeTypePresenceDescription
streetstringRequired—
building_numberstringOptionalZATCA expects 4 digits for SA (BR-KSA-37). Omitted or invalid values pass through to Fatoora.
districtstringOptionalDistrict / CitySubdivisionName. Recommended for SA.
citystringRequired—
postal_codestringOptionalZATCA expects 5 digits for SA (BR-KSA-66). Invalid formats pass through to Fatoora.
countrystringRequired—
Child object: LineItemDto
AttributeTypePresenceDescription
descriptionstringRequiredItem description
description_arstringOptional—
quantitynumberRequiredMin 0.0001
unit_pricenumberRequiredIn SAR
vat_category"S" | "Z" | "E" | "O"OptionalS = 15% standard; Z/E/O = 0%. Default S. For Z/E/O, send vat_exemption_code (ZATCA VATEX-SA-*); missing/wrong codes are validated by Fatoora (warnings/errors), not API validation errors.
vat_exemption_codestringOptionalRecommended when vat_category is Z, E, or O; code should match category (e.g. Z→VATEX-SA-32, Z→VATEX-SA-HEA for a Saudi patient's private healthcare, Z→VATEX-SA-35 for a qualifying medicine). VATEX-SA-HEA and VATEX-SA-EDU return 400 BUYER_NATIONAL_ID_REQUIRED unless the simplified buyer is id_scheme NAT. Other missing or wrong codes pass through to Fatoora.

Code examples

await fetch('https://api.esnadapi.com/v1/invoices/prepayment', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${apiKey}`,
    'Idempotency-Key': 'wallet-topup-001',
  },
  body: JSON.stringify({
    egs_unit_id: egsUnitId,
    invoice_type: 'standard',
    invoice_number: 'PRE-001',
    invoice_date: '2025-01-15',
    invoice_time: '10:00:00',
    seller: { name: 'Acme Ltd', vat_number: '300012345600003', cr_number: '1010010000', address: { street: 'King Fahd Rd', building_number: '1234', district: 'Al Olaya', city: 'Riyadh', postal_code: '12271', country: 'SA' } },
    buyer: { name: 'Buyer Co', vat_number: '310987654300003', address: { street: 'Olaya St', building_number: '2000', district: 'Al Olaya', city: 'Riyadh', postal_code: '12271', country: 'SA' } },
    line_items: [{ description: 'Wallet top-up', quantity: 1, unit_price: 1000 }],
  }),
});

Success response (200)

{
  "invoice_id": "inv_pre_1",
  "uuid": "prepayment-uuid",
  "metadata": null,
  "status": "cleared",
  "document_type": "prepayment",
  "subtotal": 1000,
  "vat": 150,
  "total": 1150,
  "prepaid": 0,
  "payable": 1150,
  "signed_xml_url": "/v1/invoices/inv_pre_1/xml",
  "pdf_url": "/v1/invoices/inv_pre_1/pdf"
}

Error responses

  • 400
    {
      "error": {
        "code": "BUYER_REQUIRED_FOR_B2B_PREPAYMENT",
        "message": "Buyer is required for standard (B2B) prepayment invoices",
        "retryable": false
      }
    }
GET/v1/invoices#

List invoices (cursor pagination)

Returns a paginated list of invoices. Filter by status, invoice_type, document_type, date range, and egs_unit_id.

Requires API Key (Bearer)

Query parameters

NameTypeRequiredDescription
cursorstringNoPagination cursor from previous response
limitnumberNoPage size
statusstringNoFilter by status
invoice_typestringNosimplified | standard
document_typestringNoinvoice | credit_note | debit_note | prepayment
date_fromstringNoYYYY-MM-DD
date_tostringNoYYYY-MM-DD
egs_unit_idstringNoFilter by EGS unit

Code examples

const res = await fetch(
  `${BASE}/v1/invoices?limit=20&status=reported&egs_unit_id=${egsUnitId}`,
  { headers: { Authorization: `Bearer ${apiKey}` } }
);
const { data, pagination } = await res.json();

Success response (200)

{
  "data": [
    {
      "invoice_id": "uuid",
      "uuid": "invoice-uuid",
      "invoice_number": "INV-001",
      "metadata": {
        "loan_reference": "LN-2026-01482",
        "contract_id": "C-100"
      },
      "invoice_type": "simplified",
      "document_type": "invoice",
      "status": "reported",
      "total": 115,
      "invoice_date": "2025-01-15",
      "created_at": "2025-01-15T10:00:00.000Z",
      "environment": "sandbox",
      "zatca_compliant": true,
      "zatca_warning_count": 0,
      "resubmit": true
    }
  ],
  "pagination": {
    "limit": 20,
    "next_cursor": "cursor-token",
    "has_more": true,
    "total_count": 150
  }
}
GET/v1/invoices/:id#

Invoice detail with timeline

Returns full invoice details including line items and status timeline. Always includes zatca_compliant, zatca_warning_count, zatca_warnings, and resubmit — treat reported/cleared with zatca_compliant: false as accepted-but-not-fully-compliant (do not resubmit). When submission is still in progress or failed, also returns retry_count, next_retry_at, and last_error — use these (or webhooks) after a create returned HTTP 202. Prepayment invoices include remaining_prepaid (unused wallet balance). Tax invoices that settled a 386 include prepaid, payable, and prepaid_invoices.

Requires API Key (Bearer)

Code examples

const res = await fetch(`${BASE}/v1/invoices/${invoiceId}`, {
  headers: { Authorization: `Bearer ${apiKey}` },
});
const invoice = await res.json();

Success response (200)

{
  "invoice_id": "uuid",
  "uuid": "invoice-uuid",
  "invoice_number": "INV-001",
  "metadata": {
    "loan_reference": "LN-2026-01482",
    "contract_id": "C-100"
  },
  "egs_unit_id": "egs-uuid",
  "invoice_type": "simplified",
  "document_type": "invoice",
  "status": "reported",
  "environment": "sandbox",
  "subtotal": 100,
  "vat": 15,
  "total": 115,
  "prepaid": 0,
  "payable": 115,
  "remaining_prepaid": null,
  "prepaid_invoices": [],
  "currency": "SAR",
  "invoice_date": "2025-01-15",
  "invoice_date_hijri": "1446-07-15",
  "reported_at": "2025-01-15T10:05:00.000Z",
  "cleared_at": null,
  "report_deadline": "2025-01-16T10:00:00.000Z",
  "retry_count": 0,
  "next_retry_at": null,
  "last_error": null,
  "zatca_status": "REPORTED",
  "zatca_compliant": true,
  "zatca_warning_count": 0,
  "zatca_warnings": [],
  "resubmit": true,
  "signed_xml_url": "/v1/invoices/uuid/xml",
  "pdf_url": "/v1/invoices/uuid/pdf",
  "buyer": null,
  "qr_code": null,
  "line_items": [
    {
      "line_number": 1,
      "description": "Product A",
      "quantity": 2,
      "unit_price": 50,
      "vat_category": "S",
      "vat_rate": 15,
      "line_total": 115
    }
  ],
  "timeline": [
    {
      "status": "pending",
      "at": "2025-01-15T10:00:00.000Z"
    },
    {
      "status": "submitted",
      "at": "2025-01-15T10:00:05.000Z"
    },
    {
      "status": "reported",
      "at": "2025-01-15T10:05:00.000Z"
    }
  ]
}

Example when status is queued (after HTTP 202)

{
  "invoice_id": "uuid",
  "uuid": "invoice-uuid",
  "status": "queued",
  "retry_count": 2,
  "next_retry_at": "2025-01-15T10:07:00.000Z",
  "last_error": "Fatoora gateway timeout",
  "reported_at": null,
  "cleared_at": null,
  "signed_xml_url": "/v1/invoices/uuid/xml",
  "pdf_url": "/v1/invoices/uuid/pdf",
  "qr_code": "base64-tlv...",
  "timeline": [
    { "status": "pending", "at": "2025-01-15T10:00:00.000Z" },
    { "status": "queued", "at": "2025-01-15T10:00:01.000Z" }
  ]
}
GET/v1/invoices/export/xml#

Download ZIP of approved signed XML

Returns a ZIP of cleared or reported signed XML matching the filters (production or sandbox), plus manifest.json. Each ZIP is capped at 500 invoices because API Gateway/Lambda cannot stream a six-year archive in one HTTP body. If you match more, the first request without part returns 400 EXPORT_TOO_LARGE with parts_total — then GET the same URL with part=0 … part=N-1 using the same Bearer token. Files are not public S3 links. Dashboard Archive auto-downloads those parts.

Requires API Key (Bearer)

Query parameters

NameTypeRequiredDescription
environmentstringNosandbox | production
date_fromstringNoYYYY-MM-DD inclusive
date_tostringNoYYYY-MM-DD inclusive
egs_unit_idstringNo—
document_typestringNoinvoice | credit_note | debit_note | prepayment
partintegerNo0-based ZIP page. Required when the match set is larger than 500. Response headers: X-Export-Part, X-Export-Parts-Total, X-Export-Has-More, X-Export-Total-Count.

Code examples

const res = await fetch(`${BASE}/v1/invoices/export/xml?environment=production&date_from=2025-01-01&date_to=2025-12-31`, {
  headers: { Authorization: `Bearer ${apiKey}` },
});
if (res.status === 400) {
  const err = await res.json();
  if (err.error?.code === 'EXPORT_TOO_LARGE') {
    for (let part = 0; part < err.error.parts_total; part++) {
      const zip = await fetch(`${BASE}/v1/invoices/export/xml?environment=production&date_from=2025-01-01&date_to=2025-12-31&part=${part}`, {
        headers: { Authorization: `Bearer ${apiKey}` },
      });
      // save zip
    }
  }
} else {
  const blob = await res.blob();
}

Success response (200)

(ZIP stream, Content-Type: application/zip; X-Export-Invoice-Count, X-Export-Part, X-Export-Parts-Total)

Error responses

  • 404
    {
      "error": {
        "code": "EXPORT_EMPTY",
        "message": "No cleared or reported invoices match these filters",
        "retryable": false
      }
    }
  • 400
    {
      "error": {
        "code": "EXPORT_TOO_LARGE",
        "message": "This export matches 501 invoices. Download ZIP parts with part=0 … part=1 (500 invoices each). Same Bearer auth — not a public link.",
        "retryable": false,
        "max": 500,
        "total_count": 501,
        "parts_total": 2,
        "part_size": 500
      }
    }
GET/v1/invoices/:id/xml#

Download signed XML

Returns the signed UBL XML for the invoice (from S3 archive or DB when S3 is disabled). Response is application/xml with Content-Disposition attachment. Use for ZATCA compliance and archiving. metadata is not part of this XML. signed_xml_url is null when XML is not stored (e.g. older invoices).

Requires API Key (Bearer)

Code examples

const res = await fetch(`${BASE}/v1/invoices/${invoiceId}/xml`, {
  headers: { Authorization: `Bearer ${apiKey}` },
});
const blob = await res.blob();
// Save or process blob (XML)

Success response (200)

(Binary XML stream with Content-Type: application/xml)

Error responses

  • 404
    {
      "message": "Signed XML not available for this invoice."
    }
GET/v1/invoices/:id/pdf#

Download PDF

Returns a human-readable PDF of the invoice (seller, buyer if B2B, line items, totals). When metadata.loan_reference is set, the PDF header includes it as Loan: …. Other metadata keys are not printed. Use for display, printing, or sending to customers. For ZATCA compliance use the signed XML endpoint instead. Requires the same Bearer token as other invoice endpoints.

Requires API Key (Bearer)

Code examples

const res = await fetch(`${BASE}/v1/invoices/${invoiceId}/pdf`, {
  headers: { Authorization: `Bearer ${apiKey}` },
});
const blob = await res.blob();
// e.g. save or open in new tab
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'invoice.pdf';
a.click();

Success response (200)

(Binary PDF stream with Content-Type: application/pdf)