Twitch API authentication with OAuth using PHP

From May 11th 2020 Twitch has implemented OAuth to its helix API version, now instead of just needing the client id key to make API calls you also need to authenticate with OAuth too.

Using the Twitch API is still straight forward except OAuth access tokens do expire and will need refreshes after a period of time.

For this post I will be using the doCurl function that is found here.

Getting authorization code

The first step is getting the authorization code, which is eventually used to get the OAuth access token.

Doing this is done by visiting a URL that you must build first.

You will need your client id, redirect URI and the scope.

Get your client id, client secret and redirect URI by creating an “app” at the Twitch dev portal here.

The redirect URI is what the user gets redirected to after authorizing your app, if you’re building a project that only you will be using just set this to that projects directory or localhost it doesn’t matter.

Scope is the permission you’re authorizing for, see here for the list of possible scopes.

Put the URL into your browser and accept the terms for the apps access, then you will be redirected. Check the webpage address to find your code.

It will be like:


Getting access token

Now do a POST request using your newly obtained code to find the access token and refresh token.

Using the doCurl function:

echo doCurl('', 'POST');

Make sure to put in your client id, client secret, authorization code and redirect URI.

Upon success it will return:


Here is your access token, refresh token and the access tokens expiration time in seconds.

Making an API call

Making a call is done by adding a header for Authorization: Bearer ACCESS_TOKEN_HERE alongside the existing client id header Client-ID: CLIENT_ID_HERE

Using the doCurl function:

echo doCurl('', 'GET', array('Authorization: Bearer ACCESS_TOKEN_HERE','Client-ID: CLIENT_ID_HERE'));

Add in your access token and client id, upon success it will show the top 25 streams at the current time.

Refreshing token

If you had your authorization working and get this response:

"message":"Invalid OAuth token"

Good chance your access token is expired and you can now refresh it.

Refreshing is done by doing a POST request:

echo doCurl('', 'POST');

Using your refresh token, client id and client secret, on success it will return data like:

  "access_token": "XXX",
  "refresh_token": "XYZ",
  "scope": "viewing_activity_read"

Now you can take down your new access and refresh token to continue your API calls.

Here is a post I made on automating OAuth token refresh.

Official documentation/helpful links:

Twitch OAuth announcment

Twitch docs getting OAuth token

Twitch docs sending access token

Twitch docs refreshing access tokens