ZATCA e-invoicing in C# / .NET

By Matheel · Updated

One HTTP request from C# / .NET (HttpClient + Npgsql): Matheel builds the invoice, signs it, files it with ZATCA and returns ZATCA's answer, the legal XML and the PDF with the QR.

1. Try it now (no key)

// dotnet new console, then Program.cs:
using System.Net.Http.Json; using System.Text.Json;

using var http = new HttpClient();
var r = await http.PostAsJsonAsync("https://matheel.app/api/v1/invoices", new {
    environment = "sandbox", pdf = true, invoice = new {
        type = "simplified", line_items = new[] { new { name = "قهوة", quantity = 2, price = "50.00" } } } });
var res = await r.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine(res.GetProperty("status")); // reported

2. The ready function, after payment

It locks the device row (so two payments at once never fork the chain), files the invoice with "pdf": true and saves the new device_token. Any non-200 rolls the transaction back and the old token stays valid.

// Npgsql + HttpClient. Same flow on SQL Server: SELECT … WITH (UPDLOCK, ROWLOCK).
public async Task<JsonElement> MatheelInvoice(NpgsqlConnection db, object[] items) {
    await using var tx = await db.BeginTransactionAsync();
    var token = (string)await new NpgsqlCommand("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE", db, tx).ExecuteScalarAsync();
    http.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MATHEEL_KEY"));
    var r = await http.PostAsJsonAsync("https://matheel.app/api/v1/invoices",
        new { device_token = token, pdf = true, invoice = new { type = "simplified", line_items = items } });
    var res = await r.Content.ReadFromJsonAsync<JsonElement>();
    if (!r.IsSuccessStatusCode) throw new Exception(res.ToString()); // tx rolls back on dispose
    var up = new NpgsqlCommand("UPDATE matheel_device SET token = @t WHERE id = 1", db, tx);
    up.Parameters.AddWithValue("t", res.GetProperty("device_token").GetString());
    await up.ExecuteNonQueryAsync();
    await tx.CommitAsync();
    return res; // Convert.FromBase64String(res.GetProperty("pdf").GetString()) is the PDF
}

3. For production

FAQ

Do I need a ZATCA library for C# / .NET?

No. Matheel is a plain JSON API: one HTTP request. Signing, the XML, the certificate and filing with ZATCA all happen at Matheel.

Where do I keep the device token?

One row in your database (a matheel_device table). After every 200, save the new device_token in the same transaction.

Can I try before subscribing?

Yes, on the developer sandbox without a key: the request below returns ZATCA's real answer and the PDF.

Try it now on the developer sandbox

No key, no signup: a real ZATCA answer, with the bilingual PDF and the QR.

Start Pricing