I’m using CURL to get access token and refresh token.
Now i have 2 functions:
public function handle_google_oauth_request() {
if (isset($_POST['authorize'])) {
$auth_url = 'https://accounts.google.com/o/oauth2/auth?';
$auth_url .= 'client_id=' . urlencode($this->client_id);
$auth_url .= '&redirect_uri=' . urlencode($this->redirect_uri);
$auth_url .= '&scope=' . urlencode($this->scope);
$auth_url .= '&response_type=code';
wp_redirect($auth_url);
exit;
}
}
public function handle_google_code() {
if (isset($_GET['code'])) {
$code = $_GET['code'];
$url = 'https://oauth2.googleapis.com/token';
$params = array(
'code' => $code,
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->redirect_uri,
'grant_type' => 'authorization_code',
);
$params_string = http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
$response = curl_exec($ch);
curl_close($ch);
if ($response === false) {
echo 'cURL error: ' . curl_error($ch);
} else {
$token_data = json_decode($response, true);
if (isset($token_data['access_token'])) {
$access_token = $token_data['access_token'];
update_option('google_access_token', $access_token);
}
}
}
}
In result – i can take access token from my handle_google_code function. But i can’t get refresh token.
Does anyone have any ideas to solve this problem?
I know that i need to add 2 parameter in $auth_url:
$auth_url .= '&prompt=consent';
$auth_url .= '&access_type=offline';
But in result – i take error invalid_grant Bad Request.
I also tried to get a refresh token by deleting my application from account access rights and getting a token again, this also did not help.
2
Answers
i found a solution. If i add
die()
in the end of handle_google_code function. - It's works.For some reason the function is executed twice. After much manipulation I could not find the reason for this behavior. But in the end I was able to get the token... Thank you!
I’m going to take a guess that the client type you created was a web client. Web clients only return the refresh token the first time the user authorizes them. Google expects you to store it.
Go to the users account under third party applications and remove the access it will then request you to authorize it again.
Or you can take the access token you have and send a request to the revoke end point that will also remove access.
Then try again you should get a new refresh token.
offline access
I also think your missing access_type
if you add access_type=offline you should get a refresh token back
see web-server#creatingclient