Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twitch Api Php Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require nicklaw5/twitch-api-php
    

    Ensure your composer.json includes "minimum-stability": "dev" if using dev versions.

  2. 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
    );
    
  3. 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
    
  4. 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
    

Implementation Patterns

Workflows

1. OAuth Flow (User Authentication)

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');
}

2. Rate Limiting & Caching

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);
});

3. Webhooks (e.g., Subscriptions, Raids)

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
    }
}

4. Batch Processing (e.g., Fetching Multiple Streams)

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();

Integration Tips

Laravel Service Provider

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')
        );
    });
}

API Resource Transformers

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,
        ];
    }
}

Error Handling

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);
}

Gotchas and Tips

Pitfalls

1. Token Expiry

  • Twitch access tokens expire after 1 hour (or 60 days for offline tokens).
  • Fix: Implement token refresh logic:
    try {
        $client->getUserById('12345678');
    } catch (\NickLaw5\TwitchAPI\Exception\UnauthorizedException $e) {
        $token = $client->refreshAccessToken();
        session(['twitch_token' => $token]);
        retry(); // Retry the failed request
    }
    

2. Rate Limits

  • Twitch enforces 800 requests/10 minutes for most endpoints.
  • Fix: Use Laravel's 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();
    }
    

3. Webhook Verification

  • Always verify Twitch webhook payloads using the 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
    }
    

4. Deprecated Endpoints

  • The package primarily supports Helix API (recommended), but some Kraken endpoints may still exist.
  • Tip: Check the Twitch API docs for deprecations.

Debugging Tips

1. Enable Debug Mode

$client = new Client(..., ..., ..., [
    'debug' => true, // Logs HTTP requests/responses
]);

2. Log Raw Responses

Use Laravel's logging to inspect API responses:

$response = $client->getHelixEndpoint('streams');
\Log::debug('Twitch API Response', ['data' => $response->data]);

3. Common HTTP Errors

  • 401 Unauthorized: Token expired or invalid.
  • 403 Forbidden: Missing scopes or insufficient permissions.
  • 404 Not Found: Resource doesn’t exist (e.g., offline stream).
  • 429 Too Many Requests: Hit rate limits.

Extension Points

1. Custom Endpoints

Extend the client for unsupported endpoints:

$client->getHelixEndpoint('custom', [
    'method' => 'GET',
    'path' => '/custom/path',
    'params' => ['param1' => 'value'],
]);

2. Middleware for Requests

Add middleware to modify requests (e.g., headers):

$client->addMiddleware(function ($request) {
    $request->headers->set('X-Custom-Header', 'value');
});

3. Mocking for Tests

Use Laravel's Mockery to mock the client:

$mock = Mockery::mock(Client::class);
$mock->shouldReceive('getUserById')
     ->once()
     ->andReturn((object)['data' => (object)['display_name' => 'TestUser']]);

4. Event Listeners

Dispatch Laravel events for Twitch actions (e.g., new subscriber):

event(new TwitchSubscriberEvent($subscriberData));
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc