"Invalid Invoice Hash" Error During ZATCA Sandbox Testing

I don’t understand PHP, but the code works as it should, and its approved by the server.

<?php
function generateApiRequest($xmlFilePath, $xslFilePath) {
    // 1. Buka dokumen XML dengan preserveWhiteSpace = true
    $xml = new DOMDocument();
    $xml->preserveWhiteSpace = true;
    $xml->formatOutput = false;

    // Load XML dari path yang diberikan
    if (!$xml->load($xmlFilePath)) {
        throw new Exception("Failed to load XML file: $xmlFilePath");
    }

    // 1a. Ambil UUID dari elemen <cbc:UUID>
    $xpath = new DOMXPath($xml);
    $xpath->registerNamespace('cbc', 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2');
    $uuidNode = $xpath->query('//cbc:UUID')->item(0);
    
    if (!$uuidNode) {
        throw new Exception("UUID not found in the XML document.");
    }
    
    $uuid = $uuidNode->nodeValue;

    // 2. Terapkan XSL untuk transformasi
    $xsl = new DOMDocument();
    if (!$xsl->load($xslFilePath)) {
        throw new Exception("Failed to load XSL file: $xslFilePath");
    }

    $proc = new XSLTProcessor();
    $proc->importStylesheet($xsl);

    // Lakukan transformasi
    $transformedXml = $proc->transformToDoc($xml);
    if (!$transformedXml) {
        throw new Exception("XSL Transformation failed.");
    }

    // 3. Canonicalize (C14N) hasil transformasi
    $canonicalXml = $transformedXml->C14N();  // hasil transformasi dalam format C14N

    // 4. Dapatkan byte hash256 dari hasil transformasi
    $hash = hash('sha256', $canonicalXml, true);  // menghasilkan hash SHA-256 sebagai binary data

    // 5. Encode hasil hash ke Base64
    $base64Hash = base64_encode($hash);

    // 6. Encode canonicalized XML ke Base64
    $base64Invoice = base64_encode($canonicalXml);

    // 7. Buat array dengan hasil yang diinginkan
    $result = array(
        "invoiceHash" => $base64Hash,
        "uuid" => $uuid,
        "invoice" => $base64Invoice
    );

    // 8. Konversi array menjadi JSON string
    return json_encode($result);
}

// Contoh penggunaan fungsi:
$xmlFilePath = 'xmlfile.xml';
$xslFilePath = 'xslfile.xsl';

try {
    $jsonResult = generateApiRequest($xmlFilePath, $xslFilePath);
    echo $jsonResult;  // Menampilkan JSON string
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}
?>

1 Like