你好我有这个问题。我正在使用谷歌Gmail Api。我在自己的服务器上做了所有事情它工作正常。我上传到另一个,但我收到此错误致命错误:未捕获错误:调用未定义的方法Google_Client :: fetchAccessTokenWithAuthCode()。这是我的功能
<?php
require __DIR__ .'/../../vendor/autoload.php';
use Google_Client as GoogleClient;
public function getClient()
{
$client = new GoogleClient();//Call the google client
$client->setApplicationName($this->projectName);//Set project name
$client->setScopes(
[
'https://mail.google.com/',
]
);//Set Scopes
$client->setAuthConfig($this->jsonKeyFilePath);//Set Application credentials get from Google console developers
$client->setRedirectUri($this->redirectUri);//Set redirect Url
$client->setAccessType('offline');//Set offline mode to get refresh token. Usefull for cron task
$client->setApprovalPrompt('force');//Force Api to return Refresh token as sometimes it may not return
// Load previously authorized credentials from a file.
if (file_exists($this->tokenFile)) {
$accessToken = json_decode(file_get_contents($this->tokenFile), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
//Check the unique code returned by Google Auth
if (isset($_GET['code'])) {
$authCode = $_GET['code'];
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
header('Location: ' . filter_var($this->redirectUri, FILTER_SANITIZE_URL));
//Create file where token will be stored if not exist
if(!file_exists(dirname($this->tokenFile))) {
mkdir(dirname($this->tokenFile), 0700, true);
}
//Save returned tokens to file for next operations on behalf of user
file_put_contents($this->tokenFile, json_encode($accessToken));
}else{
//If google didnt return the auth code
exit('No code found');
}
}
//Set the token
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
// save refresh token to some variable
$refreshTokenSaved = $client->getRefreshToken();
// update access token
$client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
// pass access token to some variable
$accessTokenUpdated = $client->getAccessToken();
// append refresh token
$accessTokenUpdated['refresh_token'] = $refreshTokenSaved;
// save to file
file_put_contents($this->tokenFile, json_encode($accessTokenUpdated));
}
return $client;//return client
}
答案 0 :(得分:0)
在版本1.1.16中添加了fetchAccessTokenWithAuthCode(),您在生产环境中运行什么版本? – Dygnus 17年4月21日在21:28
检查版本后。
您也可以尝试:
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
这里也提到了类似的问题:https://github.com/googleapis/google-api-php-client/issues/1204。