### Install CloudConvert PHP SDK with Composer Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Install the SDK and Guzzle for HTTP requests using Composer. Ensure PSR-7, PSR-17, and PSR-18 compatibility by installing appropriate HTTP client and factory implementations. ```bash composer require cloudconvert/cloudconvert-php guzzlehttp/guzzle ``` -------------------------------- ### Download Output Files using CloudConvert PHP SDK Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt This method downloads a file from a CloudConvert export URL, returning a PSR-7 `StreamInterface`. Use `detach()` to get a raw PHP resource for stream copying. Ensure the 'downloads' directory exists. ```php use Psr\Http\Message\StreamInterface; $job = $cloudconvert->jobs()->wait($job); foreach ($job->getExportUrls() as $file) { // $file->url — direct download URL // $file->filename — suggested filename $stream = $cloudconvert->getHttpTransport()->download($file->url); $resource = $stream->detach(); // Convert PSR-7 stream to PHP resource $output = fopen('downloads/' . $file->filename, 'w'); stream_copy_to_stream($resource, $output); fclose($output); echo 'Saved: downloads/' . $file->filename . PHP_EOL; } ``` -------------------------------- ### Get Authenticated User Info with CloudConvert PHP SDK Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Retrieves the account details for the currently authenticated API key. Ensure you have initialized the CloudConvert client with a valid API key. ```php $user = $cloudconvert->users()->me(); echo 'User ID: ' . $user->getId() . PHP_EOL; // 12345 echo 'Username: ' . $user->getUsername() . PHP_EOL; // "johndoe" echo 'Email: ' . $user->getEmail() . PHP_EOL; // "john@example.com" echo 'Credits: ' . $user->getCredits() . PHP_EOL; // 5000 echo 'Member since: ' . $user->getCreatedAt()->format('Y-m-d') . PHP_EOL; ``` -------------------------------- ### Get Authenticated User Info Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Retrieves the account details for the currently authenticated API key, including username, email, and remaining credits. ```APIDOC ## `$cloudconvert->users()->me(): User` — Get Authenticated User Info ### Description Retrieves the account details for the currently authenticated API key, including username, email, and remaining credits. ### Method ```php $user = $cloudconvert->users()->me(); ``` ### Response #### Success Response Returns a `User` object with the following properties: - `id` (string): The user's unique identifier. - `username` (string): The user's username. - `email` (string): The user's email address. - `credits` (integer): The number of remaining credits. - `createdAt` (DateTimeImmutable): The date and time the user account was created. ### Request Example ```php $user = $cloudconvert->users()->me(); echo 'User ID: ' . $user->getId() . PHP_EOL; // 12345 echo 'Username: ' . $user->getUsername() . PHP_EOL; // "johndoe" echo 'Email: ' . $user->getEmail() . PHP_EOL; // "john@example.com" echo 'Credits: ' . $user->getCredits() . PHP_EOL; // 5000 echo 'Member since: ' . $user->getCreatedAt()->format('Y-m-d') . PHP_EOL; ``` ``` -------------------------------- ### $cloudconvert->tasks()->get(string $id): Task Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Retrieves a single task's current state by its unique identifier (UUID). ```APIDOC ## `$cloudconvert->tasks()->get(string $id): Task` — Retrieve a Task by ID Fetches a single task's current state by its UUID. ```php $task = $cloudconvert->tasks()->get('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'); echo $task->getOperation(); // e.g. "convert" echo $task->getStatus(); // "waiting" | "processing" | "finished" | "error" echo $task->getJobId(); // parent job UUID ``` ``` -------------------------------- ### `$cloudconvert->jobs()->get(string $id): Job` — Retrieve a Job by ID Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Fetches the current state of a job from the API using its UUID. Useful for polling job status asynchronously without blocking. ```APIDOC ## `get(string $id): Job` — Retrieve a Job by ID Fetches the current state of a job from the API using its UUID. Useful for polling job status asynchronously without blocking. ### Parameters #### Path Parameters - **id** (string) - Required - The UUID of the job to retrieve. ### Response #### Success Response (Job) - **Job** (Job) - The job object with its current state. ### Request Example ```php $jobId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; $job = $cloudconvert->jobs()->get($jobId); echo $job->getStatus(); // "waiting" | "processing" | "finished" | "error" echo $job->getCreatedAt()->format('Y-m-d H:i:s'); // Inspect individual tasks foreach ($job->getTasks() as $task) { echo $task->getName() . ': ' . $task->getStatus(); } ``` ``` -------------------------------- ### Initialize the SDK Client Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Creates the main SDK entry point. Accepts `api_key` (required), `sandbox` (bool, default `false`), `region` (string, optional), and `http_client` (PSR-18 `ClientInterface`, optional). Returns a `CloudConvert` instance that exposes all resource accessors. ```APIDOC ## `new CloudConvert(array $options)` — Initialize the SDK Client Creates the main SDK entry point. Accepts `api_key` (required), `sandbox` (bool, default `false`), `region` (string, optional), and `http_client` (PSR-18 `ClientInterface`, optional). Returns a `CloudConvert` instance that exposes all resource accessors. ### Request Example ```php use CloudConvert\CloudConvert; // Production client $cloudconvert = new CloudConvert([ 'api_key' => 'your-api-key-here', 'sandbox' => false, ]); // Sandbox client for testing $sandboxClient = new CloudConvert([ 'api_key' => 'your-sandbox-api-key', 'sandbox' => true, ]); // Client pinned to a specific region $regionalClient = new CloudConvert([ 'api_key' => 'your-api-key-here', 'sandbox' => false, 'region' => 'us-east', // Routes to us-east.api.cloudconvert.com ]); // Client with a custom PSR-18 HTTP client $customHttpClient = new \GuzzleHttp\Client(); $clientWithCustomHttp = new CloudConvert([ 'api_key' => 'your-api-key-here', 'http_client' => $customHttpClient, ]); ``` ``` -------------------------------- ### Task Model - Fluent Parameter Setting Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Illustrates how to use the fluent `set` method for building tasks. ```APIDOC ## `Task` Model — Fluent Parameter Setting ```php // Fluent parameter setting (for building tasks) $task = (new Task('convert', 'my-task')) ->set('input', 'import-task-name') ->set('output_format', 'png') ->set('width', 800); ``` ``` -------------------------------- ### Initialize CloudConvert SDK Client Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Create an instance of the CloudConvert client. You can configure it for production or sandbox environments, specify a region, or provide a custom HTTP client. ```php use CloudConvert\CloudConvert; // Production client $cloudconvert = new CloudConvert([ 'api_key' => 'your-api-key-here', 'sandbox' => false, ]); // Sandbox client for testing $sandboxClient = new CloudConvert([ 'api_key' => 'your-sandbox-api-key', 'sandbox' => true, ]); // Client pinned to a specific region $regionalClient = new CloudConvert([ 'api_key' => 'your-api-key-here', 'sandbox' => false, 'region' => 'us-east', // Routes to us-east.api.cloudconvert.com ]); // Client with a custom PSR-18 HTTP client $customHttpClient = new \GuzzleHttp\Client(); $clientWithCustomHttp = new CloudConvert([ 'api_key' => 'your-api-key-here', 'http_client' => $customHttpClient, ]); ``` -------------------------------- ### Create a CloudConvert Job with URL Import Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Demonstrates creating a job with multiple tasks: importing a file from a URL, converting it to PDF, and exporting it via a URL. Requires API key and sandbox configuration. ```php use \CloudConvert\CloudConvert; use \CloudConvert\Models\Job; use \CloudConvert\Models\Task; $cloudconvert = new CloudConvert([ 'api_key' => 'API_KEY', 'sandbox' => false ]); $job = (new Job()) ->setTag('myjob-1') ->addTask( (new Task('import/url', 'import-my-file')) ->set('url','https://my-url') ) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'import-my-file') ->set('output_format', 'pdf') ->set('some_other_option', 'value') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ); $cloudconvert->jobs()->create($job) ``` -------------------------------- ### Create a CloudConvert Job with File Upload Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Sets up a job to upload a local file, convert it to PDF, and export it as a URL. The upload task uses a local file path. ```php use \CloudConvert\Models\Job; use \CloudConvert\Models\Task; $job = (new Job()) ->addTask(new Task('import/upload','upload-my-file')) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'upload-my-file') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ); $job = $cloudconvert->jobs()->create($job); $uploadTask = $job->getTasks()->whereName('upload-my-file')[0]; $cloudconvert->tasks()->upload($uploadTask, fopen('./file.pdf', 'r'), 'file.pdf'); ``` -------------------------------- ### `$cloudconvert->webhookHandler()->constructEventFromRequest(...)` Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Alternative to `constructEvent()` for frameworks that provide a PSR-7 `RequestInterface` (e.g., Slim, Laravel with a PSR-7 bridge). ```APIDOC ## `$cloudconvert->webhookHandler()->constructEventFromRequest(RequestInterface $request, string $signingSecret): WebhookEvent` — Parse Webhook from PSR-7 Request Alternative to `constructEvent()` for frameworks that provide a PSR-7 `RequestInterface` (e.g., Slim, Laravel with a PSR-7 bridge). ```php // In a PSR-7 compatible framework (e.g., Slim) $app->post('/webhooks/cloudconvert', function (Request $request, Response $response) use ($cloudconvert) { $signingSecret = 'your-webhook-signing-secret'; try { $webhookEvent = $cloudconvert->webhookHandler()->constructEventFromRequest($request, $signingSecret); } catch (\CloudConvert\Exceptions\SignatureVerificationException $e) { return $response->withStatus(400); } $job = $webhookEvent->getJob(); // ... process event return $response->withStatus(200); }); ``` ``` -------------------------------- ### Job Model - Status Constants and Key Methods Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Details on the Job model, including status constants and key methods for accessing job properties. ```APIDOC ## `Job` Model — Status Constants and Key Methods ### Description The `Job` model exposes status constants and accessors for all job lifecycle properties. ### Status Constants - `Job::STATUS_WATING` - `Job::STATUS_PROCESSING` - `Job::STATUS_FINISHED` - `Job::STATUS_ERROR` ### Key Methods - `getId()`: Returns the job ID (string UUID). - `getTag()`: Returns the custom correlation tag (string|null). - `getWebhookUrl()`: Returns the webhook URL (string|null). - `getStatus()`: Returns the current job status (one of the `STATUS_*` constants). - `getCreatedAt()`: Returns the creation timestamp (`DateTimeImmutable`). - `getStartedAt()`: Returns the start timestamp (`DateTimeImmutable|null`). - `getEndedAt()`: Returns the end timestamp (`DateTimeImmutable|null`). - `getTasks()`: Returns the tasks associated with the job (`TaskCollection`). - `getLinks()`: Returns the API hypermedia links (`object|null`). - `getExportUrls()`: Returns a collection of export file URLs and filenames for finished export/url tasks. ### Request Example ```php use CloudConvert\Models\Job; // Status constants Job::STATUS_WATING; // "waiting" Job::STATUS_PROCESSING; // "processing" Job::STATUS_FINISHED; // "finished" Job::STATUS_ERROR; // "error" // After create() or wait(): $job->getId(); // string UUID $job->getTag(); // string|null — your custom correlation tag $job->getWebhookUrl(); // string|null $job->getStatus(); // one of the STATUS_* constants above $job->getCreatedAt(); // \DateTimeImmutable $job->getStartedAt(); // \DateTimeImmutable|null $job->getEndedAt(); // \DateTimeImmutable|null $job->getTasks(); // TaskCollection $job->getLinks(); // object|null (API hypermedia links) // Convenience: collect all output files from finished export/url tasks $files = $job->getExportUrls(); foreach ($files as $file) { echo $file->url . ' — ' . $file->filename . PHP_EOL; } ``` ``` -------------------------------- ### Task Model - Status Constants and Accessors Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Demonstrates the usage of status constants and accessor methods for the Task model. ```APIDOC ## `Task` Model — Status Constants and Key Methods The `Task` model exposes status constants and accessors for individual task properties, results, and error details. ```php use CloudConvert\Models\Task; // Status constants Task::STATUS_WATING; // "waiting" Task::STATUS_PROCESSING; // "processing" Task::STATUS_FINISHED; // "finished" Task::STATUS_ERROR; // "error" // Accessors $task->getId(); // string UUID $task->getName(); // string — your label, e.g. "convert-my-file" $task->getOperation(); // string — e.g. "convert", "import/url", "export/url" $task->getStatus(); // one of the STATUS_* constants $task->getMessage(); // string|null — human-readable status or error message $task->getCode(); // string|null — machine-readable error code $task->getResult(); // stdObject|null — output data (files array, form data, etc.) $task->getPayload(); // mixed — the task parameters submitted $task->getJobId(); // string|null — parent job UUID $task->getCreatedAt(); // \DateTimeImmutable|null $task->getStartedAt(); // \DateTimeImmutable|null $task->getEndedAt(); // \DateTimeImmutable|null $task->getDependsOnTasks(); // TaskCollection|null ``` ``` -------------------------------- ### Download Output Files from CloudConvert Job Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Waits for a job to complete and then downloads the exported files using the generated URLs. The downloaded content is streamed to local files. ```php $cloudconvert->jobs()->wait($job); // Wait for job completion foreach ($job->getExportUrls() as $file) { $source = $cloudconvert->getHttpTransport()->download($file->url)->detach(); $dest = fopen('output/' . $file->filename, 'w'); stream_copy_to_stream($source, $dest); } ``` -------------------------------- ### Create a Standalone Task with CloudConvert PHP SDK Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Use this to create a single conversion task independently. The task will be initialized with a 'waiting' status. Ensure you have the necessary import task ID. ```php use CloudConvert\Models\Task; $task = (new Task('convert', 'my-conversion')) ->set('input', 'some-import-task-id') ->set('output_format', 'png') ->set('width', 1920) ->set('height', 1080); $task = $cloudconvert->tasks()->create($task); echo 'Task ID: ' . $task->getId(); echo 'Status: ' . $task->getStatus(); // "waiting" ``` -------------------------------- ### `$cloudconvert->signedUrlBuilder()->createFromJob(...)` Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Creates a signed URL that encodes an entire Job definition as a URL query parameter. Anyone with the URL can trigger the conversion by visiting it (subject to your CloudConvert signed URL configuration). Uses HMAC-SHA256. ```APIDOC ## `$cloudconvert->signedUrlBuilder()->createFromJob(...)` — Generate a Signed Conversion URL Creates a signed URL that encodes an entire Job definition as a URL query parameter. Anyone with the URL can trigger the conversion by visiting it (subject to your CloudConvert signed URL configuration). Uses HMAC-SHA256. The base URL and signing secret are obtained from the [CloudConvert Dashboard](https://cloudconvert.com/dashboard/api/v2/signed-urls). ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; $job = (new Job()) ->addTask( (new Task('import/url', 'import-my-file')) ->set('url', '{{sourceUrl}}') // Placeholder replaced at runtime ) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'import-my-file') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ->set('inline', true) // Serve inline for preview ); $signedUrlBase = 'https://v.cloudconvert.com/v2/convert'; // From your dashboard $signingSecret = 'your-signed-url-secret'; // From your dashboard $cacheKey = 'doc-' . md5('https://example.com/document.docx'); // Optional cache key $url = $cloudconvert->signedUrlBuilder()->createFromJob( $signedUrlBase, $signingSecret, $job, $cacheKey ); // $url = "https://v.cloudconvert.com/v2/convert?job=eyJ...&cache_key=doc-abc123&s=hmac-sha256-signature" echo 'Signed URL: ' . $url; ``` ``` -------------------------------- ### Exception Handling Reference Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Reference for handling typed exceptions thrown by the SDK for various error conditions. ```APIDOC ## Exception Handling Reference ### Description The SDK throws typed exceptions from `CloudConvert\Exceptions\` for all error conditions. This section details how to catch and handle these exceptions. ### Exception Types - `HttpClientException`: For 4xx errors (bad request, unauthorized, payment required, not found, unprocessable). - `HttpServerException`: For 5xx errors or network failures. - `SignatureVerificationException`: For webhook signature mismatches. - `UnexpectedDataException`: For malformed JSON payloads in webhooks. ### Request Example ```php use CloudConvert\Exceptions\HttpClientException; use CloudConvert\Exceptions\HttpServerException; use CloudConvert\Exceptions\SignatureVerificationException; use CloudConvert\Exceptions\UnexpectedDataException; try { $job = $cloudconvert->jobs()->create($job); $job = $cloudconvert->jobs()->wait($job); } catch (HttpClientException $e) { // 4xx errors: bad request, unauthorized, payment required, not found, unprocessable $code = $e->getResponseCode(); // HTTP status (400, 401, 402, 403, 404, 422) $message = $e->getMessage(); // Human-readable message (may be from API body) $errorCode = $e->getErrorCode(); // Machine-readable code from API (nullable) $body = $e->getResponseBody(); // Raw decoded response array $response = $e->getResponse(); // PSR-7 ResponseInterface if ($code === 402) { echo 'Out of credits. Please top up your CloudConvert account.'; } elseif ($code === 422) { echo 'Validation error: ' . $message; // $body['errors'] contains field-level validation messages } } catch (HttpServerException $e) { // 5xx errors or network failures echo 'CloudConvert server error: ' . $e->getMessage(); } catch (SignatureVerificationException $e) { // Webhook signature mismatch echo 'Invalid webhook signature.'; } catch (UnexpectedDataException $e) { // Malformed JSON payload in webhook echo 'Bad webhook payload.'; } ``` ``` -------------------------------- ### Generate Signed Conversion URL with PHP Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Creates a signed URL that encodes an entire Job definition. This allows anyone with the URL to trigger the conversion. Uses HMAC-SHA256 for security. ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; $job = (new Job()) ->addTask( (new Task('import/url', 'import-my-file')) ->set('url', '{{sourceUrl}}') // Placeholder replaced at runtime ) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'import-my-file') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ->set('inline', true) // Serve inline for preview ); $signedUrlBase = 'https://v.cloudconvert.com/v2/convert'; // From your dashboard $signingSecret = 'your-signed-url-secret'; // From your dashboard $cacheKey = 'doc-' . md5('https://example.com/document.docx'); // Optional cache key $url = $cloudconvert->signedUrlBuilder()->createFromJob( $signedUrlBase, $signingSecret, $job, $cacheKey ); // $url = "https://v.cloudconvert.com/v2/convert?job=eyJ...&cache_key=doc-abc123&s=hmac-sha256-signature" echo 'Signed URL: ' . $url; ``` -------------------------------- ### Render HTML Form for Direct Client-Side Upload Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Use this to allow end-users to upload files directly to CloudConvert's storage. This avoids passing files through your server. Ensure the 'upload-my-file' task name matches your job configuration. ```php use CloudConvert\Models\Task; // In your controller, create the job and pass the upload task to the view $job = $cloudconvert->jobs()->create($job); $uploadTask = $job->getTasks()->whereName('upload-my-file')[0]; ``` ```html
getResult()->form->parameters as $parameter => $value): ?>
``` -------------------------------- ### Create a File Conversion Job Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Submit a new conversion job to the CloudConvert API. Define a sequence of tasks, including importing a file from a URL, converting it to a specific format, and exporting the result. ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; use CloudConvert\Exceptions\HttpClientException; use CloudConvert\Exceptions\HttpServerException; $job = (new Job()) ->setTag('order-1234') // Optional tag for correlation ->setWebhookUrl('https://myapp.com/webhooks/cloudconvert') // Optional webhook ->addTask( (new Task('import/url', 'import-my-file')) ->set('url', 'https://example.com/document.docx') ->set('filename', 'document.docx') ) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'import-my-file') ->set('output_format', 'pdf') ->set('engine', 'libreoffice') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ->set('inline', false) ->set('archive_multiple_files', false) ); try { $job = $cloudconvert->jobs()->create($job); echo 'Job created: ' . $job->getId(); // "job-uuid-here" echo 'Status: ' . $job->getStatus(); // "waiting" or "processing" echo 'Tag: ' . $job->getTag(); // "order-1234" } catch (HttpClientException $e) { echo 'Client error ' . $e->getResponseCode() . ': ' . $e->getMessage(); // $e->getErrorCode() for machine-readable code // $e->getResponseBody() for raw response array } catch (HttpServerException $e) { echo 'Server error: ' . $e->getMessage(); } ``` -------------------------------- ### List All Jobs Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Returns a JobCollection (iterable) of all jobs in the account. Supports query filters. ```php // List all finished jobs tagged 'order-1234' $jobs = $cloudconvert->jobs()->all([ 'filter[tag]' => 'order-1234', 'filter[status]' => 'finished', 'per_page' => 25, ]); foreach ($jobs as $job) { echo $job->getId() . ' — ' . $job->getTag() . ' — ' . $job->getStatus() . PHP_EOL; } ``` -------------------------------- ### List All Tasks with Filtering using CloudConvert PHP SDK Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Retrieves a collection of tasks, with options to filter by job ID, status, or operation type. This is useful for monitoring and managing multiple tasks. ```php use CloudConvert\Models\Task; $tasks = $cloudconvert->tasks()->all([ 'filter[job_id]' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'filter[status]' => Task::STATUS_FINISHED, 'filter[operation]' => 'convert', ]); foreach ($tasks as $task) { echo $task->getName() . ': ' . $task->getStatus() . PHP_EOL; } ``` -------------------------------- ### `$cloudconvert->webhookHandler()->constructEvent(...)` Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Verifies the `CloudConvert-Signature` header against the raw request payload using your signing secret, then deserializes the payload into a `WebhookEvent` model. Throws `SignatureVerificationException` if the signature is invalid or `UnexpectedDataException` if the payload is malformed. ```APIDOC ## `$cloudconvert->webhookHandler()->constructEvent(...)` — Verify and Parse Webhook Events Verifies the `CloudConvert-Signature` HMAC-SHA256 header against the raw request payload using your signing secret, then deserializes the payload into a `WebhookEvent` model. Throws `SignatureVerificationException` if the signature is invalid or `UnexpectedDataException` if the payload is malformed. ```php use CloudConvert\Exceptions\SignatureVerificationException; use CloudConvert\Exceptions\UnexpectedDataException; use CloudConvert\Models\Task; use CloudConvert\Models\WebhookEvent; // webhook.php — your webhook endpoint $cloudconvert = new \CloudConvert\CloudConvert(['api_key' => 'YOUR_API_KEY']); $signingSecret = 'your-webhook-signing-secret'; // From CloudConvert Dashboard $payload = file_get_contents('php://input'); $signature = $_SERVER['HTTP_CLOUDCONVERT_SIGNATURE'] ?? ''; try { $webhookEvent = $cloudconvert->webhookHandler()->constructEvent( $payload, $signature, $signingSecret ); } catch (UnexpectedDataException $e) { http_response_code(400); exit('Invalid payload'); } catch (SignatureVerificationException $e) { http_response_code(400); exit('Invalid signature'); } // Handle events switch ($webhookEvent->getEvent()) { case WebhookEvent::EVENT_JOB_FINISHED: $job = $webhookEvent->getJob(); echo 'Job ' . $job->getId() . ' finished. Tag: ' . $job->getTag(); // Access completed export tasks $exportTask = $job->getTasks() ->whereStatus(Task::STATUS_FINISHED) ->whereOperation('export/url')[0] ?? null; if ($exportTask) { foreach ($exportTask->getResult()->files ?? [] as $file) { // Queue download, store URL, etc. echo 'Output: ' . $file->url; } } break; case WebhookEvent::EVENT_JOB_FAILED: $job = $webhookEvent->getJob(); echo 'Job ' . $job->getId() . ' failed.'; $errorTask = $job->getTasks()->whereStatus(Task::STATUS_ERROR)[0] ?? null; if ($errorTask) { echo 'Error: ' . $errorTask->getMessage() . ' (code: ' . $errorTask->getCode() . ')'; } break; } http_response_code(200); ``` ``` -------------------------------- ### $cloudconvert->tasks()->all(array $query): TaskCollection Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Returns a `TaskCollection` of tasks, with optional filtering capabilities based on provided query parameters. ```APIDOC ## `$cloudconvert->tasks()->all(array $query): TaskCollection` — List All Tasks Returns a `TaskCollection` of tasks, optionally filtered. ```php use CloudConvert\Models\Task; $tasks = $cloudconvert->tasks()->all([ 'filter[job_id]' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'filter[status]' => Task::STATUS_FINISHED, 'filter[operation]' => 'convert', ]); foreach ($tasks as $task) { echo $task->getName() . ': ' . $task->getStatus() . PHP_EOL; } ``` ``` -------------------------------- ### Construct Webhook Event from PSR-7 Request Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Constructs a WebhookEvent object from a PSR-7 RequestInterface. Ensure you have the correct signing secret configured. ```php $webhookEvent = $cloudconvert->webhookHandler()->constructEventFromRequest($request, $signingSecret); ``` -------------------------------- ### Create a Conversion Job Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Submits a new Job to the CloudConvert API. The Job is composed of one or more `Task` objects chained by their names. Returns a hydrated `Job` model with the assigned `id`, `status`, and fully populated `tasks`. ```APIDOC ## `$cloudconvert->jobs()->create(Job $job): Job` — Create a Conversion Job Submits a new Job to the CloudConvert API. The Job is composed of one or more `Task` objects chained by their names. Returns a hydrated `Job` model with the assigned `id`, `status`, and fully populated `tasks`. ### Request Example ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; use CloudConvert\Exceptions\HttpClientException; use CloudConvert\Exceptions\HttpServerException; $job = (new Job()) ->setTag('order-1234') // Optional tag for correlation ->setWebhookUrl('https://myapp.com/webhooks/cloudconvert') // Optional webhook ->addTask( (new Task('import/url', 'import-my-file')) ->set('url', 'https://example.com/document.docx') ->set('filename', 'document.docx') ) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'import-my-file') ->set('output_format', 'pdf') ->set('engine', 'libreoffice') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ->set('inline', false) ->set('archive_multiple_files', false) ); try { $job = $cloudconvert->jobs()->create($job); echo 'Job created: ' . $job->getId(); // "job-uuid-here" echo 'Status: ' . $job->getStatus(); // "waiting" or "processing" echo 'Tag: ' . $job->getTag(); // "order-1234" } catch (HttpClientException $e) { echo 'Client error ' . $e->getResponseCode() . ': ' . $e->getMessage(); // $e->getErrorCode() for machine-readable code // $e->getResponseBody() for raw response array } catch (HttpServerException $e) { echo 'Server error: ' . $e->getMessage(); } ``` ``` -------------------------------- ### Handle CloudConvert Webhook Events Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Constructs a webhook event object from incoming payload and signature, verifying its authenticity against a signing secret. Catches invalid payload exceptions. ```php $cloudconvert = new CloudConvert([ 'api_key' => 'API_KEY', 'sandbox' => false ]); $signingSecret = '...'; // You can find it in your webhook settings $payload = @file_get_contents('php://input'); $signature = $_SERVER['HTTP_CLOUDCONVERT_SIGNATURE']; try { $webhookEvent = $cloudconvert->webhookHandler()->constructEvent($payload, $signature, $signingSecret); } catch(\\ ``` -------------------------------- ### Exception Handling with CloudConvert PHP SDK Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Handles various exceptions thrown by the CloudConvert SDK, including HTTP client errors (4xx), server errors (5xx), and specific issues like signature verification or unexpected data. Import the necessary exception classes from `CloudConvert\Exceptions\`. ```php use CloudConvert\Exceptions\HttpClientException; use CloudConvert\Exceptions\HttpServerException; use CloudConvert\Exceptions\SignatureVerificationException; use CloudConvert\Exceptions\UnexpectedDataException; try { $job = $cloudconvert->jobs()->create($job); $job = $cloudconvert->jobs()->wait($job); } catch (HttpClientException $e) { // 4xx errors: bad request, unauthorized, payment required, not found, unprocessable $code = $e->getResponseCode(); // HTTP status (400, 401, 402, 403, 404, 422) $message = $e->getMessage(); // Human-readable message (may be from API body) $errorCode = $e->getErrorCode(); // Machine-readable code from API (nullable) $body = $e->getResponseBody(); // Raw decoded response array $response = $e->getResponse(); // PSR-7 ResponseInterface if ($code === 402) { echo 'Out of credits. Please top up your CloudConvert account.'; } elseif ($code === 422) { echo 'Validation error: ' . $message; // $body['errors'] contains field-level validation messages } } catch (HttpServerException $e) { // 5xx errors or network failures echo 'CloudConvert server error: ' . $e->getMessage(); } catch (SignatureVerificationException $e) { // Webhook signature mismatch echo 'Invalid webhook signature.'; } catch (UnexpectedDataException $e) { // Malformed JSON payload in webhook echo 'Bad webhook payload.'; } ``` -------------------------------- ### `$cloudconvert->jobs()->all(array $query): JobCollection` — List All Jobs Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Returns a `JobCollection` (iterable) of all jobs in the account. Supports query filters. ```APIDOC ## `all(array $query): JobCollection` — List All Jobs Returns a `JobCollection` (iterable) of all jobs in the account. Supports query filters. ### Parameters #### Query Parameters - **query** (array) - Optional - An associative array of query parameters for filtering jobs. Common filters include `filter[tag]`, `filter[status]`, and `per_page`. ### Response #### Success Response (JobCollection) - **JobCollection** (iterable) - An iterable collection of job objects. ### Request Example ```php // List all finished jobs tagged 'order-1234' $jobs = $cloudconvert->jobs()->all([ 'filter[tag]' => 'order-1234', 'filter[status]' => 'finished', 'per_page' => 25, ]); foreach ($jobs as $job) { echo $job->getId() . ' — ' . $job->getTag() . ' — ' . $job->getStatus() . PHP_EOL; } ``` ``` -------------------------------- ### `$cloudconvert->tasks()->upload(Task $task, $file, string $fileName): ResponseInterface` — Upload a File Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Performs a multipart upload to the pre-signed CloudConvert S3 endpoint embedded in an `import/upload` task's result. The `$file` argument accepts a file path string, a PHP resource (from `fopen()`), or a PSR-7 `StreamInterface`. ```APIDOC ## `upload(Task $task, $file, string $fileName): ResponseInterface` — Upload a File Performs a multipart upload to the pre-signed CloudConvert S3 endpoint embedded in an `import/upload` task's result. The `$file` argument accepts a file path string, a PHP resource (from `fopen()`), or a PSR-7 `StreamInterface`. ### Parameters #### Path Parameters - **task** (Task) - Required - The `import/upload` task object. - **file** (string|resource|StreamInterface) - Required - The file content to upload. Can be a file path, a stream resource, or a PSR-7 StreamInterface. - **fileName** (string) - Required - The name of the file to be uploaded. ### Response #### Success Response (ResponseInterface) - **ResponseInterface** - A PSR-7 ResponseInterface object representing the upload result. ### Request Example ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; // 1. Create a job with an import/upload task $job = (new Job()) ->addTask(new Task('import/upload', 'upload-my-file')) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'upload-my-file') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ); $job = $cloudconvert->jobs()->create($job); // 2. Find the upload task (it will be in 'waiting' status with a pre-signed form) $uploadTask = $job->getTasks()->whereName('upload-my-file')[0]; // 3. Upload using a file resource $cloudconvert->tasks()->upload($uploadTask, fopen('/path/to/local/file.docx', 'r'), 'file.docx'); // 4. Wait for completion and download $job = $cloudconvert->jobs()->wait($job); foreach ($job->getExportUrls() as $file) { $source = $cloudconvert->getHttpTransport()->download($file->url)->detach(); $dest = fopen('output/' . $file->filename, 'w'); stream_copy_to_stream($source, $dest); fclose($dest); echo 'Saved: output/' . $file->filename . PHP_EOL; } ``` ``` -------------------------------- ### Upload a File for Conversion Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Performs a multipart upload to the pre-signed CloudConvert S3 endpoint embedded in an import/upload task's result. The $file argument accepts a file path string, a PHP resource (from fopen()), or a PSR-7 StreamInterface. ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; // 1. Create a job with an import/upload task $job = (new Job()) ->addTask(new Task('import/upload', 'upload-my-file')) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'upload-my-file') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ); $job = $cloudconvert->jobs()->create($job); // 2. Find the upload task (it will be in 'waiting' status with a pre-signed form) $uploadTask = $job->getTasks()->whereName('upload-my-file')[0]; // 3. Upload using a file resource $cloudconvert->tasks()->upload($uploadTask, fopen('/path/to/local/file.docx', 'r'), 'file.docx'); // 4. Wait for completion and download $job = $cloudconvert->jobs()->wait($job); foreach ($job->getExportUrls() as $file) { $source = $cloudconvert->getHttpTransport()->download($file->url)->detach(); $dest = fopen('output/' . $file->filename, 'w'); stream_copy_to_stream($source, $dest); fclose($dest); echo 'Saved: output/' . $file->filename . PHP_EOL; } ``` -------------------------------- ### HTML Form Upload Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Allows direct client-side upload of files to CloudConvert's storage by rendering an HTML form. This bypasses the need for files to pass through your server. ```APIDOC ## HTML Form Upload — Allow Direct Client-Side Upload After creating a job with an `import/upload` task, you can render an HTML form so the end user uploads their file directly to CloudConvert's storage without the file passing through your server. ```php // In your controller, create the job and pass the upload task to the view $job = $cloudconvert->jobs()->create($job); $uploadTask = $job->getTasks()->whereName('upload-my-file')[0]; ``` ```html
getResult()->form->parameters as $parameter => $value): ?>
``` ``` -------------------------------- ### HTML Form for Direct File Upload to CloudConvert Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Provides an HTML form for clients to directly upload files to CloudConvert. It uses parameters obtained from the upload task result. ```html
getResult()->form->parameters as $parameter => $value) { ?>
``` -------------------------------- ### Generate Signed URL for Conversion Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/README.md Generates a signed URL for on-demand file conversion using a job definition. Requires a signed URL base and signing secret obtained from the CloudConvert Dashboard. ```php $cloudconvert = new CloudConvert([ 'api_key' => 'API_KEY', 'sandbox' => false ]); $job = (new Job()) ->addTask( (new Task('import/url', 'import-my-file')) ->set('url', 'https://my.url/file.docx') ) ->addTask( (new Task('convert', 'convert-my-file')) ->set('input', 'import-my-file') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-my-file')) ->set('input', 'convert-my-file') ); $signedUrlBase = 'SIGNED_URL_BASE'; $signingSecret = 'SIGNED_URL_SIGNING_SECRET'; $url = $cloudConvert->signedUrlBuilder()->createFromJob($signedUrlBase, $signingSecret, $job, 'CACHE_KEY'); ``` -------------------------------- ### CloudConvert Job Model Status Constants and Key Methods Source: https://context7.com/cloudconvert/cloudconvert-php/llms.txt Access job status constants and retrieve job properties like ID, status, timestamps, and associated tasks. Use `Job::STATUS_*` constants for checking the job's current state. The `getExportUrls()` method is a convenience for collecting output files from specific task types. ```php use CloudConvert\Models\Job; // Status constants Job::STATUS_WATING; // "waiting" Job::STATUS_PROCESSING; // "processing" Job::STATUS_FINISHED; // "finished" Job::STATUS_ERROR; // "error" // After create() or wait(): $job->getId(); // string UUID $job->getTag(); // string|null — your custom correlation tag $job->getWebhookUrl(); // string|null $job->getStatus(); // one of the STATUS_* constants above $job->getCreatedAt(); // \DateTimeImmutable $job->getStartedAt(); // \DateTimeImmutable|null $job->getEndedAt(); // \DateTimeImmutable|null $job->getTasks(); // TaskCollection $job->getLinks(); // object|null (API hypermedia links) // Convenience: collect all output files from finished export/url tasks $files = $job->getExportUrls(); foreach ($files as $file) { echo $file->url . ' — ' . $file->filename . PHP_EOL; } ```