"401 Unauthorized" despite access token being passed

Hey everyone,

I’m trying to retrieve all videos of a channel through the API. I’m accessing the API with PHP and it’s supposed to be a cron once it works, so I’m using the OAuth authorization code flow to get my access token:

$curl = curl_init('https://id.twitch.tv/oauth2/token?client_id='.TWITCH_CLIENT_ID.'&client_secret='.TWITCH_CLIENT_SECRET.'&grant_type=client_credentials');

curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$curl_res = curl_exec($curl);
curl_close($curl);

As far as I can tell, the above code is correct, because I get the following response:

{
    "access_token" : "abcdefgh12345678",
    "expires_in" : 1234567,
    "token_type" : "bearer"
}

I store the access token in TWITCH_ACCESS_TOKEN:

define('TWITCH_ACCESS_TOKEN', $curl_res['access_token']);

And then I do basically the same thing to get the videos (currently with the video-id from the docs to test):

$curl = curl_init('https://api.twitch.tv/helix/videos?id=234482848');

curl_setopt($curl, CURLOPT_HEADER, array(
    'Authorization: Bearer '.TWITCH_ACCESS_TOKEN,
    'Client-ID: '.TWITCH_CLIENT_ID
));

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$curl_res = curl_exec($curl);
curl_close($curl);

But I only get the following response:

{
    "error" : "Unauthorized",
    "status" : 401,
    "message" : "OAuth token is missing"
}

To me it sounds like there’s no access token, but I do provide the token (unless the token I receive is wrong?).

Already tried changing the authorization from Bearer to OAuth, but that didn’t change anything.
Switching to a POST request only made things worse (404 Not Found instead of 401 Unauthorized).

Any ideas? So far I wasn’t able to find anything useful in the docs or in any of the forums I could find. :confused:

Thanks,
Alex

Found the fix on another API-related issue and now it works. Thanks to @BarryCarlyon! :slight_smile:

For other people with the same issue:

curl_setopt($curl, CURLOPT_HEADER, array(
    'Authorization: Bearer '.TWITCH_ACCESS_TOKEN,
    'Client-ID: '.TWITCH_CLIENT_ID
));

has to be:

curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer '.TWITCH_ACCESS_TOKEN,
    'Client-ID: '.TWITCH_CLIENT_ID
));
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.