zairakai/laravel-twitch

Complete Twitch API integration package with OAuth, EventSub, badges system and event-driven architecture

Maintainers

Package info

gitlab.com/zairakai/php-packages/laravel-twitch

Issues

Documentation

pkg:composer/zairakai/laravel-twitch

Transparency log

Fund package maintenance!

Patreon

Other

Statistics

Installs: 11

Dependents: 0

Suggesters: 0

Stars: 0

v3.1.0 2026-08-11 10:45 UTC

This package is auto-updated.

Last update: 2026-08-11 08:50:11 UTC


README

Main Develop Coverage

GitLab Release Packagist Downloads License

PHP Laravel Static Analysis Code Style

Complete Twitch API integration for Laravel: OAuth, Helix API, EventSub webhooks, and a badges system.

Features

  • Helix API — games, streams, users, clips, channels, search, and more via Twitch facade
  • OAuth 2.0 — authorization code flow, token refresh, and PKCE support via TwitchOAuth facade
  • EventSub — subscribe to and handle Twitch webhook events with signature verification
  • Badges system — fetch, cache, and display global and channel emote/badge sets
  • Event-driven — Laravel events dispatched for every received EventSub notification
  • Token management — automatic token refresh and storage

Install

composer require zairakai/laravel-twitch

Publish the config:

php artisan vendor:publish --tag=config

Add your credentials to .env:

TWITCH_CLIENT_ID=your_client_id
TWITCH_CLIENT_SECRET=your_client_secret
TWITCH_REDIRECT_URI=https://your-app.com/auth/twitch/callback
TWITCH_WEBHOOK_SECRET=your_webhook_secret

Usage

Helix API

use Zairakai\LaravelTwitch\Facades\Twitch;

// Get top games
$games = Twitch::getTopGames();

// Get streams by user ID(s)
$streams = Twitch::getStreams(userIds: ['12345', '67890']);

// Get users by login(s) or ID(s)
$users = Twitch::getUsers(logins: 'username');

// Get the currently authenticated user (after setAccessToken)
$me = Twitch::getAuthenticatedUser();

// Search channels
$results = Twitch::searchChannels('gaming');

OAuth

use Zairakai\LaravelTwitch\Facades\TwitchOAuth;

// Redirect to Twitch authorization
$authUrl = TwitchOAuth::getAuthorizationUrl(['user:read:email', 'channel:read:subscriptions']);
return redirect($authUrl);

// Exchange code for token (in callback controller)
$token = TwitchOAuth::getAccessToken(request('code'));

// Refresh token
$newToken = TwitchOAuth::refreshToken($refreshToken);

EventSub

// Subscribe to events (webhook transport)
Twitch::createEventSubSubscription(
    type: 'stream.online',
    condition: ['broadcaster_user_id' => $broadcasterId],
    callbackUrl: route('twitch.webhook'),
    secret: config('twitch.eventsub.webhook_secret'),
);

// Handle webhooks — in routes/web.php
Route::post('/twitch/webhook', [TwitchAuthController::class, 'webhook']);

// Listen to dispatched Laravel events (string-based, one event per subscription type)
// Every notification is typed: mapped types get a dedicated DTO, everything else
// gets GenericEventSubEvent - no notification is ever silently dropped or untyped.
Event::listen('twitch.channel.follow', function (string $name, array $payload) {
    /** @var \Zairakai\LaravelTwitch\Dto\EventSub\Events\ChannelFollowEvent $event */
    $event = $payload[0];
    // handle the typed follow event
});

// Hypothetical type Twitch hasn't invented yet, to illustrate the fallback -
// every type Twitch currently documents (76) already has a dedicated DTO.
Event::listen('twitch.channel.some_future_type', function (string $name, array $payload) {
    /** @var \Zairakai\LaravelTwitch\Dto\EventSub\Events\GenericEventSubEvent $event */
    $event = $payload[0]; // no dedicated DTO yet - raw payload via ->payload
});

All 76 EventSub subscription types Twitch documents are mapped to a dedicated DTO (Dto/EventSub/Events/*), each verified field-by-field against the official example payload. Any subscription type Twitch adds after this map was generated still dispatches a typed GenericEventSubEvent (type + raw payload) until it earns its own DTO - add a new DTO class and register it in EventSubEventFactory::TYPE_MAP to give it structure.

Nested structures follow the same rule as the top-level DTOs - one class per shape, reused wherever the exact same shape repeats (e.g. EventSubUserReference, ChatBadge, RewardLimitSetting, CharityAmount), a dedicated class where it doesn't (e.g. ModerateBanAction vs ModerateTimeoutAction). A handful of fields whose shape isn't confirmed by any fetched example (channel.chat.notification's unraid/charity_donation/modiversary, automod message fragments) are kept as documented array rather than guessed.

A few types deserve a note:

  • channel.moderate and channel.chat.notification are discriminated-union events - Twitch populates exactly one of several optional fields depending on a discriminator field (action / notice_type), the rest are always null.
  • channel.channel_points_custom_reward_redemption.add and .update share one DTO (ChannelPointsRedemptionEvent) - identical shape, only status differs.
  • channel.follow requires subscribing at version 2 (not the package default 1).

Configuration

Key options in config/twitch.php:

KeyDescription
client_idTwitch application client ID
client_secretTwitch application client secret
redirect_uriOAuth callback URL
webhook_secretSecret for EventSub signature verification
cache_ttlTTL in seconds for API response caching

Development

make quality        # pint + phpstan + rector + insights + markdownlint + shellcheck
make quality-fast   # pint + phpstan + markdownlint
make test           # phpunit / pest
make docs           # generate browsable API docs (phpDocumentor) into build/docs, alias: make doc

make docs (or make doc) downloads phpDocumentor (pinned version, cached in build/, gitignored) and generates a full class reference from the source itself - including every EventSub DTO and how they nest - so it can never drift from the code the way a hand-maintained type catalog would. Nothing is committed or published - open build/docs/index.html locally after running it.

Getting Help

License Security Policy Issues

Made with ❤️ by Zairakai