eet2

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

eet2

Go Go Reference

Go client for the Czech electronic sales registration EET 2.0, in force from 1 January 2027 (Act No. 180/2026 Coll., EET interface version 4). It builds the sale data message, signs it with the cash register certificate, sends it and returns the confirmation code (POK).

This library was generated by Claude (Anthropic) from the tax administration's official technical documentation. The code is tested, and sending has been verified against the live EET playground (how). Please review it before using it in production.

Installation

go get github.com/qwerty2586/eet2

Usage

d, err := eet2.NewDispatcher(eet2.PlaygroundService, "CA_EETPlayground-CZ00000019.p12", "password")
if err != nil {
	log.Fatal(err)
}

resp, err := d.SendPayment(eet2.Receipt{
	EicPopl:    "CZ00000019",
	IdJednotky: 303,
	IdPokl:     "RECEPCE",
	PoradCis:   "2027/000123",
	DatTrzby:   time.Now(),
	CelkTrzba:  decimal.RequireFromString("250.00"),
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("POK:", resp.Pok)

All Receipt fields and the EET reply attributes keep their Czech names (EicPopl, PoradCis, CelkTrzba, Opakovane, Pok, …) so they match the official specification. Everything else is in English.

Features

  • Certificate from a file or from memory: .p12 as []byte, PEM, or your own crypto.Signer (HSM, KMS). CheckP12 verifies a certificate and its password offline. → docs/certificates.md
  • Exact amounts: decimal.Decimal instead of float64. The library does not round; amounts with more than two decimal places are rejected. → docs/amounts.md
  • Resending after a failure: eet2.IsRetryable(err) and Opakovane: true. → docs/retries.md
  • Certificate renewal through the CA EET API: RenewCertificate and Confirm, swapped at runtime without a restart. → docs/certificates.md, ready-made program in example/certificate_renewal
  • Collision helper: RegisterKey() for a unique database index, so one id_pokl never registers two sales in the same second. → docs/collisions.md
  • Validation before sending against the formats from the specification. The sale fields are described in the Receipt documentation.

Examples

# send a test sale to the playground
go run ./example/playground -p12 CA_EETPlayground-CZ00000019.p12 -password <password>

# renew the cash register certificate
go run ./example/certificate_renewal -p12 register.p12 -password <password> -out register-new.p12

Limitations

  • The electronic signature of confirmation messages is not verified yet. The reply's authenticity relies on the TLS connection with a verified server certificate.
  • The library does not provide a resend queue or sale storage; that belongs in the application.
  • Certificate renewal has not been tried against the real CA EET yet, only against a simulation built from the official API specification.

Inspiration

  • prochac/eet: Go client for the original EET (2016–2022). The simplicity of its API (NewDispatcher, Receipt, SendPayment) is the direct model for this library.

Sources

  • EET 2.0 – Pro vývojáře: interface specification, data message field descriptions, access information and EET certificate authority documentation.

This library is not an official product of the Czech tax administration and is not affiliated with it.

License

MIT

Documentation

Overview

Package eet2 is a client for the Czech electronic sales registration EET 2.0 (Act No. 180/2026 Coll., EET interface version 4).

The package builds the sale data message, signs it with the cash register certificate per WS-Security (Exclusive C14N, SHA-256, RSA-SHA256), sends it synchronously to the tax administration and returns the confirmation code (POK) or an error. It can also renew the certificate through the CA EET API.

All Receipt fields and the EET reply attributes keep their Czech names (EicPopl, PoradCis, CelkTrzba, Opakovane, Pok, …) so they match the official specification.

Amounts are decimal.Decimal (github.com/shopspring/decimal) with at most two decimal places. Rounding is up to the application so that the registered amount matches the receipt.

Basic usage:

d, err := eet2.NewDispatcherFromP12(eet2.PlaygroundService, p12Bytes, "password")
if err != nil {
	log.Fatal(err)
}
resp, err := d.SendPayment(eet2.Receipt{
	EicPopl:    "CZ00000019",
	IdJednotky: 303,
	IdPokl:     "RECEPCE",
	PoradCis:   "2027/000123",
	DatTrzby:   time.Now(),
	CelkTrzba:  decimal.RequireFromString("250.00"),
})
if err != nil {
	if eet2.IsRetryable(err) {
		// queue the sale and send it again with Opakovane: true
	}
	log.Fatal(err)
}
fmt.Println("POK:", resp.Pok)

Interface specification: https://eet.gov.cz/cs/pro-vyvojare

Example
package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/qwerty2586/eet2"
	"github.com/shopspring/decimal"
)

func main() {
	// The certificate can live anywhere, e.g. in a database: its content is enough.
	p12, err := os.ReadFile("CA_EETPlayground-CZ00000019.p12")
	if err != nil {
		log.Fatal(err)
	}
	d, err := eet2.NewDispatcherFromP12(eet2.PlaygroundService, p12, "password")
	if err != nil {
		log.Fatal(err)
	}

	r := eet2.Receipt{
		EicPopl:    "CZ00000019",
		IdJednotky: 303,
		IdPokl:     "RECEPCE",
		PoradCis:   "2027/000123",
		DatTrzby:   time.Now(),
		CelkTrzba:  decimal.RequireFromString("250.00"),
	}
	resp, err := d.SendPayment(r)
	if eet2.IsRetryable(err) {
		// No POK: queue the sale and send it again, within 48 hours.
		r.Opakovane = true
		resp, err = d.SendPayment(r)
	}
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("POK:", resp.Pok)
}

Index

Examples

Constants

View Source
const (
	// MinTimeout is the shortest response time limit the law allows.
	MinTimeout = 2 * time.Second
	// DefaultTimeout is the default response time limit.
	DefaultTimeout = 3 * time.Second
)
View Source
const (
	ErrCodeTemporary  = -1 // temporary technical failure, send again later
	ErrCodeVerifiedOK = 0  // verification mode: message processed successfully
	ErrCodeEncoding   = 2  // invalid XML encoding
	ErrCodeSchema     = 3  // message failed XML schema validation
	ErrCodeSignature  = 4  // invalid SOAP message signature
	ErrCodeEIC        = 6  // malformed taxpayer EIČ
	ErrCodeTooLarge   = 7  // message too large
	ErrCodeProcessing = 8  // technical or data error
)

Error codes per the specification, ch. 3.5.4.

Variables

View Source
var ErrIncorrectPassword = pkcs12.ErrIncorrectPassword

ErrIncorrectPassword is returned (wrapped) when a PKCS#12 password is wrong. Check it with errors.Is(err, eet2.ErrIncorrectPassword).

Functions

func CheckP12

func CheckP12(p12 []byte, password string) (*x509.Certificate, error)

CheckP12 checks a PKCS#12 certificate without creating a Dispatcher: that the password is correct, that it contains an RSA key and that the key matches the certificate. It returns the certificate (EIČ in Subject.CommonName, validity in NotBefore/NotAfter). Nothing is sent anywhere.

A wrong password gives an error matching errors.Is(err, ErrIncorrectPassword).

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether the same sale should be sent again (with Opakovane: true): a connection failure, timeout or temporary server error. It returns false for validation errors and critical message errors.

func NewUUID

func NewUUID() string

NewUUID returns a random version 4 UUID (github.com/google/uuid).

EET accepts only UUID versions 1 to 5, so do not use version 7 for UuidZpravy.

Types

type CAError

type CAError struct {
	StatusCode     int
	Code           int
	Message        string
	AdditionalInfo string
	// RetryAfter is the suggested pause before the next attempt (HTTP 429).
	RetryAfter time.Duration
}

CAError is an error reply from the certificate authority API.

func (*CAError) Error

func (e *CAError) Error() string

func (*CAError) Temporary

func (e *CAError) Temporary() bool

Temporary is true for errors worth retrying later (rate limiting, server errors).

type CAService

type CAService string

CAService is the address of the EET certificate authority API (CA EET v2), used to renew the cash register certificate automatically.

const (
	// CAProductionService is the production CA EET. A Dispatcher created
	// with ProductionService uses it automatically.
	CAProductionService CAService = "https://ca.caeet.gov.cz/api"

	// CATestService is the CA EET test environment.
	CATestService CAService = "https://ca.test.caeet.gov.cz/api"

	// CATrialService is the CA EET trial environment ("zkušební prostředí").
	CATrialService CAService = "https://ca.zkus.caeet.gov.cz/api"
)

type Dispatcher

type Dispatcher struct {
	// contains filtered or unexported fields
}

Dispatcher sends sales to EET. It is safe for concurrent use, including swapping the certificate at runtime (UpdateCertificate, Renewal.Confirm).

func NewDispatcher

func NewDispatcher(service Service, p12File, password string, opts ...Option) (*Dispatcher, error)

NewDispatcher loads the cash register certificate from a PKCS#12 file (.p12/.pfx).

func NewDispatcherFromP12

func NewDispatcherFromP12(service Service, p12 []byte, password string, opts ...Option) (*Dispatcher, error)

NewDispatcherFromP12 loads the cash register certificate from PKCS#12 (.p12/.pfx) content in memory, e.g. from a database or a secrets vault.

func NewDispatcherFromPEM

func NewDispatcherFromPEM(service Service, certPEM, keyPEM []byte, opts ...Option) (*Dispatcher, error)

NewDispatcherFromPEM loads the certificate and private key in PEM format. The key may be PKCS#1 ("RSA PRIVATE KEY") or PKCS#8 ("PRIVATE KEY"). certPEM and keyPEM may also be one file containing both blocks.

func NewDispatcherWithSigner

func NewDispatcherWithSigner(service Service, cert *x509.Certificate, key crypto.Signer, opts ...Option) (*Dispatcher, error)

NewDispatcherWithSigner uses an already loaded certificate and key. Useful for keys in an HSM or cloud KMS that implement crypto.Signer.

func (*Dispatcher) BuildRequest

func (d *Dispatcher) BuildRequest(r Receipt) (xml []byte, uuid string, err error)

BuildRequest builds and signs the data message without sending it. It returns the XML and the message UUID. Useful for debugging or a custom transport.

func (*Dispatcher) Certificate

func (d *Dispatcher) Certificate() *x509.Certificate

Certificate returns the current cash register certificate (e.g. to check NotAfter).

func (*Dispatcher) RenewCertificate

func (d *Dispatcher) RenewCertificate(ctx context.Context) (*Renewal, error)

RenewCertificate renews the cash register certificate through the CA EET API and returns the new certificate. The Dispatcher keeps using the old one: it switches only in Renewal.Confirm, which you call after storing P12 and Password safely.

If the CA has an unfinished request (e.g. the application crashed before Confirm), it is picked up instead of filing a new one. The call waits for the certificate to be issued; ctx limits how long. The request keeps going at the CA after ctx is cancelled and the next call picks it up.

Renew while the current certificate is still valid. The tax administration recommends 2–3 weeks before it expires.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/qwerty2586/eet2"
)

func main() {
	p12, _ := os.ReadFile("register.p12")
	d, err := eet2.NewDispatcherFromP12(eet2.ProductionService, p12, "password")
	if err != nil {
		log.Fatal(err)
	}

	// Renew 2–3 weeks before expiry, while the old certificate is still valid.
	if time.Until(d.Certificate().NotAfter) > 21*24*time.Hour {
		return
	}
	ctx := context.Background()

	// Files a request (or resumes an unfinished one), waits for the
	// certificate to be issued and downloads it.
	renewal, err := d.RenewCertificate(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// 1. Store the new certificate safely first. If this fails nothing is
	//    lost: the next RenewCertificate downloads the same certificate again.
	//    Keep the password (renewal.Password) separately, e.g. in a secrets vault.
	if err := os.WriteFile("register-new.p12", renewal.P12, 0o600); err != nil {
		log.Fatal(err)
	}

	// 2. Only then confirm receipt. This switches the Dispatcher to the new
	//    certificate; afterwards the CA no longer offers it for download.
	if err := renewal.Confirm(ctx); err != nil {
		log.Fatal(err)
	}
	fmt.Println("new certificate valid until", d.Certificate().NotAfter)
}

func (*Dispatcher) SendPayment

func (d *Dispatcher) SendPayment(r Receipt) (*Response, error)

SendPayment sends the sale and returns the reply with the POK.

On error, check IsRetryable(err): if true, store the sale and send it again with the same data and Opakovane: true (within 48 hours at the latest).

func (*Dispatcher) SendPaymentContext

func (d *Dispatcher) SendPaymentContext(ctx context.Context, r Receipt) (*Response, error)

SendPaymentContext is SendPayment with a context. The response time limit (WithTimeout) always applies, even if the context has a later deadline.

func (*Dispatcher) UpdateCertificate

func (d *Dispatcher) UpdateCertificate(cert *x509.Certificate, key crypto.Signer) error

UpdateCertificate swaps the certificate at runtime. Sends in progress finish with the old certificate, later ones use the new one.

func (*Dispatcher) UpdateCertificateFromP12

func (d *Dispatcher) UpdateCertificateFromP12(p12 []byte, password string) error

UpdateCertificateFromP12 swaps the certificate at runtime for one from PKCS#12 content, e.g. freshly downloaded from DIS+.

type Error

type Error struct {
	Code                int
	Text                string
	Test                bool
	UuidZpravy          string
	DatOdmit            time.Time
	GlobalTransactionID string
}

Error is an error reply from EET: a critical error in the message or a temporary technical failure on the server side.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Temporary

func (e *Error) Temporary() bool

Temporary is true for a temporary technical failure on the server (negative code). The message must be sent again later.

type Option

type Option func(*Dispatcher)

Option configures a Dispatcher.

func WithCAService

func WithCAService(s CAService) Option

WithCAService sets the certificate authority API used by RenewCertificate. CAProductionService is used automatically for ProductionService.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets a custom HTTP client (proxy, custom transport…). The client must verify the server's TLS certificate.

func WithTimeout

func WithTimeout(t time.Duration) Option

WithTimeout sets the response time limit. Values below MinTimeout (2 s) are raised to MinTimeout.

type Receipt

type Receipt struct {
	// UuidZpravy is the message UUID (uuid_zpravy). Leave it empty: a fresh
	// UUID is generated for every send, which the spec requires even for
	// resends.
	UuidZpravy string

	// Opakovane marks a repeated send of the same sale (prvni_zaslani=false),
	// typically after a connection failure. The sale data must not change.
	Opakovane bool

	// Overeni enables verification mode (overeni): the server only checks
	// the message and does not register the sale.
	Overeni bool

	// EicPopl is the taxpayer's registration number (eic_popl), e.g. "CZ00000019".
	EicPopl string

	// EicPoverujiciho is the EIČ of the taxpayer who authorised EicPopl to
	// register sales on their behalf (eic_poverujiciho).
	EicPoverujiciho string

	// PovereniVicePopl marks a sale that belongs to several taxpayers
	// (povereni_vice_popl).
	PovereniVicePopl bool

	// IdJednotky is the registration unit number assigned in DIS+
	// (id_jednotky, 1–999999999).
	IdJednotky int

	// IdPokl identifies the cash register (id_pokl, 1–20 characters).
	IdPokl string

	// PoradCis is the sale's sequence number (porad_cis, 1–25 characters).
	PoradCis string

	// DatTrzby is when the sale took place (dat_trzby). It is sent in the
	// Europe/Prague time zone (+01:00 / +02:00) regardless of the system
	// time zone. Fractional seconds are dropped: truncate the time with
	// Truncate(time.Second) before storing it, so a resend loaded from the
	// database matches (see docs/retries.md).
	DatTrzby time.Time

	// CelkTrzba is the total amount in CZK including taxes (celk_trzba),
	// negative for refunds. At most two decimal places: rounding is up to
	// the application so the registered amount matches the receipt
	// (see docs/amounts.md).
	CelkTrzba decimal.Decimal

	// UrcenoCerpZuct is the amount intended for later drawing or settlement,
	// e.g. topping up credit (urceno_cerp_zuct). Valid=false omits it.
	UrcenoCerpZuct decimal.NullDecimal

	// CerpZuct is the amount drawn from earlier credit (cerp_zuct).
	// Valid=false omits it.
	CerpZuct decimal.NullDecimal
}

Receipt is one registered sale (evidovaná tržba).

Field names follow the EET data message attributes. Required fields are EicPopl, IdJednotky, IdPokl, PoradCis, DatTrzby and CelkTrzba; set the others only when they apply to the sale.

func (Receipt) RegisterKey

func (r Receipt) RegisterKey() (string, error)

RegisterKey is a helper for preventing collisions. It returns "eic_popl*id_jednotky*id_pokl*dat_trzby" with the values normalised exactly as they are sent (dat_trzby in Europe/Prague, whole seconds).

The specification requires this combination to be unique: one id_pokl may not register two sales in the same second within a registration unit. Store it in a column with a unique index, and when an insert fails on it, assign another id_pokl (or wait a second) before sending. Uniqueness of this key also guarantees uniqueness of the porad_cis combination, which only adds porad_cis to it.

The separator "*" cannot appear in any of the fields, so two different combinations never produce the same key. Unlike UniqueKey, it does not include porad_cis or the amount.

func (Receipt) UniqueKey

func (r Receipt) UniqueKey() (string, error)

UniqueKey returns the string by which EET recognises the same sale (eic|unit|register|sequence number|date and time|amount). Useful as a key for a resend queue.

func (Receipt) Validate

func (r Receipt) Validate() error

Validate checks the sale against the formats from the specification.

type RejectedError

type RejectedError struct {
	ReqID  string
	Reason string
}

RejectedError means the CA rejected the renewal request.

func (*RejectedError) Error

func (e *RejectedError) Error() string

type Renewal

type Renewal struct {
	// ReqID is the CA EET request identifier.
	ReqID string
	// P12 is the new certificate with its private key in PKCS#12 format.
	P12 []byte
	// Password opens P12.
	Password string
	// Certificate is the new certificate (NotBefore, NotAfter, SerialNumber…).
	Certificate *x509.Certificate
	// contains filtered or unexported fields
}

Renewal is an issued and downloaded new certificate whose receipt has not been confirmed yet. Store P12 and Password, then call Confirm.

Until the receipt is confirmed, the certificate can be downloaded again: the next RenewCertificate call picks up the same request (for up to 30 days after issue).

func (*Renewal) Confirm

func (r *Renewal) Confirm(ctx context.Context) error

Confirm confirms receipt of the certificate to CA EET and switches the Dispatcher to the new certificate. Call it only after P12 and Password are stored safely: once confirmed, the certificate cannot be downloaded again.

Calling it again is safe.

func (*Renewal) GoString

func (r *Renewal) GoString() string

GoString hides P12 and the password for %#v as well.

func (*Renewal) String

func (r *Renewal) String() string

String does not print P12 or the password, so they never end up in logs.

type Response

type Response struct {
	// UuidZpravy is the UUID of the sent message (uuid_zpravy).
	UuidZpravy string

	// DatPrij is when the server received the message (dat_prij).
	DatPrij time.Time

	// Pok is the confirmation code (pok, 39 characters). Empty in
	// verification mode. In the non-production environment it ends with
	// "-ff" and is not valid.
	Pok string

	// Test is true if the reply came from the non-production environment
	// (playground).
	Test bool

	// Verified is true in verification mode when the message passed all
	// checks (the server returned error code 0). The sale is NOT registered.
	Verified bool

	// Warnings are non-critical errors. The POK is valid even with warnings,
	// but the data is worth fixing.
	Warnings []Warning

	// GlobalTransactionID is the X-Global-Transaction-Id header, useful when
	// tracking down problems with the tax administration's support.
	GlobalTransactionID string
}

Response is a successful reply from EET.

type Service

type Service string

Service is the address of the EET web service.

const (
	// PlaygroundService is the non-production environment for developers.
	// The returned POK ends with "-ff" and is not valid.
	PlaygroundService Service = "https://pg.trzbyeet.gov.cz/eet/services/EETServiceSOAP/v4"

	// ProductionService is the production environment.
	ProductionService Service = "https://trzbyeet.gov.cz/eet/services/EETServiceSOAP/v4"
)

type UnexpectedResponseError

type UnexpectedResponseError struct {
	StatusCode          int
	Msg                 string
	GlobalTransactionID string
}

UnexpectedResponseError means the server returned a reply that cannot be processed (unexpected HTTP status, SOAP Fault, incomplete XML).

func (*UnexpectedResponseError) Error

func (e *UnexpectedResponseError) Error() string

type ValidationError

type ValidationError struct {
	Field string
	Value string
	Msg   string
}

ValidationError reports a field that does not match the format required by the specification. Such a message is never sent and must not be retried.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Warning

type Warning struct {
	Code int
	Text string
}

Warning is a non-critical error (varovani) from the reply.

Directories

Path Synopsis
example
certificate_renewal command
Command certificate_renewal renews the cash register certificate through the CA EET API.
Command certificate_renewal renews the cash register certificate through the CA EET API.
playground command
Command playground sends one test sale to the EET 2.0 non-production environment (playground) and prints the reply.
Command playground sends one test sale to the EET 2.0 non-production environment (playground) and prints the reply.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL