> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Importly in Laravel with queued jobs

> Transcribe or download any video or audio link from a Laravel app with queued jobs, with retries that respect rate limits, jobs that never start twice, and a signed webhook controller in PHP.

If your Laravel app takes video or podcast links, the media job is the one that breaks once it runs on a server: sites block datacenter IPs, and many videos have no captions to read. Call Importly from a queued job instead. It returns the transcript, a download link for the file, or the video's details, for links from YouTube, TikTok, Instagram, X, podcasts and 1,000+ other sites.

Long imports can take a few minutes, so don't hold a worker for them. One job starts the Importly job and stores its ID, and a second job checks the status and dispatches itself again 20 seconds later until it's done. A retry only ever re-runs the check, so it never starts the job twice. The code uses Laravel's `Http` client and plain `ShouldQueue` jobs, so it runs on the database, Redis or SQS queue drivers and under Horizon.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once). Add it as `IMPORTLY_API_KEY` to `.env` and to the environment your app and queue workers run in:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
```

Read it through `config/services.php`, so it still works after `php artisan config:cache`:

```php config/services.php theme={null}
'importly' => [
    'key' => env('IMPORTLY_API_KEY'),
    'webhook_secret' => env('IMPORTLY_WEBHOOK_SECRET'),
],
```

The jobs below save to a `Video` model with `url`, `importly_job_id`, `importly_status`, `importly_result` (json, cast to `array`) and `importly_error` columns:

```php database/migrations/xxxx_create_videos_table.php theme={null}
Schema::create('videos', function (Blueprint $table) {
    $table->id();
    $table->string('url');
    $table->string('importly_job_id')->nullable();
    $table->string('importly_status')->nullable();
    $table->json('importly_result')->nullable();
    $table->string('importly_error')->nullable();
    $table->timestamps();
});
```

## 2. A small client

A `429` throws `ImportlyException` with the `retryAfter` the API sent, and a `5xx` throws it with 30 seconds. A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) won't change on a retry, so it throws with `retryAfter` set to `null` and the job fails:

```php app/Exceptions/ImportlyException.php theme={null}
<?php

namespace App\Exceptions;

use RuntimeException;

class ImportlyException extends RuntimeException
{
    // $retryAfter is set for a 429 or 5xx (the same request can work after that many seconds)
    // and null for a 400 (bad link), 401 (wrong key) or 402 (balance too low)
    public function __construct(string $message, public readonly ?int $retryAfter = null)
    {
        parent::__construct($message);
    }
}
```

```php app/Services/Importly.php theme={null}
<?php

namespace App\Services;

use App\Exceptions\ImportlyException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

class Importly
{
    public static function post(string $path, array $body): array
    {
        return self::data(self::client()->post($path, $body));
    }

    public static function get(string $path, array $query): array
    {
        return self::data(self::client()->get($path, $query));
    }

    private static function client()
    {
        return Http::baseUrl('https://api.importly.io')
            ->withToken(config('services.importly.key'))
            ->acceptJson()
            ->timeout(70); // longer than the 30-second wait on /transcribe
    }

    private static function data(Response $response): array
    {
        $json = $response->json() ?? [];
        if ($response->successful() && ($json['success'] ?? false)) {
            return $json['data'];
        }

        $message = sprintf('Importly %d %s: %s', $response->status(), $json['code'] ?? '', $json['error'] ?? 'request failed');
        $retryAfter = match (true) {
            $response->status() === 429 => (int) ($json['retryAfter'] ?? 60),
            $response->serverError() => 30,
            default => null, // a retry won't change it
        };
        throw new ImportlyException($message, $retryAfter);
    }
}
```

## 3. The jobs

A shared trait waits for `retryAfter` on a `429` or `5xx`, up to 5 tries, fails straight away on anything else, and saves the outcome:

```php app/Jobs/Concerns/TracksImportlyJob.php theme={null}
<?php

namespace App\Jobs\Concerns;

use App\Exceptions\ImportlyException;
use App\Jobs\CheckImportlyJob;
use App\Models\Video;

// Shared by the jobs below
trait TracksImportlyJob
{
    public int $tries = 5;

    // Wait for retryAfter on a 429 or 5xx; fail straight away on anything else
    protected function retryOrFail(ImportlyException $error): void
    {
        $error->retryAfter === null ? $this->fail($error) : $this->release($error->retryAfter);
    }

    protected function finishOrCheck(Video $video, string $kind, array $job): void
    {
        $video->update(['importly_job_id' => $job['jobId'], 'importly_status' => $job['status']]);
        if (in_array($job['status'], ['queued', 'running'], true)) {
            CheckImportlyJob::dispatch($video->id, $kind, $job['jobId'])->delay(now()->addSeconds(20));
        } else {
            $this->saveResult($video, $job);
        }
    }

    protected function saveResult(Video $video, array $job): void
    {
        if ($job['status'] === 'completed') {
            // a transcript has result['text']; an import has result['mediaUrl'], valid for 7 days
            $video->update(['importly_status' => 'completed', 'importly_result' => $job['result']]);
        } else {
            $video->update(['importly_status' => 'failed', 'importly_error' => "{$job['code']}: {$job['message']}"]);
        }
    }
}
```

`"mode": "auto"` uses the video's captions and falls back to speech-to-text when it has none. `wait: true` holds the request open for up to 30 seconds, so a transcript from captions usually comes back from the first call and is saved straight away:

```php app/Jobs/TranscribeLink.php theme={null}
<?php

namespace App\Jobs;

use App\Exceptions\ImportlyException;
use App\Jobs\Concerns\TracksImportlyJob;
use App\Models\Video;
use App\Services\Importly;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class TranscribeLink implements ShouldQueue
{
    use Queueable, TracksImportlyJob;

    public function __construct(public int $videoId) {}

    public function handle(): void
    {
        $video = Video::findOrFail($this->videoId);
        try {
            $job = Importly::post('/transcribe', [
                'url' => $video->url,
                'mode' => 'auto', // captions, or speech-to-text when there are none
                'wait' => true, // captions usually come back within the 30-second wait
                'maxCostDollars' => 1,
            ]);
        } catch (ImportlyException $error) {
            $this->retryOrFail($error);

            return;
        }
        $this->finishOrCheck($video, 'transcribe', $job);
    }
}
```

`POST /import` returns a job ID straight away:

```php app/Jobs/ImportLink.php theme={null}
<?php

namespace App\Jobs;

use App\Exceptions\ImportlyException;
use App\Jobs\Concerns\TracksImportlyJob;
use App\Models\Video;
use App\Services\Importly;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class ImportLink implements ShouldQueue
{
    use Queueable, TracksImportlyJob;

    public function __construct(public int $videoId, public bool $audioOnly = false) {}

    public function handle(): void
    {
        $video = Video::findOrFail($this->videoId);
        try {
            $job = Importly::post('/import', [
                'url' => $video->url,
                'includeVideo' => ! $this->audioOnly,
                'videoQuality' => '720p', // a ceiling: lower if the source has no 720p
                'maxCostDollars' => 0.5, // the most this one file may cost
            ]);
        } catch (ImportlyException $error) {
            $this->retryOrFail($error);

            return;
        }
        $this->finishOrCheck($video, 'import', $job);
    }
}
```

Anything still `queued` or `running` goes to the check job:

```php app/Jobs/CheckImportlyJob.php theme={null}
<?php

namespace App\Jobs;

use App\Exceptions\ImportlyException;
use App\Jobs\Concerns\TracksImportlyJob;
use App\Models\Video;
use App\Services\Importly;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

// Checks every 20 seconds, for up to an hour
class CheckImportlyJob implements ShouldQueue
{
    use Queueable, TracksImportlyJob;

    public function __construct(public int $videoId, public string $kind, public string $jobId, public int $checks = 1) {}

    public function handle(): void
    {
        $video = Video::findOrFail($this->videoId);
        try {
            $job = Importly::get("/{$this->kind}/status", ['id' => $this->jobId]);
        } catch (ImportlyException $error) {
            $this->retryOrFail($error);

            return;
        }

        $pending = in_array($job['status'], ['queued', 'running'], true);
        if ($pending && $this->checks < 180) {
            self::dispatch($this->videoId, $this->kind, $this->jobId, $this->checks + 1)->delay(now()->addSeconds(20));
        } elseif ($pending) {
            $video->update(['importly_status' => 'failed', 'importly_error' => "still {$job['status']} after an hour"]);
        } else {
            $this->saveResult($video, $job);
        }
    }
}
```

A finished transcript's `importly_result` has `text`, and `data.segments` with `start` and `end` times in seconds. A finished import's has `mediaUrl`, a link to the file that's valid for 7 days: copy it to your disk with `Storage::put()` if you keep it, or connect your bucket once and import with `store: true` ([Save to your bucket](/docs/integrations/save-to-bucket.md)). A caption transcript costs \$0.003; speech-to-text is billed per minute, and `maxCostDollars` caps what one link can cost. See [Transcripts](/docs/features/transcripts.md) and [Downloads](/docs/features/downloads.md).

## Run it

Dispatch the job from your controller once the record is saved:

```php app/Http/Controllers/VideoController.php theme={null}
public function store(Request $request)
{
    $video = Video::create($request->validate(['url' => 'required|url']));
    TranscribeLink::dispatch($video->id);

    return redirect()->route('videos.show', $video);
}
```

Then run a worker with `php artisan queue:work` (or Horizon). The `sync` driver runs the 20-second checks back to back without waiting, so use a real queue driver outside tests.

## Webhooks

Prefer a webhook? Add `'webhookUrl' => route('importly.webhook')` to the body of `/import` or `/transcribe` (it must be a public `https://` URL), and keep the check job as a fallback: each job gets one delivery and no retries. Your signing secret is on the [API key page](https://www.importly.io/dashboard/api-key) under **Webhook signing secret**; add it as `IMPORTLY_WEBHOOK_SECRET`.

The controller checks the `Importly-Signature` header against the raw body from `$request->getContent()`, rejects requests older than 5 minutes, and accepts a match against any `v1` (there are two for 24 hours after you rotate the secret). It then reads the job from the API with the check job, and skips jobs the check job already finished:

```php app/Http/Controllers/ImportlyWebhookController.php theme={null}
<?php

namespace App\Http\Controllers;

use App\Jobs\CheckImportlyJob;
use App\Models\Video;
use Illuminate\Http\Request;

class ImportlyWebhookController extends Controller
{
    public function __invoke(Request $request)
    {
        // getContent() is the raw body: the signature covers the exact bytes Importly sent
        $rawBody = $request->getContent();
        if (! self::verifySignature($request->header('Importly-Signature'), $rawBody, config('services.importly.webhook_secret'))) {
            abort(400);
        }

        $data = json_decode($rawBody, true)['data'] ?? [];
        $video = Video::where('importly_job_id', $data['jobId'] ?? null)->first();
        // skip jobs the check job already finished; data.type is 'import' or 'transcribe'
        if ($video && in_array($video->importly_status, ['queued', 'running'], true)) {
            CheckImportlyJob::dispatch($video->id, $data['type'], $data['jobId']);
        }

        return response()->noContent();
    }

    public static function verifySignature(?string $header, string $rawBody, string $secret, int $toleranceSeconds = 300): bool
    {
        if (! $header) {
            return false;
        }
        $timestamp = null;
        $signatures = [];
        foreach (explode(',', $header) as $part) {
            [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
            if ($key === 't' && ctype_digit($value)) {
                $timestamp = (int) $value;
            } elseif ($key === 'v1') {
                $signatures[] = $value;
            }
        }
        if ($timestamp === null || abs(time() - $timestamp) > $toleranceSeconds) {
            return false;
        }
        $expected = hash_hmac('sha256', "{$timestamp}.{$rawBody}", $secret);
        foreach ($signatures as $signature) {
            if (hash_equals($expected, $signature)) {
                return true;
            }
        }

        return false;
    }
}
```

```php routes/web.php theme={null}
use App\Http\Controllers\ImportlyWebhookController;

Route::post('/webhooks/importly', ImportlyWebhookController::class)->name('importly.webhook');
```

Importly can't send a CSRF token, so leave the route out of CSRF checks:

```php bootstrap/app.php theme={null}
->withMiddleware(function (Middleware $middleware): void {
    $middleware->validateCsrfTokens(except: ['webhooks/importly']);
})
```

See [Verify signatures](/docs/webhooks.md#verify-signatures) for the header format.

## Notes

`SOURCE_THROTTLED` and `LIVE_NOT_SUPPORTED` are the failure codes that can work on a later attempt (a stream that is still live, or a site that is busy for now). For those, dispatch `TranscribeLink` or `ImportLink` again later; every other failure code is final. See [Media unavailable](/docs/errors/media-unavailable.md) and [Source throttled](/docs/errors/source-throttled.md).

`POST /import` allows 240 requests per hour per key, and an account can have 50 imports queued or running at once. Status endpoints allow 3,600 requests per hour per job type; a check every 20 seconds is 180 an hour for each job in progress, so about 20 jobs can poll at once. Put these jobs on their own queue (`->onQueue('media')`) and run a limited number of workers for it. For hundreds of links, see [Batch imports](/docs/integrations/batch-imports.md).

A `youtube.com/playlist?list=…` link is rejected with `PLAYLIST_NOT_SUPPORTED`. Dispatch one job per video instead.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.