zairakai / laravel-twitch
Complete Twitch API integration package with OAuth, EventSub, badges system and event-driven architecture
Requires
- php: ^8.4
- guzzlehttp/guzzle: ^7.8
- laravel/framework: ^12.0 || ^13.0
- spatie/laravel-data: ^4.0
Requires (Dev)
- driftingly/rector-laravel: ^2.1
- ergebnis/composer-normalize: ^2.49
- larastan/larastan: ^3.9
- laravel/pint: ^1.27
- mockery/mockery: ^1.6
- nunomaduro/phpinsights: ^2.13
- orchestra/testbench: ^10.0 || ^11.0
- phpmetrics/phpmetrics: ^2.9
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.0
- rector/rector: ^2.3
- zairakai/laravel-dev-tools: ^2.0
Suggests
- ergebnis/composer-normalize: Automated composer.json normalization
README
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
Twitchfacade - OAuth 2.0 — authorization code flow, token refresh, and PKCE support via
TwitchOAuthfacade - 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.moderateandchannel.chat.notificationare discriminated-union events - Twitch populates exactly one of several optional fields depending on a discriminator field (action/notice_type), the rest are alwaysnull.channel.channel_points_custom_reward_redemption.addand.updateshare one DTO (ChannelPointsRedemptionEvent) - identical shape, onlystatusdiffers.channel.followrequires subscribing at version2(not the package default1).
Configuration
Key options in config/twitch.php:
| Key | Description |
|---|---|
client_id | Twitch application client ID |
client_secret | Twitch application client secret |
redirect_uri | OAuth callback URL |
webhook_secret | Secret for EventSub signature verification |
cache_ttl | TTL 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
Made with ❤️ by Zairakai