title: OAuth2 Token PHP
body: <p>I need to connect with an API that is using oAuth2.
  I have never used oAuth2 before and im not really sure how to.
  The provider is giving this information:</p>
  
  <p>Obtaining an access token is done by sending an HTTP POST request to the above endpoint. The request should contain the following headers:</p>
  
  <pre><code>Authorization: Basic [client_id]:[client_secret]
  Content-Type: application/x-www-form-urlencoded
  </code></pre>
  
  <p>Where <code>[client_id]</code> and <code>[client_secret]</code> should be replaced with your information. The composed <code>[client_id]:[client_secret]</code> string should be base64 encoded.</p>
  
  <p>The header should look something like this: </p>
  
  <pre><code>Authorization: Basic bXlfY2xpZW50X2lkOnBFUnkyTGhLYko0U2FkY3ZLcklpQW5xWnprakg5bm9STUc3aUxZcWl2MA==
  </code></pre>
  
  <p>Finally, you need the following request body:</p>
  
  <pre><code>grant_type=password&amp;scope=read write&amp;username=[username]&amp;password=[password]
  </code></pre>
  
  <p>Where [username] and [password] should be replaced with your credentials. If you are accessing the API with an API-key you should replace both [username] and [password] with the API-key obtained above.</p>
  
  <p>If your request was composed correctly, and your credentials were correct, the server will return an access_token in JSON format for you to use:</p>
  
  <pre><code>{
      "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9(...)",
      "token_type":"Bearer",
      "expires_in":3600,
      "refresh_token":null
  }
  </code></pre>
  
  <p>What I tried is the following, but it returns an invalid request message:</p>
  
  <pre><code>    $api = "KEY GOES HERE";
  $authurl = "https://url.com/oauth/token";
  
  $client_id = "ID GOES HERE";
  $client_secret = "SECRET GOES HERE";
  
  // Creating base 64 encoded authkey
  $Auth_Key = $client_id.":".$client_secret;
  $encoded_Auth_Key=base64_encode($Auth_Key);
  
  $headers = array();
  $headers['Authorization'] = "Basic ".$encoded_Auth_Key;
  $headers['Content-Type'] = "application/x-www-form-urlencoded";
  
  $data = "grant_type=password&amp;scope=read write&amp;username=".$api."&amp;password=".$api."";
  
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $authurl);
  curl_setopt($ch, CURLOPT_POST, 1 );
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  
  $auth = curl_exec( $ch );
  
  if ( curl_errno( $ch ) ){
      echo 'Error: ' . curl_error( $ch );
  }
  curl_close($ch);
  
  $secret = json_decode($auth);
  $access_key = $secret-&gt;access_token;
  </code></pre>