PHP Authentication Basic Setup


I am not very familiar with the Twitch API and I’m no PHP expert, I’d appreciate any help.

I am currently trying to set up authentication/authorization with the Twitch API in PHP using the following documentation:

I was able to connect and generate authentication code with using the following PHP/Javascript:

$auth_token = "' 
    window.location = <?php echo($auth_token) ?>;
//Twitch then redirects back to my application and I have the code
      $user_code = $_GET["code"];

After I have the code I need for step 2 in the documentation I use the following PHP to try to POST to complete step 3:

  $url = '';
  $fields = array(
    'client_id' => $auth_client_id,
    'client_secret' => $auth_client_secret,
    'grant_type' => 'authorization_code',
    'redirect_uri' => $auth_redirect_uri,
    'code' => $user_code,
    'state' => null
  // use key 'http' even if you send the request to https://...
  $options = array(
      'http' => array(
          'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
          'method'  => 'POST',
          'content' => http_build_query($fields),
  $context  = stream_context_create($options);
  $result = file_get_contents($url, false, $context);


At this point I am lost, the PHP response generates the following error:

Warning: file_get_contents( failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

All I want to do is allow users to connect their twich accounts with my web app and use it for login/authentication purposes. Can anyone point me in the right direction?

Thank you in advance.

Hi Dreink!

I’m also a bit new to the Twitch API, but I think you need to change your header.

According to Twitch API MIME types, ( you should use the following as header. (Not sure if this solve your problem tho).


What I would suggest is to use cURL instead to make a HTTP request.

A simple cURL request would look like the following:

$curl = curl_init();
	$arr = array(
		'client_id' => 'Client_id',
		'client_secret' => 'Client_secret',
		'grant_type' => 'authorization_code', //Do not change this
		'redirect_uri' => 'Redirect_uri',
		'code' => $user_code,
                'state' => NULL
	curl_setopt_array($curl, array(
		CURLOPT_URL => '',
        $resp = curl_exec($curl);

(Not sure if above really works, but it should - have not tried it out yet in PHP)

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