PHPackages                             mohamedyu3/php-zatca-xml - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. mohamedyu3/php-zatca-xml

ActiveLibrary[Payment Processing](/categories/payments)

mohamedyu3/php-zatca-xml
========================

An unofficial PHP library for generating ZATCA Fatoora e-invoices. This library facilitates the creation of compliant e-invoices, QR Codes, and certificates, as well as the submission of e-invoices to ZATCA's servers. It provides developers with an easy-to-use, customizable, and robust toolkit to integrate and automate ZATCA e-invoicing processes in PHP applications.

v1.0.0(3mo ago)010↓66.7%MITPHPPHP &gt;=8.1

Since Feb 11Pushed 3mo agoCompare

[ Source](https://github.com/mohamedyu3/php-zatca-xml)[ Packagist](https://packagist.org/packages/mohamedyu3/php-zatca-xml)[ Docs](https://github.com/mohamedyu3/php-zatca-xml)[ RSS](/packages/mohamedyu3-php-zatca-xml/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (2)Used By (0)

 [![php-zatca-xml](https://camo.githubusercontent.com/6b56e0214adf2571a539acd383f1e1b55b326ffba7fbc07648fc493860ec288a/68747470733a2f2f692e696d6775722e636f6d2f684c534d7a48552e706e67)](https://camo.githubusercontent.com/6b56e0214adf2571a539acd383f1e1b55b326ffba7fbc07648fc493860ec288a/68747470733a2f2f692e696d6775722e636f6d2f684c534d7a48552e706e67)

[![php Version](https://camo.githubusercontent.com/0052355125dc62414ea2ab4653c3b3d01dc1fddc6c6801cbb26ea911118e6392/68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f7068702f6d6f68616d65647975332f7068702d7a617463612d786d6c)](https://camo.githubusercontent.com/0052355125dc62414ea2ab4653c3b3d01dc1fddc6c6801cbb26ea911118e6392/68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f7068702f6d6f68616d65647975332f7068702d7a617463612d786d6c)[![Packagist Stars](https://camo.githubusercontent.com/569b8e5de59aeca6488ab08a03e8e8f5e5e4ec7fbd14e75dfee4a1bc236802dc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f73746172732f6d6f68616d65647975332f7068702d7a617463612d786d6c)](https://packagist.org/packages/mohamedyu3/php-zatca-xml)[![Packagist Downloads](https://camo.githubusercontent.com/5663b174678a7313a9c652c2da9e7f77f9d25dec7bfa7046f6f6eb98e37c4e40/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6f68616d65647975332f7068702d7a617463612d786d6c)](https://packagist.org/packages/mohamedyu3/php-zatca-xml)[![Packagist Version](https://camo.githubusercontent.com/d2844550b42a58385816273a673739c1c92fb0e413d24e06671e4ea2167776fb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6f68616d65647975332f7068702d7a617463612d786d6c)](https://packagist.org/packages/mohamedyu3/php-zatca-xml)[![License](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://packagist.org/packages/mohamedyu3/php-zatca-xml)

Please feel free to [**contribute**](https://github.com/Mohamedyu3/php-zatca-xml/pulls?q=sort%3Aupdated-desc+is%3Apr+is%3Aopen) if you are missing features or tags
[View Examples](https://github.com/Mohamedyu3/php-zatca-xml/tree/main/examples)· [Report a bug](https://github.com/Mohamedyu3/php-zatca-xml/issues)· [Request a feature](https://github.com/Mohamedyu3/php-zatca-xml/issues)· [Ask questions](https://github.com/Mohamedyu3/php-zatca-xml/discussions)

📖 Introduction
--------------

[](#-introduction)

**PHP-ZATCA-XML** is an unofficial PHP library for generating **ZATCA Fatoora** e-invoices. It simplifies the process of creating compliant e-invoices, generating QR codes, handling certificates, and submitting invoices to **ZATCA’s servers**.

Designed for **easy integration**, this library provides developers with a **customizable, robust, and efficient toolkit** to automate the ZATCA e-invoicing process in PHP applications.

🚀 Planned Features
------------------

[](#-planned-features)

We are actively working on expanding the capabilities of this library. If you're a developer and would like to contribute, your help is highly appreciated! 💡

- **XML to JSON Conversion** – Support for converting invoices from XML to JSON format.
- **JSON/Array to Invoice** – Ability to generate invoices directly from JSON or array structures.
- **Simplified Invoice Creation** – Streamlined generation of **Simplified Invoices**, **Debit**, and **Credit** compliant with ZATCA simplified.
- **Standard Invoice Creation** – Streamlined generation **Standard Invoices**, **Debit**, and **Credit** compliant with ZATCA standards.
- **Invoice to PDF Conversion** – Generate PDF versions of invoices for easy sharing and record-keeping.

💡 **Got an idea?** Feel free to suggest it or contribute!
Let's build something great together! 🚀

✨ Features
----------

[](#-features)

- 🚀 **ZATCA-Compliant** – Easily generate valid e-invoices for ZATCA regulations
- 📜 **Invoice Creation** – Generate standard and simplified invoices in XML format
- 🔐 **Digital Signing** – Sign invoices securely to ensure compliance
- 🏷 **QR Code Generation** – Automatically generate QR codes for invoices
- 📡 **Direct Submission to ZATCA** – Send invoices directly to ZATCA’s servers
- ⚡ **Lightweight &amp; Fast** – Optimized for performance and easy integration in PHP projects
- 🔄 **Customizable &amp; Extensible** – Easily adapt the library to your needs

📌 Requirements
--------------

[](#-requirements)

### ✅ PHP Version

[](#-php-version)

- **PHP 8.1 or higher**

### ✅ Required PHP Extensions

[](#-required-php-extensions)

Ensure the following PHP extensions are installed and enabled:

- **`ext-dom`**
- **`ext-libxml`**
- **`ext-openssl`**
- **`ext-hash`**
- **`ext-mbstring`**

🛠 Installation
--------------

[](#-installation)

```
composer require mohamedyu3/php-zatca-xml
```

🚀 Usage
-------

[](#-usage)

This library simplifies the process of generating **ZATCA-compliant** e-invoices, handling **certificates**, signing invoices, and submitting them to **ZATCA’s API**. Below are the main usage examples:

---

### 📜 **1. Generating a Compliance Certificate**

[](#-1-generating-a-compliance-certificate)

First, generate a **certificate signing request (CSR)** and private key:

```
use Mohamedyu3\Zatca\CertificateBuilder;
use Mohamedyu3\Zatca\Exceptions\CertificateBuilderException;

try {
    (new CertificateBuilder())
        ->setOrganizationIdentifier('312345678901233') // The Organization Identifier must be 15 digits, starting andending with 3
        // string $solutionName .. The solution provider name
        // string $model .. The model of the unit the stamp is being generated for
        // string $serialNumber .. # If you have multiple devices each should have a unique serial number
        ->setSerialNumber('Saleh', '1n', 'SME00023')
        ->setCommonName('My Organization') // The common name to be used in the certificate
        ->setCountryName('SA') // The Country name must be Two chars only
        ->setOrganizationName('My Company') // The name of your organization
        ->setOrganizationalUnitName('IT Department') // A subunit in your organizatio
        ->setAddress('Riyadh 1234 Street') // like Riyadh 1234 Street
        ->setInvoiceType(1100)// # Four digits, each digit acting as a bool. The order is as follows: Standard Invoice, Simplified, future use, future use
        ->setProduction(false)// true = Production |  false = Testing
        ->setBusinessCategory('Technology') // Your business category like food, real estate, etc

        ->generateAndSave('output/certificate.csr', 'output/private.pem');

    echo "Certificate and private key saved.\n";
} catch (CertificateBuilderException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}
```

### 🔐 **2. Requesting a Compliance Certificate from ZATCA**

[](#-2-requesting-a-compliance-certificate-from-zatca)

Once the CSR is generated, you need to request a **compliance certificate** from **ZATCA's API**.

```
use Mohamedyu3\Zatca\ZatcaAPI;
use Mohamedyu3\Zatca\Exceptions\ZatcaApiException;

$zatcaClient = new ZatcaAPI('sandbox');

try {
    $otp = "123123"; // The OTP received from ZATCA
    $certificatePath = __DIR__ . '/output/certificate.csr';

    // Load the generated CSR
    $csr = $zatcaClient->loadCSRFromFile($certificatePath);

    // Request the compliance certificate from ZATCA
    $complianceResult = $zatcaClient->requestComplianceCertificate($csr, $otp);

    // Display the returned certificate and API secret
    echo "Compliance Certificate:\n" . $complianceResult->getCertificate() . "\n";
    echo "API Secret: " . $complianceResult->getSecret() . "\n";
    echo "Request ID: " . $complianceResult->getRequestId() . "\n";

    // Save the certificate details to a JSON file
    $outputFile = __DIR__ . '/output/ZATCA_certificate_data.json';
    $zatcaClient->saveToJson(
        $complianceResult->getCertificate(),
        $complianceResult->getSecret(),
        $complianceResult->getRequestId(),
        $outputFile
    );

    echo "Certificate data saved to {$outputFile}\n";

} catch (ZatcaApiException $e) {
    echo "API Error: " . $e->getMessage();
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

### 🧾 **3. Generating an Invoice XML**

[](#-3-generating-an-invoice-xml)

Now that we have the compliance certificate, we can generate a **ZATCA-compliant e-invoice in XML format**.

```
use Mohamedyu3\Zatca\{
    SignatureInformation, UBLDocumentSignatures, ExtensionContent, UBLExtension, UBLExtensions, Signature,
    InvoiceType, AdditionalDocumentReference, TaxScheme, PartyTaxScheme, Address, LegalEntity, Delivery,
    Party, PaymentMeans, TaxCategory, AllowanceCharge, TaxSubTotal, TaxTotal, LegalMonetaryTotal,
    ClassifiedTaxCategory, Item, Price, InvoiceLine, GeneratorInvoice, Invoice, UnitCode,
    OrderReference, BillingReference, Contract, Attachment, Storage
};

// --- Invoice Type ---
$invoiceType = (new InvoiceType())
    ->setInvoice('standard') // 'standard' or 'simplified'
    ->setInvoiceType('invoice') // 'invoice', 'debit', or 'credit', 'prepayment'
    ->setIsThirdParty(false) // Third-party transaction
    ->setIsNominal(false) // Nominal transaction
    ->setIsExportInvoice(false) // Export invoice
    ->setIsSummary(false) // Summary invoice
    ->setIsSelfBilled(false); // Self-billed invoice

// --- Supplier & Customer Information ---
$taxScheme = (new TaxScheme())->setId("VAT");

$partyTaxSchemeSupplier = (new PartyTaxScheme())->setTaxScheme($taxScheme)->setCompanyId('311111111101113');
$partyTaxSchemeCustomer = (new PartyTaxScheme())->setTaxScheme($taxScheme);

$address = (new Address())
    ->setStreetName('Prince Sultan Street')
    ->setBuildingNumber("2322")
    ->setPlotIdentification("2223")
    ->setCitySubdivisionName('Riyadh')
    ->setCityName('Riyadh')
    ->setPostalZone('23333')
    ->setCountry('SA');

// --- Delivery ---
$delivery = (new Delivery())->setActualDeliveryDate(date('Y-m-d'));

// --- Additional Document References ---
$additionalDocs = [];
$additionalDocs[] = (new AdditionalDocumentReference())
    ->setId('ICV')
    ->setUUID("23"); //Invoice counter value
$additionalDocs[] = (new AdditionalDocumentReference())
    ->setId('PIH')
    ->setAttachment($attachment); // Previous Invoice Hash
    // ->setPreviousInvoiceHash('NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ=='); // Previous Invoice Hash
$additionalDocs[] = (new AdditionalDocumentReference())
    ->setId('QR');

$legalEntity = (new LegalEntity())->setRegistrationName('Acme Widget’s LTD');

$supplierCompany = (new Party())
    ->setPartyIdentification("311111111111113")
    ->setPartyIdentificationId("CRN")
    ->setLegalEntity($legalEntity)
    ->setPartyTaxScheme($partyTaxSchemeSupplier)
    ->setPostalAddress($address);

$supplierCustomer = (new Party())
    ->setPartyIdentification("311111111111113")
    ->setPartyIdentificationId("NAT")
    ->setLegalEntity($legalEntity)
    ->setPartyTaxScheme($partyTaxSchemeCustomer)
    ->setPostalAddress($address);

// --- Invoice Items & Pricing ---
$classifiedTax = (new ClassifiedTaxCategory())->setPercent(15)->setTaxScheme($taxScheme);
$productItem = (new Item())->setName('Pencil')->setClassifiedTaxCategory($classifiedTax);
$price = (new Price())->setUnitCode(UnitCode::UNIT)->setPriceAmount(2);

$lineTaxTotal = (new TaxTotal())->setTaxAmount(0.60)->setRoundingAmount(4.60);

$invoiceLine = (new InvoiceLine())
    ->setUnitCode("PCE")
    ->setId(1)
    ->setItem($productItem)
    ->setLineExtensionAmount(4)
    ->setPrice($price)
    ->setTaxTotal($lineTaxTotal)
    ->setInvoicedQuantity(2);

$invoiceLines = [$invoiceLine];

// --- Tax Totals ---
$taxCategory = (new TaxCategory)
    ->setPercent(15)
    ->setTaxScheme($taxScheme);
$taxSubTotal = (new TaxSubTotal)
    ->setTaxableAmount(4)
    ->setTaxAmount(0.6)
    ->setTaxCategory($taxCategory);
$taxTotal = (new TaxTotal)
    ->addTaxSubTotal($taxSubTotal)
    ->setTaxAmount(0.6);

// --- Legal Monetary Total ---
$legalMonetaryTotal = (new LegalMonetaryTotal())
    ->setLineExtensionAmount(4)
    ->setTaxExclusiveAmount(4)
    ->setTaxInclusiveAmount(4.60)
    ->setPrepaidAmount(0)
    ->setPayableAmount(4.60)
    ->setAllowanceTotalAmount(0);

// --- Build the Invoice ---
$invoice = (new Invoice())
    ->setUUID('3cf5ee18-ee25-44ea-a444-2c37ba7f28be')
    ->setId('SME00023')
    ->setIssueDate(new DateTime())
    ->setIssueTime(new DateTime())
    ->setInvoiceType($invoiceType)
    ->setInvoiceCurrencyCode('SAR')
    ->setTaxCurrencyCode('SAR')
    ->setDelivery($delivery)
    ->setAccountingSupplierParty($supplierCompany)
    ->setAccountingCustomerParty($supplierCustomer)
    ->setAdditionalDocumentReferences($additionalDocs)
    ->setTaxTotal($taxTotal)
    ->setLegalMonetaryTotal($legalMonetaryTotal)
    ->setInvoiceLines($invoiceLines);
    // ......
// --- Generate XML ---
try {
    $generatorXml = GeneratorInvoice::invoice($invoice);
    $outputXML = $generatorXml->getXML();

    // Save the XML to a file
    $filePath = __DIR__ . '/output/unsigned_invoice.xml';
    (new Storage)->put($filePath, $outputXML);

    echo "Invoice XML saved to: " . $filePath . "\n";

} catch (\Exception $e) {
    echo "An error occurred: " . $e->getMessage() . "\n";
    exit(1);
}
```

### ✍️ **4. Signing the Invoice XML**

[](#️-4-signing-the-invoice-xml)

Before submitting the invoice to **ZATCA**, we need to **digitally sign** it using the **compliance certificate** obtained earlier.

```
use Mohamedyu3\Zatca\Helpers\Certificate;
use Mohamedyu3\Zatca\InvoiceSigner;
use Mohamedyu3\Zatca\Storage;

// Load the unsigned invoice XML
$xmlInvoice = (new Storage)->get(__DIR__ . '/output/unsigned_invoice.xml');

// Load the compliance certificate data from the JSON file
$json_certificate = (new Storage)->get(__DIR__ . '/output/ZATCA_certificate_data.json');

// Decode the JSON data
$json_data = json_decode($json_certificate, true, 512, JSON_THROW_ON_ERROR);

// Extract certificate details
$certificate = $json_data['certificate'];
$secret = $json_data['secret'];

// Load the private key
$privateKey = (new Storage)->get(__DIR__ . '/output/private.pem');
$cleanPrivateKey = trim(str_replace(["-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"], "", $privateKey));

// Create a Certificate instance
$certificate = new Certificate(
    $certificate,
    $cleanPrivateKey,
    $secret
);

// Sign the invoice
$signedInvoice = InvoiceSigner::signInvoice($xmlInvoice, $certificate)->getXML();
// Save the signed invoice
(new Storage)->put(__DIR__.'/output/signed_invoice.xml', $signedInvoice);
```

### 📤 **5. Submitting the Signed Invoice to ZATCA**

[](#-5-submitting-the-signed-invoice-to-zatca)

Once the invoice is **digitally signed**, it can be submitted to **ZATCA’s API** for compliance validation and clearance.

Contributing
------------

[](#contributing)

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

👨‍💻 Contributors
----------------

[](#‍-contributors)

[![](https://github.com/sevaske.png)](https://github.com/sevaske.png)
[sevaske](https://github.com/sevaske)

Thank you all for your continuous support and contributions!

### Special Credits

[](#special-credits)

This project has also benefited from some code snippets and ideas from the [SallaApp/ZATCA](https://github.com/SallaApp/ZATCA) repository. We appreciate their contribution to the community.

License
-------

[](#license)

This project is licensed under the [MIT License](https://github.com/Mohamedyu3/php-zatca-xml/blob/main/LICENSE).

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance82

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 80% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

97d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/af44d1b429cfdec1789c6259989e3a7c6eb54402a8cd359447c34bbaca4bb409?d=identicon)[mohamedyu3](/maintainers/mohamedyu3)

---

Top Contributors

[![Saleh7](https://avatars.githubusercontent.com/u/5176469?v=4)](https://github.com/Saleh7 "Saleh7 (56 commits)")[![sevaske](https://avatars.githubusercontent.com/u/42838184?v=4)](https://github.com/sevaske "sevaske (10 commits)")[![myousrycds](https://avatars.githubusercontent.com/u/242933890?v=4)](https://github.com/myousrycds "myousrycds (4 commits)")

---

Tags

qr codexmlinvoiceE-Invoiceublinvoiceelectronic invoicexml invoiceubl invoicedigital invoiceZATCAzatca-xmlfatoora

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mohamedyu3-php-zatca-xml/health.svg)

```
[![Health](https://phpackages.com/badges/mohamedyu3-php-zatca-xml/health.svg)](https://phpackages.com/packages/mohamedyu3-php-zatca-xml)
```

###  Alternatives

[saleh7/php-zatca-xml

An unofficial PHP library for generating ZATCA Fatoora e-invoices. This library facilitates the creation of compliant e-invoices, QR Codes, and certificates, as well as the submission of e-invoices to ZATCA's servers. It provides developers with an easy-to-use, customizable, and robust toolkit to integrate and automate ZATCA e-invoicing processes in PHP applications.

5112.5k](/packages/saleh7-php-zatca-xml)[sevaske/php-zatca-xml

An unofficial PHP library for generating ZATCA Fatoora e-invoices. This library facilitates the creation of compliant e-invoices, QR Codes, and certificates, as well as the submission of e-invoices to ZATCA's servers. It provides developers with an easy-to-use, customizable, and robust toolkit to integrate and automate ZATCA e-invoicing processes in PHP applications.

193.3k1](/packages/sevaske-php-zatca-xml)[num-num/ubl-invoice

A modern object-oriented PHP library to create and read valid UBL and EN 16931/Peppol BIS 3.0 files

135820.5k](/packages/num-num-ubl-invoice)[cleverit/ubl_invoice

A PHP wrapper for UBL invoices

36283.4k](/packages/cleverit-ubl-invoice)[atgp/factur-x

PHP library to manage your Factur-X / ZUGFeRD 2.0 PDF invoices files

138825.5k3](/packages/atgp-factur-x)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
