I made a function which tries to get access token from refresh token, but i get an error:
Error: Failed to get access token, HTTP code: 401, response: { "error": "unauthorized_client", "error_description": "Unauthorized" }
I tried to test the url with keys on https://reqbin.com/ but there i also get unauthorized.
I tested some code with access token and it works so refresh token should also work.
function get_google_access_token() {
$client_id = 'x';
$client_secret = 'x';
$refresh_token = 'x';
$url = "https://oauth2.googleapis.com/token";
$data = [
"grant_type" => "refresh_token",
"client_id" => $client_id,
"client_secret" => $client_secret,
"refresh_token" => $refresh_token,
];
$options = [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/x-www-form-urlencoded"
],
];
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpcode !== 200) {
throw new Exception("Failed to get access token, HTTP code: $httpcode, response: $response");
}
$result = json_decode($response, true);
if (!isset($result['access_token'])) {
throw new Exception("No access token found in response");
}
return $result['access_token'];
}
try {
$accessToken = get_google_access_token();
echo "Access Token: " . $accessToken;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}