Search code examples
phpqr-codetlv

How to create and parse Tag, Length, Value (TLV) in PHP and encode it in Base64


There is a new regulation from the Government asking all VAT registered companies to implement QR CODE in the new E-Invoice.

  • The QR code fields shall be encoded in Tag-Length-Value (TLV) format with the tag values specified in the “Tag” column of the adjacent table.

  • The TLV encoding shall be as follows:

    • Tag: the tag value as mentioned above stored in one byte.
    • Length: the length of the byte array resulted from the UTF8 encoding of the field value. The length shall be stored in one byte.
    • Value: the byte array resulting from the UTF8 encoding of the field value.

How do I create TLV From an Array of Information? Is there a library that I can use?

$arr = [
    1 => 'Company Name',
    2 => '1234567890',
    3 => '2021/10/11 17:20:00',
    4 => '1000',
    5 => '150'
];

Solution

  • Yes, the QR code required is not a normal QR code with a link. It should be TLV base64 encoded. It can be done very easily. the values need to be hexed and then combined which will contain ASCII control characters.

    If you still don't get it, Luckily, You can use the following package by Salla to generate a QR code from the array.

    https://github.com/SallaApp/ZATCA

    Make sure to follow the Tag structure provided by the ZATCA (GAZT previously). The package's example has the correct array:

    $generatedString = GenerateQrCode::fromArray([
        new Seller('Salla'), // seller name
        new TaxNumber('1234567891'), // seller tax number
        new InvoiceDate('2021-07-12T14:25:09Z'), // invoice date as Zulu ISO8601 @see https://en.wikipedia.org/wiki/ISO_8601
        new InvoiceTotalAmount('100.00'), // invoice total amount
        new InvoiceTaxAmount('15.00') // invoice tax amount
        // TODO :: Support others tags
    ])->toTLV();