googleworkspace / php-samples Goto Github PK
View Code? Open in Web Editor NEWPHP samples for Google Workspace APIs
License: Apache License 2.0
PHP samples for Google Workspace APIs
License: Apache License 2.0
Enter verification code: 4/2wADbs9_wqAJ****1 2 Skip a few*****QwZ9NNvlSWfSy5
gU
PHP Warning: count(): Parameter must be an array or an object that implements C
ountable in C:\xampp\composer\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.p
hp on line 67
Warning: count(): Parameter must be an array or an object that implements Counta
ble in C:\xampp\composer\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on
line 67
Name, Major:
Alexandra, English
Andrew, Math
Anna, English
Becky, Art
Benjamin, English
Carl, Art
Carrie, English
Dorothy, Math
Dylan, Math
Edward, English
Ellen, Physics
Fiona, Art
John, Physics
Jonathan, Math
Joseph, English
Josephine, Math
Karen, English
Kevin, Physics
Lisa, Art
Mary, Physics
Maureen, Physics
Nick, Art
Olivia, Physics
Pamela, Math
Patrick, Art
Robert, English
Sean, Physics
Stacy, Math
Thomas, Art
Will, Math
C:\xampp\composer\vendor>
I got this error in People Api authentication
, i use same credentials in javascript but in php it give me error, Please see the issue behind this and solve this
Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 403, "message": "Request had insufficient authentication scopes.", "errors": [ { "message": "Request had insufficient authentication scopes.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } } in C:\xampp\htdocs\gpeople\vendor\google\apiclient\src\Google\Http\REST.php:118 Stack trace: #0 C:\xampp\htdocs\gpeople\vendor\google\apiclient\src\Google\Http\REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 C:\xampp\htdocs\gpeople\vendor\google\apiclient\src\Google\Task\Runner.php(181): Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 C:\xampp\htdocs\gpeople\vendor\google\apiclient\src\Google\Http\REST.php(58): Google_Task_Runner->run() #3 C:\xampp\htdocs\gpeople\vendor\google\apiclient\src\Google\Client.php(779): Goo in C:\xampp\htdocs\gpeople\vendor\google\apiclient\src\Google\Http\REST.php on line 118
Here is the code
`<?php
require DIR . '/vendor/autoload.php';
/**
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('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('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_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());
}
}
}`
(Please search existing issues before creating a new one.)
Sample:
Fatal error: Uncaught Exception: This application must be run on the command line. in C:\xampp\htdocs\quickstart.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\quickstart.php on line 5
1.
1.
php -v
):PHP Fatal error: Can't use method return value in write context in /var/www/html/mywebdirectory/quickstart.php on line 66
When using the sheets quickstart for php: https://developers.google.com/sheets/api/quickstart/php
I am able to install everything as required, running it gives me a url successfully, but going to that url for verification yields a 400 error with the message
Error: invalid_request
Invalid parameter value for access_type: 'offline ' is not valid
Runs throught example without errors
Problems with required Guzzle Client...
PHP Warning: count(): Parameter must be an array or an object that implements Countable in C:\Users[...]\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
Warning: count(): Parameter must be an array or an object that implements Countable in C:\Users[...]\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
php -v
):PHP 7.2.5 (cli)Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in C:\wamp64\www\gmail\vendor\guzzlehttp\guzzle\src\Message\MessageFactory.php on line 197
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in C:\wamp64\www\gmail\vendor\guzzlehttp\guzzle\src\Message\MessageFactory.php on line 216
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in C:\wamp64\www\gmail\vendor\guzzlehttp\guzzle\src\Message\MessageFactory.php on line 254
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in C:\wamp64\www\gmail\vendor\guzzlehttp\guzzle\src\Message\MessageFactory.php on line 357
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\CurlFactory.php on line 363
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\CurlFactory.php on line 382
Fatal error: Uncaught GuzzleHttp\Ring\Exception\RingException: cURL error 60: SSL certificate problem: unable to get local issuer certificate in C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\CurlFactory.php:127
Stack trace:
#0 C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\CurlFactory.php(91): GuzzleHttp\Ring\Client\CurlFactory::createErrorResponse(Array, Array, Array)
#1 C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\CurlHandler.php(96): GuzzleHttp\Ring\Client\CurlFactory::createResponse(Array, Array, Array, Array, Resource id #83)
#2 C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\CurlHandler.php(68): GuzzleHttp\Ring\Client\CurlHandler->_invokeAsArray(Array)
#3 C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\Middleware.php(54): GuzzleHttp\Ring\Client\CurlHandler->__invoke(Array)
#4 C:\wamp64\www\gmail\vendor\guzzlehttp\ringphp\src\Client\Middleware.php(30): GuzzleHttp\Ring\Client\Middleware::GuzzleHttp\Ring\Client{closure}(Array)
#5 C:\wamp64\www\gmail\vendor\guzzlehttp\ in C:\wamp64\www\gmail\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 51
what is content of autoload.php?
Hello, Everything went well until I had to copy the code to the command line.
I`m not an expert at all, it must be something simple, but I Cant find any info about this.
When I hit enter I get
-bash: [given code ************]: No such file or directory
If you need any more information, please ask.
Thanks in advance
I worked on php google calendar api and i find an issue on token generation
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'invalid json token' in E:\xampp\htdocs\test\admin\calendar\quickstart\vendor\google\apiclient\src\Google\Client.php:428 Stack trace: #0 E:\xampp\htdocs\test\admin\calendar\quickstart\quickstart.php(29): Google_Client->setAccessToken(NULL) #1 E:\xampp\htdocs\test\admin\calendar\quickstart\quickstart.php(68): getClient() #2 {main} thrown in E:\xampp\htdocs\test\admin\calendar\quickstart\vendor\google\apiclient\src\Google\Client.php on line 428
token.json is not generated automatically
(Please search existing issues before creating a new one.)
Sample:
I was thinking when i reply a code again in the code. it's not happen and not ran when i ran into command prompt or web.
Fatal error: Uncaught Exception: Aplikasi ini hanya dapat dijalankan di command line interface in C:\xampp1\htdocs\login-testing\quickstart.php:6 Stack trace: #0 {main} thrown in C:\xampp1\htdocs\login-testing\quickstart.php on line 6
php -v 7
):Hello. I am php developer and want to upload files using api
I saw https://developers.google.com/drive/api/v3/quickstart/php
it works well. then i did https://developers.google.com/drive/api/v3/manage-uploads
include 'quickstart.php';
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'photo.jpg'));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
and ran
I got error.
files (1v_fkI4BUZDZts_ZNp4LgDZcr6oNEfPNm)
Getting started (0B5fJx4717Z0yc3RhcnRlcl9maWxl)
PHP Notice: Undefined variable: driveService in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php on line 6
Notice: Undefined variable: driveService in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php on line 6
PHP Notice: Trying to get property 'files' of non-object in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php on line 6
Notice: Trying to get property 'files' of non-object in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php on line 6
PHP Fatal error: Uncaught Error: Call to a member function create() on null in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php:6
Stack trace:
#0 {main}
thrown in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php on line 6
Fatal error: Uncaught Error: Call to a member function create() on null in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php:6
Stack trace:
#0 {main}
thrown in C:\xampp\htdocs\linkedexchanger.com\php\google\upload.php on line 6
PS C:\xampp\htdocs\linkedexchanger.com\php\google>
Please help, thanks
Uncaught InvalidArgumentException: file does not exist in /var/www/html/solveapi/google-drive/vendor/google/apiclient/src/Google/Client.php:859
(Please search existing issues before creating a new one.)
Sample:
return spreadsheet details without warnings
returned spreadsheet details but with warnings
PHP Warning: count(): Parameter must be an array or an object that implements Countable in C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
PHP Stack trace:
PHP 1. {main}() C:\inetpub\wwwroot\google-sheet-api\quickstart.php:0
PHP 2. Google_Service_Sheets_Resource_SpreadsheetsValues->get() C:\inetpub\wwwroot\google-sheet-api\quickstart.php:70
PHP 3. Google_Service_Sheets_Resource_SpreadsheetsValues->call() C:\inetpub\wwwroot\google-sheet-api\vendor\google\apiclient-services\src\Google\Service\Sheets\Resource\SpreadsheetsValues.php:222
PHP 4. Google_Client->execute() C:\inetpub\wwwroot\google-sheet-api\vendor\google\apiclient\src\Google\Service\Resource.php:232
PHP 5. Google_Http_REST::execute() C:\inetpub\wwwroot\google-sheet-api\vendor\google\apiclient\src\Google\Client.php:779
PHP 6. Google_Task_Runner->run() C:\inetpub\wwwroot\google-sheet-api\vendor\google\apiclient\src\Google\Http\REST.php:58
PHP 7. Google_Http_REST::doExecute() C:\inetpub\wwwroot\google-sheet-api\vendor\google\apiclient\src\Google\Task\Runner.php:181
PHP 8. Google\Auth\HttpHandler\Guzzle6HttpHandler->__invoke() C:\inetpub\wwwroot\google-sheet-api\vendor\google\apiclient\src\Google\Http\REST.php:74
PHP 9. GuzzleHttp\Client->send() C:\inetpub\wwwroot\google-sheet-api\vendor\google\auth\src\HttpHandler\Guzzle6HttpHandler.php:34
PHP 10. GuzzleHttp\Client->sendAsync() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Client.php:104
PHP 11. GuzzleHttp\Client->transfer() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Client.php:97
PHP 12. GuzzleHttp\HandlerStack->__invoke() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Client.php:268
PHP 13. GuzzleHttp\Middleware::GuzzleHttp{closure}() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\HandlerStack.php:67
PHP 14. GuzzleHttp\RedirectMiddleware->__invoke() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Middleware.php:57
PHP 15. GuzzleHttp\Middleware::GuzzleHttp{closure}() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php:68
PHP 16. GuzzleHttp\PrepareBodyMiddleware->__invoke() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Middleware.php:30
PHP 17. Google\Auth\Middleware\ScopedAccessTokenMiddleware->Google\Auth\Middleware{closure}() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\PrepareBodyMiddleware.php:42
PHP 18. GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler{closure}() C:\inetpub\wwwroot\google-sheet-api\vendor\google\auth\src\Middleware\ScopedAccessTokenMiddleware.php:146
PHP 19. GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler{closure}() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php:51
PHP 20. GuzzleHttp\Handler\CurlHandler->__invoke() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php:28
PHP 21. GuzzleHttp\Handler\CurlFactory::finish() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php:43
PHP 22. GuzzleHttp\Handler\CurlFactory->release() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:107
PHP 23. count() C:\inetpub\wwwroot\google-sheet-api\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:67
php -v
): 7.2.7I think i found a bug in : https://github.com/gsuitedevs/php-samples/blob/master/drive/quickstart/quickstart.php
Sample:
https://youtu.be/NMGaXlq0qAk
the token to auto renew
the token doesn't renew and I am prompted for auth url again
run the example
https://github.com/gsuitedevs/php-samples/blob/master/drive/quickstart/quickstart.php
Windows 10 Home/ 64
C:\Users\User>php -v
PHP 7.2.22 (cli) (built: Aug 28 2019 09:29:01) ( ZTS MSVC15 (Visual C++ 2017) x64 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Xdebug v2.7.2, Copyright (c) 2002-2019, by Derick Rethans
$renewed = 0;
// Refresh the token if possible, else fetch a new one.
if ( $client->getRefreshToken() ) {
$client->fetchAccessTokenWithRefreshToken( $client->getRefreshToken() );
$renewed = 1;
} 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 ) );
}
}
if (! $renewed) {
// Save the token to a file.
if ( ! file_exists( dirname( $tokenPath ) ) ) {
$mkdir_res = mkdir( dirname( $tokenPath ), 0700, true );
if ( empty( $mkdir_res ) ) {
throw new Exception( "Cannot create parent directory for file: " . $tokenPath );
}
}
$save_res = file_put_contents( $tokenPath, json_encode( $client->getAccessToken() ), LOCK_EX );
if ( empty( $save_res ) ) {
throw new Exception( "Cannot save file: " . $tokenPath );
}
}
(Please search existing issues before creating a new one.)
Sample:
print the list of events form the calendar
#11
PHP Warning: count(): Parameter must be an array or an object that implements Countable in C:\MAMP\htdocs\API\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
PHP Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcur
l-errors.html) in C:\MAMP\htdocs\API\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:187
Stack trace:
#0 C:\MAMP\htdocs\API\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
#1 C:\MAMP\htdocs\API\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Han
dler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#2 C:\MAMP\htdocs\API\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\E
asyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#3 C:\MAMP\htdocs\API\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(28): GuzzleHttp\Handler in C:\MAMP\htdocs\API\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 187
why its require to generate token again after 3600 , first time calendar api work fine as per google code but after expire 3600 need to generate again through quickstart.php , can its generate automatically?
After I tried to execute the first example of the Google API Tutorial quickstart.php. I obtained the following error message ;
PHP Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\calendario\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\calendario\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
No upcoming events found.
php -v
): PHP 7.4.2 (cli) (built: Jan 21 2020 17:52:43) ( ZTS Visual C++ 2017 x64 )It Works!
I wanted to see the protocol as everything works in detail, but the directory did not find such information. I think the conversion code itself could fit in a couple of lines of the program, but I did not succeed because I do not know the protocol. I got closer to the truth but the SSL connection could not be promoted. So you had to use your ready code and this code works! Thank you! It was a bit difficult, because I do not know English perfectly, but I did everything perfectly.
(Please search existing issues before creating a new one.)
Sample:
Not sure.
This error_log file was created:
[] PHP Fatal error: Uncaught InvalidArgumentException: Invalid token format in /home/example1/public_html/temp/calendar/vendor/google/apiclient/src/Google/Client.php:433
Stack trace:
#0 /home/example1/public_html/temp/calendar/quickstart.php(39): Google_Client->setAccessToken(Array)
#1 /home/example1/public_html/temp/calendar/quickstart.php(52): getClient()
#2 {main}
thrown in /home/example1/public_html/temp/calendar/vendor/google/apiclient/src/Google/Client.php on line 433
[] PHP Fatal error: Uncaught InvalidArgumentException: Invalid token format in /home/example1/public_html/temp/calendar/vendor/google/apiclient/src/Google/Client.php:433
Stack trace:
#0 /home/example1/public_html/temp/calendar/quickstart.php(39): Google_Client->setAccessToken(Array)
#1 /home/example1/public_html/temp/calendar/quickstart.php(52): getClient()
#2 {main}
thrown in /home/example1/public_html/temp/calendar/vendor/google/apiclient/src/Google/Client.php on line 433
php -v
): 7.0.31Apparently the tutorial did work as the second time I run php quickstart.php PuTTY displays a list of near-future events from Google Calendar.
I am trying to append some values in spreadsheet using google api php client.
I have successfully added data in the sheet but every time I run the code, it start appending values from column where the previous ended in the next row.
I am trying to append values in new row every time but it must start from column A.
Lets say I am inserting these values: array( array( "Item", '', "Ship Date" ) );
Now, when I run this code it appends "Item" on column A of a new row and "Ship Date" on column C. This is correct.
But when I run the same code again, it appends the data in new row but starts with Column C and ends with column E.
And so on.
I want the next time also the data should start appending from column A and ends on column C.
If you do not have blank/space values then the issue is not replicated, it works great. The issue is only replicated with blank/space values in my array.
Here is a screenshot of my test insertion: http://bakingcode.org/hitesh/2019-13-21-25.png
As a workaround first I am getting all the values from the sheet and then count it to get the last row, then make the range accordingly to append values starting from column A.
But there can be a lot of data lets say in lakhs, then this will put unnecessary load on server.
I am also not getting any function to get the last row where data is present.
Can you please help me in getting the last row or even better let me insert blank/space values and still the insertion starts with column A.
My specifications:
PHP version ( 7.2.14 ):
OS ( Linux ):
Hi,
basic reading is working fine but when I am trying to write some values in google sheet it giving http error 500
SAMPLE
<?php
require __DIR__ . '/vendor/autoload.php';
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$credentialsPath = 'token.json';
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
$client = getClient();
$service = new Google_Service_Sheets($client);
$spreadsheetId = '13zWB1_uY5CdPGLuSXRWAgD0lE7QVrbTDW_9V5lqdNAY';
$range = "Sheet1!A1:C3";
$options = array('valueInputOption' => 'RAW');
$values = [
["Name", "Roll No.", "Contact"],
["Anis", "001", "+88017300112233"],
["Ashik", "002", "+88017300445566"]
];
$body = new Google_Service_Sheets_ValueRange(['values' => $values]);
$result = $service->spreadsheets_values->batchUpdate($spreadsheetId, $range, $body, $options);
?>
php -7.0.26
):Hello, in my project I need to read the events that the user has in Google calendar, what I do is follow the procedure of this web page and when I am requesting the data, it shows an error status 405 method, saying that I must enable the "cors" and I do not know in which part of the api that I have in my google account I can do that, or if I have to initiate a curl in php to enable that.
Code:
if (
isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'
) {
$the_html = $_GET['action']();
echo $the_html;
} else {
echo "don't be silly";
die();
}
function get_times()
{
require_once('./connection.php');
$date = new DateTime($_GET['date']);
$day_after = new DateTime($_GET['date']);
$day_after->add(new DateInterval('P1D'));
for($i=0;$i<24;$i++) {
$innerHTML_arr[] = "<option value='$i'>$i:00</option>";
}
$client = getClient();
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'timeMin' => date('c',$date->getTimestamp()),
'timeMax' => date('c',$day_after->getTimestamp()),
);
$results = $service->events->listEvents($calendarId, $optParams);
$the_html="";
foreach ($results->getItems() as $event) {
$s = new DateTime($event->start->dateTime);
$start = date('G',$s->getTimestamp());
$minutes = date('i', $s->getTimestamp());
unset($innerHTML_arr[$start][$minutes]);
}
$the_html.=implode("",$innerHTML_arr);
return $the_html;
}
the last code is in a php file that i call from other php file with a request GET, with javascript pure
Code:
function get_times(date_picker) {
var date = date_picker.value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('dump').innerHTML = xhttp.responseText;
}
};
xhttp.open('GET', './calendars.php?action=get_times&date=' + date + '&t=' + Math.random());
xhttp.setRequestHeader('X-Requested-With', 'xmlhttprequest');
xhttp.send();
}
Select a any date and the browser show:
Event1
Event2
Event3
...
PHP 7.2.5
):Hi I have used this library and found below error
(Please search existing issues before creating a new one.)
Sample:
Terminal throws an error:
Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /Users/e32398/Sites/composer_test/vendor/google/auth/src/OAuth2.php:650
Stack trace:
#0 /Users/e32398/Sites/composer_test/vendor/google/apiclient/src/Google/Client.php(339): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /Users/e32398/Sites/composer_test/quickstart.php(26): Google_Client->createAuthUrl()
#2 /Users/e32398/Sites/composer_test/quickstart.php(58): getClient()
#3 {main}
thrown in /Users/e32398/Sites/composer_test/vendor/google/auth/src/OAuth2.php on line 650
php -v
): 7.1.7I am using quickkstart that is available in documentation, but it always said no connection available.
But when i try same credentials from javascript it works fine.
if i am wrong somewhere please suggest me.
here is the link of code from documentation that i use in my projecrt
https://developers.google.com/people/quickstart/php
Thanku.
Based on the site of https://qiita.com/wtanabe/items/ead266f065bdcb14a0c6
I created quickstart.php, but without the 14th line of Google_Client class
I get an error, I am in trouble.
here the coding,
<?php
mkdir("/path/www/calendar/quickstart/google-api-php-client-master/src/google/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);
$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);
}
}
Hello, for my project I need to be able to modify a calendar with PHP. To begin, I'm trying out Google's test (https://developers.google.com/calendar/quickstart/php)
When executing the command 'php quickstart.php' I have the following error.
PHP Fatal error: Uncaught Google_Exception: Invalid client secret JSON file. in /var/www/html/google-api-php-client/src/Google/Client.php:171 Stack trace: #0 /var/www/html/quickstart.php(17): Google_Client->setAuthConfig('credentials.jso...') #1 /var/www/html/quickstart.php(63): getClient() #2 {main} thrown in /var/www/html/google-api-php-client/src/Google/Client.php on line 171
I tried creating other client ID but the problem is the same
I followed the guide but I block on it.
In the Google Developers i made another credentials.json and i checked it but it's not the solution.
Maybe i have a problem with Oauth?
<?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('Gmail API PHP Quickstart');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = 'token.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));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$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()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
// [END gmail_quickstart]
i want make token.js file for every user dynamic
Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/
libcurl-errors.html) in E:\wamp\www\Gmail API Quickstart\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:187
Stack trace:
#0 E:\wamp\www\Gmail API Quickstart\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHa
ndle), Array)
#1 E:\wamp\www\Gmail API Quickstart\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandle
r), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#2 E:\wamp\www\Gmail API Quickstart\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Ob
ject(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#3 E:\wamp\www\Gmail API Quickstart\ in E:\wamp\www\Gmail API Quickstart\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 187
PS E:\wamp\www\Gmail API Quickstart>
He utilizado el ejemplo de quickstart.php para Google Calendar y funciona todo correcto hasta que pasan algo más de dos horas y me devuelve un error al intentar refrescar el token al expirar.
He mirado en muchos foros y no funciona nada de lo que se indica.
Por favor, me puede ayudar.
Sample:
`PHP Fatal error: Uncaught LogicException: refresh token must be passed in or set as part of setAccessToken in C:\www\medel\pru\vendor\google\apiclient\src\Google\Client.php:258
Stack trace:
#0 C:\www\medel\pru\quickstart.php(51): Google_Client->fetchAccessTokenWithRefreshToken(NULL)
#1 C:\www\medel\pru\quickstart.php(59): getClient()
#2 {main}
thrown in C:\www\medel\pru\vendor\google\apiclient\src\Google\Client.php on line 258
Fatal error: Uncaught LogicException: refresh token must be passed in or set as part of setAccessToken in C:\www\medel\pru\vendor\google\apiclient\src\Google\Client.php:258
Stack trace:
#0 C:\www\medel\pru\quickstart.php(51): Google_Client->fetchAccessTokenWithRefreshToken(NULL)
#1 C:\www\medel\pru\quickstart.php(59): getClient()
#2 {main}
thrown in C:\www\medel\pru\vendor\google\apiclient\src\Google\Client.php on line 258`
1.He seguido los pasos que se indican en la guía de Google (https://developers.google.com/calendar/quickstart/php)
php -v
): PHP Vr. 7.2.6Hi, i tried to run the quickstart.php and got this error
PHP Warning: count(): Parameter must be an array or an object that implements Countable in F:\xampp\htdocs\google-group
\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
Warning: count(): Parameter must be an array or an object that implements Countable in F:\xampp\htdocs\google-group\vend
or\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67
Credentials saved to token.json
I have to reopen that issue which is related to #22
The issue was closed but it was still an error! There is missing one line in the example file:
$client->setRedirectUri(...);
Please change the documentation accordingly.
I can access the API
I see an error because the redirect uri for OAuth is not defined.
`In OAuth2.php line 650:
missing the required redirect URI`
I've followed step by step this tutorial here:
https://developers.google.com/sheets/api/quickstart/php
When opening the given URL, I see this error:
If I add a scope parameter ("https://www.googleapis.com/auth/plus.login") to the URL manually, I get this error:
Why are these parameters missing? how can I have a proper URL generated?
Thanks in advance
URL gives a login screen
URL gives a 400 error
php -v
): PHP 7.0.32-0ubuntu0.16.04.1 (cli) ( NTS )i am getting the following error when i try to run quick.php (which is named as quickstart in google drive api docs) i have copy paste the exact code but getting the error when i run it from my command line
Error:
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in C:\xampp\htdocs\dnew\vendor\google\auth\src\OAuth2.php:650
Stack trace:
#0 C:\xampp\htdocs\dnew\vendor\google\apiclient\src\Google\Client.php(339): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 C:\xampp\htdocs\dnew\quick.php(26): Google_Client->createAuthUrl()
#2 C:\xampp\htdocs\dnew\quick.php(58): getClient()
#3 {main}
thrown in C:\xampp\htdocs\dnew\vendor\google\auth\src\OAuth2.php on line 650
Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in C:\xampp\htdocs\dnew\vendor\google\auth\src\OAuth2.php:650
Stack trace:
#0 C:\xampp\htdocs\dnew\vendor\google\apiclient\src\Google\Client.php(339): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 C:\xampp\htdocs\dnew\quick.php(26): Google_Client->createAuthUrl()
#2 C:\xampp\htdocs\dnew\quick.php(58): getClient()
#3 {main}
thrown in C:\xampp\htdocs\dnew\vendor\google\auth\src\OAuth2.php on line 650
Specifications
php -v-7.2.1
):(Please search existing issues before creating a new one.)
Sample:
To be able to proceed to step 4 of the quickstart guide ( https://developers.google.com/docs/api/quickstart/php )
This error appears.
php -v
): PHP 5.6.30I get credentials.json (attached credentials.zip) and I installed composer.
Then I run "composer quickstart.php" provided in the PHP quickstart page (quickstart.php attached)
I get this url to execute: (see phpquickstartOutput.jpg file attached)
(See attached file BrowserError.jpg)
I received this error:
"
Required parameter is missing: response_type
response_type=code
access_type=offline
client_id=433334862655-7vdjqv2iaqhe452ekb8ib7t5hc2ujfqg.apps.go ogleusercontent.com
redirect_uri=urn:ietf:wg:oauth:2.0:oob
state=
scope=https:/ /www.googleapis.com/auth/activity https://www.googleapis.com/auth /drive.metadata.readonly
approval_prompt=auto
"
with the attached composer.json file
php -v
): 7.0Getting Error
PHP Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 60:
SSL certificate problem: self signed certificate in certificate chain (see http
://curl.haxx.se/libcurl/c/libcurl-errors.html)
IIS Server
Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' in C:\wamp\www\google_sheet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 187
(Please search existing issues before creating a new one.)
Sample:
php -v
):Error:
Unable to parse range: ...
Decision:
Class Data - is Spreadsheet name
(Please search existing issues before creating a new one.)
Fatal error: Uncaught exception 'Google_Service_Exception' with message
'{
"error":{
"code":400,
"message":"Unable to parse range: Class Data!A1:B",
"errors":[
{
"message":"Unable to parse range: Class Data!A1:B",
"domain":"global",
"reason":"badRequest"
}
],
"status":"INVALID_ARGUMENT"
}
}'
in
C:\xampp\htdocs\google_php_api\vendor\google\apiclient\src\Google\Http\REST.php:118 Stack trace: #0
C:\xampp\htdocs\google_php_api\vendor\google\apiclient\src\Google\Http\REST.php(94): 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
C:\xampp\htdocs\google_php_api\vendor\google\apiclient\src\Google\Task\Runner.php(181): call_user_func_array(Array, Array) #3
C:\xampp\htdocs\google_php_api\vendor\google\apiclient\src\Google\Http\REST.php(58): Google_Task_R in
C:\xampp\htdocs\google_php_api\vendor\google\apiclient\src\Google\Http\REST.php on line 118
want to show all data of sheet
want to show all data of sheet
php -v
): 5.4(Please search existing issues before creating a new one.)
Sample:
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
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()));
}
php -v
):Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.' in /Library/WebServer/Documents/sheet/vendor/google/auth/src/Cache/Item.php:129
Stack trace:
#0 /Library/WebServer/Documents/sheet/vendor/google/auth/src/Cache/Item.php(129): DateTime->__construct('now + 1500 seco...')
#1 /Library/WebServer/Documents/sheet/vendor/google/auth/src/CacheTrait.php(61): Google\Auth\Cache\Item->expiresAfter(1500)
#2 /Library/WebServer/Documents/sheet/vendor/google/auth/src/Middleware/ScopedAccessTokenMiddleware.php(171): Google\Auth\Middleware\ScopedAccessTokenMiddleware->setCachedValue('https://www.goo...', 'ya29.GlvyBVHIoH...')
#3 /Librar in /Library/WebServer/Documents/sheet/vendor/google/auth/src/Cache/Item.php on line 129
Here in the doc: https://developers.google.com/sheets/api/samples/writing#write_selectively_to_a_range
It's mentioned that we can pass null value if we do not want to update the cell and leave it as it is.
But it throws me an error "Invalid JSON payload received.", refer: http://bakingcode.org/hitesh/2019-17-25-07.png
Can you please help.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.