Overview
From C# you can send a KSeF invoice through Notaly with nothing more than HttpClient and System.Text.Json, both part of .NET. You post plain JSON to https://api.getnotaly.com/invoices, and Notaly generates the FA(3) XML, checks it against the official XSD (the same check as our FA(3) validator) and submits it to KSeF.
What do you need before you start?
You need a sandbox account and its API key. Keep the key in the NOTALY_API_KEY environment variable, never in source code. In the sandbox the seller NIP is fixed to 2745013933, and any other seller NIP returns 422 seller_nip_not_authorized before anything reaches KSeF. If you have already connected your own KSeF Demo token, use your connected NIP instead. The buyer NIP comes from the BUYER_NIP variable and has no default. Use a buyer NIP you are entitled to use: on KSeF Demo the invoice is visible to that NIP.
Today the API accepts only currency: "PLN" (other codes get 422 currency_not_supported) and the VAT rates 23, 8, 5 and 0 (domestic 0%, written as "0 KR"; export and intra-EU 0% are not supported). A unit is required on every line.
How do you send the invoice from C#?
Reference example, statically checked against the API contract but not executed by us; adjust and test it in your sandbox account.
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("NOTALY_API_KEY")
?? throw new InvalidOperationException("Set NOTALY_API_KEY");
var buyerNip = Environment.GetEnvironmentVariable("BUYER_NIP")
?? throw new InvalidOperationException("Set BUYER_NIP");
const string SellerNip = "2745013933"; // sandbox seller NIP; with a KSeF Demo connection use your connected NIP
// Issue date = today in Poland, not the server's local or UTC date
var warsaw = TimeZoneInfo.FindSystemTimeZoneById("Europe/Warsaw");
var issueDate = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, warsaw).ToString("yyyy-MM-dd");
var number = "FV/2026/10/001";
var invoice = new
{
number,
issueDate,
currency = "PLN",
seller = new { nip = SellerNip, name = "Your company", address = new { line1 = "ul. Przykładowa 1, 00-001 Warszawa", country = "PL" } },
buyer = new { nip = buyerNip, name = "Test Customer", address = new { line1 = "ul. Próbna 2, 30-001 Kraków", country = "PL" } },
// money as decimal: serialised as 2 and 200
items = new[] { new { name = "Consulting", unit = "h", quantity = 2m, unitNetPrice = 200m, vatRate = 23 } }
};
using var http = new HttpClient { BaseAddress = new Uri("https://api.getnotaly.com/"), Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var request = new HttpRequestMessage(HttpMethod.Post, "invoices") { Content = JsonContent.Create(invoice) };
// one key per invoice, derived from its number: reuse it on every retry of this invoice
request.Headers.Add("Idempotency-Key", "demo-" + number.Replace('/', '-'));
using var response = await http.SendAsync(request);
var body = ReadJson(await response.Content.ReadAsStringAsync());
if (!response.IsSuccessStatusCode)
{
Console.Error.WriteLine($"HTTP {(int)response.StatusCode}: {Str(body, "error") ?? "unknown"}");
var message = Str(body, "message");
if (message != null) Console.Error.WriteLine(message); // e.g. a body that does not match the schema
if (body.ValueKind == JsonValueKind.Object && body.TryGetProperty("details", out var details))
Console.Error.WriteLine(details.ToString()); // validation_failed / xsd_invalid
return 1;
}
var id = Str(body, "id");
var status = Str(body, "status");
var error = Str(body, "error");
Console.WriteLine($"Invoice {id}: {status} (number {Str(body, "number")})");
// Poll while submitted (every 5 s) or draft + ksef_submitting (every 30 s): Notaly resends that draft itself,
// which can take several minutes. Never send a new POST for it. In production prefer webhooks.
for (var i = 0; i < 60 && (status == "submitted" || (status == "draft" && error == "ksef_submitting")); i++)
{
if (status == "submitted" && error == "ksef_duplicate_review") break;
await Task.Delay(TimeSpan.FromSeconds(status == "draft" ? 30 : 5));
var current = ReadJson(await http.GetStringAsync($"invoices/{id}"));
status = Str(current, "status");
error = Str(current, "error");
if (status == "rejected") Console.Error.WriteLine($"Rejected: {error}");
}
if (status == "draft")
{
Console.Error.WriteLine($"Draft ({error ?? "null"}): do not create a new invoice. If ksef_submitting, Notaly is resending it, so check GET /invoices/{id}; otherwise write to hello@getnotaly.com with the invoice id.");
return 1;
}
if (status == "submitted" && error == "ksef_duplicate_review")
Console.Error.WriteLine("ksef_duplicate_review: KSeF already has this invoice from an earlier attempt. Do not reissue it with another number; Notaly links it to the KSeF record.");
Console.WriteLine($"Status: {status}");
return status == "accepted" ? 0 : 1;
static JsonElement ReadJson(string s)
{
try { return JsonDocument.Parse(s).RootElement.Clone(); }
catch (JsonException) { return default; }
}
static string? Str(JsonElement el, string name) =>
el.ValueKind == JsonValueKind.Object && el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() : null;To try it, run dotnet new console -o NotalyKsef, replace Program.cs with the code above, then run NOTALY_API_KEY=... BUYER_NIP=... dotnet run. Quantity and price are decimal literals (2m, 200m), so the JSON carries exactly 2 and 200. double and float can shift amounts by a fraction of a grosz, so keep money in decimal all the way through. The issue date is computed for Europe/Warsaw because, close to midnight, the server's local or UTC date can already be a different day.
What does the response tell you?
A successful POST returns the invoice object. Always read status; do not assume the invoice was sent. submitted means KSeF received the invoice and returned a reference number. If the response is draft with error: "ksef_submitting", KSeF has not confirmed the submission yet. Do not send a new POST and do not issue the invoice again under a new number: Notaly resends the same XML automatically. Poll GET /invoices/{id} until the status is submitted. Such a draft already counts towards the three sandbox invoices. If the status is submitted with error: "ksef_duplicate_review", KSeF already has this invoice from an earlier attempt. Do not reissue it with another number; we link it to the KSeF record on our side. If you need it sooner, write to hello@getnotaly.com with the invoice id. If the invoice is draft with error: "ksef_retry_exhausted", Notaly has stopped resending it automatically (after 24 hours, or earlier if KSeF returned a definitive error). Do not create a new invoice: write to hello@getnotaly.com with the invoice id, and we check in KSeF whether it arrived before anything is resent. If an invoice is still draft with error: null or ksef_unavailable after about a minute, Notaly does not resend it: do not create a new invoice; write to hello@getnotaly.com with the invoice id.
Sending the same request again with the same Idempotency-Key returns the invoice already stored and creates nothing new. Use one key per invoice, derived from its number as above. A new Guid on every call protects nothing. In the sandbox the returned number carries a short suffix, for example FV/2026/10/001/ab12cd34, so do not compare it with the number you sent.
Which error codes should you handle?
Branch on the error code, never on the message text, which can change. A body that does not match the schema (a missing field, a wrong type, a VAT rate outside 23/8/5/0 or an issueDate not in YYYY-MM-DD) gets 422 validation_failed with a message before any other check. After that the API checks, in this order: 422 currency_not_supported, 422 unit_required, then 422 validation_failed with a details array. Next come the connection codes: 422 ksef_not_connected, ksef_connection_pending and ksef_connection_invalid mean you need to connect, validate or reconnect your KSeF token in the dashboard; ksef_production_disabled means KSeF production is switched off in Notaly right now, so nothing was sent; ksef_plan_required means the account needs a paid plan. After those come 422 seller_nip_not_authorized, 402 quota_exceeded and 422 xsd_invalid (with details; nothing was sent or counted). A 503 (ksef_unavailable or validator_unavailable) is transient and nothing was stored, so retry with backoff and the same key. 401 means the API key is missing or invalid.
How do you follow the invoice to the end?
The loop polls GET /invoices/{id} while the status is submitted (every 5 seconds) or draft with ksef_submitting (every 30 seconds), for at most 60 checks, and never sends a new POST. It stops on submitted with ksef_duplicate_review, on any other draft and on a final status. The lifecycle is draft → submitted → accepted or rejected. An accepted invoice gets ksefNumber and pdfUrl. Notaly requests the UPO and adds it to the invoice when KSeF issues it. A rejected invoice carries a stable code such as ksef_rejected:<code>. In production, subscribe to webhooks instead of polling.
Notaly validates and submits invoices. It is not a tax, accounting or legal advisor, and VAT rates and tax classification remain your responsibility.
Summary
- .NET 8, HttpClient + System.Text.Json, no NuGet packages.
- API key and buyer NIP come from env, with no defaults. Sandbox seller NIP:
2745013933. - Money in
decimal, issue date in Europe/Warsaw, one Idempotency-Key per invoice. - After the POST, read
statusanderror:submitted→ poll or webhook;draft+ksef_submitting→ keep polling, never a new POST;submitted+ksef_duplicate_review→ do not reissue;draft+ksef_retry_exhausted→ write to hello@getnotaly.com with the invoice id. - Handle error codes, not messages.
Sources
Source: www.podatki.gov.pl