// Пример интеграции с API предварительной записи (C# / .NET 6+). // // В примере используется https://timira.ru — основной домен. Каждый клиент // должен заменить его на свой внешний IP или домен, где развёрнута его копия // системы (путь /api/queue/booking не меняется). // // Переменные окружения: // QUEUE_BASE — https://timira.ru (адрес своей установки) // QUEUE_API_KEY — ключ из админки «API-ключи» // // Песочница: // QUEUE_API_KEY=qk_test_sandbox_6b1f0c9d8e7a5b4c3d2e1f0a9b8c7d6e using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; public sealed class QueueBookingException : Exception { public int Status { get; } public string? Code { get; } public QueueBookingException(int status, string? code, string message) : base(message) { Status = status; Code = code; } } public sealed class QueueBookingClient : IDisposable { // Тестовый ключ песочницы (публичный). Для боевой работы замените на // live-ключ из админки «API-ключи» и храните его в секрете. public const string TestApiKey = "qk_test_sandbox_6b1f0c9d8e7a5b4c3d2e1f0a9b8c7d6e"; private readonly HttpClient _http; private readonly string _root; public QueueBookingClient(string? baseUrl = null, string? apiKey = null) { var baseAddress = (baseUrl ?? Environment.GetEnvironmentVariable("QUEUE_BASE") ?? "https://timira.ru").TrimEnd('/'); var key = apiKey ?? Environment.GetEnvironmentVariable("QUEUE_API_KEY") ?? TestApiKey; if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Не указан QUEUE_API_KEY"); _root = baseAddress + "/api/queue/booking"; _http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; _http.DefaultRequestHeaders.Add("X-API-Key", key); } private async Task RequestAsync(HttpMethod method, string path, object? body = null, string? idempotencyKey = null) { using var request = new HttpRequestMessage(method, _root + path); if (body is not null) request.Content = JsonContent.Create(body); if (!string.IsNullOrEmpty(idempotencyKey)) request.Headers.Add("Idempotency-Key", idempotencyKey); using var response = await _http.SendAsync(request); var text = await response.Content.ReadAsStringAsync(); JsonElement data; try { data = JsonSerializer.Deserialize(text); } catch (JsonException) { throw new QueueBookingException((int)response.StatusCode, "invalid_response", text); } if (!response.IsSuccessStatusCode) { var code = data.TryGetProperty("code", out var c) ? c.GetString() : "http_error"; var message = data.TryGetProperty("error", out var e) ? e.GetString() : text; throw new QueueBookingException((int)response.StatusCode, code, message ?? "Ошибка API"); } return data; } public Task ListServicesAsync() => RequestAsync(HttpMethod.Get, "/services"); public Task GetRulesAsync() => RequestAsync(HttpMethod.Get, "/schedule"); public Task GetSlotsAsync(int serviceId, string date) => RequestAsync(HttpMethod.Get, $"/slots?service_id={serviceId}&date={Uri.EscapeDataString(date)}"); public Task CreateBookingAsync(int serviceId, string scheduledAt, object customer, string? note = null, string? idempotencyKey = null) => RequestAsync(HttpMethod.Post, "", new { service_id = serviceId, scheduled_at = scheduledAt, customer, note, }, idempotencyKey ?? Guid.NewGuid().ToString()); public Task GetBookingAsync(string reference) => RequestAsync(HttpMethod.Get, "/" + Uri.EscapeDataString(reference)); public Task ListBookingsAsync(string date, string status = "booked", int page = 1, int limit = 50) => RequestAsync(HttpMethod.Get, $"?date={Uri.EscapeDataString(date)}&status={status}&page={page}&limit={limit}"); public Task CancelBookingAsync(string reference, string reason = "") => RequestAsync(HttpMethod.Post, $"/{Uri.EscapeDataString(reference)}/cancel", new { reason }); public Task RescheduleBookingAsync(string reference, string scheduledAt) => RequestAsync(HttpMethod.Post, $"/{Uri.EscapeDataString(reference)}/reschedule", new { scheduled_at = scheduledAt }); public void Dispose() => _http.Dispose(); } public static class Demo { public static async Task RunAsync() { using var client = new QueueBookingClient(); var services = await client.ListServicesAsync(); var serviceId = services.GetProperty("queues")[0].GetProperty("services")[0].GetProperty("id").GetInt32(); var today = DateTime.Now.ToString("yyyy-MM-dd"); var slots = await client.GetSlotsAsync(serviceId, today); JsonElement? available = null; foreach (var slot in slots.GetProperty("slots").EnumerateArray()) { if (slot.GetProperty("available").GetBoolean()) { available = slot; break; } } if (available is null) { Console.WriteLine("На сегодня свободных слотов нет"); return; } var booking = await client.CreateBookingAsync( serviceId, available.Value.GetProperty("iso").GetString()!, new { name = "Иван", phone = "+79990000000", email = "i@example.ru" }, "Создано из C#"); Console.WriteLine($"Создана запись: {booking.GetProperty("booking_ref")} / {booking.GetProperty("number")}"); } }