title: PHP. How to get the access token. Authenticating with OAuth 2.0 for Google API
body: <p><a href="http://www.jensbits.com/2011/12/20/authenticating-with-oauth-2-0-for-google-api-access-with-php/" rel="nofollow">I found this function</a> that supposedly gets the accessToken, but I get nothing.
  I do have the <code>$_REQUEST['code']</code>, and the other information needed in this function.</p>
  
  <p>Any ideas what is wrong here?
  Thanks.</p>
  
  <pre><code>//Oauth 2.0: exchange token for session token so multiple calls can be made to api
  if(isset($_REQUEST['code'])){
      $_SESSION['accessToken'] = get_oauth2_token($_REQUEST['code']);
  }
  
  //returns session token for calls to API using oauth 2.0
  function get_oauth2_token($code) {
      global $client_id;
      global $client_secret;
      global $redirect_uri;
  
      $oauth2token_url = "https://accounts.google.com/o/oauth2/token";
      $clienttoken_post = array(
      "code" =&gt; $code,
      "client_id" =&gt; $client_id,
      "client_secret" =&gt; $client_secret,
      "redirect_uri" =&gt; $redirect_uri,
      "grant_type" =&gt; "authorization_code"
      );
  
      $curl = curl_init($oauth2token_url);
  
      curl_setopt($curl, CURLOPT_POST, true);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
      curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  
      $json_response = curl_exec($curl);
      curl_close($curl);
  
      $authObj = json_decode($json_response);
  
      if (isset($authObj-&gt;refresh_token)){
          //refresh token only granted on first authorization for offline access
          //save to db for future use (db saving not included in example)
          global $refreshToken;
          $refreshToken = $authObj-&gt;refresh_token;
      }
  
      $accessToken = $authObj-&gt;access_token;
      return $accessToken;
  }
  </code></pre>