ZATCA e-invoicing in Go

By Matheel · Updated

One HTTP request from Go (net/http + database/sql): 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)

// go run main.go: the sandbox needs no key
package main

import ("bytes"; "encoding/json"; "fmt"; "net/http")

func main() {
	body, _ := json.Marshal(map[string]any{"environment": "sandbox", "pdf": true, "invoice": map[string]any{
		"type": "simplified", "line_items": []map[string]any{{"name": "قهوة", "quantity": 2, "price": "50.00"}}}})
	r, _ := http.Post("https://matheel.app/api/v1/invoices", "application/json", bytes.NewReader(body))
	var res map[string]any
	json.NewDecoder(r.Body).Decode(&res)
	fmt.Println(res["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.

// database/sql + net/http.
func MatheelInvoice(db *sql.DB, items []map[string]any) (map[string]any, error) {
	tx, err := db.Begin()
	if err != nil { return nil, err }
	defer tx.Rollback() // no-op after Commit
	var token string
	if err := tx.QueryRow("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE").Scan(&token); err != nil { return nil, err }
	body, _ := json.Marshal(map[string]any{"device_token": token, "pdf": true,
		"invoice": map[string]any{"type": "simplified", "line_items": items}})
	req, _ := http.NewRequest("POST", "https://matheel.app/api/v1/invoices", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("MATHEEL_KEY"))
	r, err := http.DefaultClient.Do(req)
	if err != nil { return nil, err }
	defer r.Body.Close()
	var res map[string]any
	json.NewDecoder(r.Body).Decode(&res)
	if r.StatusCode != 200 { return nil, fmt.Errorf("matheel %d: %v", r.StatusCode, res) }
	if _, err := tx.Exec("UPDATE matheel_device SET token = $1 WHERE id = 1", res["device_token"]); err != nil { return nil, err }
	return res, tx.Commit()
}

3. For production

FAQ

Do I need a ZATCA library for Go?

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