I am trying to use Google APIs with craft cms. To pull data from my calendar from Google. I modify the quickstsrt.php that Google had on Github. That works but when I went to add the code to my Craft plugin it's not able to find the JSON file anymore
I have the same code working outside of craft. I have gone through the google results and was not able to find any solution that would work. it may be the why I authorized my google account but like I said the PHP works outside of craft
public function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig(credentials.json);
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
InvalidArgumentException: file "/home/mesicdev/www/craft/plugins/credentials.json" does not exist in /home/mesicdev/public_html/craft/plugins/calendarpuller/src/services/vendor/google/apiclient/src/Google/Client.php:870
Stack trace:
0 /home/mesicdev/public_html/craft/plugins/calendarpuller/src/services/CalendarService.php(87): Google_Client->setAuthConfig('/home/mesicdev/...')
1 /home/mesicdev/public_html/craft/plugins/calendarpuller/src/services/CalendarService.php(60): campnonet\calendarpuller\services\CalendarService->getClient()
2 /home/mesicdev/public_html/craft/plugins/calendarpuller/src/controllers/CalendarController.php(63): campnonet\calendarpuller\services\CalendarService->getCalendarInfo()
3 [internal function]: campnonet\calendarpuller\controllers\CalendarController->actionDefault(true)
4 /home/mesicdev/public_html/craft/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
5 /home/mesicdev/public_html/craft/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
6 /home/mesicdev/public_html/craft/vendor/craftcms/cms/src/web/Controller.php(109): yii\base\Controller->runAction('default', Array)
7 /home/mesicdev/public_html/craft/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('default', Array)
8 /home/mesicdev/public_html/craft/vendor/craftcms/cms/src/web/Application.php(297): yii\base\Module->runAction('calendar-puller...', Array)
9 /home/mesicdev/public_html/craft/vendor/yiisoft/yii2/web/Application.php(103): craft\web\Application->runAction('calendar-puller...', Array)
10 /home/mesicdev/public_html/craft/vendor/craftcms/cms/src/web/Application.php(286): yii\web\Application->handleRequest(Object(craft\web\Request))
11 /home/mesicdev/public_html/craft/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
12 /home/mesicdev/public_html/craft/web/index.php(21): yii\base\Application->run()
13 {main}
you have an error in this line
$client->setAuthConfig(credentials.json);
This should be a path to a real file.
use this instead:
$client->setAuthConfig("/path/to/credentials.json");
I am wrong for whatever reason I forgot to add the /src folder when typing my path to json Thaks for your help
Related
I've been trying to set up the sample PHP Quickstart.
When I try running it as is I get the following error :
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php:685
Stack trace:
#0 /opt/lampp/htdocs/rev_wip/vendor/google/apiclient/src/Client.php(406): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /opt/lampp/htdocs/rev_wip/quickstart.php(40): Google\Client->createAuthUrl()
#2 /opt/lampp/htdocs/rev_wip/quickstart.php(64): getClient()
#3 {main}
thrown in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php on line 685
So I add a URI :
// $redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
Now I get (when I run it on the browser) :
Authorization Error
Error 400: redirect_uri_mismatch
You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.
If you're the app developer, register the redirect URI in the Google Cloud Console.
Learn more
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you’re the app developer, make sure that these request details comply with Google policies.
redirect_uri: http://localhost/rev_wip/quickstart.php
I am thinking that this example is a Desktop APP and so there should be no Redirect URI. I, however get the common redirect URI error when I run it on the CLI.
How should I go about it?
Thank you all in advance.
Here is the code that I am working with:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName('People API PHP Quickstart');
$client->setScopes(Google_Service_PeopleService::CONTACTS_READONLY);
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = __DIR__ . '/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath) , true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath) , 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_PeopleService($client);
// Print the names for up to 10 connections.
$optParams = array(
'pageSize' => 10,
'personFields' => 'names,emailAddresses',
);
$results = $service
->people_connections
->listPeopleConnections('people/me', $optParams);
if (count($results->getConnections()) == 0) {
print "No connections found.\n";
}
else {
print "People:\n";
foreach ($results->getConnections() as $person) {
if (count($person->getNames()) == 0) {
print "No names found for this connection\n";
}
else {
$names = $person->getNames();
$name = $names[0];
printf("%s\n", $name->getDisplayName());
}
}
}
?>
In the tutorial you're linking to there's a section called "Troubleshooting" under which there's a section about the exact error you're facing:
https://developers.google.com/people/quickstart/php#uncaught_invalidargumentexception_missing_the_required_redirect_uri
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type.
This code requires an OAuth client ID of type Other, which will be
created for you when using the button in Step 1. If creating your own
client ID please ensure you select the correct type.
This suggests you didn't complete step 1 properly or that you have supplied your own client ID of the wrong type.
I've run into the problem with Google API quickstart. I couldn't verify the token because it says that the token format is invalid. The strangest part was that I was able to make it run a few months ago on another project, but now I can't do anything.
My quickstart.php look as:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s\n", $row[0], $row[4]);
}
}
When I attempt to enter the token it returns following error
Fatal error: Uncaught InvalidArgumentException: Invalid token format in ..\vendor\google\apiclient\src\Google\Client.php:469
Stack trace:
#0 ..\quickstart.php(45): Google_Client->setAccessToken()
#1 ..\quickstart.php(63): getClient()
#2 {main}
thrown in ..\vendor\google\apiclient\src\Google\Client.php on line 469
I've tried to append for $authCode token manually, but it didn't work.
So it literally was my mistake, our front engine changed the link "a bit" so it wasn't be able to be verified. As I've changed to a random domain and copied the token everything worked well.
I am new to the Google APIs and also to somewhat to PHP. I know there has been quite some similar questions, but going through them all in the last few days I didn't manage to handle my problem.
I am building an app which reads from and writes to google sheets, and using a simple API key with a public sheet I am able to read without problems. I didn't manage to figure out the Service Account authorization though.
I have made the sheet private and authorized the service account e-mail address editor access to the sheet.
I double and triple checked the client_id, email address, sheet id.
Here is my code:
function update_stat($spreadsheet_range)
{
session_start();
$client_id = 'XXXXXXXXXX';
$email_address = 'xxx#xxxx.iam.gserviceaccount.com';
$service_account_file = __DIR__ . '/sheetsCS.json';
$spreadsheet_id = 'xxxxxxxxxxxxxxxxxxxxxx';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file);
date_default_timezone_set("Europe/Rome");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);
$result = $service->spreadsheets_values->get($spreadsheet_id, $spreadsheet_range);
return $result;
}
No matter what I try, I get the following error:
[25-Nov-2020 09:22:07 Europe/Rome] PHP Fatal error: Uncaught Google\Service\Exception: {"error":"invalid_grant","error_description":"Invalid JWT Signature."} in /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php:128
Stack trace:
#0 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php(103): Google\Http\REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#1 [internal function]: Google\Http\REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#2 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Task/Runner.php(181): call_user_func_array(Array, Array)
#3 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php(66): Google\Task\Runner->run()
#4 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-int in /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php on line 128
What am I missing to make this work?
You might also want to check this Quickstart guide for Google Sheets API in PHP
https://developers.google.com/sheets/api/quickstart/php
Contents:
Guidelines on how to enable Google Sheets API
How to install Google Client Library
Setup a sample code
Run the sample code
Sample Code:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s\n", $row[0], $row[4]);
}
}
At initial stages of setting this up in a project.
I have enabled it the Google Developer page and trying to follow quickstart quide
https://developers.google.com/calendar/quickstart/php
however as with most Google API tutorials this 'quickstart' does not work.
I am taken through the authorization pages and given a code which I enter in the terminal but after a long time I am just given the error
PHP Fatal error: Uncaught RuntimeException: Unable to read from stream in [site root]/vendor/guzzlehttp/psr7/src/Stream.php
Stack trace:
#0 [site root]/vendor/guzzlehttp/psr7/src/functions.php(382): GuzzleHttp\Psr7\Stream->read()
#1 [site root]/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(214): GuzzleHttp\Psr7\copy_to_stream()
#2 [site root]/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(133): GuzzleHttp\Handler\StreamHandler->drain()
#3 [site root]/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(50): GuzzleHttp\Handler\StreamHandler->createResponse()
#4 [site root]/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php(66): GuzzleHttp\Handler\StreamHandler->__invoke()
#5 [site root]/vendor/guzzlehttp/guzzle/src/Middleware.php(29): GuzzleHttp\PrepareBodyMiddleware->__invoke()
#6 [site root]/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php(70): GuzzleHtt in [site root]/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 52
No token.json file is created however the directory is writable.
As suspected the Google code is wrong.
Changing the scope on line 16 allows it to run correctly.
$client->setScopes("https://www.googleapis.com/auth/calendar.readonly");
Full code:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
//$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setScopes("https://www.googleapis.com/auth/calendar.readonly");
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
if (empty($events)) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($events as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
I am currently facing a very strange problem, indeed I've been following this very same guide (https://developers.google.com/google-apps/calendar/quickstart/php) from Google API documentation. I tried it twice, at the first time it work like a charm but after the access token had expire the script provided straight by Google API Doc was unable to refresh it.
TL;DR
Here is the error message:
sam#ssh:~$ php www/path/to/app/public/quickstart.php
Fatal error: Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in /home/pueblo/www/path/to/app/vendor/google/apiclient/src/Google/Client.php:258
Stack trace:
#0 /home/pueblo/www/path/to/app/public/quickstart.php(55): Google_Client->fetchAccessTokenWithRefreshToken(NULL)
#1 /home/pueblo/www/path/to/app/public/quickstart.php(76): getClient()
#2 {main}
thrown in /home/pueblo/www/path/to/app/vendor/google/apiclient/src/Google/Client.php on line 258
Here is the part of the php script from google I've modified:
require_once __DIR__ . '/../vendor/autoload.php';
// I don't want the creds to be in my home folder, I prefer them in the app's root
define('APPLICATION_NAME', 'LRS API Calendar');
define('CREDENTIALS_PATH', __DIR__ . '/../.credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/../client_secret.json');
I also modified the expandHomeDirectory so I could "disable" it without modifying too much code:
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return $path;
// return str_replace('~', realpath($homeDirectory), $path);
}
So to check if I was wrong or if Google was, I did an experiment: yesterday night I launch the quickstart script from ssh to check if it was working, and indeed it was, so I decided to check this morning if it still working just as it was before I slept and it wasn't so I think there's something wrong with Google's quickstart.php.
I hope someone could help me, I already checked all the other posts about the subject but they are all outdated.
I got the same problem recently and i solved it with this.
<?php
$client->setRedirectUri($this->_redirectURI);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
I explain .....
Refresh token is not returned because we didnt force the approvalPrompt. The offline mode is not enought. We must force the approvalPrompt. Also the redirectURI must be set before these two options. It worked for me.
This is my full function
<?php
private function getClient()
{
$client = new Google_Client();
$client->setApplicationName($this->projectName);
$client->setScopes(SCOPES);
$client->setAuthConfig($this->jsonKeyFilePath);
$client->setRedirectUri($this->redirectUri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
// 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));
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));
if(!file_exists(dirname($this->tokenFile))) {
mkdir(dirname($this->tokenFile), 0700, true);
}
file_put_contents($this->tokenFile, json_encode($accessToken));
}else{
exit('No code found');
}
}
$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;
//Set the new acces token
$accessToken = $refreshTokenSaved;
$client->setAccessToken($accessToken);
// save to file
file_put_contents($this->tokenFile,
json_encode($accessTokenUpdated));
}
return $client;
}
My advice is save refresh token to .json immediately after get access token and if access token expired use refresh token.
In my projects work this way:
public static function getClient()
{
$client = new Google_Client();
$client->setApplicationName('JhvInformationTable');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = 'token.json';
$credentialsPath2 = 'refreshToken.json';
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
//printf("Open the following link in your browser:\n%s\n", $authUrl);
//print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
//echo "<script> location.href='".$authUrl."'; </script>";
//exit;
$authCode ='********To get code, please uncomment the code above********';
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$refreshToken = $client->getRefreshToken();
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
file_put_contents($credentialsPath2, json_encode($refreshToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$refreshToken = json_decode(file_get_contents($credentialsPath2), true);
$client->fetchAccessTokenWithRefreshToken($refreshToken);
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
I have faced the same issue with new google api library. Search for solution brought the following link:
RefreshToken Not getting send back after I get new token google sheets API
Based on that information, I have modified the quickstart code part to fit my needs. After first authorization with Google I have obtained drive-php-quickstart.json which contains refresh_token that expires in 3600 seconds or one hour. The refresh token is issued only once, so if it is lost, then re-authorization is required.
So, that to have it always in drive-php-quickstart.json I have done following:
// 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($credentialsPath, json_encode($accessTokenUpdated));
}
just some update for anyone having trouble with this message, mostly it's because only first command fetchAccessTokenWithAuthCode() generates credencials that contains the refresh token (technically forever valid - no 2 hours validity if you dont revoke it). When you get the new one it replaces the original one yet it does not contains the refresh token that it needs so next time you need to update the token, it will crash. This can be easily fixed by replacing the refresh function to for example this:
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$oldAccessToken=$client->getAccessToken();
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$accessToken=$client->getAccessToken();
$accessToken['refresh_token']=$oldAccessToken['refresh_token'];
file_put_contents($credentialsPath, json_encode($accessToken));
}
Now everytime you update the access token your refresh token is passed down too.
I had the same issues and finally go this to work:
Backstory:
I received the same error. Here is what I found:
This error:
PHP Fatal error: Uncaught LogicException: refresh token must be passed in or set as part of setAccessToken in /Library/WebServer/Documents/Sites/test/scripts/vendor/google/apiclient/src/Google/Client.php:267
Is referencing the update access token (aka Refresh) method:
$client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
Why was it failing? Long story short, I realized when I printed out the $accessToken array, which comes from decoding this json file (per the quickstart code you posted/that comes from google)
credentials/calendar-php-quickstart.json
I found the error due to how the accessToken array prints out when I print_r:
Array
(
[access_token] => Array
(
[access_token] => xyz123
[token_type] => Bearer
[expires_in] => 3600
[refresh_token] => xsss112222
[created] => 1511379484
)
)
Solution:
$refreshToken = $accessToken["access_token"]["refresh_token"];
right before this line:
$client->fetchAccessTokenWithRefreshToken($refreshToken);
I can finally refresh the token as needed when it expires in an hour. I think the devs of this article assumed the array prints as:
Array
(
[access_token] => xyz123
[token_type] => Bearer
[expires_in] => 3600
[refresh_token] => xsss112222
[created] => 1511379484
)
so they thought you could simply do $accessToken["refresh_token"]; That is not correct.
Now we have a valid value for $refreshToken, so the error should go away if you do this. I also updated the author via the feedback link to let them know about this, in case other php devs encounter this issue. Hopefully this helps somebody. My apologies if I formatted this post poorly I am new to S.E. I just wanted to share as I finally got this to work.
You need to serialize the accestoken when you write it to the credentialsPath.
// Exchange authorization code for an access token.
$accessToken = $client->authenticate($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
$serArray = serialize($accessToken);
file_put_contents($credentialsPath, $serArray);
printf("Credentials saved to %s\n", $credentialsPath);
And when you read from the file you need to unserialize it.
if (file_exists($credentialsPath)) {
$unserArray = file_get_contents($credentialsPath);
$accessToken = unserialize($unserArray);
}
Full function
function getClient() {
$client = new Google_Client();
// Set to name/location of your client_secrets.json file.
$client->setAuthConfigFile('client_secret.json');
// Set to valid redirect URI for your project.
$client->setRedirectUri('http://localhost');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_YouTube::YOUTUBE_READONLY);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$unserArray = file_get_contents($credentialsPath);
$accessToken = unserialize($unserArray);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->authenticate($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
$serArray = serialize($accessToken);
file_put_contents($credentialsPath, $serArray);
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, $client->getAccessToken());
}
return $client;
}
Google has updated their PHP Quickstart, with an improved method to handle this:
Snippet below:
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
In my case I had forgotten to set the access type as "offline" without which the refresh token was not being generated.
$client->setAccessType('offline');
Once this is done, the sample code given in the google documentation will work.
// Exchange authorization code for an access token.
// "refresh_token" is returned along with the access token
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
So After some time vieweing this code:
// Exchange authorization code for an access token.
// "refresh_token" is returned along with the access token
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
all was needed is this change:
// Exchange authorization code for an access token.
// "refresh_token" is returned along with the access token
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($accessToken);
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
since this function $client->getRefreshToken() returns null, and if you provide the $accessToken directly, it will work just fine and update your file, hope it resolves somebody issue.