CloudConvert PHP SDK

repository·master·Indexed 42 days ago

https://github.com/cloudconvert/cloudconvert-php

The official PHP SDK for the CloudConvert API v2. It enables developers to automate file conversions, uploads, and downloads using a Job and Task based system. The SDK supports PSR-7, PSR-17, and PSR-18 interfaces, provides a WebhookHandler for verifying event signatures, and includes a SignedUrlBuilder for on-demand conversions.

Tokens
6.8K
Snippets
34
Records
37
Agent score
53%

What's inside CloudConvert

  1. Create a conversion job

    master

    To perform a conversion, instantiate a CloudConvert client, build a Job object, and add Task objects to it. Tasks define the operations (e.g., import/url, convert, export/url) and their parameters using the set() method. Finally, call $cloudconvert->jobs()->create($job) to submit the job.

    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);
  2. Install the cloudconvert-php SDK

    master

    Install the SDK using Composer. Because the SDK relies on PSR-7, PSR-17, and PSR-18 interfaces, you must also install an HTTP client implementation (like Guzzle) and an HTTP factory implementation.

    composer require cloudconvert/cloudconvert-php guzzlehttp/guzzle
  3. Generate Signed URLs

    master

    Signed URLs allow for on-demand file conversion via URL query parameters. Use the signedUrlBuilder() to generate a URL from a Job object. You will need a signedUrlBase and a signingSecret obtained from the CloudConvert Dashboard.

    $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');
  4. Upload files to CloudConvert

    master

    You can upload files using the import/upload task type. After creating the job, retrieve the specific upload task and use the $cloudconvert->tasks()->upload() method. This method accepts a string (filename), a PHP resource, or a PSR-7 StreamInterface as the second parameter.

    Alternatively, you can allow clients to upload directly to CloudConvert by using the form parameters provided in the task result.

    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');
  5. Download files from a completed job

    master

    To download files, first wait for the job to complete using $cloudconvert->jobs()->wait($job). Then, iterate through the export URLs provided by $job->getExportUrls(). Use $cloudconvert->getHttpTransport()->download($file->url) to get a PSR-7 StreamInterface, which can be converted to a PHP resource via detach() for standard file operations.

    $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);
    
    }
  6. Handle Webhook events

    master

    Webhooks allow you to receive notifications about job status changes. You can verify the authenticity of a webhook using the webhookHandler().

    1. Using raw payload and signature: Pass the raw php://input content, the HTTP_CLOUDCONVERT_SIGNATURE header, and your signing secret to constructEvent().
    2. Using a PSR-7 Request: Pass a RequestInterface and the signing secret to constructEventFromRequest().

    If verification fails, the SDK throws UnexpectedDataException or SignatureVerificationException.

    $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(\CloudConvert\Exceptions\UnexpectedDataException $e) {
        // Invalid payload
        http_response_code(400);
        exit();
    } catch(\CloudConvert\Exceptions\SignatureVerificationException $e) {
        // Invalid signature
        http_response_code(400);
        exit();
    }
    
    $job = $webhookEvent->getJob();
    
    $job->getTag(); // can be used to store an ID
    
    $exportTask = $job->getTasks()
                ->whereStatus(Task::STATUS_FINISHED) // get the task with 'finished' status ...
                ->whereName('export-it')[0];        // ... and with the name 'export-it'
  7. Configure the API Region

    master

    By default, the SDK uses the region set in your CloudConvert account settings. To override this and use a specific fixed region, pass the region key in the CloudConvert constructor.

    // Pass the region to the constructor
    $cloudconvert = new CloudConvert([
        'api_key' => 'API_KEY',
        'sandbox' => false,
        'region'  => 'us-east'
    ]);
  8. Configure CloudConvert client options

    master

    When initializing the CloudConvert client, you can provide the following configuration options:

    OptionTypeRequiredDefaultDescription
    api_keystringYesN/AYour CloudConvert API key
    sandboxbooleanNofalseWhether to use the sandbox environment
    http_clientClientInterfaceNoN/AA custom PSR-18 HTTP client
    regionstringNoN/AThe API region to use
  9. Upload a file to an import/upload task with upload()

    master

    To upload a file for a task with the import/upload operation, use the upload() method.

    Requirements:

    • The task operation must be import/upload.
    • The task status must be waiting (represented by Task::STATUS_WATING).
    • The task must have a result containing a form object (which includes the upload URL and parameters).

    Parameters:

    • $task: The Task instance ready for upload.
    • $file: The file content, which can be a string, a resource, or a `Psr

    <Stream><Interface>`.

    • $fileName (optional): The name to assign to the file.

    Returns a Psr\Http\Message\ResponseInterface on success.

    $response = $cloudconvert->tasks()->upload($task, $fileContent, 'filename.png');
  10. Access CloudConvert resources

    master

    The CloudConvert client acts as an entry point to various API resources. Use the following methods to access specific resource controllers:

    • $client->users(): Returns a UsersResource instance for managing user-related data.
    • $client->jobs(): Returns a JobsResource instance for managing conversion jobs.
    • $client->tasks(): Returns a TasksResource instance for managing individual tasks within jobs.
    • $client->webhookHandler(): Returns a WebhookHandler instance to process incoming webhooks.
    • $client->signedUrlBuilder(): Returns a SignedUrlBuilder instance for generating signed URLs.
    $jobs = $cloudconvert->jobs();
    // Use $jobs to interact with the Jobs API
  11. Process incoming CloudConvert webhooks with WebhookHandler

    master

    The WebhookHandler class is used to verify and transform incoming CloudConvert webhook payloads into WebhookEvent objects. This ensures that the webhook request is authentic and contains valid data.

    To use it, you must provide your webhook signingSecret (obtained from your CloudConvert dashboard). The handler supports two methods of construction:

    1. constructEvent: Use this if you have the raw JSON payload and the signature string manually.
    2. constructEventFromRequest: Use this if you are using a PSR-7 compatible request object (e.g., from a framework like Slim or Guzzle). It automatically extracts the payload from the body and the signature from the CloudConvert-Signature header.

    If the signature does not match the payload and your secret, it throws a SignatureVerificationException. If the payload is malformed, it throws an UnexpectedDataException.

    use CloudConvert\Handler\WebhookHandler;
    use CloudConvert\Hydrator\Hydrator;
    
    // 1. Setup the handler with a hydrator
    $hydrator = new Hydrator();
    $handler = new WebhookHandler($hydrator);
    $signingSecret = 'your_signing_secret';
    
    // 2. Example: Processing a PSR-7 Request (e.g., in a middleware or controller)
    try {
        $webhookEvent = $handler->constructEventFromRequest($psr7Request, $signingSecret);
        
        // Access event data
        echo $webhookEvent->getPayload();
    } catch (\CloudConvert\Exceptions\SignatureVerificationException $e) {
        // Handle invalid signature
    } catch (\CloudConvert\Exceptions\UnexpectedDataException $e) {
        // Handle invalid JSON/data
    }