My goal is to manage to use the Google APIs in general, in particular here i need to send emails using Gmail API. I saved in the DB the 'refresh_token' given to me from Google Server the first time i did the login (using Gmail credentials), and now, as written into the guides, it seems that I have to do a server request (I'm using PHP) to the google server like the following.
[I looked also here:
https://developer.salesforce.com/forums/?id=906F00000008tKWIAY https://developers.google.com/identity/protocols/OAuth2InstalledApp#formingtheurl ]
My code is the following:
$data = //'grant_type=refresh_token'.
//'&refresh_token='.$refreshtoken; (first option)
'&grant_type=password'.
'&username=mygmail'.
'&password=mypasswordgmail'; (second option)
'&client_id='."xxx".
'&client_secret='."yyy".
$additional_headers = array('Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($token_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $additional_headers);
$server_output = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $status != 200 )
{
echo 'token_url: '.$token_url."<br>";
echo 'params: '.$data."<br><br>";
echo 'response: '.$server_output."<br>";
die("Error: call to URL $token_url failed with status $status<br>");
}
curl_close($ch);
And what I get as an answer is something like (using password):
response: { "error": "unsupported_grant_type", "error_description": "Invalid grant_type: password" }
Error: call to URL https://www.googleapis.com/oauth2/v4/token failed with status 400
Or (using the refresh_token):
response: { "error": "invalid_grant", "error_description": "Bad Request" }
Error: call to URL https://www.googleapis.com/oauth2/v4/token failed with status 400
I use this in the rest of the code:
$guzzleClient = new \GuzzleHttp\Client(array('curl' => array(CURLOPT_SSL_VERIFYPEER => false, ), ));
$redirectUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$gclient = new Google_Client();
$gclient->setHttpClient($guzzleClient);
$gclient->setAuthConfig('client_secret/client_secret.json');
$gclient->setRedirectUri($redirectUri);
$gclient->setAccessType('offline');
$gclient->setApprovalPrompt('force');
$gclient->addScope("https://mail.google.com/");
$gclient->addScope("https://www.googleapis.com/auth/gmail.compose");
$gclient->addScope("https://www.googleapis.com/auth/gmail.modify");
$gclient->addScope("https://www.googleapis.com/auth/gmail.readonly");
$gclient->addScope('https://www.googleapis.com/auth/userinfo.email');
$gclient->addScope('https://www.googleapis.com/auth/userinfo.profile');
what's wrong??