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)
}
Output:
Index ¶
- Constants
- Variables
- func CheckP12(p12 []byte, password string) (*x509.Certificate, error)
- func IsRetryable(err error) bool
- func NewUUID() string
- type CAError
- type CAService
- type Dispatcher
- func NewDispatcher(service Service, p12File, password string, opts ...Option) (*Dispatcher, error)
- func NewDispatcherFromP12(service Service, p12 []byte, password string, opts ...Option) (*Dispatcher, error)
- func NewDispatcherFromPEM(service Service, certPEM, keyPEM []byte, opts ...Option) (*Dispatcher, error)
- func NewDispatcherWithSigner(service Service, cert *x509.Certificate, key crypto.Signer, opts ...Option) (*Dispatcher, error)
- func (d *Dispatcher) BuildRequest(r Receipt) (xml []byte, uuid string, err error)
- func (d *Dispatcher) Certificate() *x509.Certificate
- func (d *Dispatcher) RenewCertificate(ctx context.Context) (*Renewal, error)
- func (d *Dispatcher) SendPayment(r Receipt) (*Response, error)
- func (d *Dispatcher) SendPaymentContext(ctx context.Context, r Receipt) (*Response, error)
- func (d *Dispatcher) UpdateCertificate(cert *x509.Certificate, key crypto.Signer) error
- func (d *Dispatcher) UpdateCertificateFromP12(p12 []byte, password string) error
- type Error
- type Option
- type Receipt
- type RejectedError
- type Renewal
- type Response
- type Service
- type UnexpectedResponseError
- type ValidationError
- type Warning
Examples ¶
Constants ¶
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 )
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 ¶
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 ¶
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.
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.
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)
}
Output:
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 ¶
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.
type Option ¶
type Option func(*Dispatcher)
Option configures a Dispatcher.
func WithCAService ¶
WithCAService sets the certificate authority API used by RenewCertificate. CAProductionService is used automatically for ProductionService.
func WithHTTPClient ¶
WithHTTPClient sets a custom HTTP client (proxy, custom transport…). The client must verify the server's TLS certificate.
func WithTimeout ¶
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 ¶
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.
type RejectedError ¶
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 ¶
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.
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 ¶
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 ¶
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
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. |