Skip to content
PHP & Laravel

PHP and Laravel quickstart

Create a hosted video from a URL, play it privately, and verify webhooks from a Laravel app. The examples use Laravel’s HTTP client and nothing else, because the API is plain HTTP with JSON: every call is a POST to https://api.transcodely.com/transcodely.v1.<Service>/<Method>, with your API key as a bearer token and a snake_case JSON body.

What is published: there is no Transcodely package on Packagist. A PHP client with a Laravel integration, transcodely/transcodely-php, is in beta on GitHub and has not yet been exercised against the live API; see The beta PHP package at the end. Everything above that section works without it.

1. Configure

# .env
TRANSCODELY_API_KEY=ak_your_api_key
TRANSCODELY_WEBHOOK_SECRET=whsec_...
// config/services.php, inside the returned array
'transcodely' => [
    'key' => env('TRANSCODELY_API_KEY'),
    'webhook_secret' => env('TRANSCODELY_WEBHOOK_SECRET'),
],

Create the API key under API keys in the dashboard. Keep it on the server: never put it in a Blade view or JavaScript.

2. One helper for every call

<?php
// app/Services/Transcodely.php
namespace AppServices;

use IlluminateSupportFacadesHttp;

class Transcodely
{
    /** Calls one API method, for example call('VideoService/Get', ['id' => 'vid_…']). */
    public static function call(string $method, array $body): array
    {
        return Http::withToken(config('services.transcodely.key'))
            ->acceptJson()
            ->timeout(30)
            ->post('https://api.transcodely.com/transcodely.v1.'.$method, $body)
            ->throw()
            ->json();
    }
}

post sends the array as JSON; throw() turns an error answer into an exception.

3. Create a video from a URL

use AppServicesTranscodely;

$video = Transcodely::call('VideoService/CreateFromUrl', [
    'url' => 'https://example.com/lesson-1.mp4',
    'title' => 'Lesson 1',
    'visibility' => 'private',
])['video'];

// $video['id'] is "vid_…", $video['status'] is "processing"

The URL must be reachable over http or https. The video is transcoded and hosted for you; it becomes ready when it can play. Check with VideoService/Get (['id' => $video['id']]), or wait for the video.ready webhook in step 5.

4. Play it privately

A private video plays only with a playback token for one viewer. Ask the API for one in your controller, then put the player URL it returns in an iframe:

$minted = Transcodely::call('VideoService/CreatePlaybackToken', [
    'video_id' => $lesson->video_id,
    'viewer_id' => (string) auth()->id(),
    'expires_in' => 14400,
]);

return view('lesson', ['playerUrl' => $minted['player_url']]);
<!-- resources/views/lesson.blade.php -->
<div style="position:relative;padding-top:56.25%">
  <iframe src="{{ $playerUrl }}" title="Lesson" style="position:absolute;inset:0;width:100%;height:100%;border:0"
    allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>
</div>

Check that the signed-in user may watch the video before you mint the token. viewer_id must be an opaque id of yours, never an email address: it is readable in the token. It also turns on resume and progress per viewer (Course Progress). To sign tokens on your own server with no API call, see Protected Playback.

5. Verify webhooks

Create an endpoint under Webhooks in the dashboard, pointing at https://your-site.example/webhooks/transcodely with the video.ready event, and put its whsec_… secret in TRANSCODELY_WEBHOOK_SECRET.

Every delivery has a Transcodely-Signature header such as t=1716480293,v1=a3f7…. The v1 value is the hex HMAC-SHA-256 of the timestamp, a dot, and the raw request body, keyed with the whole secret including whsec_. While a secret is being rotated, the header carries a second v1 signed with the previous secret.

// routes/web.php
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

Route::post('/webhooks/transcodely', function (Request $request) {
    $body = $request->getContent(); // the raw body, before any decoding
    $parts = [];
    foreach (explode(',', $request->header('Transcodely-Signature', '')) as $item) {
        [$key, $value] = array_pad(explode('=', trim($item), 2), 2, '');
        $parts[$key][] = $value;
    }
    $timestamp = (int) ($parts['t'][0] ?? 0);
    if (abs(time() - $timestamp) > 300) {
        abort(400, 'stale or missing timestamp');
    }
    $expected = hash_hmac('sha256', $timestamp.'.'.$body, config('services.transcodely.webhook_secret'));
    $valid = false;
    foreach ($parts['v1'] ?? [] as $signature) {
        $valid = $valid || hash_equals($expected, $signature);
    }
    if (! $valid) {
        abort(400, 'bad signature');
    }

    $event = json_decode($body, true);
    if ($event['type'] === 'video.ready') {
        logger()->info('video ready', ['id' => $event['data']['id']]);
    }

    return response()->noContent();
});

Exclude the route from cross-site request forgery protection, which would otherwise refuse the delivery. In Laravel 11 and later, in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: ['webhooks/transcodely']);
})

Answer within 10 seconds. A 5xx, 408, 429, a timeout or a network error is retried, up to 15 attempts over about three days; any other 4xx is final. A delivery can arrive more than once, so de-duplicate on $event['id'] (also in the Webhook-Id header).

What can go wrong

throw() raises Illuminate\Http\Client\RequestException. Its response holds the answer: the JSON body has code (such as invalid_argument or not_found) and message, and the headers carry error-code with a more specific reason and X-Request-Id (req_…). Quote the request id when you contact support.

use IlluminateHttpClientRequestException;

try {
    Transcodely::call('VideoService/Get', ['id' => 'vid_missing']);
} catch (RequestException $e) {
    logger()->warning('Transcodely refused', [
        'status' => $e->response->status(),
        'code' => $e->response->json('code'),
        'error_code' => $e->response->header('error-code'),
        'request_id' => $e->response->header('X-Request-Id'),
    ]);
}
  • 401: the API key is missing, mistyped or revoked.
  • 400 with invalid_argument: a field is wrong. The message names it.
  • The iframe does not load on your site: your app limits Allowed embed domains and this host is not on the list.
  • Every webhook answers 419: the route is still behind cross-site request forgery protection.

To retry a create safely after a timeout, send the same Idempotency-Key header both times (Idempotency).

The beta PHP package

transcodely/transcodely-php (v0.1.0, MIT) is a PHP 8.2+ client with an optional Laravel 12 and 13 integration: typed resources, retries, webhook verification, playback token signing, a webhook route and a Blade player component. Its readme says plainly that it has not yet been exercised against the live API, and it is not on Packagist: Composer installs it from GitHub.

{
    "repositories": [
        { "type": "vcs", "url": "https://github.com/transcodely/transcodely-php" }
    ]
}
composer require transcodely/transcodely-php:^0.1

Its readme covers usage; report mismatches on its issues page.

Next steps

Run this against your own file

A free account runs standard-quality encodes up to 2 minutes, one at a time (a longer upload is shortened to its first 2 minutes), so the Quickstart runs with nothing set up but an API key.