PHP API call works - but not with scope

Hey!

With PHP-Files from BarryCarlyon (twitch_misc/authentication/app_access_tokens/php at main · BarryCarlyon/twitch_misc · GitHub) I’ve managed to make API calls like

<?php

include(__DIR__ . '/config.php');

$ch = curl_init('https://id.twitch.tv/oauth2/token?client_id=' . CLIENT_ID . '&client_secret=' . CLIENT_SECRET . '&grant_type=client_credentials');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);

$r = curl_exec($ch);
$i = curl_getinfo($ch);
curl_close($ch);

if ($i['http_code'] == 200) {
    $keys= json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        echo 'Got token';

        $ch = curl_init('https://api.twitch.tv/helix/chat/emotes?broadcaster_id=xxxxx');
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);		
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Client-ID: ' . CLIENT_ID,
            'Authorization: Bearer ' . $keys->access_token,
			'Content-Type: application/json'
        ));

        $r = curl_exec($ch);
        $i = curl_getinfo($ch);
        curl_close($ch);

        if ($i['http_code'] == 200) {
            // created sub OK
           echo 'created sub OK';
		   print_r($r);
		   echo json_encode($r, JSON_PRETTY_PRINT);
        } else {
           echo 'failed to create zeug: ' . $r;
        }
    } else {
        echo 'Failed to parse JSON';
    }
} else {
    echo 'Failed with ' . $i['http_code'] . ' ' . $r;
}

But all API calls which needs a scope I have no clue where to add the scope for eaxmple bits:read.

Thanks for your help

Scopes are applied to the URL that users click to provide an access token to grant access to their account.

Your code generates an app access token/client credentials which (generally speaking) is only good for “public data”

So to get private (scoped) data, you need to get permission from that user.
Which involves the following steps:

  • send the user you want to access on behalf of to your webpage.
  • user clicks a link that takes then to twitch with the scopes in the request
  • user accepts (or decliens) their account linking to your clientID
  • user comes back to your site with a ?code= you exchange the code for an access (and refresh token)

You now have a scoped user access token.

see also

Docs: Getting OAuth Access Tokens | Twitch Developers
PHP Example: twitch_misc/authentication/user_access_generator/php at main · BarryCarlyon/twitch_misc · GitHub

1 Like