This seems to be a misunderstanding of how to implement OAuth 2.0.
This step-by-step instruction is a summary of the site I've linked:
- create a client id for web application in the developer console
- make your user go to the auth url
- when he/she completed the process, the user will be redirected to the redirect uri you specified.
- on this page, your php script has to grab the
- next, you have to make a request (containing the code) to a page which provides you with an access token and a refresh token. An access token expires after 1h, then you have to get a new one with your refresh token
- once you have the access token, you can start making api requests
On the website linked at the top, you'll find detailed instructions. Hope this helps :)
In order to exchange the code for the tokens, you have to perform a post request. I don't think that'l work with
file_get_contents. I recommend using curl here.
This code should work for you, but it's not tested:
$url = 'https://accounts.google.com/o/oauth2/token'; $postfields = [ 'code'=>'YOUR_CODE', 'client_id'=>'YOUR_CLIENT_ID', 'client_secret'=>'YOUR_CLIENT_SECRET', 'redirect_uri'=>'YOUR_REDIRECT_URI', 'grant_type'=>'authorization_code' ]; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_POST, count($postfields)); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postfields)); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response);
$response now is an associative array with the keys
access_token, token_type, expires_in, refresh_token.
token_type is always
expires_in is always
3600. The other two are the important ones and you should store them safely!
You can find your client id and client secret in the developer console.
But please note that in this example, the ssl verification is disabled. That means your connection is not safe.