Go · API v2
Profirest API pro Go
Knihovna Profirest API v2 pro Go 1.24+ jen nad standardní knihovnou – pro integrace, služby a servery partnerů (rozvozové platformy, účetní můstky); s modely ze smlouvy a kontextem pro zrušení.
The Profirest API v2 library for Go 1.24+ on the standard library only – for integrations, services and partner servers (delivery platforms, accounting bridges); with models from the contract and contexts for cancellation.
Knihovna dělá za vás to, co jinak musí každá aplikace napsat a hlavně nezapomenout: spáruje zařízení kódem, připojí aplikaci partnera se souhlasem majitele (OAuth s PKCE), uloží tokeny a obnoví je jen jednou i při souběžných požadavcích a mezi procesy, přihlásí zaměstnance PINem nebo čipem, pošle Idempotency-Key u každého POST (při opakování stejný), po výpadku opakuje podle Retry-After, chyby vrací s kódem z katalogu, prochází stránky seznamů a čte proud událostí. Cesty, těla a odpovědi jsou přesně podle reference; modely všech schémat jsou vygenerované ze smlouvy.
The library does what every application otherwise has to write and, above all, not forget: it pairs a device with a code, connects a partner application with the owner's consent (OAuth with PKCE), stores the tokens and refreshes them only once even for concurrent requests and across processes, signs employees in with a PIN or a card, sends an Idempotency-Key with every POST (the same one when retrying), retries after an outage following Retry-After, returns errors with a code from the catalog, walks list pages and reads the event feed. Paths, bodies and responses are exactly as in the reference; models of all schemas are generated from the contract.
Ke stažení
Download
Archiv obsahuje knihovnu, příkladového klienta, jednotkové testy, README s podrobným návodem, licenci (MIT) a seznam změn. Instalujte ho z archivu, jak ukazuje návod níže. Výchozí adresa knihovny je ostrá https://api.mujprofirest.cz – pracuje nad ostrými daty restaurací, zkoušejte na testovací provozovně.
The archive contains the library, the example client, unit tests, a README with a detailed guide, the licence (MIT) and the changelog. Install it from the archive as shown below. The default address of the library is production https://api.mujprofirest.cz – it works on live restaurant data, test on a test restaurant.
| ModulModule | github.com/profirest/profirest-api-go, modely …/model |
| PožadavkyRequirements | Go 1.24+ |
| ZávislostiDependencies | žádné (standardní knihovna)none (standard library) |
| BalíčekPackage | profirest |
Instalace
Installation
Archiv rozbalte vedle svého modulu a připojte ho direktivou replace (po zveřejnění stačí go get github.com/profirest/profirest-api-go):
Unpack the archive next to your module and link it with a replace directive (once published, go get github.com/profirest/profirest-api-go is enough):
go mod edit -require=github.com/profirest/profirest-api-go@v1.0.0
go mod edit -replace=github.com/profirest/profirest-api-go=../profirest-api-go-1.0.0import (
profirest "github.com/profirest/profirest-api-go"
"github.com/profirest/profirest-api-go/model" // vygenerované modely (AttendancePunch, Connection…)
)Příkladový klient
Example client
Hotová aplikace k vyzkoušení: docházkový terminál v příkazové řádce. Při prvním spuštění zařízení spáruje (vypíše kód, vedoucí ho potvrdí v administraci v Správa PC / zařízení → Připojit kódem), tokeny uloží do souboru a pak přijímá příkazy. Ukazuje párování, píchnutí PINem, výběr zaměstnance při stejném PINu, rozlišení chyb podle kódu a seznam lidí v práci. Adresu API mění proměnná PROFIREST_BASE_URL, soubor s tokeny PROFIREST_TOKENS.
A ready application to try: an attendance terminal on the command line. On the first run it pairs the device (it prints a code that a manager confirms in the administration under PC / devices → Connect a device), stores the tokens in a file and then accepts commands. It shows pairing, punching with a PIN, choosing the employee when a PIN is shared, telling errors apart by code and the list of people at work. PROFIREST_BASE_URL changes the API address, PROFIREST_TOKENS the token file.
p PINpříchodarrivalo PINodchoddeparturepz PINzačátek přestávkybreak startkz PINkonec přestávkybreak endkkdo je v práciwho is at workodparovatzapomene spárováníforgets the pairingqkonecquitgo run ./examples/pichacka// Příkladový klient Profirest API v2: docházkový terminál v příkazové řádce.
//
// go run ./examples/pichacka
//
// Při prvním spuštění zařízení spáruje – vypíše kód, který vedoucí potvrdí v administraci (Správa PC / zařízení →
// Připojit zařízení). Pak čte příkazy:
//
// p PIN příchod o PIN odchod
// pz PIN začátek přestávky kz PIN konec přestávky
// k kdo je v práci odparovat zapomenout spárování q konec
//
// Proměnné prostředí: PROFIREST_BASE_URL (výchozí https://api.mujprofirest.cz), PROFIREST_TOKENS (soubor s tokeny,
// výchozí ./profirest-pichacka.json – chraňte ho jako heslo).
package main
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"strconv"
"strings"
profirest "github.com/profirest/profirest-api-go"
"github.com/profirest/profirest-api-go/model"
)
var states = map[string]string{"working": "v práci", "on_break": "na přestávce", "off": "mimo práci"}
func state(s string) string {
if v, ok := states[s]; ok {
return v
}
return s
}
func main() {
ctx := context.Background()
base := os.Getenv("PROFIREST_BASE_URL")
if base == "" {
base = "https://api.mujprofirest.cz"
}
tokens := os.Getenv("PROFIREST_TOKENS")
if tokens == "" {
tokens = "profirest-pichacka.json"
}
api := profirest.New(profirest.Options{
BaseURL: base,
ClientID: "profirest-dochazka",
Storage: profirest.NewFileStorage(tokens),
})
// 1) spárování kódem (RFC 8628) – jen poprvé, tokeny pak zůstávají v souboru
if !api.IsPaired() {
pairing, err := api.Pair(ctx, profirest.PairOptions{
Scope: "restaurants:read staff:read staff:authenticate attendance:read attendance:punch",
DeviceName: "Píchačka (příklad)",
})
if err == nil {
fmt.Println("Zařízení není spárované. Vedoucí potvrdí kód v administraci (Správa PC / zařízení → Připojit zařízení).")
fmt.Println("KÓD: " + pairing.UserCode)
fmt.Println("nebo otevřete: " + pairing.VerificationURIComplete)
_, err = pairing.Wait(ctx) // ptá se podle intervalu, než vedoucí potvrdí
}
if err != nil {
var oe *profirest.OAuthError
switch {
case errors.As(err, &oe) && oe.Code == "access_denied":
fmt.Println("Vedoucí párování odmítl.")
case errors.As(err, &oe) && oe.Code == "expired_token":
fmt.Println("Kód vypršel (10 minut). Spusťte příklad znovu.")
default:
fmt.Println("Párování se nepovedlo: " + err.Error())
}
os.Exit(1)
}
}
if api.RestaurantID() == "" {
if _, err := api.Connection(ctx); err != nil { // zapamatuje provozovnu zařízení
fmt.Println("Chyba: " + err.Error())
os.Exit(1)
}
}
rid := api.RestaurantID()
fmt.Printf("Provozovna %s. Příkazy: p/o/pz/kz PIN, k = kdo je v práci, odparovat, q = konec.\n", rid)
types := map[string]string{"p": "clock_in", "o": "clock_out", "pz": "break_start", "kz": "break_end"}
in := bufio.NewScanner(os.Stdin)
// 3) smyčka příkazů
for in.Scan() {
parts := strings.Fields(in.Text())
if len(parts) == 0 {
continue
}
cmd := strings.ToLower(parts[0])
var err error
switch {
case types[cmd] != "" && len(parts) > 1:
punch(ctx, api, in, rid, types[cmd], strings.Join(parts[1:], " "))
case cmd == "k":
var presence []model.AttendancePresence
presence, err = profirest.All[model.AttendancePresence](ctx, api, "/restaurants/"+rid+"/attendance/presence", nil)
for _, p := range presence {
fmt.Printf(" %s: %s\n", p.Employee.Name, state(p.State))
}
case cmd == "odparovat":
if err = api.Unpair(ctx); err == nil {
fmt.Println("Spárování zapomenuto.")
return
}
case cmd == "q":
return
default:
fmt.Println("Příkazy: p/o/pz/kz PIN, k, odparovat, q")
}
if err != nil {
var e *profirest.APIError
if errors.As(err, &e) && e.Code == profirest.CodeNotPaired { // vedoucí zařízení odpároval
fmt.Println("Zařízení bylo odpárováno. Spusťte příklad znovu.")
os.Exit(1)
}
if errors.As(err, &e) {
fmt.Printf("Chyba: %s (%s)\n", e.Title, e.Code)
} else {
fmt.Println("Chyba: " + err.Error())
}
}
}
}
// 2) píchnutí – id vznikne jednou na píchnutí; při opakování (výběr zaměstnance, výpadek) se posílá stejné
func punch(ctx context.Context, api *profirest.Client, in *bufio.Scanner, rid, typ, pin string) {
body := model.AttendancePunchCreate{
ID: profirest.UUID(),
Type: typ,
Credential: &model.StaffCredential{Method: "pin", Secret: pin},
}
for {
r, err := profirest.Post[model.AttendancePunch](ctx, api, "/restaurants/"+rid+"/attendance/punches", body, nil)
if err == nil {
fmt.Printf("OK: %s – %s\n", r.Employee.Name, state(r.State))
return
}
var e *profirest.APIError
if !errors.As(err, &e) {
fmt.Println("Chyba: " + err.Error())
return
}
switch e.Code {
case profirest.CodeNotPaired: // vedoucí zařízení odpároval
fmt.Println("Zařízení bylo odpárováno. Spusťte příklad znovu.")
os.Exit(1)
case profirest.CodeStaffAmbiguous: // stejný PIN má víc lidí – vybrat a poslat znovu
fmt.Println("Tento PIN má víc lidí:")
for i, c := range e.Candidates {
fmt.Printf(" %d) %s\n", i+1, c.Name)
}
fmt.Print("Číslo: ")
choice := 0
if in.Scan() {
choice, _ = strconv.Atoi(strings.TrimSpace(in.Text()))
}
if choice < 1 || choice > len(e.Candidates) {
fmt.Println("Zrušeno.")
return
}
id := e.Candidates[choice-1].ID
body.Credential.EmployeeID = &id
continue
case profirest.CodeStaffCredentialsInvalid:
fmt.Println("Neznámý PIN.")
case profirest.CodeStaffLocked:
wait := "chvíli"
if e.RetryAfter != nil {
wait = fmt.Sprintf("%d s", int(e.RetryAfter.Seconds()))
}
fmt.Printf("Moc špatných pokusů – zkuste to za %s.\n", wait)
case profirest.CodeAttendanceStateConflict:
fmt.Println("Teď to nejde: " + e.Title)
case profirest.CodeNetworkError, profirest.CodeTimeout:
fmt.Println("Bez sítě – zkuste znovu.") // skutečný terminál by píchnutí uložil a poslal dávkou
default:
fmt.Printf("Chyba: %s (%s)\n", e.Title, e.Code)
}
return
}
}Spárovat zařízení
Pair a device
Pokladna, kuchyňský displej, docházkový terminál a telefon kurýra se připojují kódem (RFC 8628). Zařízení ukáže kód, vedoucí ho zadá v administraci (Správa PC / zařízení → Připojit kódem) a vybere provozovnu; zařízení si tokeny vyzvedne samo a pak pracuje jen pro ni. Kód platí 10 minut; knihovna se ptá podle interval (5 s), po slow_down o 5 s déle a výpadek sítě přečká. Odmítnutí vedoucím = access_denied, propadlý kód = expired_token.
A register, kitchen display, attendance terminal and courier phone connect with a code (RFC 8628). The device shows the code, a manager enters it in the administration (PC / devices → Connect a device) and chooses the restaurant; the device collects its tokens itself and then works only for it. The code is valid for 10 minutes; the library polls every interval (5 s), 5 s slower after slow_down, and survives a network outage. A refusal by the manager = access_denied, an expired code = expired_token.

api := profirest.New(profirest.Options{
ClientID: "profirest-dochazka",
Storage: profirest.NewFileStorage("/var/lib/pichacka/profirest.json"),
OnUnpaired: func(reason *profirest.OAuthError) { showPairing() },
})
if !api.IsPaired() {
pairing, err := api.Pair(ctx, profirest.PairOptions{
Scope: "restaurants:read staff:read staff:authenticate attendance:read attendance:punch",
DeviceName: "Píchačka u vchodu",
})
if err != nil {
return err
}
fmt.Println("Kód:", pairing.UserCode, pairing.VerificationURIComplete)
if _, err := pairing.Wait(ctx); err != nil { // *OAuthError: access_denied, expired_token
return err
}
}
fmt.Println("Provozovna", api.RestaurantID())Webová aplikace: pairing.State() uložte do session (JSON) a v dalším požadavku zavolejte api.ResumePairing(state).Poll(ctx) – na server se zeptá jen po uplynutí intervalu.
A web application: store pairing.State() in the session (JSON) and call api.ResumePairing(state).Poll(ctx) in the next request – it asks the server only after the interval.
| AplikaceApplication | client_id |
|---|---|
| Pokladna a mobilní číšníkRegister and mobile waiter | profirest-pos |
| Kuchyňský displej, výdej, pořadníkKitchen display, pickup, queue screen | profirest-kds |
| Docházkový terminálAttendance terminal | profirest-dochazka |
| Telefon kurýraCourier phone | profirest-kuryr |
| Aplikace partnera (e-shop)Partner application (e-shop) | přidělí Profirestassigned by Profirest |
Docházkový terminál
Attendance terminal
POST /v2/restaurants/{restaurant_id}/attendance/punches. Na terminálu se nikdo nepřihlašuje – každé píchnutí nese PIN nebo čip. id vznikne na zařízení ve chvíli píchnutí (UUIDv7 řazené podle času) a stejné id server nikdy nezapíše dvakrát: první zápis vrátí 201, opakování 200 se stejným tělem. Chyby se rozlišují podle kódu, ne podle HTTP stavu.
POST /v2/restaurants/{restaurant_id}/attendance/punches. Nobody signs in on a terminal – every punch carries a PIN or a card. The id is made on the device when the person punches (a time-ordered UUIDv7) and the server never records the same id twice: the first write returns 201, a repeat 200 with the same body. Errors differ by code, not by HTTP status.
res, err := api.Post(ctx, "/restaurants/"+api.RestaurantID()+"/attendance/punches", map[string]any{
"id": profirest.UUID(), // UUIDv7
"type": "clock_in", // clock_out, break_start, break_end
"credential": map[string]any{"method": "pin", "secret": pin},
}, nil)
var apiErr *profirest.APIError
switch {
case err == nil:
var punch model.AttendancePunch
_ = res.Decode(&punch)
fmt.Println(punch.Employee.Name, punch.State) // working, on_break, off
case errors.As(err, &apiErr) && apiErr.Code == profirest.CodeStaffAmbiguous:
chooseEmployee(apiErr.Candidates) // znovu se stejným id a credential.employee_id
case errors.As(err, &apiErr) && apiErr.Code == profirest.CodeStaffLocked:
showLocked(apiErr.RetryAfter)
case profirest.ErrorCode(err) == profirest.CodeNetworkError, profirest.ErrorCode(err) == profirest.CodeTimeout:
saveOffline() // později dávkou …/punches/batch
default:
return err
}Bez sítě píchnutí uložte i s id a časem occurred_at a pošlete později dávkou (nejvýš 100) na POST …/attendance/punches/batch – každá položka má vlastní výsledek. Frontu držte jen na zařízení, nese PINy.
Without a network store the punch with its id and occurred_at and send it later in a batch (at most 100) to POST …/attendance/punches/batch – every item gets its own result. Keep the queue on the device only, it carries PINs.
Pokladna a zaměstnanec
Register and employee
Na pokladně se zaměstnanec přihlásí PINem nebo čipem a knihovna pak posílá jeho token v hlavičce Profirest-Staff-Token u každého požadavku sama; token drží jen v paměti. Relace vyprší po nečinnosti (idle_timeout_seconds, každý úspěšný požadavek ji prodlouží) a nejpozději v max_expires_at – počítá se podle hodin zařízení. Stejný PIN víc lidí = 409 staff_ambiguous s kandidáty: nechte vybrat a zavolejte znovu s employee_id. Volba staff u požadavku: automaticky (výchozí – poslat, je-li někdo přihlášený), vyžadovat (bez přihlášení chyba staff_session_required a nic se neodešle), neposílat, nebo konkrétní token.
On a register an employee signs in with a PIN or a card and the library then sends their token in the Profirest-Staff-Token header with every request itself; the token stays in memory only. The session ends after inactivity (idle_timeout_seconds, every successful request extends it) and at max_expires_at at the latest – counted by the device clock. Several people with the same PIN = 409 staff_ambiguous with candidates: let the person choose and call again with employee_id. The staff request option: automatic (default – send it when somebody is signed in), required (without a sign-in the error staff_session_required and nothing is sent), never, or a specific token.
session, err := api.SignInStaff(ctx, rid, model.StaffCredential{Method: "pin", Secret: pin})
var apiErr *profirest.APIError
if errors.As(err, &apiErr) && apiErr.Code == profirest.CodeStaffAmbiguous {
who := chooseEmployee(apiErr.Candidates)
session, err = api.SignInStaff(ctx, rid, model.StaffCredential{Method: "pin", Secret: pin, EmployeeID: &who})
}
// token zaměstnance pošle knihovna sama; StaffRequired = bez přihlášení se požadavek ani neodešle
_, err = api.Post(ctx, "/restaurants/"+rid+"/receipts", receipt, &profirest.RequestOptions{Staff: profirest.StaffRequired})
api.SignOutStaff(ctx, "")Aplikace partnera
Partner application
E-shop nebo jiná aplikace partnera se připojuje se souhlasem majitele restaurace (authorization code + PKCE S256). Na serveru je to důvěrný klient: client_secret posílá knihovna jako HTTP Basic (client_secret_basic, RFC 6749 2.3.1) a nikdy nepatří do aplikace u zákazníka. Ověřovač PKCE a state drží mezi přesměrováním a zpětným voláním úložiště; zpětné volání ověří state a iss (RFC 9207) a vymění kód za tokeny. Jedna instance = jedno připojení: tokeny i rozpracovaný souhlas leží pod jedním klíčem úložiště a výchozí klíč (profirest-api:<clientId>) je jeden pro celou aplikaci. Pro každý připojený účet proto použijte vlastní instanci s vlastním klíčem úložiště odvozeným z ID účtu ve vašem systému (znáte ho už před přesměrováním) – se společným klíčem by souhlas dalšího majitele přepsal tokeny předchozího a dva souběžné souhlasy by si přepsaly state. Víc provozoven jednoho majitele je jedno připojení. Když už token máte odjinud, předejte ho jako pevný access token – knihovna ho pošle a nikdy neobnovuje.
An e-shop or another partner application connects with the consent of the restaurant owner (authorization code + PKCE S256). On a server it is a confidential client: the library sends the client_secret as HTTP Basic (client_secret_basic, RFC 6749 2.3.1) and it never belongs into an app on the customer's device. The PKCE verifier and state are kept in the storage between the redirect and the callback; the callback checks state and iss (RFC 9207) and exchanges the code for tokens. One instance = one connection: the tokens and a consent in progress sit under one storage key, and the default key (profirest-api:<clientId>) is one for the whole application. So use a separate instance with its own storage key for every connected account, derived from the account ID in your system (you know it before the redirect) – with a shared key the consent of the next owner would overwrite the tokens of the previous one and two concurrent consents would overwrite each other's state. Several restaurants of one owner are one connection. When you already have a token from elsewhere, pass it as a fixed access token – the library sends it and never refreshes it.


api := profirest.New(profirest.Options{
ClientID: "muj-eshop",
ClientSecret: os.Getenv("PROFIREST_CLIENT_SECRET"),
Storage: profirest.NewFileStorage("/var/lib/eshop/profirest-tokens.json"),
StorageKey: "account-7",
})
http.HandleFunc("/profirest/connect", func(w http.ResponseWriter, r *http.Request) {
u, _ := api.AuthorizationURL(profirest.AuthorizationOptions{
RedirectURI: "https://eshop.example.cz/profirest/callback",
Scope: "restaurants:read catalog:read orders:write",
})
http.Redirect(w, r, u, http.StatusFound)
})
http.HandleFunc("/profirest/callback", func(w http.ResponseWriter, r *http.Request) {
conn, err := api.CompleteAuthorization(r.Context(), r.URL.String()) // ověří state a iss
…
})Požadavky
Requests
Cesty se píšou relativně k /v2, přesně jako v referenci (/oauth/… a /.well-known/… jdou od kořene). Tělo: objekt nebo model → JSON; řetězec nebo bajty → syrově s typem obsahu (zálohy ZIP). Dotaz: prázdné hodnoty se vynechají, pole se spojí čárkou. Odpověď: JSON dekódovaný, 204 nic, jiný obsah bajty. U POST pošle knihovna vlastní Idempotency-Key a při automatickém opakování stejný; když požadavek opakujete vy (po restartu aplikace), předejte vlastní klíč uložený u záznamu. Klíč knihovny žije jen v paměti procesu, po pádu aplikace ho nemáte – u zápisů, které se nesmí provést dvakrát (objednávka), proto vlastní klíč vytvořte a uložte k záznamu dřív, než požadavek odešlete (server výsledek drží 24 hodin). Objednávka má navíc pojistky nezávislé na klíči: kalkulace jde použít jen jednou (409 quote_already_used) a external_id je trvalé (409 external_id_conflict); obě chyby nesou ID existující objednávky. Tokeny (Authorization i Profirest-Staff-Token) odcházejí jen na adresu API, nikdy na cizí absolutní adresu; přesměrování se nesledují.
Paths are written relative to /v2, exactly as in the reference (/oauth/… and /.well-known/… go from the root). Body: an object or a model → JSON; a string or bytes → raw with a content type (ZIP backups). Query: empty values are left out, arrays are joined with a comma. Response: JSON decoded, 204 nothing, other content bytes. For a POST the library sends its own Idempotency-Key and the same one on an automatic retry; when you repeat a request yourself (after an application restart), pass your own key stored with the record. The library's key lives only in the memory of the process, after a crash you do not have it – for writes that must not happen twice (an order) create your own key and store it with the record before you send the request (the server keeps the result for 24 hours). An order also has guards that do not depend on the key: a quote can be used only once (409 quote_already_used) and external_id is permanent (409 external_id_conflict); both errors carry the ID of the existing order. Tokens (Authorization and Profirest-Staff-Token) go only to the API address, never to a foreign absolute URL; redirects are not followed.
res, err := api.Get(ctx, "/restaurants/11/catalog", &profirest.RequestOptions{Query: map[string]any{"channel": "pos"}})
// ETag a If-Match
res, err = api.Get(ctx, "/customers/"+id, nil)
_, err = api.Patch(ctx, "/customers/"+id, map[string]any{"name": "Jana Nováková"},
&profirest.RequestOptions{IfMatch: res.Header.Get("ETag")})
// vlastní Idempotency-Key uložený u objednávky
_, err = api.Post(ctx, "/restaurants/11/orders", order, &profirest.RequestOptions{IdempotencyKey: "order-" + localID})
// binární tělo a stažení
zip, _ := os.ReadFile("zaloha.zip")
_, err = api.Post(ctx, "/restaurants/"+rid+"/backups", zip, &profirest.RequestOptions{ContentType: "application/zip"})
res, err = api.Get(ctx, "/restaurants/"+rid+"/backups/"+backupID+"/content", &profirest.RequestOptions{Accept: "application/zip"})Seznamy po stránkách
Paged lists
Seznamy vrací {data, next_cursor}. Knihovna projde stránky sama (všechny položky najednou, nebo stránku po stránce); konec je stránka bez next_cursor nebo prázdná stránka. Kurzor je neprůhledný řetězec – nikdy ho neskládejte.
Lists return {data, next_cursor}. The library walks the pages itself (all items at once, or page by page); the end is a page without next_cursor or an empty page. The cursor is an opaque string – never build one.
staff, err := profirest.All[model.StaffMember](ctx, api, "/restaurants/11/staff", nil)
for page, err := range api.Pages(ctx, "/restaurants/11/attendance/presence", nil) {
if err != nil {
return err
}
render(page.Data) // []json.RawMessage, page.NextCursor
}Proud událostí
Event feed
Proud událostí knihovna čte dokola. Když běží služba proudu, čte živě GET /v2/events/stream (Server-Sent Events) – událost přijde pár sekund po změně a nic se nedotazuje. Když neběží (503), na starším serveru nebo s vlastním transportem, který neumí číst odpověď po kouscích, čte GET /v2/events a o proud se pokusí znovu za Retry-After (výchozí 5 minut). Kurzor je v obou stejný (u proudu jde jako Last-Event-ID), přechod nic nepřeskočí; výpadek spojení není chyba – připojí se znovu za 2 s, 4 s, po třetím nezdaru minutu dotazuje. Volba stream (výchozí zapnuto; vypnuto = jen dotazování) a dotaz, zda teď běží proud, mají jména podle jazyka (viz Metody); krok pro cron (once) dělá dál jeden dotaz GET /v2/events. Kurzor posune a uloží až po úspěšném zpracování – událost tak přijde aspoň jednou, zpracování má být idempotentní (např. podle id události). Plnou stránku dožene hned, jinak čeká interval (5 s); bez uloženého kurzoru začne na konci proudu. Po 410 cursor_expired zavolá obsluhu resetu (načtěte si stav znovu), při chybě čeká podle Retry-After nebo déle a déle (až 60 s) a ztráta spárování čtení ukončí. limit je nejvýš 100. Kurzor leží v úložišti pod events_cursor[:provozovna][:typy].
The library reads the event feed in a loop. While the stream service runs, it reads GET /v2/events/stream live (Server-Sent Events) – an event arrives a few seconds after the change and nothing is polled. When it does not run (503), on an older server or with a custom transport that cannot read a response in pieces, it reads GET /v2/events and tries the stream again after Retry-After (5 minutes by default). The cursor is the same in both (the stream gets it as Last-Event-ID), switching skips nothing; a dropped connection is not an error – it reconnects after 2 s, 4 s, and after the third failure polls for a minute. The stream option (on by default; off = polling only) and the query whether the stream runs now are named per language (see Methods); the cron step (once) still makes one GET /v2/events request. It moves and stores the cursor only after successful processing – an event arrives at least once, so processing should be idempotent (for example by the event id). A full page is caught up at once, otherwise it waits the interval (5 s); without a stored cursor it starts at the end of the feed. After 410 cursor_expired it calls the reset handler (reload your state), on an error it waits per Retry-After or longer and longer (up to 60 s), and losing the pairing ends the reading. limit is at most 100. The cursor lives in the storage under events_cursor[:restaurant][:types].
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
err := api.WatchEvents(ctx, profirest.WatchOptions{ // běží do zrušení ctx
RestaurantID: rid,
Types: []string{"order.created", "order.status_changed"},
OnEvents: func(ctx context.Context, events []model.Event) error {
for _, e := range events {
handle(e) // chyba = kurzor se neposune a stránka přijde znovu
}
return nil
},
OnReset: func(*profirest.APIError) { reloadEverything() },
})
// NoStream: true = jen dotazování; watcher := api.NewEventWatcher(opts) → watcher.Run(ctx), watcher.IsStreaming()
// cron: api.NewEventWatcher(opts).Once(ctx) – jeden dotaz GET /v2/eventsChyby
Errors
Každá chyba API přijde jako výjimka s kódem z katalogu (RFC 9457). Rozhodujte se podle kódu, ne podle HTTP stavu – kódy se nikdy nemění, nové mohou přibýt. Název pro člověka je česky nebo anglicky podle volby jazyka.
Every API error arrives as an exception with a code from the catalog (RFC 9457). Decide by the code, not by the HTTP status – codes never change, new ones may come. The title for a person is in Czech or English depending on the language option.
_, err := api.Post(ctx, "/restaurants/"+rid+"/quotes", quote, nil)
var apiErr *profirest.APIError
if errors.As(err, &apiErr) && apiErr.Code == profirest.CodeValidationFailed {
for _, f := range apiErr.Errors {
log.Printf("%s: %s", f.Pointer, f.Message)
}
}
log.Printf("Profirest %s (%s)", profirest.ErrorCode(err), apiErr.RequestID)| VlastnostProperty | ObsahContent |
|---|---|
| Code | kód z katalogu (konstanty Code…); profirest.ErrorCode(err) ho vrátí z libovolné chybythe catalog code (constants Code…); profirest.ErrorCode(err) returns it from any error |
| Status | HTTP stav; 0 = odpověď nepřišlaHTTP status; 0 = no answer |
| Title, Detail | text pro člověka; Error() = Title – Detailtext for a person; Error() = Title – Detail |
| Errors | chyby polí: Pointer, Code, Messagefield errors: Pointer, Code, Message |
| Candidates | kandidáti u staff_ambiguouscandidates for staff_ambiguous |
| ExistingID | existující objekt u konfliktůthe existing object for conflicts |
| RetryAfter, Retryable | doba z Retry-After (*time.Duration), zda knihovna opakujethe Retry-After duration (*time.Duration), whether the library retries |
| RequestID, Problem | ID požadavku pro podporu, celé tělo chybyrequest ID for support, the whole error body |
| *OAuthError | chyby párování a připojení: Code (access_denied, expired_token…), Descriptionpairing and connection errors: Code (access_denied, expired_token…), Description |
| context.Canceled | zrušení vaším ctx (neopakuje se)cancellation by your ctx (not retried) |
Kódy jen z knihovny
Library-only codes
| KódCode | StavStatus | KdyWhen |
|---|---|---|
| network_error | 0 | server nejde zastihnout (bez sítě, DNS); opakovatelnéthe server cannot be reached (no network, DNS); retryable |
| timeout | 0 | odpověď nepřišla včas; opakovatelnéno answer in time; retryable |
| not_paired | 401 | zařízení nemá tokeny nebo ho server odpároval – spárujte znovuthe device has no tokens or the server unpaired it – pair again |
| unexpected_redirect | 3xx | server odpověděl přesměrováním; knihovna ho nesleduje, aby tokeny neodešly jinam (Location je v detailu); neopakuje sethe server answered with a redirect; the library does not follow it so tokens never go elsewhere (Location is in the detail); not retried |
| staff_session_required | 403 | požadavek vyžaduje přihlášeného zaměstnance – nic se neodeslalothe request requires a signed-in employee – nothing was sent |
Opakování a výpadky
Retries and outages
Knihovna opakuje jen to, co opakovat jde, nejvýš 3× se stejným tělem a Idempotency-Key. Odstup se zdvojnásobuje od 1 s do 30 s s rozptylem ±25 %, aby se zařízení po výpadku nevrátila všechna najednou. Retry-After (sekundy i HTTP datum) má přednost; delší než 30 s knihovna nečeká a vrátí chybu s počtem sekund.
The library retries only what can be retried, at most 3× with the same body and Idempotency-Key. The delay doubles from 1 s up to 30 s with ±25 % jitter so devices do not all come back at once after an outage. Retry-After (seconds or an HTTP date) wins; the library does not wait longer than 30 s and returns the error with the seconds.
| OdpověďResponse | OpakujeRetried | PoznámkaNote |
|---|---|---|
| network_error, timeout | anoyes | i POST – Idempotency-Key je stejnýPOST too – the Idempotency-Key is the same |
| 429 rate_limited | anoyes | po Retry-Afterafter Retry-After |
| 409 idempotency_in_progress | anoyes | stejný požadavek ještě běžíthe same request is still running |
| 500, 502, 503, 504 | anoyes | |
| 401 invalid_token | jednouonce | po obnově tokenu (nepočítá se do opakování)after refreshing the token (not counted) |
| 429 staff_locked | neno | zámek po špatných PINech – ukažte, kdy to zkusita lock after wrong PINs – show when to try |
| ostatní 4xxother 4xx | neno | opravte požadavek nebo ukažte název chybyfix the request or show the error title |
Tokeny a úložiště
Tokens and storage
Stav klienta (tokeny, provozovna zařízení, kurzory událostí) ukládá rozhraní úložiště se třemi metodami – načíst, uložit a smazat řetězec. Paměťové úložiště vydrží do konce procesu, souborové drží JSON s právy jen pro vlastníka. Access token platí 30 minut; knihovna ho obnoví minutu před koncem a po 401 invalid_token. Refresh token veřejného klienta platí jen na jedno použití – sdílí-li úložiště víc procesů, obnovuje pod zámkem úložiště jen jeden a ostatní použijí jeho nový token. invalid_grant (zařízení odpárováno) tokeny smaže a zavolá obsluhu odpárování; invalid_client a unauthorized_client jsou přechodné a tokeny nechá. Pod klíčem profirest-api:<client_id> leží JSON se stejnými klíči ve všech knihovnách.
The client state (tokens, the device's restaurant, event cursors) is kept by a storage interface with three methods – read, write and delete a string. Memory storage lasts until the process ends; file storage keeps JSON readable by the owner only. An access token is valid for 30 minutes; the library refreshes it a minute before the end and after 401 invalid_token. A public client's refresh token is single-use – when several processes share the storage, only one refreshes under the storage lock and the others use its new token. invalid_grant (device unpaired) deletes the tokens and calls the unpaired handler; invalid_client and unauthorized_client are temporary and keep them. Under the key profirest-api:<client_id> lies JSON with the same keys in every library.
type TokenStorage interface {
Get(key string) (value string, ok bool, err error)
Set(key, value string) error
Remove(key string) error
}
type LockingStorage interface { // víc procesů nad jedním úložištěm (obnova tokenu jen jednou)
TokenStorage
WithLock(name string, fn func() error) error
}NewMemoryStorage() (výchozí) vydrží do konce procesu, NewFileStorage(path) zamyká <soubor>.lock (LockFileEx na Windows, flock jinde). Klient je bezpečný pro souběžné gorutiny; obnova tokenu proběhne jen jednou.
NewMemoryStorage() (default) lasts until the process ends, NewFileStorage(path) locks <file>.lock (LockFileEx on Windows, flock elsewhere). The client is safe for concurrent goroutines; the token is refreshed only once.
Reference
Volby klienta
Client options
api := profirest.New(profirest.Options{ClientID: "…", Storage: …})| VolbaOption | VýchozíDefault | VýznamMeaning |
|---|---|---|
| BaseURL | https://api.mujprofirest.cz | adresa APIAPI address |
| ClientID | – | client_id aplikaceyour client_id |
| ClientSecret | – | jen na serveru partneraon a partner server only |
| AccessToken | – | pevný token bez obnovya fixed token, never refreshed |
| Language, NoLanguage | cs | jazyk názvů chyb; NoLanguage = bez hlavičkylanguage of error titles; NoLanguage = no header |
| Storage, StorageKey | MemoryStorage, profirest-api:<ClientID> | úložiště stavu a klíčstate storage and key |
| Retries | 3 | opakování opakovatelných chyb (profirest.Int(0) = bez)retries of retryable errors (profirest.Int(0) = none) |
| RetryDelay | 1 s | první odstupthe first delay |
| MaxRetryWait | 30 s | nejdelší Retry-Afterthe longest Retry-After |
| Timeout | 30 s | limit jednoho pokusu včetně tělalimit of one attempt including the body |
| RefreshMargin | 60 s | kolik před koncem obnovit tokenhow long before the end to refresh |
| OnUnpaired, OnStaffExpired | – | ztráta spárování / konec relace zaměstnancelost pairing / end of the staff session |
| HTTPClient | vlastníown | *http.Client bez sledování přesměrování*http.Client without following redirects |
| Clock, Sleep | systémsystem | hodiny a uspání (testy)clock and sleep (tests) |
Metody
Methods
| MetodaMethod | VracíReturns | Co děláWhat it does |
|---|---|---|
| Pair(ctx, PairOptions) | *Pairing | UserCode, VerificationURIComplete, Wait(ctx), Poll(ctx), Cancel(), State() |
| ResumePairing(PairingState) | *Pairing | pokračování párování v dalším požadavkucontinue pairing in the next request |
| IsPaired(), RestaurantID(), DeviceID(), Scopes() | bool, string, string, []string | stav spárovánípairing state |
| Connection(ctx), Unpair(ctx) | *model.Connection, error | připojení; zapomenout spárováníconnection; forget the pairing |
| AuthorizationURL(opts), CompleteAuthorization(ctx, url) | string, *model.Connection | připojení partnera (PKCE)partner connection (PKCE) |
| SignInStaff(ctx, rid, cred), SignOutStaff(ctx, token), Staff() | *model.StaffSession, –, *StaffInfo | zaměstnanec a jeho relacethe employee and their session |
| Request, Get, Post, Put, Patch, Delete | *Response, error | res.Decode(&v), res.Status, res.Header |
| Pages(ctx, path, opts), All(…), profirest.All[T](…) | iter.Seq2, []json.RawMessage, []T | stránky seznamu, všechny položkylist pages, all items |
| WatchEvents(ctx, opts), NewEventWatcher(opts) | error, *EventWatcher | čtení do zrušení ctx – živý proud, bez služby dotazování (NoStream, StreamIdleTimeout, IsStreaming()); Once(ctx) = jeden dotazreads until ctx is cancelled – live stream, polling without the service (NoStream, StreamIdleTimeout, IsStreaming()); Once(ctx) = one request |
| profirest.UUID() | string | UUIDv7 pro id záznamůa UUIDv7 for record ids |
| OfflineVerifyPin(member, pin), OfflineSign(member, pin, receipt), OfflineMessage(receipt) | (bool, error), (string, error), (string, error) | offline schválení účtenky vedoucím: kontrola překlepu v PINu (offline_approval.check, jen 8 bitů) a approval_signature; podpis ověří serveroffline approval of a receipt by a manager: a PIN typo check (offline_approval.check, only 8 bits) and the approval_signature; the server verifies the signature |
Volby požadavku (*RequestOptions): Query, ContentType, IdempotencyKey / NoIdempotencyKey, IfMatch, IfNoneMatch, Staff (StaffAuto, StaffRequired, StaffNone, StaffToken(t)), Retries, Timeout, Accept, Header, NoAuth.
Request options (*RequestOptions): Query, ContentType, IdempotencyKey / NoIdempotencyKey, IfMatch, IfNoneMatch, Staff (StaffAuto, StaffRequired, StaffNone, StaffToken(t)), Retries, Timeout, Accept, Header, NoAuth.
Bezpečnost
Security
client_secretpatří jen na server, nikdy do aplikace na zařízení nebo v prohlížeči.client_secretbelongs on a server only, never into an app on a device or in a browser.- Tokeny zařízení patří zařízení a jen jeho provozovně. Soubor s tokeny chraňte jako heslo; ztracené zařízení odpárujte v administraci – tokeny přestanou platit hned.
- Device tokens belong to the device and its restaurant only. Protect the token file like a password; unpair a lost device in the administration – its tokens stop working at once.
- Token zaměstnance zůstává jen v paměti a končí nečinností. PIN knihovna nikam neukládá.
- The staff token stays in memory only and ends with inactivity. The library never stores a PIN.
- Tokeny odcházejí jen na adresu API; přesměrování se nesledují.
- Tokens go only to the API address; redirects are not followed.
- Offline fronta docházkového terminálu nese PINy – držte ji jen na zařízení a po odeslání ji smažte.
- The offline queue of an attendance terminal carries PINs – keep it on the device only and delete it after sending.
Změny
Changes
| VerzeVersion | ZměnaChange |
|---|---|
| 1.0.0 | První verze pro Go 1.24+: klient jen nad standardní knihovnou, párování (i mezi požadavky), OAuth s PKCE, tokeny se zámkem mezi procesy, zaměstnanci, opakování, stránkování (iterátory), proud událostí, modely, příkladový klient.First version for Go 1.24+: a client on the standard library only, pairing (also across requests), OAuth with PKCE, tokens with a lock across processes, employees, retries, paging (iterators), the event feed, models, the example client. |