PHP code example of visionapi / visionapi-php

1. Go to this page and download the library: Download visionapi/visionapi-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

visionapi / visionapi-php example snippets


use VisionApi\Client;

$vision = new Client(); // reads $_ENV['VISION_API_KEY']

$res = $vision->analyze(['file' => 'invoice.pdf', 'preset' => 'invoice']);

echo $res['result']['invoice_id']['value'];  // 'A-10422'
echo $res['result']['total']['value'];       // 1284.5, or null if the invoice has no total
echo $res['credits_used'], $res['credits_remaining'];

[
  'invoice_id' => ['value' => 'A-10422', 'confidence' => 'high'],
  'carrier'    => ['value' => null,      'confidence' => 'low'],
  'line_item'  => [
    ['description' => ['value' => 'Widget', 'confidence' => 'high'],
     'quantity'    => ['value' => 2,        'confidence' => 'high'],
     'amount'      => ['value' => 25.0,     'confidence' => 'mid']],
  ],
]

use VisionApi\Result;

Result::unwrap($res['result']);
// ['invoice_id' => 'A-10422', 'carrier' => null, 'line_item' => [['description' => 'Widget', …]]]

Result::unwrap($res['result'], dropNull: true);   // only what was actually found
Result::value($res['result'], 'total', 0);        // 1284.5, or 0 when absent
Result::rows($res['result'], 'line_item');        // [] when the invoice has no lines
Result::present($res['result']);                  // ['invoice_id', 'total', 'line_item']
Result::missing($res['result']);                  // ['carrier', …]
Result::belowConfidence($res['result'], 'high');  // fields to route to a human

$vision->analyze(['file' => 'invoice.pdf', 'preset' => 'invoice']);           // a path
$vision->analyze(['file' => fopen('invoice.pdf', 'rb'), …]);                  // an open stream
$vision->analyze(['file' => $bytes, …]);                                      // raw bytes
$vision->analyze(['file' => ['scan.png', $bytes], …]);                        // bytes + a name
$vision->analyze(['file_url' => 'https://example.com/invoice.pdf', …]);       // a public URL
$vision->analyze(['file_base64' => $encoded, …]);                             // "data:" prefix optional

$res = $vision->analyze([
    'file' => 'invoice.pdf',
    'preset' => 'invoice',
    'schema' => [
        // Plain form — the string is the description, type defaults to string.
        'machine_serial' => 'Serial number of the machine being invoiced, without the "SN:" prefix',

        // Typed form.
        'total_net' => ['type' => 'number', 'description' => 'Total before tax'],
        'signed_on' => ['type' => 'date', 'description' => 'Date the contract was signed'],

        // Reserved key: injects fields into every row of the preset's line-item array.
        'line_item' => ['lot_number' => 'The lot number printed on the line, if present'],
    ],
]);

$vision->createSchema('our-invoices', 'invoice', ['machine_serial' => '…']);
$vision->analyze(['file' => 'invoice.pdf', 'schema_name' => 'our-invoices']);

foreach ($vision->presets() as $preset) {          // no API key eld_count']} fields\n";
}

$invoice = $vision->preset('invoice');
array_column($invoice['fields'], 'name');

// 1. You know what it is.
$vision->analyze(['file' => 'receipt.jpg', 'preset' => 'receipt']);

// 2. You don't, and you want the data anyway. Classification is free.
$res = $vision->analyze(['file' => 'unknown.pdf', 'preset' => 'auto']);
$res['detection']['preset'];        // what ran
$res['detection']['fallback'];      // true = "shape unknown", not a match
$res['detection']['alternatives'];  // the rest of the ranking, best first

// 3. The *type* is the decision — routing a mixed inbox, or refusing to spend
//    on a 40-page PDF until you know what it is. Far cheaper than extracting.
$guess = $vision->detect(['file' => 'unknown.pdf']);
if (!$guess['fallback']) {
    $vision->analyze(['file' => 'unknown.pdf', 'preset' => $guess['recommended']]);
}

$res = $vision->ask([
    'file' => 'photo.jpg',
    'questions' => ['Is there a dog in the image?', 'How many people are visible?'],
]);

foreach ($res['answers'] as $answer) {
    match ($answer['verdict']) {
        'yes', 'no' => handle($answer['verdict']),
        'uncertain' => flagForReview($answer),  // the image does not settle it — a real answer
        'n/a'       => print($answer['answer']), // it wasn't a yes/no question
    };
}

// Submit, then poll. waitForTask handles the loop and the failure case.
$task = $vision->analyzeAndWait([
    'file' => 'contract-80-pages.pdf',
    'preset' => 'contract',
    'pages' => '1-50',
    'poll_interval' => 2.0,
    'max_wait' => 900.0,
    'on_poll' => fn (array $t) => Log::info($t['status']),
]);

// Or submit and walk away — the result comes to you.
$ref = $vision->analyzeAsync([
    'file' => 'contract.pdf',
    'preset' => 'contract',
    'webhook_url' => 'https://yourapp.com/hooks/vision',
]);

use VisionApi\Webhook;
use VisionApi\Exception\WebhookSignatureException;

// Laravel
public function __invoke(Request $request)
{
    try {
        $event = Webhook::verify(
            $request->getContent(),                       // the raw body, untouched
            $request->header('X-Vision-Signature'),
            config('services.vision.webhook_secret')
        );
    } catch (WebhookSignatureException) {
        return response()->noContent(400);                // never parse an unverified body
    }

    ProcessVisionResult::dispatch($event);                // ack fast, work afterwards
    return response()->noContent(202);                    // any 2xx is success
}

use VisionApi\Exception\{ApiException, InsufficientCreditsException, SyncTimeoutException, UnsupportedTypeException};

try {
    $res = $vision->analyze(['file' => 'scan.pdf', 'preset' => 'invoice']);
} catch (InsufficientCreditsException $e) {
    alertOps("needs {$e->tatus}) request_id={$e->requestId}");
}

$vision->analyze(['file' => $path, 'preset' => 'invoice', 'idempotency_key' => "invoice-{$invoice->id}"]);

$vision = new Client([
    'api_key' => $_ENV['VISION_API_KEY'],   // default: $_ENV['VISION_API_KEY']
    'base_url' => 'https://api.visionapi.io', // default; override for a self-hosted deployment
    'timeout' => 120.0,                      // per request, seconds
    'max_retries' => 3,
    'auto_idempotency' => true,
    'headers' => ['X-Trace-Id' => $traceId], // sent on every request
    'transport' => $myTransport,             // swap the HTTP layer (tests, proxies, metrics)
]);

// config/services.php
'vision' => [
    'key' => env('VISION_API_KEY'),
    'webhook_secret' => env('VISION_WEBHOOK_SECRET'),
],

// AppServiceProvider::register()
$this->app->singleton(Client::class, fn () => new Client(['api_key' => config('services.vision.key')]));

$credits = $vision->credits();
// $credits['buckets'] are spent in order: subscription → rollover → pack → welcome

foreach ($vision->eachRequest(limit: 100) as $record) {
    echo "{$record['created_at']} {$record['endpoint']} {$record['preset']} {$record['credits_used']}\n";
}
bash
composer 
bash
export VISION_API_KEY=sk_live_…
php examples/analyze.php invoice.pdf