Twitch API Integration with Website
Twitch API (Helix) is used for displaying stream status, embedding players, verifying channel subscribers, and authorization via Twitch. Relevant for gaming sites, streamer communities, and fan services.
Authentication (App Access Token)
async function getTwitchToken(): Promise<string> {
const resp = await fetch('https://id.twitch.tv/oauth2/token', {
method: 'POST',
body: new URLSearchParams({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'client_credentials',
}),
});
const data = await resp.json();
return data.access_token;
}
Stream Status
async function getStreamStatus(channelName: string): Promise<StreamStatus | null> {
const token = await getTwitchToken();
const resp = await fetch(
`https://api.twitch.tv/helix/streams?user_login=${channelName}`,
{
headers: {
'Authorization': `Bearer ${token}`,
'Client-Id': CLIENT_ID,
},
}
);
const data = await resp.json();
const stream = data.data[0];
if (!stream) return null;
return {
isLive: true,
title: stream.title,
game: stream.game_name,
viewers: stream.viewer_count,
startedAt: stream.started_at,
thumbnail: stream.thumbnail_url.replace('{width}', '640').replace('{height}', '360'),
};
}
Player Embedding
<!-- Twitch Embed -->
<div id="twitch-player"></div>
<script src="https://player.twitch.tv/js/embed/v1.js"></script>
<script>
new Twitch.Embed('twitch-player', {
channel: 'channel_name',
width: '100%',
height: 480,
parent: ['example.com'], // domain is required
autoplay: false,
muted: false,
});
</script>
OAuth2: Authorization via Twitch + Subscription Check
// Check if user is subscribed to the channel
public function checkSubscription(string $userToken, string $broadcasterId): bool
{
$user = Http::withToken($userToken)
->withHeaders(['Client-Id' => config('services.twitch.client_id')])
->get('https://api.twitch.tv/helix/users')
->json('data.0');
$sub = Http::withToken($userToken)
->withHeaders(['Client-Id' => config('services.twitch.client_id')])
->get('https://api.twitch.tv/helix/subscriptions/user', [
'broadcaster_id' => $broadcasterId,
'user_id' => $user['id'],
]);
return $sub->status() === 200;
}
EventSub for Notifications
Twitch EventSub allows receiving webhook notifications about stream start/end:
// Subscribe to stream.online event
Http::withToken($appToken)
->withHeaders(['Client-Id' => CLIENT_ID])
->post('https://api.twitch.tv/helix/eventsub/subscriptions', [
'type' => 'stream.online',
'version' => '1',
'condition' => ['broadcaster_user_id' => $broadcasterId],
'transport' => [
'method' => 'webhook',
'callback' => 'https://example.com/webhooks/twitch',
'secret' => config('services.twitch.webhook_secret'),
],
]);
Implementation time: 2–3 business days.







