PHPackages                             saleh7/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. saleh7/php-zatca-xml

ActiveLibrary[Payment Processing](/categories/payments)

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.

v2.4(3mo ago)5618.1k—8.7%31MITPHPPHP &gt;=8.1CI passing

Since Jan 9Pushed 3mo ago8 watchersCompare

[ Source](https://github.com/Saleh7/php-zatca-xml)[ Packagist](https://packagist.org/packages/saleh7/php-zatca-xml)[ Docs](https://github.com/Saleh7/php-zatca-xml)[ RSS](/packages/saleh7-php-zatca-xml/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (6)Dependencies (8)Versions (7)Used By (0)

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

[![php Version](https://camo.githubusercontent.com/9f4cfe1e3ec2db93a11ae84848e930ea2df06019c99d2a2a5951176f463312bd/68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f7068702f73616c6568372f7068702d7a617463612d786d6c)](https://camo.githubusercontent.com/9f4cfe1e3ec2db93a11ae84848e930ea2df06019c99d2a2a5951176f463312bd/68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f7068702f73616c6568372f7068702d7a617463612d786d6c)[![Packagist Stars](https://camo.githubusercontent.com/c3d0308aaf32ec9188b4bdf6d139c3f0e1a97e44d47fa3eaf209393d9d4ea36f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f73746172732f73616c6568372f7068702d7a617463612d786d6c)](https://packagist.org/packages/saleh7/php-zatca-xml)[![Packagist Downloads](https://camo.githubusercontent.com/c98396e2c5344c4d7df84bf14a30251f938ef22ea9f761548c58168b908ae96c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616c6568372f7068702d7a617463612d786d6c)](https://packagist.org/packages/saleh7/php-zatca-xml)[![Packagist Version](https://camo.githubusercontent.com/1aa7621fbc820508427965d58ad1186a4496372b5c04911ce860ea21b59f55c1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616c6568372f7068702d7a617463612d786d6c)](https://packagist.org/packages/saleh7/php-zatca-xml)[![License](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://packagist.org/packages/saleh7/php-zatca-xml)

[View Examples](https://github.com/Saleh7/php-zatca-xml/tree/main/examples) · [Report a bug](https://github.com/Saleh7/php-zatca-xml/issues) · [Discussions](https://github.com/Saleh7/php-zatca-xml/discussions)

> ✅ **Production Tested** — Full onboarding flow (CSR → Compliance → 6 Invoice Types → Production Certificate → Invoice Reporting) successfully tested against ZATCA production API on **March 31, 2026** using **Ubuntu 24.04 / PHP 8.4**.

Introduction
------------

[](#introduction)

**PHP-ZATCA-XML** is a PHP library for generating ZATCA-compliant e-invoices (Fatoora). It handles the full lifecycle: certificate generation, XML invoice creation, digital signing, QR codes, and API submission to ZATCA.

Built to match the official **ZATCA Java SDK (R3.4.8)** specifications: secp256k1 keys, SHA256withECDSA signatures, UBL 2.1 XML, and all three environment tiers.

Features
--------

[](#features)

- **Certificate Builder** aligned with ZATCA SDK (CSR generation, secp256k1, proper DN order, Arabic support)
- **Invoice Generation** for Standard and Simplified invoices (Invoice, Credit Note, Debit Note)
- **Digital Signing** with XAdES-BES enveloped signatures
- **QR Code Generation** per ZATCA TLV specification
- **Full API Client** covering all 6 ZATCA endpoints (compliance, production, reporting, clearance, renewal)
- **Response Objects** with typed accessors for validation results, warnings, and errors
- **Data Mapper** to build invoices from arrays/JSON (e-commerce integration)

Requirements
------------

[](#requirements)

- PHP 8.1+
- Extensions: `ext-dom`, `ext-openssl`, `ext-hash`, `ext-mbstring`

Installation
------------

[](#installation)

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

Quick Start: Production Onboarding
----------------------------------

[](#quick-start-production-onboarding)

The full ZATCA onboarding flow in 4 steps:

### Step 1: Generate CSR + Private Key

[](#step-1-generate-csr--private-key)

> 📄 Full example: [`examples/Certificates/GeneratorCertificate.php`](examples/Certificates/GeneratorCertificate.php)

```
use Saleh7\Zatca\CertificateBuilder;

(new CertificateBuilder)
    ->setOrganizationIdentifier('3XXXXXXXXXXXXX3')   // 15-digit VAT number
    ->setSerialNumber('ERP', '1.0', 'unique-device-uuid')
    ->setCommonName('ERP-886431145-3XXXXXXXXXXXXX3')
    ->setCountryName('SA')
    ->setOrganizationName('Your Company Name')       // Arabic supported
    ->setOrganizationalUnitName('Branch Name')
    ->setAddress('RRRD2929')
    ->setInvoiceType('1100')                         // Standard + Simplified
    ->setEnvironment(CertificateBuilder::ENV_PRODUCTION)
    ->setBusinessCategory('Supply activities')
    ->generateAndSave('output/certificate.csr', 'output/private.pem');
```

**Environment options:**

- `ENV_PRODUCTION` → `ZATCA-Code-Signing` (live)
- `ENV_NONPROD` → `TSTZATCA-Code-Signing` (sandbox/test)
- `ENV_SIMULATION` → `PREZATCA-Code-Signing` (pre-production)

### Step 2: Request Compliance Certificate (CCSID)

[](#step-2-request-compliance-certificate-ccsid)

> 📄 Full example: [`examples/Certificates/RequestComplianceCertificate.php`](examples/Certificates/RequestComplianceCertificate.php)

Get an OTP from [fatoora.zatca.gov.sa](https://fatoora.zatca.gov.sa), then:

```
use Saleh7\Zatca\ZatcaAPI;

$api = new ZatcaAPI('production'); // or 'sandbox', 'simulation'
$csr = file_get_contents('output/certificate.csr');

$result = $api->requestComplianceCertificate($csr, $otp);

$api->saveToJson(
    $result->getCertificate(),
    $result->getSecret(),
    $result->getRequestId(),
    'output/compliance_credentials.json'
);
```

### Step 3: Compliance Check (6 Invoice Types)

[](#step-3-compliance-check-6-invoice-types)

> 📄 Full automated example: [`examples/Certificates/ComplianceCheck.php`](examples/Certificates/ComplianceCheck.php)

Submit 6 test invoices to pass compliance validation:

```
$creds = json_decode(file_get_contents('output/compliance_credentials.json'), true);

$response = $api->validateInvoiceCompliance(
    $creds['certificate'],
    $creds['secret'],
    $signedInvoiceXml,
    $invoiceHash,
    $uuid
);

if ($response->isSuccess()) {
    echo "PASS: " . $response->getValidationStatus();
}
```

Required types: Standard Invoice, Standard Credit Note, Standard Debit Note, Simplified Invoice, Simplified Credit Note, Simplified Debit Note.

> See [`examples/Certificates/ComplianceCheck.php`](examples/Certificates/ComplianceCheck.php) for an automated script that generates, signs, and submits all 6 types.

### Step 4: Request Production Certificate (PCSID)

[](#step-4-request-production-certificate-pcsid)

> 📄 Included automatically in [`examples/Certificates/ComplianceCheck.php`](examples/Certificates/ComplianceCheck.php)

After all 6 invoices pass:

```
$prodResult = $api->requestProductionCertificate(
    $creds['certificate'],
    $creds['secret'],
    $creds['requestId']
);

$api->saveToJson(
    $prodResult->getCertificate(),
    $prodResult->getSecret(),
    $prodResult->getRequestId(),
    'output/production_credentials.json'
);
```

Submitting Invoices
-------------------

[](#submitting-invoices)

### Reporting (B2C / Simplified)

[](#reporting-b2c--simplified)

> 📄 Full example: [`examples/InvoiceSimplified/simplified_invoice.php`](examples/InvoiceSimplified/simplified_invoice.php)

```
$prod = json_decode(file_get_contents('output/production_credentials.json'), true);

$response = $api->submitReportingInvoice(
    $prod['certificate'], $prod['secret'],
    $signedXml, $invoiceHash, $uuid
);

$response->isReported();         // true if REPORTED
$response->getReportingStatus(); // "REPORTED"
$response->getValidationStatus();
$response->getWarningMessages();
$response->getErrorMessages();
```

### Clearance (B2B / Standard)

[](#clearance-b2b--standard)

> 📄 Full example: [`examples/InvoiceStandard/standard_invoice.php`](examples/InvoiceStandard/standard_invoice.php)

```
$response = $api->submitClearanceInvoice(
    $prod['certificate'], $prod['secret'],
    $signedXml, $invoiceHash, $uuid
);

$response->isCleared();                // true if CLEARED
$response->getClearedInvoice();        // Base64 stamped invoice
$response->getDecodedClearedInvoice(); // XML string
```

### Certificate Renewal

[](#certificate-renewal)

```
$renewed = $api->renewProductionCertificate(
    $prod['certificate'], $prod['secret'],
    $newCsr, $otp
);
```

Invoice Generation
------------------

[](#invoice-generation)

### From Array (e-commerce integration)

[](#from-array-e-commerce-integration)

```
use Saleh7\Zatca\Mappers\InvoiceMapper;
use Saleh7\Zatca\GeneratorInvoice;

$invoiceData = [
    'uuid'            => '3cf5ee18-ee25-44ea-a444-2c37ba7f28be',
    'id'              => 'INV-001',
    'issueDate'       => '2025-01-15',
    'issueTime'       => '14:30:00',
    'currencyCode'    => 'SAR',
    'taxCurrencyCode' => 'SAR',
    'invoiceType'     => [
        'invoice' => 'simplified',  // or 'standard'
        'type'    => 'invoice',     // 'invoice', 'credit', or 'debit'
    ],
    'supplier' => [
        'registrationName' => 'Your Company',
        'taxId'            => '3XXXXXXXXXXXXX3',
        'identificationId' => 'XXXXXXXXXX',
        'identificationType' => 'CRN',
        'address' => [
            'street' => 'Main Street', 'buildingNumber' => '1234',
            'subdivision' => 'District', 'city' => 'Riyadh',
            'postalZone' => '12345', 'country' => 'SA',
        ],
    ],
    'invoiceLines' => [
        [
            'id' => 1, 'unitCode' => 'PCE', 'quantity' => 2,
            'lineExtensionAmount' => 200,
            'item' => [
                'name' => 'Product Name',
                'classifiedTaxCategory' => [['percent' => 15, 'taxScheme' => ['id' => 'VAT']]],
            ],
            'price' => ['amount' => 100, 'unitCode' => 'UNIT'],
            'taxTotal' => ['taxAmount' => 30, 'roundingAmount' => 230],
        ],
    ],
    // ... taxTotal, legalMonetaryTotal, etc.
];

$invoice = (new InvoiceMapper())->mapToInvoice($invoiceData);
$xml = GeneratorInvoice::invoice($invoice)->getXML();
```

### Signing

[](#signing)

```
use Saleh7\Zatca\Helpers\Certificate;
use Saleh7\Zatca\InvoiceSigner;

$certificate = new Certificate($certString, $privateKeyString, $secret);
$signer = InvoiceSigner::signInvoice($xml, $certificate);

$signedXml   = $signer->getInvoice();
$invoiceHash = $signer->getHash();
```

API Reference
-------------

[](#api-reference)

MethodEndpointReturns`requestComplianceCertificate($csr, $otp)`POST /compliance`ComplianceCertificateResult``validateInvoiceCompliance(...)`POST /compliance/invoices`ComplianceInvoiceResponse``requestProductionCertificate(...)`POST /production/csids`ProductionCertificateResult``renewProductionCertificate(...)`PATCH /production/csids`ProductionCertificateResult``submitReportingInvoice(...)`POST /invoices/reporting/single`ReportingResponse``submitClearanceInvoice(...)`POST /invoices/clearance/single`ClearanceResponse`All response objects extend `ApiResponse` with: `isSuccess()`, `hasWarnings()`, `hasErrors()`, `getValidationStatus()`, `getWarningMessages()`, `getErrorMessages()`, `toArray()`.

Examples
--------

[](#examples)

FileDescription[`Certificates/GeneratorCertificate.php`](examples/Certificates/GeneratorCertificate.php)Generate CSR + private key[`Certificates/RequestComplianceCertificate.php`](examples/Certificates/RequestComplianceCertificate.php)Request compliance certificate[`Certificates/ComplianceCheck.php`](examples/Certificates/ComplianceCheck.php)Automated 6-invoice compliance + production cert[`InvoiceSimplified/simplified_invoice.php`](examples/InvoiceSimplified/simplified_invoice.php)Simplified invoice generation + signing[`InvoiceStandard/standard_invoice.php`](examples/InvoiceStandard/standard_invoice.php)Standard invoice generation + signingContributing
------------

[](#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)[![](https://github.com/habibalkhabbaz.png)](https://github.com/habibalkhabbaz)

License
-------

[](#license)

[MIT License](https://github.com/Saleh7/php-zatca-xml/blob/main/LICENSE)

###  Health Score

54

—

FairBetter than 96% of packages

Maintenance82

Actively maintained with recent releases

Popularity43

Moderate usage in the ecosystem

Community19

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 84.9% 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

Every ~236 days

Recently: every ~103 days

Total

6

Last Release

90d ago

Major Versions

v1.0 → v2.02025-02-14

PHP version history (2 changes)v1.0PHP ^7.4||^8.1

v2.0PHP &gt;=8.1

### Community

Maintainers

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

---

Top Contributors

[![Saleh7](https://avatars.githubusercontent.com/u/5176469?v=4)](https://github.com/Saleh7 "Saleh7 (62 commits)")[![sevaske](https://avatars.githubusercontent.com/u/42838184?v=4)](https://github.com/sevaske "sevaske (10 commits)")[![habibalkhabbaz](https://avatars.githubusercontent.com/u/31035020?v=4)](https://github.com/habibalkhabbaz "habibalkhabbaz (1 commits)")

---

Tags

certificates-generatore-invoicesfatoorainvoicephpqrcodexmlzatcaqr codexmlinvoiceE-Invoiceublinvoiceelectronic invoicexml invoiceubl invoicedigital invoiceZATCAzatca-xmlfatoora

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[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.

2113.9k1](/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

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

A PHP wrapper for UBL invoices

36287.1k](/packages/cleverit-ubl-invoice)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

751291.4k43](/packages/civicrm-civicrm-core)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M577](/packages/shopware-core)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

273.0k](/packages/eslazarev-wildberries-sdk)

PHPackages © 2026

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