ZATCA e-invoicing in Java / Kotlin

By Matheel · Updated

One HTTP request from Java / Kotlin (java.net.http + JDBC): 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)

// Java 15+; import java.net.URI; import java.net.http.*;
var body = """
  {"environment":"sandbox","pdf":true,"invoice":{"type":"simplified",
   "line_items":[{"name":"قهوة","quantity":2,"price":"50.00"}]}}""";
var res = HttpClient.newHttpClient().send(
    HttpRequest.newBuilder(URI.create("https://matheel.app/api/v1/invoices"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(body)).build(),
    HttpResponse.BodyHandlers.ofString());
System.out.println(res.body()); // {"status":"reported", "pdf":"JVBERi0…", …}

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.

// JDBC + java.net.http. Jackson (or any JSON library) for the body.
public Map<String, Object> matheelInvoice(Connection db, List<Map<String, Object>> items) throws Exception {
  db.setAutoCommit(false);
  try {
    ResultSet rs = db.createStatement().executeQuery("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE");
    rs.next();
    String body = json.writeValueAsString(Map.of("device_token", rs.getString(1), "pdf", true,
        "invoice", Map.of("type", "simplified", "line_items", items)));
    HttpResponse<String> r = http.send(HttpRequest.newBuilder(URI.create("https://matheel.app/api/v1/invoices"))
        .header("Content-Type", "application/json").header("Authorization", "Bearer " + System.getenv("MATHEEL_KEY"))
        .POST(HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
    Map<String, Object> res = json.readValue(r.body(), Map.class);
    if (r.statusCode() != 200) throw new IllegalStateException(r.body());
    PreparedStatement up = db.prepareStatement("UPDATE matheel_device SET token = ? WHERE id = 1");
    up.setString(1, (String) res.get("device_token")); up.executeUpdate();
    db.commit();
    return res;
  } catch (Exception e) { db.rollback(); throw e; }
}

3. For production

FAQ

Do I need a ZATCA library for Java / Kotlin?

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