nicklaw5/twitch-api-php
PHP client library for the Twitch API. Includes easy methods for Helix and legacy endpoints, OAuth authentication flows, and request helpers to fetch streams, users, channels, videos, clips, and more. Useful for building Twitch integrations in PHP apps.
Installation
composer require nicklaw5/twitch-api-php
Ensure your composer.json includes "minimum-stability": "dev" if using dev versions.
Authentication Register an application at Twitch Developer Console to obtain a Client ID and Client Secret. Initialize the client in Laravel:
use NickLaw5\TwitchAPI\Client;
$client = new Client(
env('TWITCH_CLIENT_ID'),
env('TWITCH_CLIENT_SECRET'),
env('TWITCH_ACCESS_TOKEN') // Optional: Pre-authenticated token
);
First Use Case: Fetching User Data
$user = $client->getUserById('12345678'); // Replace with a valid user ID
dd($user->data->display_name); // Outputs the Twitch username
Environment Variables
Add to .env:
TWITCH_CLIENT_ID=your_client_id
TWITCH_CLIENT_SECRET=your_client_secret
TWITCH_ACCESS_TOKEN=null # Leave empty for OAuth flow
Use Laravel's session to handle Twitch OAuth:
// Redirect user to Twitch for auth
$authUrl = $client->getAuthorizationUrl(
['scope' => ['user_read', 'channel_read:subscriptions']],
'http://your-app.com/callback'
);
return redirect()->to($authUrl);
// Handle callback in Laravel route
public function handleTwitchCallback(Request $request) {
$token = $client->getAccessTokenFromCode($request->code);
session(['twitch_token' => $token]);
return redirect()->route('dashboard');
}
Cache API responses to avoid hitting rate limits (Twitch allows 800 requests/10 minutes for most endpoints):
use Illuminate\Support\Facades\Cache;
$stream = Cache::remember("twitch_stream_{$userId}", now()->addMinutes(5), function() use ($client, $userId) {
return $client->getStreamByUserId($userId);
});
Use Laravel's queue:work to process webhook payloads asynchronously:
// Twitch webhook endpoint
public function handleWebhook(Request $request) {
$payload = $request->json()->all();
dispatch(new ProcessTwitchWebhook($payload));
}
// Job class
class ProcessTwitchWebhook implements ShouldQueue {
public function handle() {
// Process subscription/raid data
}
}
Use Laravel's collect() and each() for batch operations:
$userIds = [12345, 67890, ...];
$streams = collect($userIds)->map(function($id) use ($client) {
return $client->getStreamByUserId($id);
})->filter();
Bind the Twitch client to Laravel's container for dependency injection:
// app/Providers/AppServiceProvider.php
public function register() {
$this->app->singleton(Client::class, function() {
return new Client(
env('TWITCH_CLIENT_ID'),
env('TWITCH_CLIENT_SECRET'),
session('twitch_token')
);
});
}
Use Laravel's ApiResource to shape responses:
class TwitchStreamResource extends JsonResource {
public function toArray($request) {
return [
'title' => $this->title,
'viewers' => $this->viewer_count,
'url' => 'https://twitch.tv/' . $this->user_login,
];
}
}
Centralize Twitch API errors in a Handler:
// app/Exceptions/Handler.php
public function render($request, Throwable $exception) {
if ($exception instanceof \NickLaw5\TwitchAPI\Exception\TwitchAPIException) {
return response()->json([
'error' => $exception->getMessage(),
'status' => $exception->getCode(),
], $exception->getCode());
}
return parent::render($request, $exception);
}
try {
$client->getUserById('12345678');
} catch (\NickLaw5\TwitchAPI\Exception\UnauthorizedException $e) {
$token = $client->refreshAccessToken();
session(['twitch_token' => $token]);
retry(); // Retry the failed request
}
throttle middleware or implement exponential backoff:
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
try {
$response = $client->getHelixEndpoint('streams');
} catch (TooManyRequestsHttpException $e) {
sleep($e->getRetryAfter() + 1); // Respect Retry-After header
retry();
}
Twitch-Signature header:
public function handleWebhook(Request $request) {
$payload = $request->getContent();
$signature = $request->header('Twitch-Signature');
$secret = env('TWITCH_WEBHOOK_SECRET');
if (!hash_equals($signature, hash_hmac('sha256', $payload, $secret))) {
abort(403, 'Invalid signature');
}
// Process payload
}
$client = new Client(..., ..., ..., [
'debug' => true, // Logs HTTP requests/responses
]);
Use Laravel's logging to inspect API responses:
$response = $client->getHelixEndpoint('streams');
\Log::debug('Twitch API Response', ['data' => $response->data]);
Extend the client for unsupported endpoints:
$client->getHelixEndpoint('custom', [
'method' => 'GET',
'path' => '/custom/path',
'params' => ['param1' => 'value'],
]);
Add middleware to modify requests (e.g., headers):
$client->addMiddleware(function ($request) {
$request->headers->set('X-Custom-Header', 'value');
});
Use Laravel's Mockery to mock the client:
$mock = Mockery::mock(Client::class);
$mock->shouldReceive('getUserById')
->once()
->andReturn((object)['data' => (object)['display_name' => 'TestUser']]);
Dispatch Laravel events for Twitch actions (e.g., new subscriber):
event(new TwitchSubscriberEvent($subscriberData));
How can I help you explore Laravel packages today?