To parse invoices and bank statements in C# (.NET), POST the PDF to https://api.parserkit.com/v1/parse with HttpClient. It costs $0.02 a page with 50 pages free, and our 1-page test invoice passed 8 of 8 checks.

Parse invoices and bank statements in C#

The program below runs on .NET 8 with no NuGet packages. It uploads a PDF, waits for the job (an invoice takes under 20 seconds), prints the verification result, saves the Excel and CSV files and checks the HMAC-SHA256 signature on each webhook event.

Updated

What you need

You need .NET 8 and a console project from dotnet new console. There is nothing else to install: HttpClient with MultipartFormDataContent sends the file, System.Text.Json reads the answer, HttpListener runs the webhook receiver, and HMACSHA256.HashData with CryptographicOperations.FixedTimeEquals checks signatures. Sign in at parserkit.com, create a key under API keys in the dashboard and set it in PARSERKIT_API_KEY; the program sends it as Authorization: Bearer <key>. Set PARSERKIT_WEBHOOK_URL to get a webhook for each job, and PARSERKIT_WEBHOOK_SECRET for the receiver.

The program

Program.cs uses top-level statements and has two commands: dotnet run -- parse <file> [preset] and dotnet run -- serve <port>. The preset defaults to invoice; pass bank_statement for a bank statement. On parse, it POSTs your file as multipart form data to https://api.parserkit.com/v1/parse?wait=25 with the preset and an optional webhook_url, waits for the job, reads verification and data, and downloads the spreadsheet files. A very large result comes back with data_omitted set to true and a data_url link instead of inline data; the program then prints the verification status and stops.

Program.cs
// Parse a document with the parserkit API, save its Excel and CSV files, and check webhook signatures.
//   dotnet run -- parse invoice.pdf [preset]
//   dotnet run -- serve 8000
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

const string Api = "https://api.parserkit.com";
const int MaxAttempts = 5;
const int MaxWaitS = 60;
const int MaxBodyBytes = 10 * 1024 * 1024;

var http = new HttpClient { Timeout = TimeSpan.FromSeconds(90) };

if (args is ["parse", var file, ..])
{
    try
    {
        var job = await Parse(file, args.Length > 2 ? args[2] : "invoice");
        Report(job);
        await Download(job);
    }
    catch (ParserkitException error)
    {
        Console.Error.WriteLine($"parserkit error {error.Message}");
        return 1;
    }
}
else if (args is ["serve", var port])
{
    await Serve(int.Parse(port));
}
else
{
    Console.Error.WriteLine("usage: dotnet run -- parse <file> [preset] | serve <port>");
    return 2;
}
return 0;

// Sends one request, waiting out 429 and 503 answers for as long as Retry-After asks
async Task<HttpResponseMessage> Send(Func<HttpRequestMessage> request)
{
    for (var attempt = 1; ; attempt++)
    {
        HttpResponseMessage response;
        try
        {
            response = await http.SendAsync(request());
        }
        catch (Exception error) when (error is HttpRequestException or TaskCanceledException && attempt < MaxAttempts)
        {
            Console.WriteLine($"network error ({error.GetType().Name}), retrying in 2 s");
            await Task.Delay(2000);
            continue;
        }
        if ((int)response.StatusCode < 400) return response;

        var isJson = response.Content.Headers.ContentType?.MediaType == "application/json";
        var body = isJson ? await ReadJson(response) : JsonDocument.Parse("{}").RootElement;
        var waitS = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 0);
        var retryable = response.StatusCode is HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable && Get(body, "job") is null;
        if (retryable && waitS > 0 && waitS <= MaxWaitS && attempt < MaxAttempts)
        {
            Console.WriteLine($"{(int)response.StatusCode} {Get(body, "error", "code")}, retrying in {waitS} s");
            await Task.Delay(waitS * 1000);
            continue;
        }

        var requestId = Get(body, "error", "request_id") ?? (response.Headers.TryGetValues("Request-Id", out var ids) ? ids.First() : null);
        throw new ParserkitException($"{(int)response.StatusCode} {Get(body, "error", "code")}: {Get(body, "error", "message")} (request_id {requestId}, job {Get(body, "job", "id") ?? "none"})");
    }
}

HttpRequestMessage Authorized(HttpRequestMessage request)
{
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("PARSERKIT_API_KEY"));
    return request;
}

async Task<JsonElement> Parse(string path, string preset)
{
    var bytes = await File.ReadAllBytesAsync(path);
    var webhookUrl = Environment.GetEnvironmentVariable("PARSERKIT_WEBHOOK_URL");

    // One key for this upload, sent again on every retry, so the API never starts a second job
    var idempotencyKey = Guid.NewGuid().ToString();
    var response = await Send(() =>
    {
        var form = new MultipartFormDataContent
        {
            { new ByteArrayContent(bytes), "file", Path.GetFileName(path) },
            { new StringContent(preset), "preset" },
        };
        if (webhookUrl is not null) form.Add(new StringContent(webhookUrl), "webhook_url");

        var request = new HttpRequestMessage(HttpMethod.Post, $"{Api}/v1/parse?wait=25") { Content = form };
        request.Headers.Add("Idempotency-Key", idempotencyKey);
        return Authorized(request);
    });

    // 202 means the job is still running. GET holds each call up to 25 s and answers 200 whatever the status, so we watch the status
    var job = await ReadJson(response);
    var waitS = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 2);
    while (Get(job, "status") is "queued" or "running")
    {
        Console.WriteLine($"{(int)response.StatusCode} {Get(job, "id")} is {Get(job, "status")}, checking again in {waitS} s");
        await Task.Delay(waitS * 1000);
        var jobUrl = $"{Api}/v1/jobs/{Get(job, "id")}?wait=25";
        response = await Send(() => Authorized(new HttpRequestMessage(HttpMethod.Get, jobUrl)));
        job = await ReadJson(response);
        waitS = 2;
    }

    if (Get(job, "status") == "failed")
    {
        var requestId = response.Headers.TryGetValues("Request-Id", out var ids) ? ids.First() : null;
        throw new ParserkitException($"failed {Get(job, "error", "code")}: {Get(job, "error", "message")} (request_id {requestId}, job {Get(job, "id")})");
    }
    return job;
}

void Report(JsonElement job)
{
    Console.WriteLine($"{Get(job, "id")}: {Get(job, "status")}, {Get(job, "pages")} page(s), ${Get(job, "cost_usd")}");
    if (job.GetProperty("data_omitted").GetBoolean())
    {
        Console.WriteLine($"verification: {Get(job, "verification_status")}, the full result is at data_url");
        return;
    }

    var verification = job.GetProperty("verification");
    var checks = verification.GetProperty("checks").EnumerateArray().ToList();
    Console.WriteLine($"verification: {Get(verification, "status")}, {Get(verification, "coverage", "checked")} of {Get(verification, "coverage", "values")} values checked");
    Console.WriteLine($"checks: {checks.Count(check => Get(check, "status") == "pass")} of {checks.Count} pass");
    foreach (var check in checks.Where(check => Get(check, "status") != "pass"))
    {
        Console.WriteLine($"  {Get(check, "status")} {Get(check, "kind")} {Get(check, "path")}: {Get(check, "message")}");
    }

    var data = job.GetProperty("data");
    if (Get(job, "preset") == "bank_statement")
    {
        Console.WriteLine($"{Get(data, "bank", "name")}, {Get(data, "period_start")} to {Get(data, "period_end")}: {data.GetProperty("transactions").GetArrayLength()} transactions,"
            + $" opening {Get(data, "opening_balance")}, closing {Get(data, "closing_balance")} {Get(data, "currency")}");
    }
    else
    {
        Console.WriteLine($"invoice {Get(data, "invoice_number")} from {Get(data, "vendor", "name")}, {Get(data, "issue_date")}:"
            + $" {data.GetProperty("line_items").GetArrayLength()} lines, total {Get(data, "grand_total")} {Get(data, "currency")}");
    }
    foreach (var warning in job.GetProperty("warnings").EnumerateArray())
    {
        Console.WriteLine($"warning {Get(warning, "code")}: {Get(warning, "message")}");
    }
}

async Task Download(JsonElement job)
{
    foreach (var output in job.GetProperty("outputs").EnumerateArray())
    {
        var name = Get(output, "name");
        if (name is not ("output.xlsx" or "output.csv")) continue;

        // Signed links need no API key; keep them out of your logs
        var response = await Send(() => new HttpRequestMessage(HttpMethod.Get, Get(output, "url")));
        var content = await response.Content.ReadAsByteArrayAsync();
        var target = $"{Get(job, "id")}-{name}";
        await File.WriteAllBytesAsync(target, content);
        Console.WriteLine($"saved {target} ({content.Length} bytes)");
    }
}

async Task Serve(int port)
{
    var secret = Environment.GetEnvironmentVariable("PARSERKIT_WEBHOOK_SECRET") ?? throw new InvalidOperationException("set PARSERKIT_WEBHOOK_SECRET first");
    var listener = new HttpListener();
    listener.Prefixes.Add($"http://*:{port}/");
    listener.Start();
    Console.WriteLine($"listening on port {port}");

    // Each delivery runs on its own task, so one slow client can't hold up the rest
    while (true)
    {
        var context = await listener.GetContextAsync();
        _ = Task.Run(() => Receive(context, secret));
    }
}

async Task Receive(HttpListenerContext context, string secret)
{
    try
    {
        if (context.Request.ContentLength64 is < 0 or > MaxBodyBytes)
        {
            Console.WriteLine("missing or oversized body, answered 413");
            context.Response.StatusCode = 413;
            return;
        }

        using var buffer = new MemoryStream();
        await context.Request.InputStream.CopyToAsync(buffer);
        var rawBody = buffer.ToArray();
        if (!VerifySignature(secret, rawBody, context.Request.Headers["Parserkit-Signature"] ?? ""))
        {
            Console.WriteLine("signature check failed, answered 401");
            context.Response.StatusCode = 401;
            return;
        }

        var webhookEvent = JsonSerializer.Deserialize<JsonElement>(rawBody);
        var headers = context.Request.Headers;
        Console.WriteLine($"signature ok: {Get(webhookEvent, "type")} {Get(webhookEvent, "data", "id")} ({headers["Idempotency-Key"]}, attempt {headers["Parserkit-Attempt"]})");
        context.Response.StatusCode = 200;
    }
    catch (Exception error)
    {
        Console.WriteLine($"delivery failed ({error.GetType().Name}), answered 500");
        context.Response.StatusCode = 500;
    }
    finally
    {
        context.Response.Close();
    }
}

static bool VerifySignature(string secret, byte[] rawBody, string header, int toleranceS = 300)
{
    var parts = new Dictionary<string, string>();
    foreach (var part in header.Split(','))
    {
        var pair = part.Split('=', 2);
        if (pair.Length == 2) parts[pair[0]] = pair[1];
    }
    if (!parts.TryGetValue("t", out var tText) || !long.TryParse(tText, out var t)) return false;
    if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - t) > toleranceS) return false;

    var signed = Encoding.UTF8.GetBytes($"{t}.").Concat(rawBody).ToArray();
    var expected = Encoding.UTF8.GetBytes(Convert.ToHexString(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed)).ToLowerInvariant());
    var given = Encoding.UTF8.GetBytes(parts.GetValueOrDefault("v1", ""));
    return CryptographicOperations.FixedTimeEquals(expected, given);
}

static async Task<JsonElement> ReadJson(HttpResponseMessage response) =>
    JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStreamAsync());

static string? Get(JsonElement element, params string[] path)
{
    foreach (var name in path)
    {
        if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(name, out element)) return null;
    }
    return element.ValueKind == JsonValueKind.Null ? null : element.ToString();
}

class ParserkitException(string message) : Exception(message);

Run it

On a one-page invoice the job succeeds for $0.02, verification.status comes back verified when every check passes, and the program saves output.xlsx and output.csv.

Terminal
$ dotnet run -- parse invoice-kesselbach-3397.pdf
job_qs7ma7jzmdf74x9f0e3t: succeeded, 1 page(s), $0.02
verification: verified, 35 of 35 values checked
checks: 8 of 8 pass
invoice KB-26-3397 from Kesselbach Antriebstechnik GmbH, 2026-11-05: 4 lines, total 3494.73 EUR
saved job_qs7ma7jzmdf74x9f0e3t-output.xlsx (10136 bytes)
saved job_qs7ma7jzmdf74x9f0e3t-output.csv (552 bytes)
Fields the program reads from the job
FieldWhat it holdsOur run
statusqueued, running, succeeded or failedsucceeded
verification.statusverified, partial, unverified or discrepancyverified
verification.coverageValues read and values with a check35 and 35
verification.checksOne entry per check, with kind, path, status and message8, all pass
dataThe fields read from the documentinvoice KB-26-3397, total 3494.73 EUR
outputsSigned links to the files5 files
warningsAnything the parser flaggednone
cost_usdWhat the job cost0.02
The same job, trimmed
{
  "id": "job_qs7ma7jzmdf74x9f0e3t",
  "status": "succeeded",
  ...
  "cost_usd": 0.02,
  "verification_status": "verified",
  ...
  "verification": {
    "status": "verified",
    "math_balanced": true,
    "coverage": {
      "values": 35,
      "checked": 35
    },
    "checks": [
      {
        "kind": "line_total",
        "path": "line_items[0].total",
        "fields": [
          "line_items[0].quantity",
          "line_items[0].unit_price",
          "line_items[0].total"
        ],
        "status": "pass",
        "expected": 756,
        "actual": 756,
        "difference": 0,
        "page": 1,
        "message": "quantity x unit price"
      },
      ...
      {
        "kind": "sum",
        "path": "grand_total",
        "fields": [
          "line_items[].total",
          "tax_total",
          "subtotal",
          "grand_total"
        ],
        "status": "pass",
        "expected": 3494.73,
        "actual": 3494.73,
        "difference": 0,
        "page": 1,
        "message": "the line totals + tax"
      }
    ],
    "repairs": [],
    "barcodes": []
  },
  ...
  "warnings": []
}

Trimmed with ...: the other job fields and the other checks.

The wait query parameter can be 0 to 60 seconds (default 60). Our job finished 17 seconds after it was created, so the POST answered 200 right away with the finished job. When a job takes longer than wait, the POST answers 202 with Location and Retry-After: 2. The program then calls GET /v1/jobs/{id}?wait=25, which holds up to 25 seconds and answers 200 with the job whatever its status, and keeps asking while status is queued or running. If the status is failed, the program stops with its error code.

Excel and CSV files

Every finished job lists signed links in outputs; for this invoice they were output.json, output.xlsx, output.csv, quickbooks.csv and xero.csv. The program downloads output.xlsx and output.csv. Those links need no API key and last at least an hour, so keep them out of your logs.

outputs, from the same job
[
  ...
  {
    "name": "output.xlsx",
    "bytes": 10136,
    "url": "https://files.parserkit.com/f/7d/acct_.../job_qs7ma7jzmdf74x9f0e3t/out/output.xlsx?exp=1794051600&sig=...",
    "expires_at": "2026-11-07T11:40:00.000Z"
  },
  {
    "name": "output.csv",
    "bytes": 552,
    "url": "https://files.parserkit.com/f/7d/acct_.../job_qs7ma7jzmdf74x9f0e3t/out/output.csv?exp=1794051600&sig=...",
    "expires_at": "2026-11-07T11:40:00.000Z"
  },
  ...
]

Trimmed to the two files the program saves. The signature in each link and the account id are replaced with ...

job_qs7ma7jzmdf74x9f0e3t-output.csv
invoice_number,issue_date,due_date,vendor.name,currency,description,quantity,unit_price,total
KB-26-3397,2026-11-05,2026-12-05,Kesselbach Antriebstechnik GmbH,EUR,"Drive belt HTD 8M-1200, 30 mm",40,18.90,756.00
KB-26-3397,2026-11-05,2026-12-05,Kesselbach Antriebstechnik GmbH,EUR,"Gear motor 0.37 kW, ratio 1:20",6,214.50,1287.00
KB-26-3397,2026-11-05,2026-12-05,Kesselbach Antriebstechnik GmbH,EUR,Bearing unit UCP 205,25,12.35,308.75
KB-26-3397,2026-11-05,2026-12-05,Kesselbach Antriebstechnik GmbH,EUR,"Service call, hours",7.5,78.00,585.00

As saved by the run, without the UTF-8 byte order mark at the start of the file.

Errors and retries

Every error answer has error.code, error.message and error.request_id, also in the Request-Id header. A wrong API key gets 401 UNAUTHORIZED with a request id, and no job is created.

Terminal
$ env PARSERKIT_API_KEY=pkit_live_not_a_real_key dotnet run -- parse invoice-kesselbach-3397.pdf
parserkit error 401 UNAUTHORIZED: invalid API key (request_id a56bb5bdbbc314f9, job none)

429 (RATE_LIMITED, BUSY, CONTENT_REFUSALS) and 503 (CONTAINER_UNAVAILABLE) carry a Retry-After header. When it is 60 seconds or less, the program waits that long and tries again, up to 5 attempts; a longer wait stops it with the error. It does not retry other errors or a failed job. An HttpRequestMessage can only be sent once, so Send() takes a function that builds a fresh request for each attempt, with the same random UUID in Idempotency-Key. The same key and request within 24 hours return the same job instead of starting a second one, and the same key with a different request answers 409 IDEMPOTENCY_CONFLICT. See Errors and limits.

Webhook signatures

With webhook_url set, parserkit POSTs an event such as job.succeeded or job.failed to your HTTPS URL with Parserkit-Signature, Idempotency-Key (the event id, the same on every attempt), Parserkit-Attempt, Parserkit-Event and Parserkit-Job-Id. Parserkit-Signature looks like t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of "<t>.<raw body>" keyed with your whsec_ signing secret from Webhooks. Check it on the raw body bytes before parsing JSON, compare in constant time with CryptographicOperations.FixedTimeEquals, and refuse a t more than 300 seconds from your clock. The receiver also refuses bodies over 10 MB and runs each delivery on its own task, so one slow client cannot hold up the rest. Store the event id to skip repeats and answer with a 2xx fast, since there are up to 5 attempts at 15 seconds each (Webhooks).

Terminal, the receiver
$ dotnet run --no-build -- serve 8004
listening on port 8004
...
signature ok: job.succeeded job_qs7ma7jzmdf74x9f0e3t (evt_o0pxiblsv1jpy7kchj6d, attempt 1)
signature check failed, answered 401

Our receiver ran on port 8004 behind a tunnel. The first request is the real delivery; the second is the same delivery with the first digit of grand_total changed. Lines from earlier local tests are cut at ...

We pointed webhook_url at the receiver from this page through a tunnel. The real delivery for our run, evt_o0pxiblsv1jpy7kchj6d, got 200. The same delivery sent again with one digit of an amount changed got 401, and in a local test a delivery with a timestamp more than 300 seconds old also got 401.

Questions

Do I need any NuGet packages?

No. It runs on .NET 8 with a plain dotnet new console project and uses built-in libraries for HTTP, JSON, the webhook listener and HMAC-SHA256.

What are the file size and page limits?

A multipart upload to /v1/parse takes files up to 25 MB, or up to 100 MB by file_url or /v1/uploads, with up to 250 pages a job. Results and files are kept 7 days, or 90 days on Pro.

What do the verification statuses mean?

verified means every required value has a check and none fail, partial means some value has no check, and unverified means there are no checks. discrepancy means a check still fails after repair; verification.coverage has the counts and each item in verification.checks its kind, path, status and message.

How much does it cost, and do retries or duplicates cost extra?

Parsing costs $0.02 a page, with 50 pages free ($1 of credit) when you sign in with Google; see pricing. Failed jobs and exact duplicates cost nothing, and a retry with the same Idempotency-Key within 24 hours returns the original job without starting a second one.

NextPHP

Your first $1 is free, 50 pages with every check and export.