我的目標是設法使用Google API,特別是在這裏我需要使用Gmail API發送電子郵件。 我在數據庫中保存了第一次登錄(使用Gmail憑據)時從Google Server發給我的'refresh_token',現在,如同寫入指南一樣,似乎我必須執行服務器請求(我使用PHP)到谷歌服務器,如下所示。如何使用存儲的refresh_token或密碼在PHP中發送請求到谷歌服務器?
[我也看了這裏:
https://developer.salesforce.com/forums/?id=906F00000008tKWIAY https://developers.google.com/identity/protocols/OAuth2InstalledApp#formingtheurl ]
我的代碼如下:
$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);
而我得到的答案是一樣的東西(使用密碼) :
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
或(使用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
我的代碼的其餘部分使用:
$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');
出了什麼問題?
謝謝阿比爾。我指定了脫機類型,但仍然是相同的錯誤。 – cris