diegobtrindade
diegobtrindade

Reputation: 1

PHP get Twitch account stream key

I would like to know how I get and generate a new stream key from my twitch.tv account.

$clientId = "";
$clientSecret = "";
$channelName = "";
$channelId = "";

$url = "https://id.twitch.tv/oauth2/token";
$data = array(
    "client_id" => $clientId,
    "client_secret" => $clientSecret,
    "grant_type" => "client_credentials"
);

$options = array(
    "http" => array(
        "header" => "Content-type: application/x-www-form-urlencoded\r\n",
        "method" => "POST",
        "content" => http_build_query($data),
    ),
);

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$data = json_decode($response, true);
$accessToken = $data["access_token"];

// ...

I already got the access token, but I don't know which url to access to get or generate a new key in my account...

I tried to get the Twitch stream key via API and failed.

Upvotes: -1

Views: 169

Answers (2)

violetflare
violetflare

Reputation: 103

You must make sure you're using the user access token and not the app access token.

Upvotes: 0

Mehdi
Mehdi

Reputation: 756

there is an endpoint for getting the stream key: Get Stream Key. This endpoint returns the channel’s stream key. You need to pass your channel ID as a parameter and use your access token as a header. The URL for this endpoint is:

https://api.twitch.tv/helix/streams/key?broadcaster_id={channelId}

You can use the following code snippet to call this endpoint and get your stream key:

$url = "https://api.twitch.tv/helix/streams/key?broadcaster_id=" . $channelId;
$headers = [
    "Authorization: Bearer " . $accessToken,
    "Client-Id: " . $clientId
];

$options = [
    "http" => [
        "header" => implode("\r\n", $headers),
        "method" => "GET"
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$data = json_decode($response, true);
$streamKey = $data["data"][0]["stream_key"];

Upvotes: 1

Related Questions