PHP code example of iajson / client

1. Go to this page and download the library: Download iajson/client 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/ */

    

iajson / client example snippets


use IaJson\Client\IaJsonClient;

// Discover a site's ia.json and create a client
$client = IaJsonClient::discover('techstore.example.com');

// Call a public endpoint (no authentication needed)
$results = $client->call('search_products', ['q' => 'wireless headphones']);

// Inspect the site
$site = $client->getSite();
echo $site['name']; // "TechStore"
echo $site['type']; // "ecommerce"

use IaJson\Client\Discovery;

$discovery = new Discovery();
$spec = $discovery->fetch('example.com');

// $spec is the full parsed ia.json array
echo $spec['version'];        // "1.0.0"
echo $spec['api']['base_url']; // "https://example.com/api/v1"

$client = IaJsonClient::discover('techstore.example.com');

// Get all endpoints
$all = $client->getEndpoints();

// Get only public endpoints
$public = $client->getEndpoints('public');

// Get protected endpoints ({
    $results = $client->call('search_products', ['q' => 'laptop']);
}

// Get rate limit info
$rateLimit = $client->getRateLimit(); // e.g., "1000/hour"

$client = IaJsonClient::discover('techstore.example.com');

// Step 1: Register your agent
$response = $client->register([
    'name' => 'My AI Assistant',
    'domain' => 'myai.example.com',
    'webhook_url' => 'https://myai.example.com/ia/verify',
    'contact' => '[email protected]',
    'description' => 'AI shopping assistant',
]);

// Step 2: Your webhook receives a verification_code from the site.
// Step 3: Submit the verification code:
$credentials = $client->verify('vc_abc123def456');

// The client now has credentials set automatically.
// You can also store and re-use them:
echo $credentials['api_key']; // "ia_live_..."
echo $credentials['secret'];  // "sec_..."

$client = IaJsonClient::discover('techstore.example.com');
$client->setCredentials('ia_live_abc123', 'sec_xyz789');

// Now you can call protected endpoints
$inventory = $client->call('get_inventory');

$client = IaJsonClient::discover('techstore.example.com');
$client->setCredentials('ia_live_abc123', 'sec_xyz789');

// Get the OAuth helper
$oauth = $client->getOAuth(
    clientId: 'your_client_id',
    clientSecret: 'your_client_secret',
);

// Step 1: Get the authorization URL for the user to visit
$result = $oauth->getAuthorizationUrl(
    redirectUri: 'https://myai.example.com/callback',
    scopes: ['cart:read', 'cart:write', 'orders:write'],
    state: 'random_csrf_token',
);

echo $result['url']; // Redirect user here
// If PKCE is 

use IaJson\Client\Auth\Signer;

// Sign a request
$signature = Signer::sign(
    secret: 'sec_xyz789',
    timestamp: time(),
    body: '{"product_id":"prod_123","quantity":2}',
    algorithm: 'sha256',
);

// Generate all auth headers at once
$headers = Signer::createSignedHeaders(
    apiKey: 'ia_live_abc123',
    secret: 'sec_xyz789',
    body: '{"product_id":"prod_123"}',
    algorithm: 'sha256',
    prefix: 'X-IA-',
);

// Result:
// [
//     'X-IA-Key' => 'ia_live_abc123',
//     'X-IA-Signature' => 'a1b2c3d4...',
//     'X-IA-Timestamp' => '1707753600',
// ]

// Verify an incoming signature (server-side)
$valid = Signer::verify(
    secret: 'sec_xyz789',
    providedSignature: $incomingSignature,
    timestamp: (int) $incomingTimestamp,
    body: $rawRequestBody,
    algorithm: 'sha256',
    maxAgeSeconds: 60,
);

use IaJson\Client\Exceptions\IaJsonException;
use IaJson\Client\Exceptions\AuthenticationException;
use IaJson\Client\Exceptions\RateLimitException;

try {
    $result = $client->call('get_inventory');
} catch (RateLimitException $e) {
    // HTTP 429 - retry after the suggested delay
    $retryAfter = $e->getRetryAfter(); // seconds, or null
    sleep($retryAfter ?? 60);
} catch (AuthenticationException $e) {
    // HTTP 401/403 - invalid key, expired signature, etc.
    echo $e->getErrorCode(); // e.g., "invalid_signature"
} catch (IaJsonException $e) {
    // Any other ia.json error
    echo $e->getMessage();
    echo $e->getErrorCode();
    print_r($e->getErrorDetails());
}

use IaJson\Client\Laravel\Facades\IaJson;

// Call endpoints
$products = IaJson::call('search_products', ['q' => 'laptop']);
$inventory = IaJson::call('get_inventory');

// Inspect the site
$site = IaJson::getSite();
$endpoints = IaJson::getEndpoints('public');
$capabilities = IaJson::getCapabilities();

use IaJson\Client\IaJsonClient;

class ProductController extends Controller
{
    public function search(Request $request, IaJsonClient $iajson)
    {
        $results = $iajson->call('search_products', [
            'q' => $request->input('query'),
        ]);

        return response()->json($results);
    }
}

// bootstrap/app.php (Laravel 11+)
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'iajson.verify' => \IaJson\Client\Laravel\Middleware\VerifyIaSignature::class,
    ]);
})

// app/Http/Kernel.php (Laravel 10)
protected $middlewareAliases = [
    // ...
    'iajson.verify' => \IaJson\Client\Laravel\Middleware\VerifyIaSignature::class,
];

Route::middleware('iajson.verify')->prefix('api/v1')->group(function () {
    Route::get('/inventory', [InventoryController::class, 'index']);
    Route::post('/orders', [OrderController::class, 'store']);
});

// Option A: Static key mapping
'verification' => [
    'keys' => [
        'ia_live_agent1_key' => 'sec_agent1_secret',
        'ia_live_agent2_key' => 'sec_agent2_secret',
    ],
],

// Option B: Custom resolver (e.g., from database)
'verification' => [
    'secret_resolver' => function (string $apiKey): ?string {
        $agent = \App\Models\AiAgent::where('api_key', $apiKey)->first();
        return $agent?->secret;
    },
],

public function index(Request $request)
{
    $apiKey = $request->attributes->get('iajson_api_key');
    // Use $apiKey to identify which agent is making the request
}
bash
php artisan vendor:publish --tag=iajson-config