i am using php 5.3.3, and codeigniter 2.1.0.
what i want to do is set up a service account, so a user can add an appointment in a text entry field on my website, then have that appointment added to a shared shared google calendar.
i have a google account, and using : https://code.google.com/apis/console I created a new project called 'pqp'
on services: enabled the calendar api
on api access: i created an oath 2.0 client id… product name = pqp, application type = service account.
downloaded the key 46… -privatekey.p12. there is a screenshot of the settings:
I got an svn checkout of the google-api-php-client (28/6/2012)
In the google-api-php-client/src/config.php I changed lines:
25: 'application_name' => 'pqp',
28: 'oauth2_client_id' => '373xxx730.apps.googleusercontent.com',
57: 'ioFileCache_directory' => 'tmp/apiClient', // my apache user does not have access to the system /tmp folder. + tmp/apiClient has permissions of 777 on the server.
using this link:
http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php?spec=svn445&r=395
I modified it to:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller{
function __construct()
{
parent::__construct();
}
function index()
{
set_include_path(get_include_path() . PATH_SEPARATOR .dirname(__FILE__).'/../libraries/google-api-php-client/src');
ini_set('error_reporting',E_ALL);
ini_set('display_errors','1');
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
define('CLIENT_ID','3731xxx44730.apps.googleusercontent.com');
define('SERVICE_ACCOUNT_NAME','373xxx244730#developer.gserviceaccount.com');
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
define('KEY_FILE',dirname(__FILE__).'/../../461290xxx796c0b7db9582c-privatekey.p12');
require_once "apiClient.php";
require_once "contrib/apiCalendarService.php";
$client = new apiClient();
$client->setApplicationName("pqp");
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
echo 'client access token is set.<br/>';
}
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(KEY_FILE);
$creds = new apiAssertionCredentials(SERVICE_ACCOUNT_NAME,array('https://www.googleapis.com/auth/calendar'),$key);
$client->setAssertionCredentials($creds);
$client->setClientId(CLIENT_ID);
$service = new apiCalendarService($client);
echo 'client:<br/>';
var_dump($client);
echo 'service:<br/>';
var_dump($service);
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
echo 'token is good!, so creating an event....';
echo $this->insert_event($service,'testing summary','my location','2012-06-29T10:00:00.000+10:00','2012-06-29T10:00:00.000+10:00');
}
}
function insert_event($service,$summary,$location,$from,$to){
$event = new Event();
$event->setSummary($summary);
$event->setLocation($location);
$start = new EventDateTime();
$start->setDateTime($from);
$event->setStart($start);
$end = new EventDateTime();
$end->setDateTime($to);
$event->setEnd($end);
$attendee1 = new EventAttendee();
$attendee1->setEmail('test#example.com');
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
return $createdEvent->getId();
}
}
a pastie of the output is here:
the $client object is not authenticated, the getAccessToken is not set, and the event is not inserted.
i have found it difficult to work out which settings in the $config file to change because there is different nomenclature. i guess this is an artifact of how the code has progressed.
are the settings in src/config.php correct? do i need to alter any more settings?
it is my understanding that if i create the service account, download the key file, and the contents of this file with my developer id, it should return a token, and there is no need to set up a redirection uri.. is that correct? this is the functionality i want. i don't want the user to have to authorise access because the website will only ever interact with one google account.
So, the question is, how do i get this calendar api to authenticate using a google service account?
You can try this one if you not already...
EDIT: this one intresting but if you still feel like to write one yourself then try this THE mother of the oauth2. helpful
About Service Account at google-api-php-client that you use(always take the trunk's one with SVN) I can't found in that code manipulations any reference apiAssertionCredentials::generateAssertion()
definitely there is no call to auth in there
public function __construct(
$serviceAccountName,
$scopes,
$privateKey,
$privateKeyPassword = 'notasecret',
$assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
$prn = false) {
$this->serviceAccountName = $serviceAccountName;
$this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
$this->privateKey = $privateKey;
$this->privateKeyPassword = $privateKeyPassword;
$this->assertionType = $assertionType;
$this->prn = $prn;
}
and this method should be called I guess...
public function generateAssertion() {
$now = time();
$jwtParams = array(
'aud' => apiOAuth2::OAUTH2_TOKEN_URI,
'scope' => $this->scopes,
'iat' => $now,
'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
'iss' => $this->serviceAccountName,
);
if ($this->prn !== false) {
$jwtParams['prn'] = $this->prn;
}
return $this->makeSignedJwt($jwtParams);
}
EDIT:
Pardon. In fresh ver. look's like it's Google_OAuth2::refreshTokenWithAssertion() actualy who should start the real proces
Related
I'm trying to access & write my dummy calendar make new functionality of the website but something prevents me from making changes to my dummy calendar.
So far when I try to used this code:
$event = $calendar->calendars->get(xxxxxx.com_dsjiub0krm61i5vu1mvee8rh9o#group.calendar.google.com);
The result is similar to the Googles Calendar's API explore.
My Calendar API
$calendarId2 = 'xxxxxx.com_dsjiub0krm61i5vu1mvee8rh9o#group.calendar.google.com';
$jobname = "Tesla";
$joblocation = "USA";
$jobdescription = "Interview with Elon Musk.";
$startofjob = "2019-03-29T10:00:00.000+00:00";
$endofjob = "2019-03-30T18:00:00.000+00:00";
try {
$client = GetGoogleClient();
$calendar = new \Google_Service_Calendar($client);
$event = new \Google_Service_Calendar_Event(array(
'summary' => $jobname,
'location' => $joblocation,
'description' => $jobdescription,
'end' => array(
'dateTime' => $endofjob,
'timeZone' => 'Asia/Manila',
),
'start' => array(
'dateTime' => $startofjob,
'timeZone' => 'Asia/Manila',
),
));
$event = $calendar->events->insert($calendarId2, $event);
}
catch(\Exception $e) {
return ["error" => $e->getMessage()];
}
The message would always say this "You need to have writer access to this calendar." even though I have shared the calendar to the Service Account with permission Make changes to events or Make changes and manage sharing
Additional info
function GetGoogleClient(){
$client = new Google_Client();
//$client->setAuthConfig($credentialsFile);
$client->addScope("https://www.googleapis.com/auth/drive", Google_Service_Sheets::SPREADSHEETS);
$client->addScope("https://www.googleapis.com/auth/calendar");
//$client->addScope("https://www.googleapis.com/auth/calendar.events"); //same error result event with or without
$client->setAuthConfig(CONST_GOOGLE_SERVICE_ACCOUNT_KEY);
$client->setSubject(CONST_GOOGLE_SERVICE_ACCOUNT_EMAIL);
$client->useApplicationDefaultCredentials();
return $client;
}
Check that the settings are correct in Google Admin Console. One reason that you would not be able to change the settings on an individual calendar is that the ability to make changes has been restricted on a domain wide basis.
If you are want to use a service account on GSuite organization you have to:
login with a Gsuite normal account (also not administrator)
create an API Project
enable calendar api
manage credentials and add a service account
download the json authorization file of the service account and copy the client_id in the json file
enable domain wide delegation for the service account in the console from the account that created the service account.
enable calendar API
login with a domain administrator account and go to Google Admin Console and go to Security -> API Controls -> Domain Wide Delegation
than add New API Client, insert the client_id at point 4 and the scope https://www.googleapis.com/auth/calendar (or one from: calendar.events, calendar.events.readonly, calendar.readonly, calendar.settings.readonly)
now that service account can impersonate anyone.
This is a sample code:
<?php
## composer require google/apiclient:^2.0
require __DIR__ . '/vendor/autoload.php';
/* the path of the auth file downloaded from google */
const AUTH_JSON_FILE = 'service-account-test-12345678.json';
/* the subject to impersonate */
const SUBJECT_TO_IMPERSONATE = 'acmeuser#mydomain.com';
/* take calendar id from calendar settings > embed calendar (the default calendar has the same as SUBJECT_TO_IMPERSONATE */
const CALENDAR_ID = "a_abcde123456fghijk789....#group.calendar.google.com";
/* date of the test event*/
const TEST_EVENT_DATE = '2021-01-26';
function getClient() {
$googleClient = new Google_Client();
$googleClient->setApplicationName("Anything you want");
$googleClient->setAuthConfig(AUTH_JSON_FILE);
$googleClient->setScopes([Google_Service_Calendar::CALENDAR]);
$googleClient->setSubject(SUBJECT_TO_IMPERSONATE);
return $googleClient;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
/* Create a test event on 2021-01-26 */
$event = new Google_Service_Calendar_Event();
$event->setSummary("Test event title");
$event->setDescription("Test description.....");
$start = new Google_Service_Calendar_EventDateTime();
$start->setDate(TEST_EVENT_DATE);
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDate(TEST_EVENT_DATE);
$event->setEnd($end);
$createdEvent = $service->events->insert(CALENDAR_ID, $event);
echo $createdEvent->getId();
"You need to have writer access to this calendar."
You may have shared it with the service account but did you give it write access? or just read access? I think you should double check this its normally the cause of the issue. Remember this is only going to give it access to this one calendar.
Also i think you should check your scopes just use
$client->addScope("https://www.googleapis.com/auth/calendar");
I think they are clobbering each other. Take a step back make sure calendar works then add your drive stuff
I am trying to access to a calendar created by my application via cron, and I get a calendar with the same name that the calendar the application creates, but the id is absolutely different... This is my code:
public function cronTest()
{
$this->g_client = new Google_Client();
$this->g_client->setApplicationName($this->config->item("APPLICATION_NAME"));
$service = $this->getCronService("CalendarTest-46bde015a16.p12");
$calendar = $this->getCalendar($service);
}
private function getCronService($file)
{
$key = file_get_contents(CREDENTIALS_PATH.$file);
$cred = new Google_Auth_AssertionCredentials($this->config->item("google_service_id"), SCOPES, $key);
$this->g_client->setAssertionCredentials($cred);
if($this->g_client->getAuth()->isAccessTokenExpired())
$this->g_client->getAuth()->refreshTokenWithAssertion($cred);
return new Google_Service_Calendar($this->g_client);
}
private function getCalendar($service)
{
$calendarList = $service->calendarList->listCalendarList();
echo "getCalendar<br>";
foreach ($calendarList->getItems() as $calendarListEntry)
{
echo $calendarListEntry->getSummary()." with id:".$calendarListEntry->getId()."<br>";
echo "<br>";
if($calendarListEntry->getSummary()=="Auto-Citas")
echo "found";
//return $calendarListEntry->getId();
}
die;
}
When I execute it from the command line (simulating the cron):
wget www.domain.com/prototipo/alien/cronTest
I get this:
Calendar
Auto-Citas with id:h0gefmo7vjqlr4lp0r2n93vk9c#group.calendar.google.com
found
But, the id of calendar created with this application doesn´t match with this id...
Before this attempt with ron, I had to learn how to use the API, in this way I needed to remove sometimes the same calendar. So what I do, was remove one more time the Auto-Citas on my calendar, and call the function on my app to create a new calendar with a different name, then I made again the request of the "simulated cron" (wget www.domain.com/prototipo/alien/cronTest) and the result is the same than before: only one calendar called Auto-Citas, but nothing about the new calendar.
The functionality is to create a module anti-absenteeism, sending an email or sms to the user two hours before the appointment(cita=appointment)
For this tasks I have to function more... but they aren´t important for the case:
$events = $this->getDates($service,$calendar,$min,$max);
$this->transformDates($events, $service, ",phone");
Ok... I find solution just here (the google official docs). I need to use the option of user_to_impersonate.
$client_email = '1234567890-a1b2c3d4e5f6g7h8i#developer.gserviceaccount.com';
$private_key = file_get_contents('MyProject.p12');
$scopes = implode(' ', array(Google_Service_Calendar::CALENDAR));
$user_to_impersonate = 'user#example.org';
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate,
);
struggling to understand the oauth2 token and refresh token processes
ive got this code
$url = 'https://www.googleapis.com/oauth2/v3/token';
$data = array('client_id' => 'clientid', 'client_secret' => 'secret','refresh_token' => 'token','grant_type' => 'refresh_token');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded",
'method' => 'POST',
'approval_prompt'=>'force',
'access_type'=>'offline',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
that code above gives me an access token , and i followed this link suggested by one fellow stackoverflower, pinoyyid, BUT , im confunsed on how to correctly use the resulting access token to access drive and copy a file...
all the process ive seen usually involves $client = new Google_Client() and im not sure on how to use the whole POST http://..... thing, so basically i need to figure out if i use the access token i got with the code above in a new instance of google client, or i simply do a post to a url with necesary info ( which im not clear on also ) any help/clarification is appreciated guys really
EDIT #1
what i want to achieve is to allow the end user to access my drive via my webpage, to let them copy a spreadsheet in my drive , and access it via my website, to store data on the spreadsheet,the spreadsheet will always be on my drive, never on the end user
EDIT #2
code as per your posts is as follows, using the service account,,,,the files are inside that gmail account which i created on the api console a service account
<?php
require 'Google/autoload.php';
$client = new Google_Client();
// Replace this with your application name.
$client->setApplicationName("TEST");
// Replace this with the service you are using.
$service = new Google_Service_Drive($client);
// This file location should point to the private key file.
$key = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/number-privatekey.p12');
$user_to_impersonate = 'admin#testpr.com';
$cred = new Google_Auth_AssertionCredentials(
'number#developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/drive'), ****//this here has to be drive not drive.file
$key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
$user_to_impersonate
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$originFileId = "longnumber";
$copyTitle = 'copied';
$newfile = copyFile($service, $originFileId, $copyTitle);
print_r($newfile);
function copyFile($service, $originFileId, $copyTitle)
{
$copiedFile = new Google_Service_Drive_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
?>
so got it working just now, ty all for your time guys really and edited my post to reflect the dang thing
If you want to give the end user access to your drive, you have to give your application authority to make API calls on behalf of a user (in this case you) in your domain. For this you have to set up a service account and generate a p12 key in the Google Developers Console. You have to enter the https://www.googleapis.com/auth/drive API scope in your Admin Console as well.
Full explanation and examples can be found here: https://developers.google.com/api-client-library/php/auth/service-accounts.
To achieve this you also need the Google API's client library: https://github.com/google/google-api-php-client (also mentioned in the Google manual).
Code example to let users make API calls on behalf of one of your accounts: https://developers.google.com/api-client-library/php/guide/aaa_oauth2_service
I'm trying to use a service account to create entries on a Google calendar. I'm really close on this, but the very last line won't work. I get a 500 Internal Service Error when I let this run. Otherwise, the program runs error free, for whatever that is worth.
The Calendar.php file contents can be found here. The insert() method that I am trying to call begins on line 1455 of that file.
<?php
function calendarize ($title, $desc, $ev_date, $cal_id) {
session_start();
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path( '../google-api-php-client/src/');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
// (not real keys)
$client_id = '843319906820-jarm3f5ctbtjj9b7lp5qdcqal54p1he6.apps.googleusercontent.com';
$service_account_name = '843319906820-jarm3f5ctbtjj7b7lp5qdcqal54p1he6#developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client/calendar-249226a7a27a.p12';
// echo pageHeader("Service Account Access");
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("xxxx Add Google Calendar Entries");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
// Prior to this, the code has mostly come from Google's example
// google-api-php-client / examples / service-account.php
// and relates to getting the access tokens.
// The rest of this is about setting up the calendar entry.
//Set the Event data
$event = new Google_Service_Calendar_Event();
$event->setSummary($title);
$event->setDescription($desc);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDate($ev_date);
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDate($ev_date);
$event->setEnd($end);
$calendarService = new Google_Service_Calendar($client);
$calendarList = $calendarService->calendarList;
$events = $calendarService->events;
// if I leave this line, my code won't crash (but it won't do anything, either)
//echo "here"; die();
$events.insert($cal_id, $event, false);
}
?>
I figured this out. Since I don't see any complete examples of using service accounts with API v3, I'm just going to post my complete solution for reference. There are a few of things that you need to do in addition to implementing the code, however:
1) You need to go to the Google Developer's console and mark your account as a 'service account'. This will differentiate it from a web application. The important difference is that nobody will be prompted to log in to their account before the events are added since the account will belong to your application, not an end user. For more information see this article, starting on page 5.
2) You need to create a public/private key pair. From the developer's console, click on Credentials. Under you service account, click on 'Generate new P12 key'. You'll need to store this somewhere. That file location becomes the $key_file_location variable string in the code below.
3) Also from the developer's console, you need to enable the Calendar API. From your project, on the left margin you'll see APIs. Select that and find the Calendar API. Click it, accept the terms of service, and verify that it is now displayed under Enabled APIs with a status of On
4) In Google Calendar that you want to add events to, under settings, click Calendar Settings then on 'Share this Calendar' at the top. Under 'Share with specific people' in the 'Person' field, paste in the email address from the service account credentials. Change the permission settings to 'Make changes to events'. Don't forget to save the change.
Then, implement this code somewhere.
Comment if something is confusing or omitted. Good luck!
<?php
function calendarize ($title, $desc, $ev_date, $cal_id) {
session_start();
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path( '../google-api-php-client/src/');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
//obviously, insert your own credentials from the service account in the Google Developer's console
$client_id = '843319906820-xxxxxxxxxxxxxxxxxxxdcqal54p1he6.apps.googleusercontent.com';
$service_account_name = '843319906820-xxxxxxxxxxxxxxxxxxxdcqal54p1he6#developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client/calendar-xxxxxxxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$calendarService = new Google_Service_Calendar($client);
$calendarList = $calendarService->calendarList;
//Set the Event data
$event = new Google_Service_Calendar_Event();
$event->setSummary($title);
$event->setDescription($desc);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($ev_date);
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($ev_date);
$event->setEnd($end);
$createdEvent = $calendarService->events->insert($cal_id, $event);
echo $createdEvent->getId();
}
?>
Some helpful resources:
Github example for service accounts
Google Developers Console for inserting events in API v3
Using OAuth 2.0 to Access Google APIs
Here is the Google API Client 2.0 way to do
Follow Alex's Answer Go Google Developer's console to create Service Account, but create credential in JSON
Follow Google API Client Upgrade Guide, install by composer and include in the way of
require_once 'vendor/autoload.php';
Follow Alex's Answer to go to Google Calendar to share the calendar with Service Account ID
xxxxx#yyyy.iam.gserviceaccount.com
Take Ref. to below coding and the most important one is the calendar id should be the email of calendar creator, but not primary
<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$application_creds = __DIR__.'/secret.json'; //the Service Account generated cred in JSON
$credentials_file = file_exists($application_creds) ? $application_creds : false;
define("APP_NAME","Google Calendar API PHP"); //whatever
$client->setAuthConfig($credentials_file);
$client->setApplicationName(APP_NAME);
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
//Setting Complete
//Go Google Calendar to set "Share with ..." Created in Service Account (xxxxxxx#sustained-vine-198812.iam.gserviceaccount.com)
//Example of Use of API
$service = new Google_Service_Calendar($client);
$calendarId = 'xxxx#gmail.com'; //NOT primary!! , but the email of calendar creator that you want to view
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
echo "Upcoming events:";
echo "<hr>";
echo "<table>";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
echo "<tr>";
echo"<td>".$event->getSummary()."</td>";
echo"<td>".$start."</td>";
echo "</tr>";
}
echo "</table>";
}
I'm trying to get some info of my Google Analytics account using PHP. I already followed the steps for creating a Service Account in the Google Console API in this answer. I'm using the Google API Client for PHP.
This is the code I've got so far:
<?php
$path_to_src = 'src';
// These files are in /src, upload its contents to your web server
require_once $path_to_src . '/Google_Client.php';
require_once $path_to_src . '/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '***'; //my private key
// Initialise the Google Client object
$client = new Google_Client();
// Your 'Product name'
$client->setApplicationName('My App Name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'**', //gserviceaccount mail
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('***'); // my cliente ID
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// create service and get data
$service = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:****'; // my profile id
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
I've enabled the openssl extension in PHP:
When browsing to the location of the php script, I just get a almost forever loading and the following error:
I'm using PHP 5.4.7:
After debuging the Google API Client code, it looks like the script is breaking at this line:
if (!openssl_sign($data, $signature, $this->privateKey, "sha256"))
Anything below this line does not get called. Looks like the error happens in this line. Is there a incompatibility here, or something?
One thing for starters you should change:
You instantiate the AnalyticsService twice. Take out the one you're not using:
$service = new Google_AnalyticsService($client);
See if that helps your problem at all.