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 ;-)
Related
I'm attempting to user Google API's via PHP to retrieve calendar events. My Environment
Windows: 10
PHP: 7.0
Apache: 2.4
Google API's loaded via command: composer require google/apiclient:"^2.0"
I'm using the following as test code (test2.php):
<html>
<head>
<title>PHP Test</title>
</head>
<body>
This is a line of text in test2.php
<?php
require_once 'C:\PHP\vendor\autoload.php';
$client = new Google_Client();
// $credentialsJson should contain the path to the json file downloaded from the API site
$credentialsJson = 'C:\Apache24\htdocs\credentials.json';
$credentials = $client->loadServiceAccountJson(
$credentialJson,
'https://www.googleapis.com/auth/calendar'
);
$client->setAssertionCredentials($credentials);
$service = new Google_Service_Calendar($client);
// $calendarId should contain the calendar id found on the settings page of the calendar
$calendarId = '*****myCalendarID*****';
$events = $service->events->listEvents($calendarId);
echo $events;
?>
</body>
</html>
I place the test2.php file in C:\Apache24\htdocs.
When I browse to: localhost/test2.php the browser displays:
This is a line of text in test2.php
Fatal error: Uncaught Error: Call to undefined method Google_Client::loadServiceAccountJson() in C:\Apache24\htdocs\test2.php:14 Stack trace: #0 {main} thrown in C:\Apache24\htdocs\test2.php on line 14
Why would this not find the method "loadServiceAccountJson"?
Thanks for looking at this.
I am not sure what tutorial you are following. this is the code i use.
ServiceAccount.php
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Note: A service account is not you using this will be requesting data from the service accounts google calendar account. if you want it to have access to your personal calendar your going to have to take the service account email address and share your calendar with it like you would any other user.
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'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
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).
I'm getting the following errors when trying to use OATH2 to authenticate against the Google Analytics API (v3):
Warning: openssl_sign() expects parameter 4 to be long, string given in google-api-php-client/src/auth/Google_P12Signer.php on line 60
Google_AuthException: Unable to sign data in google-api-php-client/src/auth/Google_P12Signer.php on line 61
Here's my PHP code:
// api dependencies
require_once(dirname(__FILE__) . '/../../vendor/google-api-php-client/src/Google_Client.php');
require_once(dirname(__FILE__) . '/../../vendor/google-api-php-client/src/contrib/Google_AnalyticsService.php');
session_start();
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName(APP_NAME);
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'xxxxxxx#developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents('xxxxxxxxxx-privatekey.p12') // keyfile
));
// other settings
$client->setClientId('xxxxxxx.apps.googleusercontent.com');
$client->setAccessType('offline_access');
// create service
$service = new Google_AnalyticsService($client);
$properties = $service->management_webproperties->listManagementWebproperties("~all");
print_r($properties);
if I print_r($service) I get a valid object with no errors. It is the listManagementWebproperties() call that generates the errors.
Does anyone please have a solution? It looks like the Google_Client might be in flux, since it was edited just a couple of days ago. I obtained it from trunk via SVN, NOT via the download page which I believe has an older version that does not support service accounts. Thanks.
According to the openssl_sign() PHP documentation, the 4th parameter should be an int.
http://php.net/manual/en/function.openssl-sign.php
bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )
In the code for Google_P12Signer they are using it like this:
if (!openssl_sign($data, $signature, $this->privateKey, "sha256")) {
throw new Google_AuthException("Unable to sign data");
}
Passing "sha256" which is obviously not an INT. There isn't an OPENSSL_ALGO_* defined for sha256 according to this: http://www.php.net/manual/en/openssl.signature-algos.php which means it won't work.
What you will have to do is define your own OPENSSL_ALGO_SHA256, sort of like you see in this code: http://pastebin.com/qdCyC0Pe
Someone wrote a patch to help also: http://php.it2y.info/missing-sha256-sha512-families-of-signature-algorithms.html