### Install CloudConvert PHP SDK Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Install the SDK and a compatible HTTP client via Composer. ```bash composer require cloudconvert/cloudconvert-php guzzlehttp/guzzle ``` -------------------------------- ### 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 ``` -------------------------------- ### Initialize CloudConvert Client Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Minimal setup required to instantiate the CloudConvert client using an API key. ```php $cloudconvert = new CloudConvert([ 'api_key' => 'YOUR_API_KEY' ]); ``` -------------------------------- ### Full SDK Configuration Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Example demonstrating a complete configuration including environment variables and a custom Guzzle client. ```php use CloudConvert\CloudConvert; use GuzzleHttp\Client as GuzzleClient; $httpClient = new GuzzleClient([ 'timeout' => 30, 'connect_timeout' => 10, 'proxy' => 'http://proxy.company.com:8080', ]); $cloudconvert = new CloudConvert([ 'api_key' => $_ENV['CLOUDCONVERT_API_KEY'], 'sandbox' => $_ENV['APP_ENV'] === 'testing', 'region' => $_ENV['CLOUDCONVERT_REGION'] ?? 'us-east', 'http_client' => $httpClient, ]); ``` -------------------------------- ### GET /v2/tasks Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md List all tasks. ```APIDOC ## GET /v2/tasks ### Description List all tasks associated with the account. ### Method GET ### Endpoint /v2/tasks ``` -------------------------------- ### GET /v2/jobs Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md List all jobs. ```APIDOC ## GET /v2/jobs ### Description List all jobs associated with the account. ### Method GET ### Endpoint /v2/jobs ``` -------------------------------- ### Handling HttpClientException Scenarios Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/errors.md Examples for handling specific HTTP status codes and inspecting detailed error responses. ```php try { $job = $cloudconvert->jobs()->create($jobDefinition); } catch (\CloudConvert\Exceptions\HttpClientException $e) { if ($e->getResponseCode() === 402) { echo "Error: Out of credits"; echo "Current credit balance: " . $cloudconvert->users()->me()->getCredits(); } elseif ($e->getResponseCode() === 400) { echo "Error: Invalid job configuration"; echo "Details: " . json_encode($e->getResponseBody()); } elseif ($e->getResponseCode() === 401) { echo "Error: Invalid API key"; } else { throw $e; } } ``` ```php try { $job = $cloudconvert->jobs()->create($job); } catch (\CloudConvert\Exceptions\HttpClientException $e) { $statusCode = $e->getResponseCode(); $responseBody = $e->getResponseBody(); $errorCode = $e->getErrorCode(); if (isset($responseBody['errors'])) { foreach ($responseBody['errors'] as $field => $errors) { echo "Field '$field' has errors: " . implode(', ', $errors); } } } ``` -------------------------------- ### Complete Webhook Endpoint Implementation Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/WebhookHandler.md A full example of receiving, verifying, and processing a CloudConvert webhook event in PHP. ```php $_ENV['CLOUDCONVERT_API_KEY'], 'sandbox' => false ]); $signingSecret = $_ENV['CLOUDCONVERT_WEBHOOK_SECRET']; // Get raw request body $payload = file_get_contents('php://input'); $signature = $_SERVER['HTTP_CLOUDCONVERT_SIGNATURE'] ?? ''; try { $webhookEvent = $cloudconvert->webhookHandler() ->constructEvent($payload, $signature, $signingSecret); } catch (\CloudConvert\Exceptions\SignatureVerificationException $e) { http_response_code(400); exit('Invalid signature'); } catch (\CloudConvert\Exceptions\UnexpectedDataException $e) { http_response_code(400); exit('Malformed payload'); } // Process event $job = $webhookEvent->getJob(); switch ($webhookEvent->getEvent()) { case \CloudConvert\Models\WebhookEvent::EVENT_JOB_FINISHED: // Handle successful completion foreach ($job->getExportUrls() as $file) { // Download and process results $stream = $cloudconvert->getHttpTransport() ->download($file->url); // Store file... } break; case \CloudConvert\Models\WebhookEvent::EVENT_JOB_FAILED: // Handle failure foreach ($job->getTasks() as $task) { if ($task->getStatus() === \CloudConvert\Models\Task::STATUS_ERROR) { // Log error: $task->getMessage(), $task->getCode() } } break; } http_response_code(204); exit(); ``` -------------------------------- ### get(string $id, $query = null) Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/TasksResource.md Retrieves a single task by ID. ```APIDOC ## get(string $id, $query = null) ### Description Retrieves a single task by ID. ### Parameters - **$id** (string) - Required - Task ID UUID - **$query** (array) - Optional - Optional query parameters ### Returns - **Task** - Task object with current state ``` -------------------------------- ### GET /v2/users/me Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Retrieve current user information. ```APIDOC ## GET /v2/users/me ### Description Retrieve information about the currently authenticated user. ### Method GET ### Endpoint /v2/users/me ``` -------------------------------- ### Retrieve Job Timestamps Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Job.md Access creation, start, and end times to calculate job duration. ```php $job = $cloudconvert->jobs()->get($jobId); echo "Created: " . $job->getCreatedAt()->format('Y-m-d H:i:s'); if ($job->getEndedAt()) { $duration = $job->getEndedAt()->getTimestamp() - $job->getCreatedAt()->getTimestamp(); echo "Duration: " . $duration . " seconds"; } ``` -------------------------------- ### Implementing Retry Logic for HttpServerException Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/errors.md Example of using exponential backoff to handle transient server errors. ```php $maxRetries = 3; $retryCount = 0; $backoffSeconds = 1; while ($retryCount < $maxRetries) { try { $job = $cloudconvert->jobs()->create($job); break; // Success } catch (\CloudConvert\Exceptions\HttpServerException $e) { $retryCount++; if ($retryCount >= $maxRetries) { throw $e; } sleep($backoffSeconds); $backoffSeconds *= 2; // Exponential backoff } } ``` -------------------------------- ### GET /v2/tasks/{id} Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Retrieve details for a specific task. ```APIDOC ## GET /v2/tasks/{id} ### Description Retrieve the status and details of a specific task by its ID. ### Method GET ### Endpoint /v2/tasks/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the task. ``` -------------------------------- ### get(string $id, $query = null) Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/JobsResource.md Retrieves a single job by ID with current status and task information. ```APIDOC ## get(string $id, $query = null) ### Description Retrieves a single job by ID with current status and task information. ### Parameters - **$id** (string) - Required - Job ID UUID - **$query** (array) - Optional - Optional query parameters ### Returns - **Job** - Job object with current state ### Throws - **HttpClientException** (401) - Unauthorized - **HttpClientException** (404) - Job not found - **HttpServerException** - Server-side errors ``` -------------------------------- ### GET /v2/jobs/{id} Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Retrieve details for a specific job. ```APIDOC ## GET /v2/jobs/{id} ### Description Retrieve the status and details of a specific job by its ID. ### Method GET ### Endpoint /v2/jobs/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the job. ``` -------------------------------- ### Retrieve Account Creation Date Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/User.md Gets the account creation timestamp as a DateTimeImmutable object. ```php $created = $user->getCreatedAt(); echo "Account created: " . $created->format('Y-m-d H:i:s'); $days = (new \DateTime())->diff($created); echo "Account age: " . $days->days . " days"; ``` -------------------------------- ### Calculate Task Execution Duration Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Task.md Calculates the total execution time in seconds by comparing the start and end timestamps. ```php if ($task->getStartedAt() && $task->getEndedAt()) { $duration = $task->getEndedAt()->getTimestamp() - $task->getStartedAt()->getTimestamp(); echo "Execution time: " . $duration . " seconds"; } ``` -------------------------------- ### Create and Configure a Job Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Job.md Initialize a new Job instance and chain task additions using the fluent interface. ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; $job = new Job(); $job->setTag('batch-1') ->addTask(new Task('import/url', 'import-1')) ->addTask(new Task('convert', 'convert-1')); ``` -------------------------------- ### Create and Configure Tasks Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Task.md Demonstrates creating import, conversion, and export tasks with specific parameters. ```php use CloudConvert\Models\Task; // Import from URL $importTask = new Task('import/url', 'import-step'); // Convert format $convertTask = new Task('convert', 'convert-step'); $convertTask->set('output_format', 'pdf'); // Export to URL $exportTask = new Task('export/url', 'export-step'); $exportTask->set('input', 'convert-step'); ``` -------------------------------- ### Configure SDK for Production Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Retrieve configuration from environment variables with fallback defaults for production deployments. ```php $cloudconvert = new CloudConvert([ 'api_key' => getenv('CLOUDCONVERT_API_KEY'), 'sandbox' => false, 'region' => getenv('CLOUDCONVERT_REGION') ?: 'us-east', ]); ``` -------------------------------- ### Configure SDK with Environment Variables Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Initialize the CloudConvert client by mapping environment variables to configuration keys. ```php $cloudconvert = new CloudConvert([ 'api_key' => $_ENV['CLOUDCONVERT_API_KEY'], 'sandbox' => $_ENV['CLOUDCONVERT_SANDBOX'] === 'true', 'region' => $_ENV['CLOUDCONVERT_REGION'], ]); ``` -------------------------------- ### Initialize CloudConvert Client Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/CloudConvert.md Configure the client with an API key and optional settings like sandbox mode or region. ```php use CloudConvert\CloudConvert; // Initialize with production API key $cloudconvert = new CloudConvert([ 'api_key' => 'eyJ0eXAiOiJKV1QiLCJhbGc...', 'sandbox' => false ]); // Or sandbox mode for testing $cloudconvert = new CloudConvert([ 'api_key' => 'your_sandbox_api_key', 'sandbox' => true, 'region' => 'us-east' ]); ``` -------------------------------- ### Get Job ID Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Task.md Retrieves the UUID of the job associated with the task. ```php $jobId = $task->getJobId(); ``` -------------------------------- ### Perform File Conversion Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Initialize the client and execute a conversion job by chaining import, convert, and export tasks. ```php use CloudConvert\CloudConvert; use CloudConvert\Models\Job; use CloudConvert\Models\Task; // Initialize client $cloudconvert = new CloudConvert([ 'api_key' => 'your-api-key', 'sandbox' => false ]); // Create a conversion job $job = (new Job()) ->setTag('my-conversion') ->addTask( (new Task('import/url', 'import-step')) ->set('url', 'https://example.com/file.docx') ) ->addTask( (new Task('convert', 'convert-step')) ->set('input', 'import-step') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-step')) ->set('input', 'convert-step') ); // Submit job $job = $cloudconvert->jobs()->create($job); // Wait for completion $job = $cloudconvert->jobs()->wait($job); // Download results if ($job->getStatus() === Job::STATUS_FINISHED) { foreach ($job->getExportUrls() as $file) { echo "Download: " . $file->url; } } ``` -------------------------------- ### Configure SDK for Staging Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Connect to the production API for final testing using staging-specific credentials. ```php $cloudconvert = new CloudConvert([ 'api_key' => 'YOUR_STAGING_API_KEY', 'sandbox' => false, // Use production API 'region' => 'us-east', // Use production region ]); ``` -------------------------------- ### Get Task Operation Type Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Task.md Retrieves the operation type identifier for the task, such as 'convert' or 'import/url'. ```php $operation = $task->getOperation(); if ($operation === 'convert') { // Configure conversion options } ``` -------------------------------- ### Configure SDK for Development or Testing Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Use sandbox mode to perform tests without consuming production credits. ```php $cloudconvert = new CloudConvert([ 'api_key' => 'YOUR_SANDBOX_API_KEY', 'sandbox' => true, ]); ``` -------------------------------- ### Initialize Task Constructor Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Task.md Defines the signature for creating a new Task instance. ```php public function __construct(?string $operation = null, ?string $name = null) ``` -------------------------------- ### 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) ``` -------------------------------- ### Validate Configuration Options Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Demonstrates how the SDK throws a RuntimeException when provided with invalid configuration types or empty values. ```php try { $cloudconvert = new CloudConvert([ 'api_key' => '', // Empty string 'sandbox' => 'yes', // Should be boolean ]); } catch (RuntimeException $e) { // symfony/options-resolver throws on validation failure echo $e->getMessage(); } ``` -------------------------------- ### Implement Multi-Tenant Configuration Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Uses a factory class to instantiate separate CloudConvert clients based on account-specific configuration retrieved from a data source. ```php class CloudConvertFactory { public static function create($accountId) { $config = getAccountConfig($accountId); return new \CloudConvert\CloudConvert([ 'api_key' => $config['api_key'], 'sandbox' => $config['sandbox'], 'region' => $config['region'] ?? 'us-east', ]); } } // Usage $client1 = CloudConvertFactory::create('account-1'); $client2 = CloudConvertFactory::create('account-2'); ``` -------------------------------- ### Get Task Name Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Task.md Retrieves the unique name identifier for the task, which is used to reference the task within a job. ```php $name = $task->getName(); // Reference this task from other tasks: ->set('input', $name) ``` -------------------------------- ### CloudConvert::__construct Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/CloudConvert.md Initializes the CloudConvert API client with configuration options. ```APIDOC ## CloudConvert::__construct ### Description Initializes the CloudConvert API client with configuration options. ### Parameters - **api_key** (string) - Required - CloudConvert API key from your dashboard - **sandbox** (boolean) - Optional - Enable sandbox mode for testing (default: false) - **http_client** (ClientInterface) - Optional - Custom PSR-18 HTTP client instance - **region** (string) - Optional - Region override: us-east, eu-west, etc. ### Returns CloudConvert instance ``` -------------------------------- ### Configure Sandbox Environment Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Toggle between sandbox and production environments using the sandbox boolean flag. ```php 'sandbox' => true ``` ```php $cloudconvert = new CloudConvert([ 'api_key' => 'sandbox_key_...', 'sandbox' => true // Use sandbox environment ]); // Production (default) $cloudconvert = new CloudConvert([ 'api_key' => 'production_key_...', 'sandbox' => false // Or omit for default ]); ``` -------------------------------- ### Create a standalone task Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/TasksResource.md Initializes a new task with specific operation and parameters, then persists it via the API. ```php $task = (new Task('convert', 'my-convert')) ->set('input_format', 'docx') ->set('output_format', 'pdf') ->set('input', 'https://example.com/file.docx'); $createdTask = $cloudconvert->tasks()->create($task); echo $createdTask->getId(); ``` -------------------------------- ### Configure Async HTTP Client Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Use an HTTPlug-compatible client for asynchronous operations. ```php use Http\Client\Socket\Client as SocketClient; $asyncClient = new SocketClient(); $cloudconvert = new CloudConvert([ 'api_key' => '...', 'http_client' => $asyncClient, ]); ``` -------------------------------- ### POST /v2/{operation} Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Create a new task. ```APIDOC ## POST /v2/{operation} ### Description Create a new task for a specific operation. ### Method POST ### Endpoint /v2/{operation} ### Parameters #### Path Parameters - **operation** (string) - Required - The operation type for the task. ``` -------------------------------- ### all($query = null) Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/TasksResource.md Retrieves a paginated list of all tasks in your account. ```APIDOC ## all($query = null) ### Description Retrieves a paginated list of all tasks in your account. ### Parameters - **$query** (array) - Optional - Query parameters for pagination ### Returns - **TaskCollection** - Collection of Task objects ``` -------------------------------- ### 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'); ``` -------------------------------- ### Filter and process job collections in PHP Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/JobCollection.md Demonstrates method chaining to filter jobs by status, creation date, and tags, as well as counting jobs by status. ```php // Get all finished jobs created today with export URLs $allJobs = $cloudconvert->jobs()->all(); $today = new DateTime('today'); $todaysFinished = $allJobs ->whereStatus(\CloudConvert\Models\Job::STATUS_FINISHED) ->filter(function ($job) use ($today) { return $job->getCreatedAt() >= $today; }) ->filter(function ($job) { return count($job->getExportUrls()) > 0; }); foreach ($todaysFinished as $job) { foreach ($job->getExportUrls() as $file) { echo "File: " . $file->filename . PHP_EOL; } } // Find failed jobs from specific users (by tag prefix) $failedJobs = $allJobs ->whereStatus(\CloudConvert\Models\Job::STATUS_ERROR) ->filter(function ($job) { return $job->getTag() && strpos($job->getTag(), 'user-') === 0; }); // Count jobs by status $byStatus = [ 'finished' => count($allJobs->whereStatus(\CloudConvert\Models\Job::STATUS_FINISHED)), 'error' => count($allJobs->whereStatus(\CloudConvert\Models\Job::STATUS_ERROR)), 'processing' => count($allJobs->whereStatus(\CloudConvert\Models\Job::STATUS_PROCESSING)), 'waiting' => count($allJobs->whereStatus(\CloudConvert\Models\Job::STATUS_WATING)), ]; echo json_encode($byStatus); ``` -------------------------------- ### all($query = null) Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/JobsResource.md Retrieves a paginated list of all jobs in your account. ```APIDOC ## all($query = null) ### Description Retrieves a paginated list of all jobs in your account. ### Parameters - **$query** (array) - Optional - Query parameters for pagination/filtering ### Returns - **JobCollection** - Collection of Job objects ### Throws - **HttpClientException** (401) - Unauthorized - **HttpServerException** - Server-side errors ``` -------------------------------- ### Create a new job Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/JobsResource.md Submit a job with configured import, conversion, and export tasks to the CloudConvert API. ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; $job = (new Job()) ->setTag('myconversion-1') ->addTask( (new Task('import/url', 'import-task')) ->set('url', 'https://example.com/document.docx') ) ->addTask( (new Task('convert', 'convert-task')) ->set('input', 'import-task') ->set('output_format', 'pdf') ->set('color_mode', 'color') ) ->addTask( (new Task('export/url', 'export-task')) ->set('input', 'convert-task') ); $createdJob = $cloudconvert->jobs()->create($job); echo $createdJob->getId(); // e.g., '12345678-1234-1234-1234-123456789012' ``` -------------------------------- ### Manage Job Lifecycle Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/INDEX.md Common methods for creating, monitoring, retrieving, and downloading job results. ```php 1. Create: $cloudconvert->jobs()->create($job) 2. Monitor: $cloudconvert->jobs()->wait($job) or refresh($job) 3. Retrieve: $cloudconvert->jobs()->get($id) 4. Download: $job->getExportUrls() ``` -------------------------------- ### Convert file from URL Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Create a job with import, convert, and export tasks to process a file from a remote URL. ```php $job = (new Job()) ->addTask( (new Task('import/url', 'import')) ->set('url', 'https://example.com/file.docx') ) ->addTask( (new Task('convert', 'convert')) ->set('input', 'import') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export')) ->set('input', 'convert') ); $job = $cloudconvert->jobs()->create($job); $job = $cloudconvert->jobs()->wait($job); foreach ($job->getExportUrls() as $file) { echo $file->url; } ``` -------------------------------- ### Configure API Key Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Set the required API key for authentication. ```php 'api_key' => 'eyJ0eXAiOiJKV1QiLCJhbGc...' ``` ```php $cloudconvert = new CloudConvert([ 'api_key' => 'eyJ0eXAiOiJKV1QiLCJhbGc...' // From dashboard ]); ``` -------------------------------- ### Configure Task Parameters Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Task.md Uses the fluent interface to set operation-specific parameters for a task. ```php $task = (new Task('convert', 'my-convert')) ->set('input', 'import-task-name') ->set('output_format', 'pdf') ->set('color_mode', 'color') ->set('quality', 'high'); // For import/url $importTask = (new Task('import/url', 'import')) ->set('url', 'https://example.com/document.docx'); // For export/url $exportTask = (new Task('export/url', 'export')) ->set('input', 'convert-step'); ``` -------------------------------- ### Initialize WebhookHandler Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/WebhookHandler.md Constructor for the WebhookHandler class, typically accessed via the CloudConvert client instance. ```php public function __construct(HydratorInterface $hydrator) ``` -------------------------------- ### POST /v2/jobs Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Create a new conversion job. ```APIDOC ## POST /v2/jobs ### Description Create a new job in the CloudConvert system. ### Method POST ### Endpoint /v2/jobs ``` -------------------------------- ### Implement Caching with Cache Key Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/SignedUrlBuilder.md Use a unique cache key to enable result caching for repeated conversions of the same input file. ```php $cacheKey = md5($fileContent); // Unique key for this file $job = (new Job()) ->addTask( (new Task('import/url', 'import')) ->set('url', 'https://example.com/file.docx') ) ->addTask( (new Task('convert', 'convert')) ->set('input', 'import') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export')) ->set('input', 'convert') ); // First conversion with cache key $url = $cloudconvert->signedUrlBuilder() ->createFromJob($signedUrlBase, $signingSecret, $job, $cacheKey); // Subsequent conversions with same input will be faster ``` -------------------------------- ### create(Job $job) Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/JobsResource.md Creates a new job and submits it to the CloudConvert API. ```APIDOC ## create(Job $job) ### Description Creates a new job and submits it to the CloudConvert API. ### Parameters - **$job** (Job) - Required - Job object with tasks configured ### Returns - **Job** - The created job with API response data including ID and timestamps ### Throws - **HttpClientException** (400) - Invalid job structure or missing required task parameters - **HttpClientException** (401) - Unauthorized (invalid API key) - **HttpClientException** (402) - Insufficient credits - **HttpClientException** (422) - Unprocessable job configuration - **HttpServerException** - Server-side errors (5xx) ``` -------------------------------- ### Handle webhooks Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Verify incoming webhook signatures and process job events. ```php $signingSecret = $_ENV['CLOUDCONVERT_WEBHOOK_SECRET']; try { $webhookEvent = $cloudconvert->webhookHandler() ->constructEvent( file_get_contents('php://input'), $_SERVER['HTTP_CLOUDCONVERT_SIGNATURE'], $signingSecret ); } catch (\CloudConvert\Exceptions\SignatureVerificationException $e) { http_response_code(400); exit('Invalid signature'); } $job = $webhookEvent->getJob(); if ($webhookEvent->getEvent() === WebhookEvent::EVENT_JOB_FINISHED) { // Process results foreach ($job->getExportUrls() as $file) { // Download and process } } ``` -------------------------------- ### Generate a signed URL from a Job definition Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/SignedUrlBuilder.md Constructs a signed URL by defining a job with import, conversion, and export tasks, then signing it with a secret key. ```php use CloudConvert\Models\Job; use CloudConvert\Models\Task; $job = (new Job()) ->addTask( (new Task('import/url', 'import-step')) ->set('url', 'https://example.com/document.docx') ) ->addTask( (new Task('convert', 'convert-step')) ->set('input', 'import-step') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-step')) ->set('input', 'convert-step') ); $signedUrlBase = 'https://myapp.cloudconvert.com'; // From dashboard $signingSecret = 'your-signing-secret'; // From dashboard $url = $cloudconvert->signedUrlBuilder() ->createFromJob($signedUrlBase, $signingSecret, $job); // URL can now be shared or embedded echo 'Convert to PDF'; ``` -------------------------------- ### List and filter tasks Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/TasksResource.md Retrieves a collection of tasks and demonstrates filtering by operation or status. ```php $allTasks = $cloudconvert->tasks()->all(); foreach ($allTasks as $task) { echo $task->getId() . ": " . $task->getOperation() . PHP_EOL; } // Filter by operation $conversions = $allTasks->whereOperation('convert'); // Filter by status $finished = $allTasks->whereStatus(Task::STATUS_FINISHED); ``` -------------------------------- ### Configure Custom HTTP Client Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Inject a custom PSR-18 compliant HTTP client for API communication. ```php 'http_client' => $guzzleClient ``` ```php use GuzzleHttp\Client; $guzzleClient = new Client([ 'timeout' => 30, 'connect_timeout' => 10, ]); $cloudconvert = new CloudConvert([ 'api_key' => '...', 'http_client' => $guzzleClient ]); ``` -------------------------------- ### createFromJob() Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/SignedUrlBuilder.md Generates a signed URL from a provided Job object, encoding the job configuration and tasks for secure on-demand conversion. ```APIDOC ## createFromJob(string $base, string $signingSecret, Job $job, ?string $cacheKey) ### Description Creates a signed URL from a job definition. The URL encodes the entire job configuration including all tasks and parameters using HMAC-SHA256. ### Parameters - **$base** (string) - Required - Signed URL base from CloudConvert dashboard. - **$signingSecret** (string) - Required - Signing secret from CloudConvert dashboard webhook settings. - **$job** (Job) - Required - Job object with complete configuration. - **$cacheKey** (string) - Optional - Optional cache key to reuse previous conversion results. ### Returns - **string** - The complete signed URL ready to be used. ### Example ```php $url = $cloudconvert->signedUrlBuilder()->createFromJob($signedUrlBase, $signingSecret, $job); ``` ``` -------------------------------- ### Upload file for conversion Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Upload a local file to a job using the import/upload task type. ```php $job = (new Job()) ->addTask(new Task('import/upload', 'upload')) ->addTask( (new Task('convert', 'convert')) ->set('input', 'upload') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export')) ->set('input', 'convert') ); $job = $cloudconvert->jobs()->create($job); $uploadTask = $job->getTasks()->whereName('upload')[0]; $cloudconvert->tasks()->upload($uploadTask, fopen('./file.pdf', 'r'), 'file.pdf'); $job = $cloudconvert->jobs()->wait($job); ``` -------------------------------- ### me() Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/UsersResource.md Retrieves information about the currently authenticated user account. ```APIDOC ## me() ### Description Retrieves information about the currently authenticated user account. ### Method SDK Method: `public function me(): User` ### Returns - **User** - Current authenticated user's account information ### Exceptions - **HttpClientException** (401) - Invalid or missing API key - **HttpServerException** - Server-side errors ### Example ```php $user = $cloudconvert->users()->me(); echo "Username: " . $user->getUsername(); echo "Email: " . $user->getEmail(); echo "Available Credits: " . $user->getCredits(); echo "Account Created: " . $user->getCreatedAt()->format('Y-m-d'); ``` ``` -------------------------------- ### Configure Webhook URL Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Job.md Set a callback URL to receive notifications when the job reaches a terminal state. ```php $job = (new Job()) ->setWebhookUrl('https://myapp.com/webhooks/cloudconvert') ->addTask(...); ``` -------------------------------- ### Retrieve and download export URLs Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Job.md Wait for a job to finish and download the resulting files using the provided export URLs. ```php $job = $cloudconvert->jobs()->wait($job); if ($job->getStatus() === Job::STATUS_FINISHED) { foreach ($job->getExportUrls() as $file) { echo "Download: " . $file->filename . " from " . $file->url . PHP_EOL; // Download the file $stream = $cloudconvert->getHttpTransport()->download($file->url); file_put_contents('./output/' . $file->filename, $stream); } } ``` -------------------------------- ### 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); } ``` -------------------------------- ### Handle Insufficient Credits (402) in PHP Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/errors.md Catch HttpClientException and check for a 402 status code to identify when account credits are exhausted. ```php try { $job = $cloudconvert->jobs()->create($job); } catch (HttpClientException $e) { if ($e->getResponseCode() === 402) { $user = $cloudconvert->users()->me(); echo "Insufficient credits. Current balance: " . $user->getCredits(); } } ``` -------------------------------- ### List all jobs Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/JobsResource.md Retrieve a paginated collection of jobs and filter them by status. ```php $allJobs = $cloudconvert->jobs()->all(); foreach ($allJobs as $job) { echo $job->getId() . ': ' . $job->getStatus() . PHP_EOL; } // Filter completed jobs $finishedJobs = $allJobs->whereStatus(\CloudConvert\Models\Job::STATUS_FINISHED); ``` -------------------------------- ### Generate Dynamic Job Configuration Signed URLs Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/SignedUrlBuilder.md Iterate through multiple output formats to generate unique signed URLs for each conversion task. ```php // Generate URLs for different conversion formats $formats = ['pdf', 'png', 'docx']; $urls = []; foreach ($formats as $format) { $job = (new Job()) ->addTask( (new Task('import/url', 'import')) ->set('url', $userFileUrl) // From user's uploaded file ) ->addTask( (new Task('convert', 'convert')) ->set('input', 'import') ->set('output_format', $format) ) ->addTask( (new Task('export/url', 'export')) ->set('input', 'convert') ); $urls[$format] = $cloudconvert->signedUrlBuilder() ->createFromJob($signedUrlBase, $signingSecret, $job); } // User can download in any format foreach ($urls as $format => $url) { echo 'Download as ' . strtoupper($format) . ''; } ``` -------------------------------- ### Add tasks to a job Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Job.md Chain multiple task definitions to a job instance using a fluent interface before submission. ```php $job = (new Job()) ->addTask( (new Task('import/url', 'step-1')) ->set('url', 'https://example.com/input.docx') ) ->addTask( (new Task('convert', 'step-2')) ->set('input', 'step-1') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'step-3')) ->set('input', 'step-2') ); // Submit job with 3 tasks in sequence $result = $cloudconvert->jobs()->create($job); ``` -------------------------------- ### Build Signed URLs Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/CloudConvert.md Generate on-demand conversion URLs using the signed URL builder. ```php $builder = $cloudconvert->signedUrlBuilder(); $url = $builder->createFromJob($base, $secret, $job, $cacheKey); ``` -------------------------------- ### createFromJob Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/SignedUrlBuilder.md Generates a signed URL from a Job object, which can be used to embed conversion tasks directly into client-side forms. ```APIDOC ## SignedUrlBuilder::createFromJob ### Description Generates a signed URL using a provided base URL, signing secret, and a Job object. This URL includes an HMAC-SHA256 signature to ensure the integrity of the job payload. ### Method SDK Method ### Parameters - **signedUrlBase** (string) - Required - The base domain for the signed URL obtained from the CloudConvert dashboard. - **signingSecret** (string) - Required - The secret key used to sign the URL, configured in the CloudConvert dashboard. - **job** (Job) - Required - The Job object containing the tasks to be executed. ### Example ```php $signedUrl = $cloudconvert->signedUrlBuilder() ->createFromJob($signedUrlBase, $signingSecret, $job); ``` ``` -------------------------------- ### Create Signed URL Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/configuration.md Uses the signed URL builder to generate a URL from a job, requiring a base URL and signing secret from environment variables. ```php $signedUrlBase = getenv('CLOUDCONVERT_SIGNED_URL_BASE'); $signingSecret = getenv('CLOUDCONVERT_SIGNED_URL_SECRET'); $url = $cloudconvert->signedUrlBuilder() ->createFromJob($signedUrlBase, $signingSecret, $job); ``` -------------------------------- ### Implement per-operation error handling Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/errors.md Apply targeted error handling for specific operations like job creation, file uploads, and webhook validation to provide context-aware feedback. ```php // Creating jobs try { $job = $cloudconvert->jobs()->create($job); } catch (HttpClientException $e) { if ($e->getResponseCode() === 400) { // Validate job structure if (count($job->getTasks()) === 0) { echo "Error: Job must contain at least one task"; } } } // Uploading files try { $cloudconvert->tasks()->upload($uploadTask, $filePath); } catch (HttpClientException $e) { if ($e->getResponseCode() === 402) { echo "Insufficient credits for conversion"; } } catch (HttpServerException $e) { echo "Upload failed, will retry"; } // Validating webhooks try { $event = $cloudconvert->webhookHandler() ->constructEvent($payload, $signature, $secret); } catch (SignatureVerificationException $e) { http_response_code(400); exit("Unauthorized"); } catch (UnexpectedDataException $e) { http_response_code(400); exit("Invalid payload"); } ``` -------------------------------- ### create(Task $task) Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/TasksResource.md Creates a standalone task in the API. ```APIDOC ## create(Task $task) ### Description Creates a standalone task in the API. Most workflows create tasks as part of a job instead. ### Parameters - **$task** (Task) - Required - Task object with operation and parameters configured ### Returns - **Task** - The created task with API response data ``` -------------------------------- ### Generate signed URLs Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/README.md Create a secure, signed URL for a job to allow temporary access to conversion results. ```php $job = (new Job()) ->addTask( (new Task('import/url', 'import')) ->set('url', 'https://example.com/file.docx') ) ->addTask( (new Task('convert', 'convert')) ->set('input', 'import') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export')) ->set('input', 'convert') ); $url = $cloudconvert->signedUrlBuilder() ->createFromJob( 'https://myapp.cloudconvert.com', $_ENV['CLOUDCONVERT_SIGNED_URL_SECRET'], $job ); echo 'Convert to PDF'; ``` -------------------------------- ### WebhookHandler::constructEvent Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/WebhookHandler.md Verifies the signature of an incoming webhook request and constructs a WebhookEvent object. ```APIDOC ## WebhookHandler::constructEvent ### Description Verifies the `CloudConvert-Signature` header against the raw request body using the provided signing secret. If the signature is valid, it returns a `WebhookEvent` object; otherwise, it throws a `SignatureVerificationException`. ### Parameters - **payload** (string) - Required - The raw request body received from the webhook. - **signature** (string) - Required - The value of the `CloudConvert-Signature` header. - **signingSecret** (string) - Required - The secret key provided in the CloudConvert dashboard. ### Exceptions - **\CloudConvert\Exceptions\SignatureVerificationException** - Thrown if the signature does not match. - **\CloudConvert\Exceptions\UnexpectedDataException** - Thrown if the payload is malformed. ``` -------------------------------- ### Manage Job Tags Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/Job.md Retrieve or set a custom tag for tracking and grouping jobs. ```php $tag = $job->getTag(); if ($tag) { echo "Job tag: $tag"; } ``` ```php $job = (new Job()) ->setTag('order-12345-pdf-conversion') ->addTask(...); ``` -------------------------------- ### Generate and Embed Signed URL in HTML Form Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/SignedUrlBuilder.md Creates a job with import, conversion, and export tasks, then generates a signed URL to be used as the action attribute in an HTML form. ```php // Generate signed URL with import/upload task $job = (new Job()) ->addTask(new Task('import/upload', 'upload-step')) ->addTask( (new Task('convert', 'convert-step')) ->set('input', 'upload-step') ->set('output_format', 'pdf') ) ->addTask( (new Task('export/url', 'export-step')) ->set('input', 'convert-step') ); $signedUrl = $cloudconvert->signedUrlBuilder() ->createFromJob($signedUrlBase, $signingSecret, $job); ?>
``` -------------------------------- ### Handle Webhook Events in Workflow Source: https://github.com/cloudconvert/cloudconvert-php/blob/master/_autodocs/api-reference/WebhookEvent.md Construct the event from a payload and process it based on the event type. ```php // Receive webhook $webhookEvent = $cloudconvert->webhookHandler() ->constructEvent($payload, $signature, $signingSecret); // Get event information $eventType = $webhookEvent->getEvent(); $job = $webhookEvent->getJob(); // Process based on event type switch ($eventType) { case \CloudConvert\Models\WebhookEvent::EVENT_JOB_CREATED: // Optional: log that job was created break; case \CloudConvert\Models\WebhookEvent::EVENT_JOB_FINISHED: // Job succeeded - download results foreach ($job->getExportUrls() as $file) { $stream = $cloudconvert->getHttpTransport() ->download($file->url); saveResultFile($file->filename, $stream); } // Update database to mark conversion complete updateJobStatus($job->getTag(), 'completed'); break; case \CloudConvert\Models\WebhookEvent::EVENT_JOB_FAILED: // Job failed - log error details foreach ($job->getTasks() as $task) { if ($task->getStatus() === \CloudConvert\Models\Task::STATUS_ERROR) { logError( $job->getTag(), $task->getName(), $task->getCode(), $task->getMessage() ); } } // Update database to mark conversion failed updateJobStatus($job->getTag(), 'failed'); break; } ```