PHPackages                             sevaske/zatca-api - 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. sevaske/zatca-api

ActiveLibrary

sevaske/zatca-api
=================

2.0.2(3mo ago)43.5k—6.6%31MITPHPPHP ^7.4||^8.0CI passing

Since Jul 9Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/sevaske/zatca-api)[ Packagist](https://packagist.org/packages/sevaske/zatca-api)[ RSS](/packages/sevaske-zatca-api/feed)WikiDiscussions v2 Synced 1mo ago

READMEChangelog (7)Dependencies (7)Versions (9)Used By (1)

[![php Version](https://camo.githubusercontent.com/0b3954e6fc6c9801eaae54623e1402030ba579e12a0b5110c78beaf28a83f623/68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f7068702f73657661736b652f7a617463612d617069)](https://camo.githubusercontent.com/0b3954e6fc6c9801eaae54623e1402030ba579e12a0b5110c78beaf28a83f623/68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f7068702f73657661736b652f7a617463612d617069)[![Packagist Stars](https://camo.githubusercontent.com/465b0dddc011500d0e1be305932c41c68bd7f155de63bfdfecbdce60623142f1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f73746172732f73657661736b652f7a617463612d617069)](https://packagist.org/packages/sevaske/zatca-api)[![Packagist Downloads](https://camo.githubusercontent.com/25a932c61139379b851bdee5bbb489d8ff19590e68a01aab3de7d3ca2f39e026/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73657661736b652f7a617463612d617069)](https://packagist.org/packages/sevaske/zatca-api)[![Packagist Version](https://camo.githubusercontent.com/4b8dc060f37db8164dc8f7928dd9a7d0ff12b7f18fc290e22b59b2efa84c5493/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73657661736b652f7a617463612d617069)](https://packagist.org/packages/sevaske/zatca-api)[![License](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://packagist.org/packages/sevaske/zatca-api)

ZATCA API PHP Client
====================

[](#zatca-api-php-client)

This is a simple PHP library to work with the ZATCA API. You can send invoice data and manage certificates easily.

⚠️ **Note:** This is an unofficial library and not maintained by ZATCA. I do not provide personal support or consulting.

If you’re looking for a library to generate XML invoices, you can use this one:

---

Features
--------

[](#features)

- Full coverage of ZATCA API endpoints (reporting, clearance, compliance)
- Authentication via certificate and secret or auth token
- Supports middleware for request/response processing
- Typed response objects for easy validation and error handling
- Supports multiple environments: sandbox, simulation, production
- Follows PSR standards (PSR-4, PSR-7, PSR-17, PSR-18)
- Works with any PSR-18 compatible HTTP client (e.g., Guzzle)

Environments
------------

[](#environments)

EnvironmentPurposeCertificatessandboxCSR + basic testingSandbox certificatesimulationCompliance invoices (6 required)Compliance certproductionReal invoicesProduction certInvoice types
-------------

[](#invoice-types)

- **Reporting (B2P)**
    Used for invoices issued to consumers.
- **Clearance (B2B)**
    Used for invoices issued to VAT-registered businesses.

Authentication flow
-------------------

[](#authentication-flow)

1. Generate CSR (outside this library)
2. Request compliance certificate
3. Create `ZatcaAuth` from certificate + secret
4. Submit simulation invoices
5. Request production certificate
6. Switch client to `production` environment

Immutability
------------

[](#immutability)

Methods like `withEnvironment()` and `withMiddleware()` return a **new client instance**.
The original client is not modified.

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

[](#installation)

```
composer require sevaske/zatca-api:^2.0
```

Usage
-----

[](#usage)

#### Client Initialization

[](#client-initialization)

Create HTTP client and factories for PSR-17 / PSR-18. For example, GuzzleHttp

```
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use Sevaske\ZatcaApi\ZatcaClient;

$httpClient = new Client();
$factory = new HttpFactory();

// Initialize ZatcaClient with sandbox environment
$client = new ZatcaClient(
    $httpClient,
    $factory, // RequestFactoryInterface
    $factory, // StreamFactoryInterface
    'sandbox' // environment: sandbox | simulation | production
);
```

#### Compliance Certificate Request

[](#compliance-certificate-request)

```
use Sevaske\ZatcaApi\Exceptions\ZatcaRequestException;
use Sevaske\ZatcaApi\Exceptions\ZatcaResponseException;

/**
* @var Sevaske\ZatcaApi\ZatcaClient $client
*/

try {
    $certificateResponse = $client->complianceCertificate('your .csr file content', '112233');
} catch (ZatcaRequestException|ZatcaResponseException $e) {
    // handle
}

$credentials = [
    'requestId' => $certificateResponse->requestId(),
    'certificate' => $certificateResponse->certificate(),
    'secret' => $certificateResponse->secret(),
];

print_r($credentials);
file_put_contents('output/credentials.json', json_encode($credentials, JSON_PRETTY_PRINT));
```

#### Authorized requests

[](#authorized-requests)

Create AuthToken from compliance certificate to make authorized requests.

```
use Sevaske\ZatcaApi\ZatcaAuth;

/**
* @var Sevaske\ZatcaApi\Responses\CertificateResponse $certificateResponse
* @var Sevaske\ZatcaApi\ZatcaClient $client
*/

$authToken = new ZatcaAuth($certificateResponse->certificate(), $certificateResponse->secret());
$client->setAuthToken($authToken);
```

#### Submitting Invoices

[](#submitting-invoices)

Once you have a valid compliance certificate and auth token, you can submit invoices in the simulation environment.

**Submitting 6 documents is required to switch to production mode.**

```
use Sevaske\ZatcaApi\Exceptions\ZatcaRequestException;
use Sevaske\ZatcaApi\Exceptions\ZatcaResponseException;

/**
* @var Sevaske\ZatcaApi\ZatcaClient $client
*/

try {
    // B2P
    $client->reportingInvoice('b2p invoice xml', 'hash', 'uuid');
    $client->reportingInvoice('b2p debit note xml', 'hash', 'uuid');
    $client->reportingInvoice('b2p credit note xml', 'hash', 'uuid');

    // B2B
    $client->clearanceInvoice('b2b invoice xml', 'hash', 'uuid');
    $client->clearanceInvoice('b2b debit note xml', 'hash', 'uuid');
    $client->clearanceInvoice('b2b credit note xml', 'hash', 'uuid');
} catch (ZatcaRequestException|ZatcaResponseException $e) {
    // handle
}
```

#### Production Onboarding

[](#production-onboarding)

After submitting the required simulation invoices, you can request a production certificate.

**This certificate allows you to submit real invoices in the production environment.**

```
use Sevaske\ZatcaApi\Exceptions\ZatcaRequestException;
use Sevaske\ZatcaApi\Exceptions\ZatcaResponseException;

/**
* @var \Sevaske\ZatcaApi\ZatcaClient $client
*/

try {
    $productionCertificateResponse = $client->productionCertificate($certificateResponse->requestId());

    $credentials = [
        'requestId' => $productionCertificateResponse->requestId(),
        'certificate' => $productionCertificateResponse->certificate(),
        'secret' => $productionCertificateResponse->secret(),
    ];

    // display
    print_r($credentials);

    // save
    file_put_contents('output/production-credentials.json', json_encode($credentials, JSON_PRETTY_PRINT));
} catch (ZatcaRequestException|ZatcaResponseException $e) {
    // handle
}
```

#### Submitting Production Invoices

[](#submitting-production-invoices)

Once the client is configured with the production certificate and environment, you can submit real invoices to ZATCA.

```
use Sevaske\ZatcaApi\ZatcaAuth;
use Sevaske\ZatcaApi\Exceptions\ZatcaRequestException;
use Sevaske\ZatcaApi\Exceptions\ZatcaResponseException;

/**
* @var Sevaske\ZatcaApi\ZatcaClient $client
* @var Sevaske\ZatcaApi\Responses\ProductionCertificateResponse $productionCertificateResponse
*/
$productionClient = $client->withEnvironment('production');
$productionAuth = new ZatcaAuth($productionCertificateResponse->certificate(), $productionCertificateResponse->secret());
$productionClient->setAuthToken($productionAuth);

try {
    // submitting production invoices
    $responseReporting = $productionClient->reportingInvoice('my real B2P invoice xml', 'hash', 'uuid');
    $responseClearance = $productionClient->clearanceInvoice('my real B2B invoice xml', 'hash', 'uuid');
} catch (ZatcaRequestException|ZatcaResponseException $e) {
    // handle
}

print_r($responseReporting->toArray());
print_r($responseClearance->toArray());
```

Middleware
----------

[](#middleware)

Middleware in `ZatcaClient` allows you to inspect, modify, or wrap HTTP requests and responses. It works as a pipeline, meaning that multiple middleware can be chained together, each receiving the request and a `$next` callable that continues to the next middleware and ultimately to the HTTP client.

`ZatcaClient` provides four ways to manage middleware:

1. **`withMiddleware($middleware)`** – returns a **new cloned instance** with the provided middleware. Existing middleware in the original client is **replaced** in the clone.
2. **`setMiddleware($middleware)`** – **mutates the current instance**, replacing its middleware with the given ones.
3. **`attachMiddleware($middleware)`** – **mutates the current instance**, adding the given middleware to the end of the existing middleware stack.
4. **`withoutMiddleware()`** - returns a **new cloned instance** with no middleware attached.

All middleware must implement the `MiddlewareInterface`:

```
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface MiddlewareInterface
{
    /**
     * @param RequestInterface $request The incoming request
     * @param callable $next Callable to forward the request to the next middleware or the HTTP client
     * @return ResponseInterface
     */
    public function handle(RequestInterface $request, callable $next): ResponseInterface;
}
```

#### Example

[](#example)

For example, implementation of "logging" requests and responses:

```
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Sevaske\ZatcaApi\Interfaces\MiddlewareInterface;

// Attach a custom middleware to inspect requests and responses
$client = $client->withMiddleware(new class implements MiddlewareInterface
{
    public function handle(RequestInterface $request, callable $next): ResponseInterface
    {
        // request
        $this->info('URL: ');
        $this->info((string) $request->getUri());
        $this->info('Body: ');
        $this->info($this->safeStreamContents($request->getBody()));

        /**
         * @var $response \Psr\Http\Message\ResponseInterface
         */
        $response = $next($request);

        // response
        $this->info('Response:');
        $this->info($this->safeStreamContents($response->getBody()));

        return $response;
    }

    private function safeStreamContents(\Psr\Http\Message\StreamInterface $stream): string
    {
        if (! $stream->isSeekable()) {
            return '[unseekable stream]';
        }

        // Save original cursor position
        $pos = $stream->tell();

        // Read from beginning
        $stream->rewind();
        $content = $stream->getContents();

        // Restore original cursor
        $stream->seek($pos);

        return $content;
    }

    private function info(string $text): void
    {
        echo "\n\r".$text;
    }
});
```

Exception handling
------------------

[](#exception-handling)

The library throws the following exceptions which you can catch and handle:

- `ZatcaException` — general exception class
- `ZatcaRequestException` — errors during the HTTP request
- `ZatcaResponseException` — errors processing the API response

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance81

Actively maintained with recent releases

Popularity29

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~27 days

Recently: every ~19 days

Total

9

Last Release

95d ago

Major Versions

0.0.1 → v1.02025-07-17

v1.x-dev → 2.0.0-alpha2025-11-26

PHP version history (2 changes)0.0.1PHP ^8.1

2.0.0-alphaPHP ^7.4||^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/94643c38672a39a9b675ab6d43f5c1d3c0789300cc052f742a960e0a7d70847e?d=identicon)[sevaske](/maintainers/sevaske)

---

Top Contributors

[![sevaske](https://avatars.githubusercontent.com/u/42838184?v=4)](https://github.com/sevaske "sevaske (62 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sevaske-zatca-api/health.svg)

```
[![Health](https://phpackages.com/badges/sevaske-zatca-api/health.svg)](https://phpackages.com/packages/sevaske-zatca-api)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[shopify/shopify-api

Shopify API Library for PHP

4634.8M16](/packages/shopify-shopify-api)[swisnl/json-api-client

A PHP package for mapping remote JSON:API resources to Eloquent like models and collections.

211473.2k12](/packages/swisnl-json-api-client)[laudis/neo4j-php-client

Neo4j-PHP-Client is the most advanced PHP Client for Neo4j

184616.9k31](/packages/laudis-neo4j-php-client)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)

PHPackages © 2026

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