How to Get Google Drive Refresh Token and Access Token Using PHP cURL
In this tutorial, I will show how to generate a Google Drive refresh token and use that refresh token to get a new access token using PHP cURL. This method is useful when you want to connect your PHP application with Google Drive API for file upload, file copy, file download, or automation tasks.
This script does two main things:
- Redirects the user to Google OAuth login page
- Exchanges authorization code for refresh token
- Uses refresh token to generate access token anytime
Complete PHP Code
<?php
function getRefreshToken($authCode) {
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$clientSecret = "YOUR_GOOGLE_CLIENT_SECRET";
$redirectUri = "https://yourdomain.com/token.php";
$tokenUrl = "https://oauth2.googleapis.com/token";
$postData = [
"code" => $authCode,
"client_id" => $clientId,
"client_secret" => $clientSecret,
"redirect_uri" => $redirectUri,
"grant_type" => "authorization_code"
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
if (isset($response['refresh_token'])) {
return $response['refresh_token'];
} else {
return "Error: Failed to get refresh token.";
}
}
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$redirectUri = urlencode("https://yourdomain.com/access-token.php");
$authUrl = "https://accounts.google.com/o/oauth2/auth?client_id=$clientId&redirect_uri=$redirectUri&response_type=code&scope=https://www.googleapis.com/auth/drive&access_type=offline&prompt=consent";
header("Location: $authUrl");
exit;
function getAccessToken($refreshToken) {
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$clientSecret = "YOUR_GOOGLE_CLIENT_SECRET";
$tokenUrl = "https://oauth2.googleapis.com/token";
$postData = [
"client_id" => $clientId,
"client_secret" => $clientSecret,
"refresh_token" => $refreshToken,
"grant_type" => "refresh_token",
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response['access_token'] ?? null;
}
?>
What This Code Does
1. Redirect User to Google OAuth Page
This part sends the user to Google’s login and permission page:
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$redirectUri = urlencode("https://yourdomain.com/token.php");
$authUrl = "https://accounts.google.com/o/oauth2/auth?client_id=$clientId&redirect_uri=$redirectUri&response_type=code&scope=https://www.googleapis.com/auth/drive&access_type=offline&prompt=consent";
header("Location: $authUrl");
exit;
Important values:
response_type=codemeans Google will return an authorization codescope=https://www.googleapis.com/auth/drivegives full Drive accessaccess_type=offlineis required to get a refresh tokenprompt=consentforces Google to show the permission screen and return refresh token
2. Exchange Authorization Code for Refresh Token
After Google redirects back to your callback URL with a code, this function exchanges it for a refresh token:
function getRefreshToken($authCode) {
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$clientSecret = "YOUR_GOOGLE_CLIENT_SECRET";
$redirectUri = "https://yourdomain.com/token.php";
$tokenUrl = "https://oauth2.googleapis.com/token";
$postData = [
"code" => $authCode,
"client_id" => $clientId,
"client_secret" => $clientSecret,
"redirect_uri" => $redirectUri,
"grant_type" => "authorization_code"
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
if (isset($response['refresh_token'])) {
return $response['refresh_token'];
} else {
return "Error: Failed to get refresh token.";
}
}
The refresh token is important because it allows your app to get new access tokens later without asking the user to log in again.
3. Generate Access Token from Refresh Token
Once you already have a refresh token saved, you can use it anytime to get a fresh access token:
function getAccessToken($refreshToken) {
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$clientSecret = "YOUR_GOOGLE_CLIENT_SECRET";
$tokenUrl = "https://oauth2.googleapis.com/token";
$postData = [
"client_id" => $clientId,
"client_secret" => $clientSecret,
"refresh_token" => $refreshToken,
"grant_type" => "refresh_token",
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response['access_token'] ?? null;
}
This access token is then used in Google Drive API requests such as:
- Upload file
- Copy file
- Delete file
- Get metadata
- Download file
Example OAuth Flow
- User opens
token.php - User is redirected to Google login page
- User allows Drive permission
- Google redirects back with authorization code
- Your script exchanges that code for refresh token
- You save refresh token in config or database
- Later you use refresh token to generate access token
Example Callback Handling
You can use this simple callback logic inside your token.php file:
<?php
if (!isset($_GET['code'])) {
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$redirectUri = urlencode("https://yourdomain.com/token.php");
$authUrl = "https://accounts.google.com/o/oauth2/auth?client_id=$clientId&redirect_uri=$redirectUri&response_type=code&scope=https://www.googleapis.com/auth/drive&access_type=offline&prompt=consent";
header("Location: $authUrl");
exit;
}
$authCode = $_GET['code'];
function getRefreshToken($authCode) {
$clientId = "YOUR_GOOGLE_CLIENT_ID";
$clientSecret = "YOUR_GOOGLE_CLIENT_SECRET";
$redirectUri = "https://yourdomain.com/token.php";
$tokenUrl = "https://oauth2.googleapis.com/token";
$postData = [
"code" => $authCode,
"client_id" => $clientId,
"client_secret" => $clientSecret,
"redirect_uri" => $redirectUri,
"grant_type" => "authorization_code"
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response['refresh_token'] ?? 'Failed to get refresh token';
}
echo getRefreshToken($authCode);
?>
Requirements
- PHP with cURL enabled
- Google Cloud project
- OAuth client ID and client secret
- Google Drive API enabled
- Correct redirect URI added in Google Cloud Console
Common Errors
redirect_uri_mismatch
This means the redirect URI in your PHP code does not exactly match the one added in Google Cloud Console.
invalid_client
This means your client ID or client secret is wrong.
Failed to get refresh token
This can happen when:
- You already approved the app before and Google did not issue a new refresh token
access_type=offlineis missingprompt=consentis missing
Important Security Note
- Never publish your real Google client secret in a blog post
- Store client secret in config file outside public web root if possible
- Do not expose refresh token publicly
- Use environment variables or secure config storage in production
Conclusion
In this tutorial, we learned how to get a Google Drive refresh token and how to generate an access token from that refresh token using PHP cURL. This is a very useful setup for any Google Drive automation project, especially if you want long-term access without repeated login.
