PHP code example of andreaballarin / acube-italy-receipts
1. Go to this page and download the library: Download andreaballarin/acube-italy-receipts library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
andreaballarin / acube-italy-receipts example snippets
use AndreaBallarin\ACubeItalyReceipts\{AuthenticationService, Environment};
$auth = new AuthenticationService(environment: Environment::Sandbox);
$token = $auth->login(
email: '[email protected]',
password: 'your-password',
);
use AndreaBallarin\ACubeItalyReceipts\Client;
$client = new Client(
bearerToken: $token,
environment: Environment::Sandbox,
mtlsCertPath: '/path/to/cert.pem',
mtlsKeyPath: '/path/to/key.pem',
mtlsKeyPassphrase: 'passphrase-if-any', // opzionale
);
use AndreaBallarin\ACubeItalyReceipts\Resources\Receipt;
Receipt::setClient($client);
use AndreaBallarin\ACubeItalyReceipts\Resources\{Merchant, MerchantDraft};
use AndreaBallarin\ACubeItalyReceipts\ValueObjects\Address;
Merchant::setClient($supplierClient); // Client con il token del Supplier, senza mTLS
$merchant = Merchant::create(new MerchantDraft(
vatNumber: '12345678901',
address: new Address(
streetAddress: 'street name',
streetNumber: 'xx',
zipCode: '00000',
city: 'City',
province: 'XX',
),
businessName: 'business name',
email: '[email protected]',
password: 'MerchantP4$$w0rd',
));
use AndreaBallarin\ACubeItalyReceipts\Resources\Pem;
$pem = Pem::create($merchant->uuid); // ancora col client Supplier
Pem::setClient($merchantClient); // Client col token del Merchant, senza mTLS
Pem::activate($pem->serialNumber, $pem->registrationKey); // non ritorna nulla
use AndreaBallarin\ACubeItalyReceipts\Resources\CashRegister;
CashRegister::setClient($merchantClient);
$cashRegister = CashRegister::create($pem->serialNumber, 'Cash register first floor');
// mtlsCertificate e privateKey sono già "unescaped" (newline reali), pronti per il disco
file_put_contents('/var/certs/pems/A2F4-000001/cr-cert.pem', $cashRegister->mtlsCertificate);
file_put_contents('/var/certs/pems/A2F4-000001/cr-key.pem', $cashRegister->privateKey);
use AndreaBallarin\ACubeItalyReceipts\Resources\ReceiptDetails;
$details = ReceiptDetails::get($receipt->uuid);
echo "Imponibile: {$details->totalTaxableAmount}, IVA: {$details->totalVatAmount}";
foreach ($details->items as $item) {
echo "{$item->description}: {$item->unitPrice}\n";
}
use AndreaBallarin\ACubeItalyReceipts\AuthenticationService;
$auth = new AuthenticationService(environment: Environment::Sandbox);
try {
$token = $auth->login(email: '[email protected]', password: 'secret');
// Usa il token con il Client
} catch (AcubeAuthenticationException $e) {
echo "Login failed: invalid credentials";
}
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\Psr16Cache;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
// Qualsiasi implementazione PSR-16 va bene (Redis, Memcached, ArrayAdapter, ecc.)
$cache = new Psr16Cache(new ArrayAdapter());
$auth = new AuthenticationService(
environment: Environment::Sandbox,
cache: $cache,
cacheLeewaySeconds: 30, // margine di sicurezza (default)
);
// Prima chiamata: fetcha da rete, cachea il token per la durata della sua validità
$token1 = $auth->loginCached(email: '[email protected]', password: 'secret');
// Successive chiamate entro la scadenza: ritorna il token cachato (nessuna rete)
$token2 = $auth->loginCached(email: '[email protected]', password: 'secret');
assert($token1 === $token2);
// Cartella locale
$client = new Client(
bearerToken: $token,
callDumpStorage: __DIR__ . '/var/acube-calls', // opzionale
);
// Oppure un disco Laravel (o qualunque oggetto con put(string $path, string $contents)),
// con sottocartella dedicata dentro quel disco
$client = new Client(
bearerToken: $token,
callDumpStorage: \Illuminate\Support\Facades\Storage::disk('tmp'),
callDumpPath: 'acube-calls', // opzionale: isola i dump in una sottocartella del disco
);
$receipt = Receipt::create(
draft: $draft,
idempotencyKey: 'unique-key-123',
idempotencyWindowSeconds: 60,
);
// Se ripeti la stessa chiave entro 60 secondi: AcubeDuplicateRequestException
use AndreaBallarin\ACubeItalyReceipts\Resources\Receipt;
$pemSerialNumber = 'A2F4-000001';
$draft = new ReceiptDraft(items: [...], ...);
try {
$receipt = Receipt::create($draft);
} catch (\Exception $e) {
if (!isUncertainError($e)) {
throw;
}
// Verifica se lo scontrino è già stato emesso (ultimi 2 minuti)
$now = new \DateTime('now', new \DateTimeZone('UTC'));
$twoMinutesAgo = (clone $now)->modify('-2 minutes')->format(\DateTimeInterface::ATOM);
$recentReceipts = Receipt::listForPem(
serialNumber: $pemSerialNumber,
documentDatetimeAfter: $twoMinutesAgo,
size: 100,
);
// Cerca uno scontrino con lo stesso importo totale
foreach ($recentReceipts->data as $existing) {
if ($existing->totalAmount === $draft->cashPaymentAmount) {
return $existing; // Già emesso
}
}
// Non trovato → riprova
return Receipt::create($draft);
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.