I'm trying to migrate the old google api to the new one, so I can get the google analytics data. I'm trying with this example, but it fires this error
Fatal error: Class 'Google_Auth_AssertionCredentials' not found in
example.php
This is how I'm trying:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once 'google-api-php-client/vendor/autoload.php';
//$p12FilePath = '/path/to/key.p12';
$serviceClientId = '395545742105.apps.googleusercontent.com';
$serviceAccountName = '395545742105#developer.gserviceaccount.com';
$scopes = array(
'https://www.googleapis.com/auth/analytics.readonly'
);
$googleAssertionCredentials = new Google_Auth_AssertionCredentials(
$serviceAccountName,
$scopes
); // <- Fatal error here
$client = new Google_Client();
$client->setAssertionCredentials($googleAssertionCredentials);
$client->setClientId($serviceClientId);
$client->setApplicationName("Project");
$analytics = new Google_Service_Analytics($client);
And I did run a search for Google_Auth_AssertionCredentials in the library wich I download from here, and Just one result: upagrading.md
Google_Auth_AssertionCredentials removed use Google_Client::setAuthConfig instead,
But how should I use it in a contructor?
I tred
$googleAssertionCredentials = new Google_Client::setAuthConfig(
$serviceAccountName,
$scopes
);
With internal server error,
Any idea what I'm missing here?
It looks like you have a mixture of the old and new (Google PHP API Client 2.0) syntax. The message "use Google_Client::setAuthConfig instead" is meant to indicate the method to use, but not that it should be called statically.
It should look like this:
$client = new Google_Client();
// set the scope(s) that will be used
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// this is needed only if you need to perform
// domain-wide admin actions, and this must be
// an admin account on the domain; it is not
// necessary in your example but provided for others
$client->setSubject('youradmin#example.com');
// set the authorization configuration using the 2.0 style
$client->setAuthConfig(array(
'type' => 'service_account',
'client_email' => '395545742105#developer.gserviceaccount.com',
'client_id' => '395545742105.apps.googleusercontent.com',
'private_key' => 'yourkey'
));
$analyticsService = new Google_Service_Analytics($client);
This syntax works for me with the current build as of this writing, which is 2.0.0-RC2.
This solution work for me:
The composer setup section in https://github.com/google/google-api-php-client/blob/master/README.md could mention both versions, something like:
composer require google/apiclient:^2.0.0#RC
Note the documentation at developers.google.com refers to V1 of this library. If you want to use the older version, instead use:
composer require google/apiclient:1.*
https://github.com/google/google-api-php-client/issues/748
Related
I'm trying to login with Google Sign-in but it's showing the 'Google_Service_OAuth2' as an undefined type.
I found this stack post: Google_Service_Oauth2 is undefined but there were no responses on it.
I installed the apiclient with composer and after research I've found that each of the files are in the correct locations (such as the src folder). Additionally, other libraries I've installed using composer are working properly.
Using command composer require google/apiclient composer installed version 2.12. I've tried installing v2.0 which is the version that most of the guides and posts I've found are using.
I've already run composer dump-autoload and restarted my machine just in case.
Here's my code:
use Google\Client;
$client = new Google_Client();
$clientID = 'MY CLIENT ID';
$clientSecret = 'MY CLIENT SECRET';
$redirectUri = 'http://localhost/dhi-portal/users/login';
$client->addScope('email');
$client->addScope('profile');
session_start();
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
if (!isset($token['error'])) {
$client->setAccessToken($token['accessToken']);
$_SESSION['accessToken'] = $token['accessToken'];
$googleService = new Google_Service_OAuth2($client);
}
}
I haven't continued further from here because it's showing the undefined type.
Any guidance would be greatly appreciated.
I had this same issue when I updated from google/apiclient version 2.9.x => 2.12.x. The problem is they changed the classes to use namespaces instead.
**Before**
$client = new Google_Client();
$service = new Google_Service_Books($client);
**After**
$client = new Google\Client();
$service = new Google\Service\Books($client);
Source: https://github.com/googleapis/google-api-php-client/blob/main/UPGRADING.md
So in your case, you need to rewrite your code like so if you wish to use 2.12.x:
$client = new Google\Client();
...
$googleService = new Google\Service\Oauth2($client);
I have this
define('CLIENT_SECRET_PATH', __DIR__ . '/config_api.json');
define('ACCESS_TOKEN', '0b502651********c52b3');
I can create a spreadsheet with this and get the id and url.
$requestBody = new Google_Service_Sheets_Spreadsheet();
$response = $service->spreadsheets->create($requestBody);
print_r($response);
$new_spr_id = $response['spreadsheetId'];
But this spreadsheet does not appears in the google sheets list as it is "protected" or something.
I am trying to set the permissions with this but get an error: Fatal error: Call to undefined method Google_Service_Drive_Permission::setValue()
insertPermission($service, $new_spr_id, '**#gmail.com' , 'user', 'owner');
function insertPermission($service, $fileId, $value, $type, $role) {
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setValue($value);
$newPermission->setType($type);
$newPermission->setRole($role);
try {
return $service->permissions->insert($fileId, $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
I need an example of creating a new spreadsheet and setting the proper permissions to it so I can modify this spreadsheet from my account etc.
Many many thanks!
Your code is not able to locate class and unable to create instance of Google_Service_Drive_Permission(). I would suggest, don't use individual function to create object of Google_Service_Drive_Permission(). Place all your code to set permissions within the code part, where you are creating file. Also if you are using multiple files, check if your files are loading properly and are located by PHP parser. Because Fatal Error for undefined method call is not due to implementation of API methods, its due to calling for methods that does not exist or you PHP parser is unable to locate.
For reference this might be helpful
http://hotexamples.com/examples/-/Google_Service_Drive_Permission/setValue/php-google_service_drive_permission-setvalue-method-examples.html
I had the same problem and wasn't able to figure it out using Google API PHP Client methods designed specifically for altering permissions. However, there is a possibility to retrieve a Guzzle instance with the authentication info from PHP Client. Therefore, we can simply call the desired API endpoint to send the request. The code below is a complete workaround for changing file owner/permission on Google Drive:
//if you're using Service Account, otherwise follow your normal authorization
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/json');
$client = new Google_Client();
$client->setScopes(Google_Service_Drive::DRIVE);
$client->useApplicationDefaultCredentials();
//Now the main code to change the file permission begins
$httpClient = $client->authorize(); //It returns a Guzzle instance with proper Headers
$result = $httpClient->request('POST', 'https://www.googleapis.com/drive/v3/files/[FILE_ID]/permissions?transferOwnership=true', [
'json' => [
'role' => 'owner',
'type' => 'user',
'emailAddress' => 'email#example.com'
]
]);
And the sample response of $result->getBody()->getContents() is:
{
"kind": "drive#permission",
"id": "14...",
"type": "user",
"role": "owner"
}
I think you're on the wrong API. Setting permission for files are found in Drive API permissions.
But to answer your question, here's how to create a new spreadsheet using spreadsheets.create from the Sheets API:
<?php
/*
* BEFORE RUNNING:
* ---------------
* 1. If not already done, enable the Google Sheets API
* and check the quota for your project at
* https://console.developers.google.com/apis/api/sheets
* 2. Install the PHP client library with Composer. Check installation
* instructions at https://github.com/google/google-api-php-client.
*/
// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';
$client = getClient();
$service = new Google_Service_Sheets($client);
// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_Spreadsheet();
$response = $service->spreadsheets->create($requestBody);
// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";
function getClient() {
// TODO: Change placeholder below to generate authentication credentials. See
// https://developers.google.com/sheets/quickstart/php#step_3_set_up_the_sample
//
// Authorize using one of the following scopes:
// 'https://www.googleapis.com/auth/drive'
// 'https://www.googleapis.com/auth/spreadsheets'
return null;
}
?>
When the files has been created and saved in your Google Drive, you can now try to set Permissions using the Drive REST API.
I am trying to use this code
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
$analytics = initializeAnalytics();
$profile = getFirstProfileId($analytics);
/*$results = getResults($analytics, $profile);
printResults($results);*/
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
function getFirstProfileId($analytics)
{
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
.....
But I get this error :
Catchable fatal error: Argument 2 passed to
Google\Auth\CredentialsLoader::makeCredentials() must be of the type
array, object given, called in
/home/julienlakq/new_site/administration/analytics/src/Google/Client.php
on line 1052 and defined in
/home/julienlakq/new_site/administration/analytics/vendor/google/auth/src/CredentialsLoader.php
on line 115
I have followed all the steps : created a jey, created a json key via google
https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php#3_setup_the_sample
Is anyone had this problem ?
Thanks a lot !
Problem solved.
First : Was using sample for v3 with v4 api :-s
Second : gone form php 5.6 to php 7
And then all is fine ;-)
I have created a PHP application using google-api-php-client. I created a Google account email id from the Google console, I generated the P12 file from there, and I put it into my local server. This works fine with "custom" PHP.
Now I would like to integrate the google-api-php-client library with my Symfony project in a custom bundle. I created a folder 'LIB' inside the /app/Resources, and I placed all files of google-api-php-client there.
Then I put the lines below inside the main controller to include the autoload.php file and to access the Google_Client class:
//require_once($this->container->getParameter( 'kernel.root_dir' ). '/../src/ABC/Bundle/TTBundle/Lib/src/Google/autoload.php');
$service_account_email = 'xxxxx-yyyyyy#developer.gserviceaccount.com';
$key_file_location = 'API-Project.p12';
// Create and configure a new client object.
$client = new Google_Client();
but it shows me the following error:
FatalErrorException: Error: Class
'ABC\Bundle\TTBundle\Controller\Google_Client' not found in
D:\wamp\www\TTPR\current\src\ABC\Bundle\TTBundle\Controller\WebAnalyticsController.php
line 133
i resolved the problem by the following steps:
1- create a function inside my controller:
2- inside the getService function , i called my self created function to include autoload.php file:
THE IMPORTANT THING NEED TO KNOW IS PUT A 'BACK SLASH' (/) WHEN CREATING OBJECT OF CLASS, I WAS MISSING THIS 'BACK SLASH' AND WASTED MY TIME, HOPE THIS WILL HELP SOME ONE AND SAVE TIME :)
protected function includeSsrsSdk()
{
require_once($this->container->getParameter( 'kernel.root_dir' ). '/../src/MWAN/Bundle/BIBundle/Lib/src/Google/autoload.php');
}
public function getService()
{
$this->includeSsrsSdk();
$service_account_email = 'xxyyzz#developer.gserviceaccount.com';
$key_file_location = $this->container->getParameter( 'kernel.root_dir' ). '/../src/MWAN/Bundle/BIBundle/Lib/API-Project-xxxx.p12';
// Create and configure a new client object.
$client = new \Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new \Google_Service_Analytics($client);
// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_email,
array(\Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
return $analytics;
}
I'm trying to add an event to a Google calendar directly from a php script but am getting this error:
Fatal error: Call to a member function insert() on a non-object...
<?php
set_include_path("scripts/google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
$path = $_SERVER['DOCUMENT_ROOT'];
$google_client = $path . '/xxxx/scripts/google-api-php-client/src/Google_Client.php';
include ($google_client);
require_once $path . '/xxxx/scripts/google-api-php-client/src/contrib/Google_CalendarService.php';
$event = new Google_Event();
$event->setSummary('Pi Day');
$event->setLocation('Math Classroom');
$start = new Google_EventDateTime();
$start->setDateTime('2013-03-14T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-03-14T10:25:00.000-05:00');
$event->setEnd($end);
// error is on this next line
$createdEvent = $cal->events->insert('some_calendar#gmail.com', $event);
echo $createdEvent->id;
?>
I've seen in many of the examples that I have looked at that some use code similar to this:
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Event Creator");
$client->setClientId('MY CLIENT ID ADDRESS IS HERE');
$client->setClientSecret('MY CLIENT SECRET KEY IS HERE');
$client->setRedirectUri('http://localhost/phpt/caladd.php');
$client->setDeveloperKey('MY API KEY IS HERE');
$cal = new Google_CalendarService($client);
But this looks to me like there is some application that is being referenced and is what is generating the calendar event. In my case, ideally, I just want my php script to make the calendar entry. There is no other "application" involved.
Do I need to have a Google_Client in order to add a simple entry to a Google Calendar? It seems excessive to me, but maybe that's the only way to do this.
Am I overlooking a step in this process? Or is there a bug in the code as I've written it. Any help is appreciated, including links to examples. Thank you.
You are trying to do this:
$cal->events->insert
But you do not have an object named $cal that I can tell. Create a new instance of $cal that conforms to what you are trying to do and then perform the insert.
You must register your application on the Google Developer's Console and if you're going to use the new official PHP Client Library, you'll have to use the Google_Client() class and set all those values in order to access the API services.
I suggest you start here: Write your First App
The sample codes on those pages use the old PHP library, but you can get an idea of what should be done and convert them to the new lib (mostly just use the new class names - check the source).