ProfirestAPI v2
C# 1.0.0 Finální smlouva · v ostrém provozu
ObsahContents
  1. PřehledOverview
  2. ZačínámeGetting started
  3. Ke staženíDownload
  4. InstalaceInstallation
  5. Příkladový klientExample client
  6. Rychlý startQuick start
  7. Spárovat zařízeníPair a device
  8. Docházkový terminálAttendance terminal
  9. Pokladna a zaměstnanecRegister and employee
  10. Aplikace partneraPartner application
  11. Jak to fungujeHow it works
  12. PožadavkyRequests
  13. Seznamy po stránkáchPaged lists
  14. Proud událostíEvent feed
  15. ChybyErrors
  16. Opakování a výpadkyRetries and outages
  17. Tokeny a úložištěTokens and storage
  18. ReferenceReference
  19. Volby klientaClient options
  20. MetodyMethods
  21. BezpečnostSecurity
  22. ZměnyChanges

C# · .NET 8 · API v2

Profirest API pro .NET

Knihovna Profirest API v2 pro .NET 8 bez závislostí – asynchronní, s modely ze smlouvy pro System.Text.Json, pro pokladní systémy, služby (BackgroundService) a servery partnerů (ASP.NET Core).

The Profirest API v2 library for .NET 8 without dependencies – asynchronous, with models from the contract for System.Text.Json, for POS systems, services (BackgroundService) and partner servers (ASP.NET Core).

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.

BalíčekPackageProfirest.Api (NuGet)
PožadavkyRequirements.NET 8+
ZávislostiDependenciesžádné (HttpClient, System.Text.Json)none (HttpClient, System.Text.Json)
Jmenné prostoryNamespacesProfirest.Api, Profirest.Api.Models, Profirest.Api.Storage

Instalace

Installation

V archivu je hotový balíček nuget/Profirest.Api.1.0.0.nupkg. Přidejte složku jako místní zdroj NuGetu (po zveřejnění stačí dotnet add package Profirest.Api):

The archive contains a ready package nuget/Profirest.Api.1.0.0.nupkg. Add the folder as a local NuGet source (once published, dotnet add package Profirest.Api is enough):

dotnet nuget add source ./profirest-api-csharp-1.0.0/nuget --name profirest-local
dotnet add package Profirest.Api --version 1.0.0
using Profirest.Api;
using Profirest.Api.Models;   // vygenerované modely (AttendancePunch, StaffSession, Connection…)
using Profirest.Api.Storage;  // MemoryTokenStorage, FileTokenStorage

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 pairingqkonecquit
dotnet run --project examples/Pichacka
examples/Pichacka/Program.cs
// Příklad: docházkový terminál (píchačka) v příkazové řádce nad Profirest API v2.
//
//   PROFIREST_BASE_URL  adresa API (výchozí https://api.mujprofirest.cz)
//   PROFIREST_TOKENS    soubor s tokeny (výchozí ./profirest-pichacka.json) – chraňte ho jako heslo
//
// Na terminálu se nikdo nepřihlašuje: každé píchnutí nese PIN zaměstnance.
using System.Text;
using Profirest.Api;
using Profirest.Api.Models;
using Profirest.Api.Storage;

Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;

var api = new ProfirestApi(new ProfirestApiOptions
{
    BaseUrl = Environment.GetEnvironmentVariable("PROFIREST_BASE_URL") ?? "https://api.mujprofirest.cz",
    ClientId = "profirest-dochazka",
    // tokeny přežijí restart; soubor se zamyká, takže obnovu tokenu udělá jen jeden proces
    Storage = new FileTokenStorage(Environment.GetEnvironmentVariable("PROFIREST_TOKENS") ?? "profirest-pichacka.json"),
    OnUnpaired = _ => Console.WriteLine("Zařízení bylo odpárováno – spusťte příklad znovu a spárujte ho."),
});

// 1) Spárování kódem (jen poprvé): vedoucí kód zadá v administraci (Správa PC / zařízení → Připojit zařízení).
if (!api.IsPaired)
{
    var pairing = await api.PairAsync(new PairOptions
    {
        Scope = "restaurants:read staff:read staff:authenticate attendance:read attendance:punch",
        DeviceName = "Píchačka (příklad)",
    });
    Console.WriteLine("KÓD: " + pairing.UserCode);
    Console.WriteLine("Potvrďte ho v administraci, nebo otevřete " + pairing.VerificationUriComplete);
    try
    {
        await pairing.Connected; // čeká, dokud vedoucí kód nepotvrdí (výpadek sítě přečká)
    }
    catch (ProfirestOAuthException e) when (e.Error is "access_denied" or "expired_token")
    {
        Console.WriteLine(e.Error == "access_denied"
            ? "Vedoucí párování odmítl."
            : "Kód vypršel (10 minut bez potvrzení) – spusťte příklad znovu.");
        return 1;
    }
}

// provozovnu zařízení si klient pamatuje z GET /v2/connection
if (api.RestaurantId == null)
{
    await api.ConnectionAsync();
}
var rid = api.RestaurantId!;
var punchesPath = $"/restaurants/{rid}/attendance/punches";

Console.WriteLine($"Provozovna {rid}. Příkazy: p PIN = příchod, o PIN = odchod, pz PIN = začátek přestávky,");
Console.WriteLine("kz PIN = konec přestávky, k = kdo je v práci, odparovat = odpárovat a skončit, q = konec.");

var types = new Dictionary<string, string>
{
    ["p"] = "clock_in",
    ["o"] = "clock_out",
    ["pz"] = "break_start",
    ["kz"] = "break_end",
};

string? line;
while ((line = Console.ReadLine()) != null)
{
    var parts = line.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
    if (parts.Length == 0)
    {
        continue;
    }
    var cmd = parts[0].ToLowerInvariant();
    if (cmd == "q")
    {
        break;
    }
    if (cmd == "odparovat")
    {
        await api.UnpairAsync(); // zapomene tokeny a zneplatní je i na serveru
        Console.WriteLine("Zařízení je odpárované.");
        break;
    }
    try
    {
        if (cmd == "k")
        {
            // seznam po stránkách – AllAsync projde všechny
            foreach (var p in await api.AllAsync<AttendancePresence>($"/restaurants/{rid}/attendance/presence"))
            {
                Console.WriteLine($"  {p.Employee.Name} – {Stav(p.State)}");
            }
        }
        else if (types.TryGetValue(cmd, out var type) && parts.Length == 2)
        {
            await Punch(type, parts[1]);
        }
        else
        {
            Console.WriteLine("Neznámý příkaz.");
        }
    }
    catch (ProfirestApiException e)
    {
        Console.WriteLine(Describe(e));
    }
}
return 0;

async Task Punch(string type, string pin)
{
    // Id vznikne JEDNOU na píchnutí (UUIDv7) – opakování se stejným Id server nikdy nezapíše dvakrát
    var body = new AttendancePunchCreate
    {
        Id = ProfirestApi.Uuid(),
        Type = type,
        Credential = new StaffCredential { Method = "pin", Secret = pin },
    };
    for (;;)
    {
        try
        {
            var punch = await api.PostAsync<AttendancePunch>(punchesPath, body);
            Console.WriteLine($"OK: {punch!.Employee.Name} – {Stav(punch.State)}");
            return;
        }
        catch (ProfirestApiException e) when (e.Code == ErrorCodes.StaffAmbiguous)
        {
            // stejný PIN má víc lidí: vybrat a poslat znovu se stejným Id a s employee_id
            Console.WriteLine("Tento PIN má víc zaměstnanců, vyberte číslo:");
            for (var i = 0; i < e.Candidates.Count; i++)
            {
                Console.WriteLine($"  {i + 1}) {e.Candidates[i].Name}");
            }
            if (!int.TryParse(Console.ReadLine(), out var n) || n < 1 || n > e.Candidates.Count)
            {
                Console.WriteLine("Píchnutí zrušeno.");
                return;
            }
            body.Credential.EmployeeId = e.Candidates[n - 1].Id;
        }
    }
}

// stav zaměstnance česky (nové hodnoty mohou přibýt – pak se vypíše, jak přišla)
static string Stav(string state) => state switch
{
    "working" => "v práci",
    "on_break" => "na přestávce",
    "off" => "mimo práci",
    _ => state,
};

// chyby podle kódu (Code), ne podle HTTP stavu – kódy se nemění
static string Describe(ProfirestApiException e) => e.Code switch
{
    ErrorCodes.StaffCredentialsInvalid => "Neznámý PIN.",
    ErrorCodes.StaffLocked => $"Příliš mnoho špatných PINů – zkuste to za {e.RetryAfter ?? 60} s.",
    ErrorCodes.AttendanceStateConflict => "Nejde: " + e.Title,
    ErrorCodes.NetworkError or ErrorCodes.Timeout => "Bez sítě – zkuste znovu.",
    ErrorCodes.NotPaired => "Zařízení není spárované – spusťte příklad znovu.",
    _ => $"Chyba: {e.Title} ({e.Code})",
};

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.

Nastavení › Správa PC / zařízení › Připojit kódem: vedoucí potvrdí kód ze zařízení a vybere provozovnu.
Nastavení › Správa PC / zařízení › Připojit kódem: vedoucí potvrdí kód ze zařízení a vybere provozovnu.Settings › PCs / devices › Connect by code: a manager confirms the code from the device and picks the restaurant.
var api = new ProfirestApi(new ProfirestApiOptions
{
    ClientId = "profirest-dochazka",
    Storage = new FileTokenStorage(@"C:\ProgramData\Pichacka\profirest.json"),
    OnUnpaired = reason => ShowPairingScreen(),
});

if (!api.IsPaired)
{
    Pairing pairing = await api.PairAsync(new PairOptions
    {
        Scope = "restaurants:read staff:read staff:authenticate attendance:read attendance:punch",
        DeviceName = "Píchačka u vchodu",
        AppVersion = "2.0.0",
    });
    ShowCode(pairing.UserCode, pairing.VerificationUriComplete);
    try { await pairing.Connected; }
    catch (ProfirestOAuthException e) { ShowPairingFailed(e.Error); return; }   // access_denied, expired_token
}
if (api.RestaurantId == null) await api.ConnectionAsync();

Webová aplikace: pairing.ToState() uložte do session a v dalším požadavku zavolejte api.ResumePairing(state).PollAsync(); pairing.Cancel() čekání ukončí.

A web application: store pairing.ToState() in the session and call api.ResumePairing(state).PollAsync() in the next request; pairing.Cancel() stops waiting.

AplikaceApplicationclient_id
Pokladna a mobilní číšníkRegister and mobile waiterprofirest-pos
Kuchyňský displej, výdej, pořadníkKitchen display, pickup, queue screenprofirest-kds
Docházkový terminálAttendance terminalprofirest-dochazka
Telefon kurýraCourier phoneprofirest-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.

var body = new AttendancePunchCreate
{
    Id = ProfirestApi.Uuid(),                 // UUIDv7
    Type = "clock_in",                        // clock_out, break_start, break_end
    Credential = new StaffCredential { Method = "pin", Secret = pin },
};
try
{
    AttendancePunch? punch = await api.PostAsync<AttendancePunch>($"/restaurants/{api.RestaurantId}/attendance/punches", body);
    Console.WriteLine($"{punch!.Employee.Name}: {punch.State}");
}
catch (ProfirestApiException e)
{
    switch (e.Code)
    {
        case ErrorCodes.StaffAmbiguous: body.Credential!.EmployeeId = ChooseEmployee(e.Candidates).Id; break;  // a poslat znovu
        case ErrorCodes.StaffCredentialsInvalid: ShowWrongPin(); break;
        case ErrorCodes.StaffLocked: ShowLocked(e.RetryAfter); break;
        case ErrorCodes.NetworkError: case ErrorCodes.Timeout: SaveOffline(body); break;
        default: ShowMessage(e.Title); break;
    }
}

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.

try
{
    await api.SignInStaffAsync(rid, new StaffCredential { Method = "pin", Secret = pin });
}
catch (ProfirestApiException e) when (e.Code == ErrorCodes.StaffAmbiguous)
{
    var who = ChooseEmployee(e.Candidates);
    await api.SignInStaffAsync(rid, new StaffCredential { Method = "pin", Secret = pin, EmployeeId = who.Id });
}
StaffInfo? staff = api.Staff;                 // Employee, ExpiresAt, MaxExpiresAt nebo null
await api.PostAsync<Receipt>($"/restaurants/{rid}/receipts", receipt, new RequestOptions { Staff = true });
await api.SignOutStaffAsync();

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.

Souhlas „Připojit přes Profirest“: majitel vybere provozovny a povolí, co aplikace smí.
Souhlas „Připojit přes Profirest“: majitel vybere provozovny a povolí, co aplikace smí.The “Connect via Profirest” consent: the owner picks the restaurants and grants the scopes.
Integrace › Připojené aplikace: provozovny, oprávnění a kdo píše zákazníkům – majitel je může kdykoli změnit nebo připojení zrušit.
Integrace › Připojené aplikace: provozovny, oprávnění a kdo píše zákazníkům – majitel je může kdykoli změnit nebo připojení zrušit.Integrations › Connected applications: restaurants, scopes and who messages the customers – the owner can change them or revoke the connection at any time.
ProfirestApi ApiFor(IServiceProvider sp, string accountId) => new(new ProfirestApiOptions
{
    ClientId = "your-client-id",
    ClientSecret = builder.Configuration["Profirest:ClientSecret"],     // nikdy ne do aplikace u zákazníka
    Storage = sp.GetRequiredService<ITokenStorage>(),
    StorageKey = "account-" + accountId,
    HttpClient = sp.GetRequiredService<IHttpClientFactory>().CreateClient("profirest"),   // AllowAutoRedirect = false
});

app.MapGet("/profirest/connect", (HttpContext ctx, IServiceProvider sp) => Results.Redirect(ApiFor(sp, AccountId(ctx))
    .AuthorizationUrl(new AuthorizationOptions { RedirectUri = "https://shop.example/profirest/callback",
                                                 Scope = "restaurants:read catalog:read orders:write" })));

app.MapGet("/profirest/callback", async (HttpContext ctx, IServiceProvider sp) =>
{
    Connection? connection = await ApiFor(sp, AccountId(ctx)).CompleteAuthorizationAsync(ctx.Request.GetEncodedUrl());
    return Results.Redirect("/settings/profirest?ok=1");
});

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.

Catalog? catalog = await api.GetAsync<Catalog>("/restaurants/11/catalog", new RequestOptions { Query = new() { ["channel"] = "pos" } });
JsonElement? raw = await api.GetAsync("/restaurants/11/catalog");    // bez modelu

// stav a hlavičky (ETag, Location)
ApiResponse r = await api.SendAsync(HttpMethod.Get, "/customers/" + id);
await api.PatchAsync("/customers/" + id, new { name = "Jana Nováková" }, new RequestOptions { IfMatch = r.ETag });

// vlastní Idempotency-Key uložený u objednávky
await api.PostAsync("/restaurants/11/orders", order, new RequestOptions { IdempotencyKey = order.LocalId });

// binární tělo a stažení
await using var zip = File.OpenRead("backup.zip");
await api.PostAsync($"/restaurants/{rid}/backups", zip, new RequestOptions { ContentType = "application/zip", Timeout = TimeSpan.FromMinutes(2) });
byte[]? content = await api.GetAsync<byte[]>($"/restaurants/{rid}/backups/{backupId}/content", new 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.

List<StaffMember> staff = await api.AllAsync<StaffMember>("/restaurants/11/staff");
await foreach (StaffMemberPage page in api.PagesAsync<StaffMemberPage>("/restaurants/11/staff"))
{
    Render(page.Data);
}

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].

public sealed class KitchenFeed(ProfirestApi api, Board board) : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken) => api.WatchEventsAsync(new WatchOptions
    {
        RestaurantId = api.RestaurantId,
        Types = new[] { "kitchen.ticket_updated", "order.created", "order.status_changed" },
        Interval = TimeSpan.FromSeconds(3),
        OnEvents = (events, ct) => board.ReloadAsync(ct),       // výjimka = stránka přijde znovu
        OnReset = _ => board.ReloadAsync(CancellationToken.None),
        OnStreamingChanged = live => board.ShowLive(live),      // živý proud, nebo dotazování GET /v2/events
    }, stoppingToken);                                          // běží do zrušení tokenu
}

Chyby

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.

try
{
    await api.PostAsync($"/restaurants/{rid}/quotes", quote);
}
catch (ProfirestApiException e) when (e.Code == ErrorCodes.ValidationFailed)
{
    foreach (var f in e.Errors) Console.WriteLine($"{f.Pointer}: {f.Message}");
}
VlastnostPropertyObsahContent
Codekód z katalogu (konstanty ErrorCodes)the catalog code (constants in ErrorCodes)
StatusHTTP stav; 0 = odpověď nepřišlaHTTP status; 0 = no answer
Title, Detail, Messagetext pro člověka; Message = Title – Detailtext for a person; Message = Title – Detail
Errorschyby polí (FieldError: Pointer, Code, Message)field errors (FieldError: Pointer, Code, Message)
Candidateskandidáti u staff_ambiguous (EmployeeRef)candidates for staff_ambiguous (EmployeeRef)
ExistingIdexistující objekt u konfliktůthe existing object for conflicts
RetryAfter, Retryablesekundy z Retry-After, zda knihovna opakujeseconds from Retry-After, whether the library retries
RequestId, ProblemID požadavku pro podporu, celé tělo chyby (JsonElement)request ID for support, the whole error body (JsonElement)
ProfirestOAuthExceptionchyby párování a připojení: Error, Descriptionpairing and connection errors: Error, Description
OperationCanceledExceptionzrušení vaším CancellationToken (neopakuje se)cancellation by your CancellationToken (not retried)

Kódy jen z knihovny

Library-only codes

KódCodeStavStatusKdyWhen
network_error0server nejde zastihnout (bez sítě, DNS); opakovatelnéthe server cannot be reached (no network, DNS); retryable
timeout0odpověď nepřišla včas; opakovatelnéno answer in time; retryable
not_paired401zařízení nemá tokeny nebo ho server odpároval – spárujte znovuthe device has no tokens or the server unpaired it – pair again
unexpected_redirect3xxserver 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_required403pož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ěďResponseOpakujeRetriedPoznámkaNote
network_error, timeoutanoyesi POST – Idempotency-Key je stejnýPOST too – the Idempotency-Key is the same
429 rate_limitedanoyespo Retry-Afterafter Retry-After
409 idempotency_in_progressanoyesstejný požadavek ještě běžíthe same request is still running
500, 502, 503, 504anoyes
401 invalid_tokenjednouoncepo obnově tokenu (nepočítá se do opakování)after refreshing the token (not counted)
429 staff_lockednenozámek po špatných PINech – ukažte, kdy to zkusita lock after wrong PINs – show when to try
ostatní 4xxother 4xxnenoopravte 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.

MemoryTokenStorage (výchozí) vydrží do konce procesu, FileTokenStorage zamyká <soubor>.lock a zapisuje přes dočasný soubor, vlastní ITokenStorage (databáze, Key Vault…) a ILockingTokenStorage se zámkem pro obnovu napříč servery. Instance klienta je bezpečná pro souběžné použití; pro každé zařízení nebo připojený účet použijte vlastní (singleton v DI je v pořádku).

MemoryTokenStorage (default) lasts until the process ends, FileTokenStorage locks <file>.lock and writes through a temporary file, your own ITokenStorage (database, Key Vault…) and ILockingTokenStorage with a lock for refreshing across servers. A client instance is safe for concurrent use; use a separate one per device or connected account (a DI singleton is fine).

Reference

Volby klienta

Client options

var api = new ProfirestApi(new ProfirestApiOptions { ClientId = "…", Storage = … });
VolbaOptionVýchozíDefaultVýznamMeaning
BaseUrlhttps://api.mujprofirest.czadresa 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
Languagecsjazyk názvů chyblanguage of error titles
Storage, StorageKeyMemoryTokenStorage, profirest-api:<ClientId>úložiště stavu a klíčstate storage and key
Retries3opakování opakovatelných chybretries of retryable errors
RetryDelay1 sprvní odstupthe first delay
MaxRetryWait30 snejdelší Retry-Afterthe longest Retry-After
Timeout30 slimit jednoho pokusulimit of one attempt
RefreshMargin60 skolik 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, HttpMessageHandlervlastníownbez přesměrování; IHttpClientFactoryno redirects; IHttpClientFactory
TimeProvider, Delaysystémsystemhodiny a uspání (testy)clock and delay (tests)

Metody

Methods

MetodaMethodVracíReturnsCo děláWhat it does
PairAsync(PairOptions)PairingUserCode, VerificationUriComplete, Connected, PollAsync(), Cancel(), ToState()
ResumePairing(PairingState)Pairingpokračování párování v dalším požadavkucontinue pairing in the next request
IsPaired, RestaurantId, Scopesbool, string?, …stav spárovánípairing state
ConnectionAsync(), UnpairAsync()Connection?, Taskpřipojení; zapomenout spárováníconnection; forget the pairing
AuthorizationUrl(options), CompleteAuthorizationAsync(url)string, Connection?připojení partnera (PKCE)partner connection (PKCE)
SignInStaffAsync, SignOutStaffAsync, StaffStaffSession, Task, StaffInfo?zaměstnanec a jeho relacethe employee and their session
GetAsync, PostAsync, PutAsync, PatchAsync, DeleteAsyncJsonElement? / T?generické převádějí na modelygeneric ones convert to models
RequestAsync, SendAsyncJsonElement?, ApiResponseobecný požadavek; stav a hlavičkya general request; status and headers
PagesAsync, AllAsyncIAsyncEnumerable, Liststránky seznamu, všechny položkylist pages, all items
WatchEventsAsync(WatchOptions, ct)Taskčtení proudu událostí do zrušení – živý proud, bez služby dotazování (Stream, StreamIdleTimeout, OnStreamingChanged)reads the event feed until cancelled – live stream, polling without the service (Stream, StreamIdleTimeout, OnStreamingChanged)
ProfirestApi.Uuid()stringUUIDv7 pro id záznamůa UUIDv7 for record ids
OfflineApprovals.VerifyPin(member, pin), Sign(member, pin, receipt), Message(receipt)bool, string, stringoffline 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, IdempotencyKey ("" = bez klíče), IfMatch, Staff, Retries, Timeout, Accept, ContentType, Headers, Auth. Každá metoda bere CancellationToken.

Request options (RequestOptions): Query, IdempotencyKey ("" = no key), IfMatch, Staff, Retries, Timeout, Accept, ContentType, Headers, Auth. Every method takes a CancellationToken.

Bezpečnost

Security

  • client_secret patří jen na server, nikdy do aplikace na zařízení nebo v prohlížeči.
  • client_secret belongs 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

VerzeVersionZměnaChange
1.0.0První verze pro .NET 8: asynchronní klient s modely pro System.Text.Json, párování (i mezi HTTP požadavky), OAuth s PKCE, tokeny se zámkem mezi procesy, zaměstnanci, opakování, stránkování, proud událostí, příkladový klient.First version for .NET 8: an asynchronous client with models for System.Text.Json, pairing (also across HTTP requests), OAuth with PKCE, tokens with a lock across processes, employees, retries, paging, the event feed, the example client.