PHPackages                             visiaquantum/laravel-fattureincloud-php-sdk - 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. [API Development](/categories/api)
4. /
5. visiaquantum/laravel-fattureincloud-php-sdk

ActiveLibrary[API Development](/categories/api)

visiaquantum/laravel-fattureincloud-php-sdk
===========================================

This package provides a simple, expressive, and robust wrapper around the official Fatture in Cloud PHP SDK. Its primary purpose is to abstract the complexity of the base SDK, offering a Laravel-native developer experience for interacting with the Fatture in Cloud API.

v0.0.2(9mo ago)01[1 PRs](https://github.com/visiaquantum/laravel-fattureincloud-php-sdk/pulls)MITPHPPHP ^8.3CI passing

Since Sep 9Pushed 3mo agoCompare

[ Source](https://github.com/visiaquantum/laravel-fattureincloud-php-sdk)[ Packagist](https://packagist.org/packages/visiaquantum/laravel-fattureincloud-php-sdk)[ Docs](https://github.com/visiaquantum/laravel-fattureincloud-php-sdk)[ RSS](/packages/visiaquantum-laravel-fattureincloud-php-sdk/feed)WikiDiscussions main Synced today

READMEChangelog (2)Dependencies (13)Versions (4)Used By (0)

Laravel Fatture in Cloud PHP SDK
================================

[](#laravel-fatture-in-cloud-php-sdk)

[![Latest Version on Packagist](https://camo.githubusercontent.com/e06f83904b8c5475e7b4b14e1091706c1c2c7cc9a510c42e5342f7b1bf770e81/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f76697369617175616e74756d2f6c61726176656c2d66617474757265696e636c6f75642d7068702d73646b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/visiaquantum/laravel-fattureincloud-php-sdk)[![GitHub Tests Action Status](https://camo.githubusercontent.com/64ac10766f0dde8402ae6e2e0b2d3c6ee151ce967773481e541bee306723a9cd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f76697369617175616e74756d2f6c61726176656c2d66617474757265696e636c6f75642d7068702d73646b2f72756e2d74657374732e796d6c3f6c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/visiaquantum/laravel-fattureincloud-php-sdk/actions?query=workflow%3Arun-tests)[![Total Downloads](https://camo.githubusercontent.com/9544787846cfaacc7d0d6f5ec07ac7708271a39c2d68fc488a1a114dc677f6a7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f76697369617175616e74756d2f6c61726176656c2d66617474757265696e636c6f75642d7068702d73646b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/visiaquantum/laravel-fattureincloud-php-sdk)

A Laravel package that provides a clean, Laravel-native wrapper around the official [Fatture in Cloud PHP SDK](https://github.com/fattureincloud/fattureincloud-php-sdk). This package abstracts the complexity of the base SDK and offers a simplified, Laravel-integrated developer experience for interacting with the Fatture in Cloud API.

The package follows Laravel ecosystem conventions with a clean, simplified architecture that provides OAuth2 authentication flows, token management, and service abstraction for seamless API integration.

Features
--------

[](#features)

- 🚀 **Laravel Native**: Built following Laravel conventions and standards
- 🔐 **OAuth2 Integration**: Complete OAuth2 authorization code flow support
- 💾 **Smart Token Management**: Automatic token storage, refresh, and encryption
- 🏗️ **Clean Architecture**: Interfaces and dependency injection throughout
- 📦 **All API Services**: Full access to all Fatture in Cloud API endpoints
- 🛡️ **Secure**: Built-in security features and encrypted token storage
- 🧪 **Well Tested**: Comprehensive test coverage with Pest PHP

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

[](#requirements)

- PHP 8.4 or higher
- Laravel 11.x or 12.x
- Fatture in Cloud Developer Account

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

[](#installation)

You can install the package via Composer:

```
composer require visiaquantum/laravel-fattureincloud-php-sdk
```

Publish the configuration file:

```
php artisan vendor:publish --tag="laravel-fattureincloud-php-sdk-config"
```

Configuration
-------------

[](#configuration)

### Environment Variables

[](#environment-variables)

Add these variables to your `.env` file:

```
# OAuth2 Credentials (for OAuth2 flow)
FATTUREINCLOUD_CLIENT_ID=your_client_id
FATTUREINCLOUD_CLIENT_SECRET=your_client_secret
FATTUREINCLOUD_REDIRECT_URL=https://yourapp.com/fatture-in-cloud/callback

# OR Manual Authentication (takes precedence if set)
FATTUREINCLOUD_ACCESS_TOKEN=your_access_token
```

### Configuration File

[](#configuration-file)

The published configuration file (`config/fatture-in-cloud.php`) includes comprehensive OAuth2 settings:

```
return [
    'client_id' => env('FATTUREINCLOUD_CLIENT_ID'),
    'client_secret' => env('FATTUREINCLOUD_CLIENT_SECRET'),
    'redirect_url' => env('FATTUREINCLOUD_REDIRECT_URL', config('app.url') . '/fatture-in-cloud/callback'),
    'access_token' => env('FATTUREINCLOUD_ACCESS_TOKEN'),

    // OAuth2 settings
    'base_uri' => env('FATTUREINCLOUD_BASE_URI', 'https://api-v2.fattureincloud.it'),
    'oauth2_base_uri' => env('FATTUREINCLOUD_OAUTH2_BASE_URI', 'https://api-v2.fattureincloud.it'),

    // Token storage settings
    'token_cache_prefix' => 'fattureincloud_tokens',
    'state_session_key' => 'fattureincloud_oauth2_state',
];
```

### OAuth2 Callback Route

[](#oauth2-callback-route)

The package automatically registers the OAuth2 callback route at `/fatture-in-cloud/callback` (named `fatture-in-cloud.callback`) using a single action invokable controller. This route:

- Processes OAuth2 authorization callbacks from Fatture in Cloud
- Handles both successful authorizations and error responses
- Validates CSRF state parameters to prevent attacks
- Exchanges authorization codes for access/refresh tokens
- Stores tokens securely using Laravel's encrypted cache
- Returns structured JSON responses for success/error scenarios

The route is registered as: `Route::get('/fatture-in-cloud/callback', OAuth2CallbackController::class)`

Usage
-----

[](#usage)

### Facade Usage

[](#facade-usage)

```
use Codeman\FattureInCloud\Facades\FattureInCloud;

// OAuth2 Authentication Flow
$authUrl = FattureInCloud::getAuthorizationUrl(['entity.clients:r', 'entity.clients:a']);
// Redirect user to $authUrl

// After callback, exchange code for token
$token = FattureInCloud::handleCallback($request);

// Create API services
$companiesApi = FattureInCloud::createService('companies');
$clientsApi = FattureInCloud::createService('clients');
$productsApi = FattureInCloud::createService('products');

// Use API services
$companies = $companiesApi->listUserCompanies();
$clients = $clientsApi->listClients($companyId);
$products = $productsApi->listProducts($companyId);
```

### Dependency Injection

[](#dependency-injection)

```
use Codeman\FattureInCloud\FattureInCloudSdk;

class InvoiceService
{
    public function __construct(
        private FattureInCloudSdk $sdk
    ) {}

    public function getClients(int $companyId): array
    {
        $clientsApi = $this->sdk->createService('clients');

        return $clientsApi
            ->listClients($companyId)
            ->getData();
    }

    public function createInvoice(int $companyId, array $invoiceData): object
    {
        $issuedDocumentsApi = $this->sdk->createService('issuedDocuments');

        return $issuedDocumentsApi
            ->createIssuedDocument($companyId, $invoiceData)
            ->getData();
    }
}
```

### Available API Services

[](#available-api-services)

The package provides access to 13+ Fatture in Cloud API services through the factory pattern:

Service KeyAPI ClassPurpose`clients``ClientsApi`Customer/client management`companies``CompaniesApi`Company information &amp; settings`info``InfoApi`System information &amp; metadata`issuedDocuments``IssuedDocumentsApi`Invoices, quotes, orders, etc.`products``ProductsApi`Product catalog management`receipts``ReceiptsApi`Receipt management`receivedDocuments``ReceivedDocumentsApi`Received invoices/documents`suppliers``SuppliersApi`Supplier management`taxes``TaxesApi`Tax rates &amp; settings`user``UserApi`User account information`settings``SettingsApi`Account settings &amp; preferences`archive``ArchiveApi`Document archiving`cashbook``CashbookApi`Cash flow &amp; transactions```
// Core Entities
$clientsApi = FattureInCloud::createService('clients');
$suppliersApi = FattureInCloud::createService('suppliers');
$productsApi = FattureInCloud::createService('products');
$issuedDocumentsApi = FattureInCloud::createService('issuedDocuments');
$receivedDocumentsApi = FattureInCloud::createService('receivedDocuments');
$receiptsApi = FattureInCloud::createService('receipts');

// Company & User Management
$companiesApi = FattureInCloud::createService('companies');
$userApi = FattureInCloud::createService('user');
$infoApi = FattureInCloud::createService('info');

// Settings & Configuration
$settingsApi = FattureInCloud::createService('settings');
$taxesApi = FattureInCloud::createService('taxes');

// Additional Services
$archiveApi = FattureInCloud::createService('archive');
$cashbookApi = FattureInCloud::createService('cashbook');
```

### OAuth2 Authentication Flow

[](#oauth2-authentication-flow)

#### 1. Generate Authorization URL

[](#1-generate-authorization-url)

```
use FattureInCloud\OAuth2\Scope;

$scopes = [
    Scope::ENTITY_CLIENTS_READ,
    Scope::ENTITY_CLIENTS_ALL,
    Scope::ENTITY_PRODUCTS_READ,
    Scope::ISSUED_DOCUMENTS_INVOICES_READ,
    Scope::ISSUED_DOCUMENTS_INVOICES_ALL
];

$authUrl = FattureInCloud::getAuthorizationUrl($scopes);
return redirect($authUrl);
```

#### 2. Handle Callback (Automatic Route)

[](#2-handle-callback-automatic-route)

The package automatically handles callbacks at `/fatture-in-cloud/callback`. You can customize the handling by creating your own controller:

```
use Codeman\FattureInCloud\Facades\FattureInCloud;

class CustomCallbackController extends Controller
{
    public function handle(Request $request)
    {
        try {
            $result = FattureInCloud::handleCallback($request);

            if ($result['success']) {
                // Token is automatically stored and encrypted
                return redirect('/dashboard')->with('success', 'Connected to Fatture in Cloud!');
            }

            return redirect('/settings')->with('error', 'Authentication failed: ' . $result['error']);
        } catch (Exception $e) {
            return redirect('/settings')->with('error', 'Authentication failed: ' . $e->getMessage());
        }
    }
}
```

#### 3. Using API Services

[](#3-using-api-services)

```
use FattureInCloud\Model\Client;
use FattureInCloud\Model\ClientType;
use FattureInCloud\Model\IssuedDocument;
use FattureInCloud\Model\IssuedDocumentType;

// Get user companies
$companiesApi = FattureInCloud::createService('companies');
$companies = $companiesApi->listUserCompanies();

// Get company ID for operations
$companyId = $companies->getData()[0]->getId();

// Create a new client
$clientsApi = FattureInCloud::createService('clients');
$newClient = new Client([
    'name' => 'New Client Ltd',
    'code' => 'CLIENT001',
    'type' => ClientType::COMPANY,
]);

$createdClient = $clientsApi->createClient($companyId, ['data' => $newClient]);

// List all products
$productsApi = FattureInCloud::createService('products');
$products = $productsApi->listProducts($companyId);

// Create an invoice
$issuedDocumentsApi = FattureInCloud::createService('issuedDocuments');
$invoice = new IssuedDocument([
    'type' => IssuedDocumentType::INVOICE,
    'entity' => $createdClient->getData(),
    'date' => date('Y-m-d'),
    'number' => 1,
    'numeration' => '/FAT',
]);

$createdInvoice = $issuedDocumentsApi->createIssuedDocument($companyId, ['data' => $invoice]);
```

### Token Management

[](#token-management)

```
use Codeman\FattureInCloud\Facades\FattureInCloud;

// Check if user is authenticated
if (FattureInCloud::isAuthenticated()) {
    // User has valid tokens
    $userInfo = FattureInCloud::createService('user')->getUserInfo();
}

// Tokens are automatically refreshed when needed
// The package handles token refresh transparently

// Clear stored tokens (logout)
FattureInCloud::clearTokens();
```

### OAuth2 Scopes

[](#oauth2-scopes)

The package supports all Fatture in Cloud OAuth2 scopes. Some common scopes include:

```
use FattureInCloud\OAuth2\Scope;

// Entity Management
Scope::ENTITY_CLIENTS_READ      // Read customers
Scope::ENTITY_CLIENTS_ALL       // Full customer access
Scope::ENTITY_SUPPLIERS_READ    // Read suppliers
Scope::ENTITY_SUPPLIERS_ALL     // Full supplier access
Scope::ENTITY_PRODUCTS_READ     // Read products
Scope::ENTITY_PRODUCTS_ALL      // Full product access

// Document Types (Issued)
Scope::ISSUED_DOCUMENTS_INVOICES_READ         // Read invoices
Scope::ISSUED_DOCUMENTS_INVOICES_ALL          // Full invoice access
Scope::ISSUED_DOCUMENTS_CREDIT_NOTES_READ     // Read credit notes
Scope::ISSUED_DOCUMENTS_CREDIT_NOTES_ALL      // Full credit note access
Scope::ISSUED_DOCUMENTS_RECEIPTS_READ         // Read receipts
Scope::ISSUED_DOCUMENTS_RECEIPTS_ALL          // Full receipt access
Scope::ISSUED_DOCUMENTS_QUOTES_READ           // Read quotes
Scope::ISSUED_DOCUMENTS_QUOTES_ALL            // Full quote access

// Other Modules
Scope::RECEIVED_DOCUMENTS_READ  // Read received documents
Scope::RECEIVED_DOCUMENTS_ALL   // Full received documents access
Scope::TAXES_READ              // Read tax settings
Scope::TAXES_ALL               // Full tax settings access
Scope::ARCHIVE_READ            // Read archived documents
Scope::ARCHIVE_ALL             // Full archive access
Scope::CASHBOOK_READ           // Read cashbook
Scope::CASHBOOK_ALL            // Full cashbook access
Scope::SETTINGS_READ           // Read settings
Scope::SETTINGS_ALL            // Full settings access
```

### Manual Authentication

[](#manual-authentication)

If you prefer to use a manually generated access token instead of OAuth2:

```
FATTUREINCLOUD_ACCESS_TOKEN=your_access_token_here
```

When an access token is configured, OAuth2 settings are ignored and the SDK will use the token directly. This is useful for:

- Server-to-server integrations
- Background jobs and scheduled tasks
- Applications that don't need user-specific authentication
- Development and testing scenarios

Architecture
------------

[](#architecture)

The package follows clean architecture principles with dependency injection and contract-based design:

```
Codeman\FattureInCloud\
├── FattureInCloudSdk (main SDK class)
├── FattureInCloudServiceProvider (Laravel service provider)
├── Controllers\ (HTTP controllers)
│   └── OAuth2CallbackController - Single action invokable controller for OAuth2 callbacks
├── Contracts\ (Laravel-convention interfaces without "Interface" suffix)
│   ├── OAuth2Manager - OAuth2 authentication contract
│   ├── StateManager - CSRF state management contract
│   ├── TokenStorage - Token persistence contract
│   └── ApiServiceFactory - API service creation contract
├── Services\ (concrete implementations)
│   ├── OAuth2AuthorizationCodeManager - OAuth2 Authorization Code flow
│   ├── SessionStateManager - Laravel session-based state management
│   ├── CacheTokenStorage - Laravel cache-based token persistence
│   └── FattureInCloudApiServiceFactory - Fatture in Cloud API services factory
├── Exceptions\ (custom exceptions)
│   ├── OAuth2Exception - OAuth2-specific errors
│   └── UnsupportedServiceException - Service creation errors
└── Facades\ (Laravel facades)
    └── FattureInCloud - Main package facade

```

### Key Architectural Features

[](#key-architectural-features)

- **Clean Architecture**: Separation of concerns with clear boundaries
- **Dependency Injection**: All dependencies are injected and easily testable
- **Contract-Based Design**: Interface-driven development for flexibility
- **Factory Pattern**: Service creation through factory for consistency
- **Single Action Controllers**: OAuth2 callback controller follows Laravel's invokable controller pattern using `__invoke()`
- **Encrypted Token Storage**: Secure token persistence using Laravel's encryption
- **Automatic Route Registration**: OAuth2 callback route registered automatically
- **Laravel Integration**: Full integration with Laravel's service container and facades

Development Commands
--------------------

[](#development-commands)

### Testing

[](#testing)

Run the full test suite using Pest:

```
composer test
```

Run tests directly:

```
vendor/bin/pest
```

Run tests with coverage report:

```
vendor/bin/pest --coverage
```

Run tests in CI mode:

```
vendor/bin/pest --ci
```

### Code Quality

[](#code-quality)

Run PHPStan static analysis:

```
composer analyse
```

Run PHPStan directly:

```
vendor/bin/phpstan analyse
```

Format code using Laravel Pint:

```
composer format
```

Format code directly:

```
vendor/bin/pint
```

### Package Development

[](#package-development)

Discover package (runs automatically after autoload dump):

```
composer prepare
```

Security Features
-----------------

[](#security-features)

- **Encrypted Token Storage**: All tokens are automatically encrypted before storage using Laravel's encryption
- **CSRF Protection**: Secure session-based state management for OAuth2 flows prevents CSRF attacks
- **Environment Configuration**: Credentials stored in environment variables prevent exposure in code
- **Automatic Token Refresh**: Transparent token refresh prevents expired token issues
- **Secure Callback Handling**: Built-in validation of OAuth2 callback parameters

Publishing Configuration
------------------------

[](#publishing-configuration)

When ready to publish package assets:

```
# Publish configuration file
php artisan vendor:publish --tag="laravel-fattureincloud-php-sdk-config"

# Publish migrations (if any)
php artisan vendor:publish --tag="laravel-fattureincloud-php-sdk-migrations"

# Publish views (if any)
php artisan vendor:publish --tag="laravel-fattureincloud-php-sdk-views"
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

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

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

### Development Workflow

[](#development-workflow)

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run tests (`composer test`)
5. Run code quality checks (`composer analyse && composer format`)
6. Commit your changes (`git commit -m 'Add some amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover a security vulnerability within this package, please send an email to the maintainers. All security vulnerabilities will be promptly addressed.

Credits
-------

[](#credits)

- [Mattia Migliorini](https://github.com/deshack)
- [Visia Quantum](https://github.com/visiaquantum)
- All Contributors

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance69

Regular maintenance activity

Popularity1

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.8% 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 ~2 days

Total

2

Last Release

296d ago

### Community

Maintainers

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

---

Top Contributors

[![deshack](https://avatars.githubusercontent.com/u/2034213?v=4)](https://github.com/deshack "deshack (73 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")

---

Tags

laravelfattureincloudCodeman by Visia Quantum srlcodemanvisiaquantumlaravel-fattureincloud-php-sdk

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/visiaquantum-laravel-fattureincloud-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/visiaquantum-laravel-fattureincloud-php-sdk/health.svg)](https://phpackages.com/packages/visiaquantum-laravel-fattureincloud-php-sdk)
```

###  Alternatives

[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.1k11.2M101](/packages/dedoc-scramble)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816333.9k3](/packages/defstudio-telegraph)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

44855.7k](/packages/harris21-laravel-fuse)

PHPackages © 2026

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