Skip to Content
TryItOn
DocsAPI ReferenceSDKsResources

Virtual Try-On SDK for PHP

Reference for the tryiton/tryiton Composer package: client options, every method, wait helpers, TryItOnException handling, live sessions and transport stubs.

The tryiton/tryiton Composer package is the official PHP client for the virtual try-on API. It wraps every server endpoint of https://tryiton.now/api/v1, throws one exception class, and polls jobs for you. New to the API? Run your first try-on with the Quickstart.

composer require tryiton/tryiton

It needs PHP 7.4 or later with the curl and json extensions. Classes live in the TryItOn namespace and load through Composer's autoloader.

Configure the client

Retry GET requests only

A retried POST /tryon/* can create a second job and hold credits twice. The client below retries GET requests on 502, 503 and 504, and leaves every POST alone.

new Client($apiKey, $baseUrl, $timeout, $transport) takes positional arguments; only the key is required. A transport is any class that implements TryItOn\HttpTransport: it sends one request and returns the status and raw body.

client.php
<?php
require __DIR__ . '/vendor/autoload.php';

use TryItOn\Client;
use TryItOn\CurlTransport;
use TryItOn\HttpTransport;

// Retry GETs (status, credits, sessions) on gateway errors. Never retry a POST:
// a retried submit can create a second job.
final class RetryGetsTransport implements HttpTransport
{
    private HttpTransport $inner;

    public function __construct(HttpTransport $inner)
    {
        $this->inner = $inner;
    }

    public function send(string $method, string $url, array $headers, ?string $body): array
    {
        for ($attempt = 1; ; $attempt++) {
            $response = $this->inner->send($method, $url, $headers, $body);
            $isRetryable = $method === 'GET' && in_array($response['status'], [502, 503, 504], true);
            if (!$isRetryable || $attempt === 3) {
                return $response;
            }
            sleep($attempt);
        }
    }
}

$client = new Client(
    getenv('TRYITON_API_KEY'),
    'https://tryiton.now/api/v1',
    60,
    new RetryGetsTransport(new CurlTransport(30))
);

print_r($client->getCredits());
ArgumentTypeDefaultDescription
$apiKeystringrequiredYour API key. An empty key throws TryItOnException with errorName ConfigError.
$baseUrlstringhttps://tryiton.now/api/v1API base URL. A trailing slash is removed.
$timeoutint60Timeout for each request, in seconds, for the default cURL transport. Ignored when you pass $transport.
$transport?TryItOn\HttpTransportCurlTransportYour own transport for retries, logging, a proxy, a PSR-18 client or a test stub. send() returns ['status' => int, 'body' => string].

Methods

Parameters are one array with the API's snake_case keys; null values are left out, so the API defaults apply. The live methods also accept camelCase keys (garmentId, endUserId). Responses are plain arrays, with the API's camelCase keys for the live methods.

MethodEndpointReturns
tryOnFashion(array $params)POST /tryon/fashionjob id (string)
tryOnHairstyle(array $params)POST /tryon/hairstylejob id (string)
tryOnTattoo(array $params)POST /tryon/tattoojob id (string)
getStatus(string $jobId)GET /status/{id}['status', 'output', 'error']
waitForResult($jobId, $pollInterval, $timeout)polls GET /status/{id}result URLs (list<string>)
getCredits()GET /creditscredit balance array
getLiveConfig()GET /live/configconfig array
prepareLiveGarment(array $params)POST /live/garmentsgarment array
prepareLiveOutfit(array $params)POST /live/outfitsgarment array
startLiveSession(array $params = [])POST /live/sessionsfull response array
listLiveSessions(array $params = [])GET /live/sessions['sessions', 'nextCursor']
getLiveSession(string $sessionId)GET /live/sessions/{id}session array
stopLiveSession(string $sessionId)POST /live/sessions/{id}/stopsession array

Client::HAIRCUTS lists the 42 accepted haircut values, and Client::VERSION is the SDK version. Response shapes are declared as PHPStan types on Client. Images are public URLs or base64 data URLs. The snippets below reuse the $client from above.

$fashionJobId = $client->tryOnFashion([
    'model_image' => 'https://example.com/model.jpg',
    'garment_image' => 'https://example.com/tshirt.jpg',
    'category' => 'clothing',
    'subcategory' => 'tops',
]);

$hairJobId = $client->tryOnHairstyle([
    'face_image' => 'https://example.com/face.jpg',
    'haircut' => 'PixieCut',
    'hair_color' => 'copper red',
]);

$tattooJobId = $client->tryOnTattoo([
    'body_image' => 'https://example.com/forearm.jpg',
    'design_image' => 'https://example.com/rose.png',
    'region' => ['x' => 0.32, 'y' => 0.18, 'w' => 0.28, 'h' => 0.34],
]);

Wait for results

waitForResult(string $jobId, float $pollInterval = 2.0, float $timeout = 120.0) polls every 2 seconds and gives up after 120 seconds. It returns the result URLs, or throws ProcessingError (the job failed) or Timeout. Every job has a final status within 4 minutes, so a 4-minute wait never gives up early. Check max_execution_time too when you wait inside a web request.

$urls = $client->waitForResult($fashionJobId, 2.0, 240.0);

Timeout only stops the wait. The job keeps running, so poll it later instead of resubmitting. To check a stored job id from a cron job or queue worker, call getStatus yourself:

$job = $client->getStatus($fashionJobId);
if ($job['status'] === 'completed') {
    print_r($job['output']);
} elseif ($job['status'] === 'failed') {
    echo 'Failed: ', $job['error'], PHP_EOL;
}

output is an empty array until the job completes, and error is the failure reason as a string, or null. See Jobs, Polling & Retries for job lifetimes.

Errors

Every API error and failed job throws TryItOn\TryItOnException. Branch on errorName, not on the message.

PropertyTypeDescription
$e->status?intHTTP status. null for errors raised by the SDK.
$e->errorName?stringThe API error name, such as OutOfCredits, or an SDK name below. null for a non-JSON error page.
$e->getMessage()stringHuman-readable text. For ProcessingError, the job's failure reason.
use TryItOn\TryItOnException;

try {
    $urls = $client->waitForResult($fashionJobId, 2.0, 240.0);
    echo $urls[0], PHP_EOL;
} catch (TryItOnException $e) {
    if ($e->errorName === 'ProcessingError') {
        echo 'Failed, not charged: ', $e->getMessage(), PHP_EOL;
    } elseif ($e->errorName === 'Timeout') {
        echo 'Still running. Poll it later.', PHP_EOL;
    } else {
        echo "{$e->status} {$e->errorName}: {$e->getMessage()}", PHP_EOL;
    }
}

The SDK adds these names, all with status null: ProcessingError, Timeout (the wait gave up), NetworkError (no response, including a cURL timeout, or any exception your transport throws), ConfigError, InvalidRequest (the body can't be encoded as JSON) and InvalidResponse (a success response without the expected field). RateLimitExceeded, ConcurrencyLimitExceeded, 500 and 503 are worth retrying with backoff. OutOfCredits, 400, 403, 404 and 413 are not. See when to retry and the full list of error codes.

Verify webhooks

Webhook::verify (SDK 2.5 or later) checks that a webhook request came from TryItOn and returns the event. Pass the raw body exactly as it arrived.

use TryItOn\TryItOnException;
use TryItOn\Webhook;

try {
    $event = Webhook::verify(file_get_contents('php://input'), $_SERVER, getenv('TRYITON_WEBHOOK_SECRET'));
} catch (TryItOnException $e) {
    http_response_code(400);
    exit;
}

http_response_code(200);
if ($event['type'] === 'tryon.completed') {
    error_log($event['data']['jobId']);
}

Webhook::verify($payload, $headers, $secret, $toleranceSeconds = 300, $now = null) returns the event as an array. Headers can be $_SERVER, getallheaders() or a PSR-7 request's getHeaders(). It throws TryItOnException with errorName "WebhookVerificationFailed" and a null status.

Live try-on from your server

Your server prepares garments and starts sessions with the API key. The shopper's browser streams with the tryiton-live package and never sees the key. Prepare each garment once, for example at catalog sync, and store its id:

$garment = $client->prepareLiveGarment([
    'garment_image' => 'https://example.com/tshirt.jpg',
    'category' => 'clothing',
    'subcategory' => 'tops',
]);

Then start a session per shopper and send the response to the browser unchanged:

live-session.php
<?php
require __DIR__ . '/vendor/autoload.php';

use TryItOn\Client;
use TryItOn\TryItOnException;

$client = new Client(getenv('TRYITON_API_KEY'));

// The browser POSTs {"garmentId": "..."} and passes the response to connectLiveTryOn.
$body = json_decode(file_get_contents('php://input'), true) ?: [];
header('Content-Type: application/json');

try {
    $start = $client->startLiveSession([
        'garment_id' => $body['garmentId'] ?? null,
        'end_user_id' => 'shopper-42', // your signed-in shopper's id, from your session
        'allowed_origin' => 'https://shop.example.com',
    ]);
    echo json_encode($start); // unchanged
} catch (TryItOnException $e) {
    http_response_code($e->status ?? 502);
    echo json_encode(['ok' => false, 'error' => ['name' => $e->errorName, 'message' => $e->getMessage()]]);
}

end_user_id gives each shopper one stream: starting again ends the previous one. allowed_origin locks the media token to your site. Sessions start on the primary stream and switch to the backup stream if it fails to connect. prepareLiveOutfit(['garment_ids' => [...]]) combines 2 or 3 prepared garments, and its id works like a garment id. The browser side is in the Real-Time Virtual Try-On Quickstart, and billing in Live Try-On Billing.

Testing

Pass a stub transport to test your code without network calls or credits:

tests/TryOnTest.php
<?php
use PHPUnit\Framework\TestCase;
use TryItOn\Client;
use TryItOn\HttpTransport;

final class StubTransport implements HttpTransport
{
    public array $requests = [];

    public function send(string $method, string $url, array $headers, ?string $body): array
    {
        $this->requests[] = ['method' => $method, 'url' => $url, 'body' => json_decode((string) $body, true)];
        return ['status' => 201, 'body' => '{"ok":true,"jobId":"job_123"}'];
    }
}

final class TryOnTest extends TestCase
{
    public function testTryOnFashion(): void
    {
        $transport = new StubTransport();
        $client = new Client('YOUR_API_KEY', 'https://tryiton.now/api/v1', 60, $transport);

        $jobId = $client->tryOnFashion([
            'model_image' => 'https://example.com/model.jpg',
            'garment_image' => 'https://example.com/tshirt.jpg',
        ]);

        $this->assertSame('job_123', $jobId);
        $this->assertSame('https://tryiton.now/api/v1/tryon/fashion', $transport->requests[0]['url']);
    }
}

Return {"ok":false,"error":{"name":"...","message":"..."}} with a 4xx status to test your error handling.

On this page