Reputation: 1559
Hello im having this problem. Im working with google Gmail Api. I did every thing on my own server it is working fine. I uploaded to another one but i get this error Fatal error: Uncaught Error: Call to undefined method Google_Client::fetchAccessTokenWithAuthCode(). Here is my function
<?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
}
Upvotes: 1
Views: 6312
Reputation: 11
fetchAccessTokenWithAuthCode() has been added in version 1.1.16, what version do you run in production? – Dygnus Apr 21 '17 at 21:28
After you've checked your version.
You could also try it with:
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
A similar problem is also mentioned here: https://github.com/googleapis/google-api-php-client/issues/1204.
Upvotes: 1