"[Error] Invalid Certificate"

Hello,

Need help with the “[Error] Invalid Certificate” error at the ‘Generate QR Code’ step during coding for the compliance.

Please help.

Below are the image of the error and the code used

Sub Main()
Try
’ ---------------- CONFIG ----------------
Dim templateFilename As String = “F:\Kapil\JUNK\ZATCA Testing\OrginalTemplate\Simplified_Invoice.xml”

        ' ✅ Use PEM files directly (already extracted from your CSID .pfx)
        Dim certPemPath As String = "F:\Kapil\JUNK\ZATCA Testing\Csrconfig\CSID From Comlience\cert.pem"
        ''Dim certPemPath As String = "F:\Kapil\JUNK\ZATCA Testing\Csrconfig\CSID From Comlience\fullchain.pem"
        ''Dim keyPemPath As String = "F:\Kapil\JUNK\ZATCA Testing\Csrconfig\CSID From Comlience\private_key_pkcs8.pem"
        Dim keyPemPath As String = "F:\Kapil\JUNK\ZATCA Testing\Csrconfig\CSID From Comlience\private_ec.pem"


        ' ✅ Compliance creds (Basic Auth: token:secret)
        Dim csidBinarySecurityTokenBase64 As String = "yyyyyy"
        Dim csidSecretBase64 As String = "abcd"

        ' Invoice header values
        Dim sellerName As String = "ABC LTD"
        Dim sellerVat As String = "300000000000123"
        Dim invoiceId As String = "SME00010-REPLACED"
        Dim invoiceUuid As String = Guid.NewGuid().ToString()
        Dim issueDate As DateTime = DateTime.UtcNow

        ' Items
        Dim items As New List(Of InvoiceLine) From {
            New InvoiceLine("1", "كتاب", 33D, 3D),
            New InvoiceLine("2", "قلم", 3D, 34D)
        }

        ' ---------------- Load template ----------------
        If Not File.Exists(templateFilename) Then Throw New FileNotFoundException("Template not found: " & templateFilename)

        Dim xmlDoc As New XmlDocument()
        xmlDoc.PreserveWhitespace = True
        xmlDoc.Load(templateFilename)

        ' ---------------- Replace header values ----------------
        Dim nsmgr = BuildNsMgr(xmlDoc)
        xmlDoc.SelectSingleNode("/def:Invoice/cbc:ID", nsmgr).InnerText = invoiceId
        xmlDoc.SelectSingleNode("/def:Invoice/cbc:UUID", nsmgr).InnerText = invoiceUuid
        xmlDoc.SelectSingleNode("/def:Invoice/cbc:IssueDate", nsmgr).InnerText = issueDate.ToString("yyyy-MM-dd")
        xmlDoc.SelectSingleNode("/def:Invoice/cbc:IssueTime", nsmgr).InnerText = issueDate.ToString("HH:mm:ss\Z")
        xmlDoc.SelectSingleNode("//cac:PartyLegalEntity/cbc:RegistrationName", nsmgr).InnerText = sellerName
        xmlDoc.SelectSingleNode("//cac:PartyTaxScheme/cbc:CompanyID", nsmgr).InnerText = sellerVat

        ' Buyer, lines, totals
        EnsureB2CMinimalBuyer(xmlDoc)
        ClearExistingInvoiceLines(xmlDoc, nsmgr)
        AppendInvoiceLines(xmlDoc, nsmgr, items)
        Dim totalEx = items.Sum(Function(i) i.UnitPrice * i.Quantity)
        Dim totalVat = Math.Round(totalEx * 0.15D, 2)
        Dim totalInc = totalEx + totalVat
        SetTotals(xmlDoc, nsmgr, totalEx, totalInc)
        EnsureQrContainer(xmlDoc, nsmgr)

        ' ---------------- Load PEMs (NO PFX EXPORT IN CODE) ----------------
        ''Dim certificateContent As String = PemUtils.LoadCertificatePem(certPemPath)
        ''Dim privateKeyContent As String = PemUtils.LoadPrivateKeyPem(keyPemPath, requirePkcs8:=True) ' SDK usually expects PKCS#8

        Dim certificateContent As String = File.ReadAllText(certPemPath, Encoding.ASCII).Replace(vbCr, "").Trim()
        Dim privateKeyContent As String = File.ReadAllText(keyPemPath, Encoding.ASCII).Replace(vbCr, "").Trim()

        ' ---------------- SIGN + QR VIA SDK ----------------
        Dim signer As New EInvoiceSigner()
        Dim result As SignResult = signer.SignDocument(xmlDoc, certificateContent, privateKeyContent)

        If result Is Nothing OrElse Not result.IsValid Then
            Dim errMsg As String = If(result IsNot Nothing AndAlso Not String.IsNullOrEmpty(result.ErrorMessage), result.ErrorMessage, "Unknown error")
            Throw New Exception("SDK signing failed: " & errMsg)
        End If

        Dim signedDoc As XmlDocument = result.SignedEInvoice

        ' ---------------- Save signed XML ----------------
        Dim outXml As String = "F:\Kapil\JUNK\ZATCA Testing\Sample invoice\invoice_signed_sdk.xml"
        result.SaveSignedEInvoice(outXml)

        ' ---------------- Compliance API ----------------
        ValidateWithComplianceAPI(signedDoc, outXml, csidBinarySecurityTokenBase64, csidSecretBase64)

    Catch ex As Exception
        txtresp.Text = "ERROR: " & ex.Message
    End Try
End Sub

Morning @kapil

Thanks for reaching out, Welcome to our community.

To provide comprehensive support as usual, can I kindly ask you to elaborate with the below:

  1. What is the environment that you are trying to integrate, Is it simulation or production?
  2. Are you using ZATCA SDK, If so what is the version? or did you implemented your own solution?
  3. What is the exact steps you followed to generate your CSR? In details?

Thanks,
Ibrahem Daoud.

Greeting Ibrahem !

It is a great relief to hear from you.

We eagerly look forward to your support in helping us with the query as we are stuck inspite of trying out multiple ways to clear it.

We have listed the answers to your questions and therein also listed the steps which we are executing with the required screen shots.

Please help asap.

God bless !

Thanks

  1. What is the environment that you are trying to integrate, Is it simulation or production?

a) We are currently trying to send b2c invoice to the Simulation. Our application is built using Asp.net with Dot Net framework 4.8

  1. Are you using ZATCA SDK, If so what is the version? or did you implemented your own solution?

a) Yes we are using Zatca SDK

b) First we generated the Simplified invoice Xml through our application

c) We then Passed this Xml Doc to the EInvoiceSigner in “Zatca.EInvoice.SDK” NameSpace of Zatca SDK DLL, whose reference we added in our Application

d) For signing, we used the Certificate PEM generated from the BinarySecuritytoken provided by Zatca Sandbox and the CSR Privatekey (EC)

e) We are using SDK of “zatca-einvoicing-sdk-DotNet-238-R3.4.4 “

  1. What is the exact steps you followed to generate your CSR? In details?

a) We generated the “csr_config.cnf” (have attached the same for your reference) and have followed the below Steps

  1. Created csr_config.cnf file & executed the following

  2. openssl ecparam -name secp256k1 -genkey -noout -out CSR_PrivateKey.pem

  3. openssl ec -in CSR_PrivateKey.pem -pubout -out CSR_publickey.pem

  4. openssl req -new -key CSR_Privatekey.pem -out request_csr.pem -config csr_config.cnf

  5. Converted the file request_csr.pem to base64 and named it as req_certificateBase64.pem

  6. Executed below steps on https://sandbox.zatca.gov.sa/IntegrationSandbox - Compliance CSID API – Authorize – Try it Out – Copy pasted the CSR Code generated in Step 5

  7. On Execution we get the following response with the Compliance CSID –

{

“requestID”: XXXXXXX,

“dispositionMessage”: “ISSUED”,

“binarySecurityToken”: “XXXXXXX”,

“secret”: “XXXXXX”,

“errors”: null

}

  1. We then save the above Response in a CSID.txt file on the local system and execute the below steps to generate the Certificate from binarysecuritytoken using windows powersell

i. Load CSID JSON and extract token

Write-Host “Step 1: Reading CSID.txt…”

$json = Get-Content “CSID.txt” | ConvertFrom-Json

$token = $json.binarySecurityToken

ii. Double Base64 decode into DER

Write-Host “Step 2: Decoding binarySecurityToken…”

$bytes1 = [Convert]::FromBase64String($token)

$tokenInner = [System.Text.Encoding]::UTF8.GetString($bytes1)

$bytes2 = [Convert]::FromBase64String($tokenInner)

[IO.File]::WriteAllBytes(“cert.der”, $bytes2)

iii. Convert DER → PEM using OpenSSL

Write-Host “Step 3: Converting DER to PEM…”

& openssl x509 -inform DER -in cert.der -out cert.pem

  1. The Cert.pem generated (from the steps listed in 8 above) and the CSR_Privatekey.pem are used to sign the Xml (Simplified Invoice) as shown in the below image

We are facing error at this stage of generation of the E-Invoice QR Code –

(Attachment csr_config.cnf is missing)

Dear @kapil

Thanks for the detailed elaboration, To provide comprehensive support as usual, Kindly share the full payload to the below mail:

SP mail: sp_support@zatca.gov.sa

Additionally, please share here the email address that you will reach out to our technical team from.

Thanks,
Ibrahem Daoud.

Dear Ibrahem ,

Looking forward to your support. We had sent the requisite details to the email provided by you.

Morning @kapil

Kindly share the email address that you reached out from.

Thanks,
Ibrahem Daoud.

Have sent you the email from “kapil.sutariya@eshowbizz.com” to “sp_support@zatca.gov.sa