// Billvox API-Client für C# (.NET 6+, HttpClient, System.Text.Json). // Abdeckung: POST /api/v1/invoices, GET /api/v1/invoices, GET /api/v1/invoices/{id}, // POST /api/v1/invoices/{id}/send, GET /api/v1/invoices/{id}/pdf, POST /api/v1/validate. // Authentifizierung: API-Key (bvx_…) oder OAuth-Zugangstoken (bvo_…) als Bearer-Token. // Die Anfrage-Objekte werden mit den JSON-Namen der Billvox-Contracts (camelCase) serialisiert – // anonyme Objekte oder eigene Klassen mit denselben Eigenschaftsnamen (RecipientName, Positions …) // funktionieren gleichermaßen. Fehler: BillvoxException mit Status, Code, Message, Details. using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace Billvox.Sdk { public sealed class BillvoxException : Exception { public int Status { get; } public string Code { get; } public IReadOnlyList Details { get; } public BillvoxException(int status, string code, string message, IReadOnlyList? details = null) : base(message) { Status = status; Code = code; Details = details ?? Array.Empty(); } } /// Antwort von POST /api/v1/invoices (ApiInvoiceCreatedResponse). public sealed class InvoiceCreated { public string? Id { get; set; } public string? InvoiceNumber { get; set; } /// draft, finalized, sent, paid oder cancelled. public string? Status { get; set; } public string? Format { get; set; } public string? Sha256Hash { get; set; } public int? NetAmountCents { get; set; } public int? TaxAmountCents { get; set; } public int? GrossAmountCents { get; set; } public string? Currency { get; set; } public string? DownloadUrl { get; set; } public List? ValidationWarnings { get; set; } public DateTime CreatedAt { get; set; } public DateTime? FinalizedAt { get; set; } /// True bei Testbelegen (Schlüssel bvx_test_…). public bool Sandbox { get; set; } } /// Antwort von POST /api/v1/invoices/{id}/send (ApiSendInvoiceResponse). public sealed class InvoiceSent { public string? Message { get; set; } public string? InvoiceId { get; set; } public string? SentTo { get; set; } /// True, wenn der Versand nur simuliert wurde (Test-Schlüssel). public bool Simulated { get; set; } } public sealed class BillvoxClient : IDisposable { private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); private readonly HttpClient _http; private readonly bool _ownsHttp; /// API-Key (bvx_…) oder OAuth-Zugangstoken (bvo_…) /// Standard: https://app.billvox.de /// Optional eigener HttpClient (z. B. aus IHttpClientFactory) public BillvoxClient(string token, string baseUrl = "https://app.billvox.de", HttpClient? httpClient = null) { if (string.IsNullOrWhiteSpace(token)) throw new ArgumentException("token (API-Key oder OAuth-Zugangstoken) fehlt.", nameof(token)); _ownsHttp = httpClient is null; _http = httpClient ?? new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; _http.BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/"); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } /// Rechnung anlegen und finalisieren. Ohne idempotencyKey wird eine GUID erzeugt. public async Task CreateInvoiceAsync(object invoice, string? idempotencyKey = null, CancellationToken ct = default) { using var antwort = await SendAsync(HttpMethod.Post, "api/v1/invoices", invoice, idempotencyKey ?? Guid.NewGuid().ToString(), ct: ct); return await LeseAsync(antwort, ct) ?? new InvoiceCreated(); } /// Rechnungsliste als JSON (Paging/Filter als Query-Parameter, z. B. page, pageSize, status). public async Task ListInvoicesAsync(IDictionary? parameter = null, CancellationToken ct = default) { var query = new StringBuilder(); if (parameter is not null) { foreach (var p in parameter) { if (string.IsNullOrEmpty(p.Value)) continue; query.Append(query.Length == 0 ? '?' : '&').Append(Uri.EscapeDataString(p.Key)).Append('=').Append(Uri.EscapeDataString(p.Value)); } } using var antwort = await SendAsync(HttpMethod.Get, "api/v1/invoices" + query, ct: ct); return await LeseAsync(antwort, ct); } public async Task GetInvoiceAsync(string invoiceId, CancellationToken ct = default) { using var antwort = await SendAsync(HttpMethod.Get, "api/v1/invoices/" + Uri.EscapeDataString(invoiceId), ct: ct); return await LeseAsync(antwort, ct); } /// /// Rechnung per E-Mail versenden. Nicht wiederholungssicher: jeder erfolgreiche Aufruf verschickt /// eine E-Mail. Nach einem Timeout zuerst mit GetInvoiceAsync prüfen, ob sentAt gesetzt ist. /// public async Task SendInvoiceAsync(string invoiceId, string recipientEmail, string? subject = null, string? message = null, CancellationToken ct = default) { var body = new { recipientEmail, subject, message }; using var antwort = await SendAsync(HttpMethod.Post, "api/v1/invoices/" + Uri.EscapeDataString(invoiceId) + "/send", body, ct: ct); return await LeseAsync(antwort, ct) ?? new InvoiceSent(); } /// PDF als Byte-Array. public async Task GetInvoicePdfAsync(string invoiceId, CancellationToken ct = default) { using var antwort = await SendAsync(HttpMethod.Get, "api/v1/invoices/" + Uri.EscapeDataString(invoiceId) + "/pdf", accept: "application/pdf", ct: ct); return await antwort.Content.ReadAsByteArrayAsync(ct); } /// E-Rechnung prüfen (XML oder PDF). Liefert das Prüfergebnis als JSON. public async Task ValidateAsync(byte[] datei, string dateiname, bool preview = false, CancellationToken ct = default) { using var form = new MultipartFormDataContent(); var inhalt = new ByteArrayContent(datei); inhalt.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(inhalt, "file", dateiname); using var antwort = await SendAsync(HttpMethod.Post, "api/v1/validate" + (preview ? "?preview=true" : ""), form: form, ct: ct); return await LeseAsync(antwort, ct); } private async Task SendAsync(HttpMethod methode, string pfad, object? json = null, string? idempotencyKey = null, HttpContent? form = null, string accept = "application/json", CancellationToken ct = default) { using var anfrage = new HttpRequestMessage(methode, pfad); anfrage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); if (idempotencyKey is not null) anfrage.Headers.Add("Idempotency-Key", idempotencyKey); if (json is not null) anfrage.Content = new StringContent(JsonSerializer.Serialize(json, JsonOptions), Encoding.UTF8, "application/json"); else if (form is not null) anfrage.Content = form; HttpResponseMessage antwort; try { antwort = await _http.SendAsync(anfrage, HttpCompletionOption.ResponseHeadersRead, ct); } catch (HttpRequestException ex) { throw new BillvoxException(0, "NETWORK", "Billvox nicht erreichbar: " + ex.Message); } if (antwort.IsSuccessStatusCode) return antwort; var status = (int)antwort.StatusCode; var code = "UNKNOWN"; var meldung = "HTTP " + status; List? details = null; try { using var doc = JsonDocument.Parse(await antwort.Content.ReadAsStringAsync(ct)); if (doc.RootElement.TryGetProperty("code", out var c)) code = c.GetString() ?? code; if (doc.RootElement.TryGetProperty("message", out var m)) meldung = m.GetString() ?? meldung; if (doc.RootElement.TryGetProperty("details", out var d) && d.ValueKind == JsonValueKind.Array) { details = new List(); foreach (var e in d.EnumerateArray()) details.Add(e.ToString()); } } catch (JsonException) { /* keine JSON-Antwort */ } antwort.Dispose(); throw new BillvoxException(status, code, meldung, details); } private static async Task LeseAsync(HttpResponseMessage antwort, CancellationToken ct) { var text = await antwort.Content.ReadAsStringAsync(ct); if (string.IsNullOrWhiteSpace(text)) return default; return JsonSerializer.Deserialize(text, JsonOptions); } public void Dispose() { if (_ownsHttp) _http.Dispose(); } } }