To parse invoices and bank statements in PHP, POST the PDF to https://api.parserkit.com/v1/parse with CURLFile. 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 PHP

The single-file script below runs on PHP 8.4 with the curl extension. It uploads a PDF from the command line, waits for the job (an invoice takes under 20 seconds), prints the verification result and saves the spreadsheet outputs; served by a web server, the same file is your webhook receiver.

Updated

What you need

You need PHP 8 with the curl extension and nothing from Composer. CURLFile handles the upload, json_decode reads the answer, and hash_hmac with hash_equals checks webhook signatures. Create a key under API keys in the dashboard and set it in PARSERKIT_API_KEY; the script 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 quickstart covers the API itself.

The program

Run php parserkit_example.php parse <file> [preset] to send a multipart POST to https://api.parserkit.com/v1/parse?wait=25 with the file, a preset (invoice by default, or bank_statement) and an optional webhook_url. If the job is not done when the first call returns, the script polls until it finishes, checks verification.status (verified, partial, unverified or discrepancy), reads the fields from data and downloads the files from outputs. For very large results, data_omitted is true and you get a data_url link instead of inline data; the script then prints the verification status and stops.

parserkit_example.php
<?php
// Parse a document with the parserkit API, save its Excel and CSV files, and check webhook signatures.
//   php parserkit_example.php parse invoice.pdf [preset]
//   php -d display_errors=0 -S 0.0.0.0:8000 parserkit_example.php    (the webhook receiver)

const API = 'https://api.parserkit.com';
const MAX_ATTEMPTS = 5;
const MAX_WAIT_S = 60;
const MAX_BODY_BYTES = 10 * 1024 * 1024;

final class ParserkitException extends Exception
{
}

// Sends one request, waiting out 429 and 503 answers for as long as Retry-After asks
function send(string $method, string $url, array $headers = [], ?array $fields = null): array
{
    for ($attempt = 1; ; $attempt++) {
        $responseHeaders = [];
        $curl = curl_init($url);
        curl_setopt_array($curl, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 90,
            CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$responseHeaders): int {
                $pair = explode(':', $line, 2);
                if (count($pair) === 2) {
                    $responseHeaders[strtolower(trim($pair[0]))] = trim($pair[1]);
                }
                return strlen($line);
            },
        ]);
        if ($fields !== null) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
        }
        $content = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);

        if ($content === false) {
            $networkError = curl_error($curl);
            if ($attempt === MAX_ATTEMPTS) {
                throw new RuntimeException("network error: $networkError");
            }
            echo "network error ($networkError), retrying in 2 s\n";
            sleep(2);
            continue;
        }
        if ($status < 400) {
            return [$status, $responseHeaders, $content];
        }

        $isJson = str_starts_with($responseHeaders['content-type'] ?? '', 'application/json');
        $body = $isJson ? json_decode($content, true) : [];
        $waitS = (int) ($responseHeaders['retry-after'] ?? 0);
        $retryable = in_array($status, [429, 503], true) && !isset($body['job']);
        if ($retryable && $waitS > 0 && $waitS <= MAX_WAIT_S && $attempt < MAX_ATTEMPTS) {
            echo "$status {$body['error']['code']}, retrying in $waitS s\n";
            sleep($waitS);
            continue;
        }

        $error = $body['error'] ?? [];
        $requestId = $error['request_id'] ?? $responseHeaders['request-id'] ?? null;
        throw new ParserkitException(sprintf(
            '%d %s: %s (request_id %s, job %s)',
            $status, $error['code'] ?? '', $error['message'] ?? '', $requestId, $body['job']['id'] ?? 'none'
        ));
    }
}

function parse(string $path, string $preset): array
{
    $auth = 'Authorization: Bearer ' . getenv('PARSERKIT_API_KEY');
    $fields = ['file' => new CURLFile($path, 'application/octet-stream', basename($path)), 'preset' => $preset];
    if (getenv('PARSERKIT_WEBHOOK_URL')) {
        $fields['webhook_url'] = getenv('PARSERKIT_WEBHOOK_URL');
    }

    // One key for this upload, sent again on every retry, so the API never starts a second job
    $idempotencyKey = 'Idempotency-Key: ' . bin2hex(random_bytes(16));
    [$status, $headers, $content] = send('POST', API . '/v1/parse?wait=25', [$auth, $idempotencyKey], $fields);

    // 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
    $job = json_decode($content, true);
    $waitS = (int) ($headers['retry-after'] ?? 2);
    while (in_array($job['status'], ['queued', 'running'], true)) {
        echo "$status {$job['id']} is {$job['status']}, checking again in $waitS s\n";
        sleep($waitS);
        [$status, $headers, $content] = send('GET', API . "/v1/jobs/{$job['id']}?wait=25", [$auth]);
        $job = json_decode($content, true);
        $waitS = 2;
    }

    if ($job['status'] === 'failed') {
        throw new ParserkitException(sprintf(
            'failed %s: %s (request_id %s, job %s)',
            $job['error']['code'], $job['error']['message'], $headers['request-id'] ?? '', $job['id']
        ));
    }
    return $job;
}

function report(array $job): void
{
    printf("%s: %s, %d page(s), $%s\n", $job['id'], $job['status'], $job['pages'], $job['cost_usd']);
    if ($job['data_omitted']) {
        printf("verification: %s, the full result is at data_url\n", $job['verification_status']);
        return;
    }

    $verification = $job['verification'];
    $passed = array_filter($verification['checks'], fn (array $check): bool => $check['status'] === 'pass');
    printf(
        "verification: %s, %d of %d values checked\n",
        $verification['status'], $verification['coverage']['checked'], $verification['coverage']['values']
    );
    printf("checks: %d of %d pass\n", count($passed), count($verification['checks']));
    foreach ($verification['checks'] as $check) {
        if ($check['status'] !== 'pass') {
            printf("  %s %s %s: %s\n", $check['status'], $check['kind'], $check['path'], $check['message']);
        }
    }

    $data = $job['data'];
    if ($job['preset'] === 'bank_statement') {
        printf(
            "%s, %s to %s: %d transactions, opening %s, closing %s %s\n",
            $data['bank']['name'], $data['period_start'], $data['period_end'], count($data['transactions']),
            $data['opening_balance'], $data['closing_balance'], $data['currency']
        );
    } else {
        printf(
            "invoice %s from %s, %s: %d lines, total %s %s\n",
            $data['invoice_number'], $data['vendor']['name'], $data['issue_date'], count($data['line_items']),
            $data['grand_total'], $data['currency']
        );
    }
    foreach ($job['warnings'] as $warning) {
        printf("warning %s: %s\n", $warning['code'], $warning['message']);
    }
}

function download(array $job, array $names = ['output.xlsx', 'output.csv']): void
{
    foreach ($job['outputs'] as $output) {
        if (!in_array($output['name'], $names, true)) {
            continue;
        }

        // Signed links need no API key; keep them out of your logs
        [, , $content] = send('GET', $output['url']);
        $target = "{$job['id']}-{$output['name']}";
        file_put_contents($target, $content);
        printf("saved %s (%d bytes)\n", $target, strlen($content));
    }
}

function verify_signature(string $secret, string $rawBody, string $header, int $toleranceS = 300): bool
{
    $parts = [];
    foreach (explode(',', $header) as $part) {
        $pair = explode('=', $part, 2);
        if (count($pair) === 2) {
            $parts[$pair[0]] = $pair[1];
        }
    }
    $t = $parts['t'] ?? '';
    if (!ctype_digit($t) || abs(time() - (int) $t) > $toleranceS) {
        return false;
    }

    $expected = hash_hmac('sha256', "$t.$rawBody", $secret);
    return hash_equals($expected, $parts['v1'] ?? '');
}

// Served by a web server (php -S, php-fpm), this file is the webhook receiver
if (PHP_SAPI !== 'cli') {
    if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > MAX_BODY_BYTES) {
        error_log('oversized body, answered 413');
        http_response_code(413);
        exit;
    }

    $rawBody = file_get_contents('php://input');
    if (!verify_signature(getenv('PARSERKIT_WEBHOOK_SECRET'), $rawBody, $_SERVER['HTTP_PARSERKIT_SIGNATURE'] ?? '')) {
        error_log('signature check failed, answered 401');
        http_response_code(401);
        exit;
    }

    $event = json_decode($rawBody, true);
    error_log(sprintf(
        'signature ok: %s %s (%s, attempt %s)',
        $event['type'], $event['data']['id'] ?? '', $_SERVER['HTTP_IDEMPOTENCY_KEY'] ?? '', $_SERVER['HTTP_PARSERKIT_ATTEMPT'] ?? ''
    ));
    http_response_code(200);
    exit;
}

if (($argv[1] ?? '') !== 'parse' || !isset($argv[2])) {
    fwrite(STDERR, "usage: php parserkit_example.php parse <file> [preset]\n");
    exit(2);
}
try {
    $job = parse($argv[2], $argv[3] ?? 'invoice');
    report($job);
    download($job);
} catch (ParserkitException $error) {
    fwrite(STDERR, "parserkit error {$error->getMessage()}\n");
    exit(1);
}

Run it

On a one-page invoice the job succeeds for $0.02, and verification.status comes back verified when every check passes. The script also prints any warnings, such as hidden_text when the API finds a word that is not visible on the page and leaves it out.

Terminal
$ php parserkit_example.php parse invoice-wattlebrook-60437.pdf
job_98v95xryjze64i7zwnpv: succeeded, 1 page(s), $0.02
verification: verified, 35 of 35 values checked
checks: 8 of 8 pass
invoice WB-60437 from Wattlebrook Supplies Pty Ltd, 2026-11-06: 4 lines, total 1440.78 AUD
warning hidden_text: 1 words on page 1 of invoice-wattlebrook-60437.pdf are not visible and were ignored
saved job_98v95xryjze64i7zwnpv-output.xlsx (10074 bytes)
saved job_98v95xryjze64i7zwnpv-output.csv (543 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 WB-60437, total 1440.78 AUD
outputsSigned links to the files5 files
warningsAnything the parser flagged1, hidden_text
cost_usdWhat the job cost0.02
The same job, trimmed
{
  "id": "job_98v95xryjze64i7zwnpv",
  "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": 392,
        "actual": 392,
        "difference": 0,
        "page": 1,
        "message": "quantity x unit price"
      },
      ...
      {
        "kind": "sum",
        "path": "grand_total",
        "fields": [
          "line_items[].total",
          "tax_total",
          "shipping",
          "subtotal",
          "grand_total"
        ],
        "status": "pass",
        "expected": 1440.78,
        "actual": 1440.78,
        "difference": 0,
        "page": 1,
        "message": "the line totals + tax + shipping"
      }
    ],
    "repairs": [],
    "barcodes": []
  },
  ...
  "warnings": [
    {
      "code": "hidden_text",
      "message": "1 words on page 1 of invoice-wattlebrook-60437.pdf are not visible and were ignored",
      "document": 0,
      "page": 1
    }
  ]
}

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

The wait query parameter takes 0 to 60 seconds (default 60). Our job finished 17 seconds after it was created, so the first POST answered 200 with the finished job. When a job takes longer than wait, the POST answers 202 with Location and Retry-After: 2. The script 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. It stops with the error code if status is failed.

Excel and CSV files

Once the job succeeds, the script saves output.xlsx and output.csv from the links in outputs, which also has output.json, quickbooks.csv and xero.csv. These signed links don't need your API key and last at least an hour, so keep them out of your logs.

outputs, from the same job
[
  ...
  {
    "name": "output.xlsx",
    "bytes": 10074,
    "url": "https://files.parserkit.com/f/7d/acct_.../job_98v95xryjze64i7zwnpv/out/output.xlsx?exp=1794051600&sig=...",
    "expires_at": "2026-11-07T11:40:00.000Z"
  },
  {
    "name": "output.csv",
    "bytes": 543,
    "url": "https://files.parserkit.com/f/7d/acct_.../job_98v95xryjze64i7zwnpv/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_98v95xryjze64i7zwnpv-output.csv
invoice_number,issue_date,due_date,vendor.name,currency,description,quantity,unit_price,total
WB-60437,2026-11-06,2026-11-20,Wattlebrook Supplies Pty Ltd,AUD,"Compostable cups, 12 oz, sleeve of 50",40,9.80,392.00
WB-60437,2026-11-06,2026-11-20,Wattlebrook Supplies Pty Ltd,AUD,"Cold brew concentrate, 5 L",12,46.50,558.00
WB-60437,2026-11-06,2026-11-20,Wattlebrook Supplies Pty Ltd,AUD,"Oat milk, barista, 1 L",72,3.15,226.80
WB-60437,2026-11-06,2026-11-20,Wattlebrook Supplies Pty Ltd,AUD,"Napkins, 2-ply, pack of 500",15,7.20,108.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 includes error.code, error.message and error.request_id, also sent in the Request-Id header. When we passed the preset statement instead of bank_statement, the API answered 400 INVALID_REQUEST with the list of valid presets, a request id, and no job.

Terminal
$ php parserkit_example.php parse invoice-wattlebrook-60437.pdf statement
parserkit error 400 INVALID_REQUEST: preset: Invalid option: expected one of "invoice"|"receipt"|"bank_statement"|"resume"|"purchase_order"|"bill_of_lading"|"generic_table" (request_id a56bb5bf2d5f3734, job none)

Answers with 429 (RATE_LIMITED, BUSY, CONTENT_REFUSALS) or 503 (CONTAINER_UNAVAILABLE) carry a Retry-After header. If it is 60 seconds or less, the script sleeps that long and tries again, up to 5 attempts; a longer wait stops it with the error, as do other errors and a failed job. Each upload gets one random Idempotency-Key, repeated on every retry, so the same key and request return the same job for 24 hours, while the same key with a different request answers 409 IDEMPOTENCY_CONFLICT.

Webhook signatures

When you pass webhook_url, parserkit POSTs events like job.succeeded or job.failed to your HTTPS URL with Parserkit-Signature, Idempotency-Key (the event id, the same on all of up to 5 attempts, 15 seconds each), Parserkit-Attempt, Parserkit-Event and Parserkit-Job-Id. The receiver in the script refuses bodies over 10 MB, reads t=<unix seconds>,v1=<hex> from Parserkit-Signature, refuses a t more than 300 seconds off the clock, and checks the HMAC-SHA256 of "<t>.<raw body>" against your whsec_ signing secret from Webhooks on the raw body in constant time before decoding JSON. Store the event id to skip repeats and answer with a 2xx fast; more in Webhooks.

Terminal, the receiver
$ php -d display_errors=0 -S 127.0.0.1:8005 parserkit_example.php
[Sat Nov  7 10:32:03 2026] PHP 8.4.23 Development Server (http://127.0.0.1:8005) started
...
[Sat Nov  7 10:37:43 2026] 127.0.0.1:51016 Accepted
[Sat Nov  7 10:37:43 2026] signature ok: job.succeeded job_98v95xryjze64i7zwnpv (evt_7wqvupzqw7gmfar8hg5k, attempt 1)
[Sat Nov  7 10:37:43 2026] 127.0.0.1:51016 Closing
[Sat Nov  7 10:37:43 2026] 127.0.0.1:51020 Accepted
[Sat Nov  7 10:37:43 2026] signature check failed, answered 401
[Sat Nov  7 10:37:43 2026] 127.0.0.1:51020 Closing

Our receiver ran on port 8005 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 ...

For a local test, run php -d display_errors=0 -S 0.0.0.0:8000 parserkit_example.php; display_errors=0 keeps PHP warnings out of the answers. Use php-fpm or Apache in production. We pointed webhook_url at the script through a tunnel, and delivery evt_7wqvupzqw7gmfar8hg5k got 200. The same payload 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 Composer or an SDK?

No. The script uses plain PHP 8 with the curl extension: CURLFile, json_decode, hash_hmac and hash_equals.

What are the file size, page and retention limits?

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

Am I charged for failed jobs or duplicate uploads?

Failed jobs and exact duplicates cost nothing. Successful jobs cost $0.02 a page, and you get 50 pages free ($1 of credit) when you sign in with Google; see pricing.

How do I know the numbers on the PDF add up?

Check verification.status on the job: verified means every required value has a check and none fail, and discrepancy means a check still fails after repair (partial and unverified mean some or all checks are missing). Each entry in verification.checks has its kind, path, status and message.

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