google-api-php-client connect with key.p12 - php

I'm able to add event to my google calendar with an API keys and OAuth 2.0 client IDs but I want to do this without the authorization screen of google.
I followed the information found on this post:
stackoverflow.com/questions/8995451/how-do-i-connect-to-the-google-calendar-api-without-the-oauth-authentication
For this, I created a 'Service account keys'. I went to my project credentials and select 'Create Credentials > Service Account Key'
Then:
service account > my_project_name
Key type > p12
I saved the key file key.p12
Here is my code:
<?php
// display error, debbug
ini_set('display_errors',1);
session_start();
require_once './google-api-php-client/src/Google_Client.php';
require_once './google-api-php-client/src/contrib/Google_CalendarService.php';
// following values are taken from : console.developers.google.com/apis/credentials?project=projectname credentials
// OAuth 2.0 client IDs : Client ID
const CLIENT_ID = 'xxxx';
// Service account keys : Service account
const SERVICE_ACCOUNT_NAME = 'my_project_name';
// key
const KEY_FILE = './key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Calendar API Quickstart");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar'),
$key)
);
$client->setClientId(CLIENT_ID);
$cal = new Google_CalendarService($client);
//Save token in session
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
// my code here
$event = new Google_Event(...
$calendarId = 'mycalendarID#group.calendar.google.com';
$event = $cal->events->insert($calendarId, $event);
?>
And here is the error message:
Fatal error: Uncaught Google_AuthException: Error refreshing the OAuth2 token, message: '{
'error' : 'invalid_client',
'error_description' : 'The OAuth client was not found.'
}' in /home/www/google-api-php-client/src/auth/Google_OAuth2.php:288
Stack trace:
#0 /home/www/google-api-php-client/src/auth/Google_OAuth2.php(264): Google_OAuth2->refreshTokenRequest(Array)
#1 /home/www/google-api-php-client/src/auth/Google_OAuth2.php(218): Google_OAuth2->refreshTokenWithAssertion()
#2 /home/www/google-api-php-client/src/service/Google_ServiceResource.php(167): Google_OAuth2->sign(Object(Google_HttpRequest))
#3 /home/www/google-api-php-client/src/contrib/Google_CalendarService.php(469): Google_ServiceResource->__call('insert', Array)
#4 /home/www/goog in /home/www/google-api-php-client/src/auth/Google_OAuth2.php on line 288
It seems that the $client->getAccessToken() isn't set but I don't know why.
Thanks in advance for your help.

Create service account key and download the *.json file that contains private keys. Put the *.json file you just downloaded in a directory of your choosing ( credentials.json file in the example ). Then go to Google Calendar->Share and add service account id on the list.
putenv( 'GOOGLE_APPLICATION_CREDENTIALS=credentials.json' );
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope( 'https://www.googleapis.com/auth/calendar' );
$client->setHttpClient( new GuzzleHttp\Client( [ 'verify' => false ] ) ); // disable ssl if necessary
$service = new Google_Service_Calendar( $client );
// list events
$service->events->listEvents( $calendar_id, array( 'timeMin' => ( new DateTime )->format( DateTime::RFC3339 ) ) );
// add event
$event = new Google_Service_Calendar_Event( $data );
$event = $service->events->insert( $calendar_id, $event );
You can find the Google APIs PHP Client Library package with autoloader in the releases page on GitHub, so the only require_once call necessary is for autoload file:
require_once '/path/to/google-api-php-client/vendor/autoload.php';
And, Google docs may help you further, this is just one way that works for me so it may be useful to you as well.

Related

Json key is missing the type field

I try to connect to my Google calendar using the google api for php, version 2.2.0. Until now I do not succeed in connecting to my calendar and that is very frustrating.
At this moment I recieve the following fatal error:
Fatal error: Uncaught InvalidArgumentException: json key is missing
the type field in
/home/servi471/public_html/wp-content/plugins/google-api-php-client-2.2.0/vendor/google/auth/src/CredentialsLoader.php:123 Stack trace: #0
/home/servi471/public_html/wp-content/plugins/google-api-php-client-2.2.0/vendor/google/auth/src/ApplicationDefaultCredentials.php(154):
Google\Auth\CredentialsLoader::makeCredentials('https://www.goo...',
Array) #1
/home/servi471/public_html/wp-content/plugins/google-api-php-client-2.2.0/src/Google/Client.php(1078):
Google\Auth\ApplicationDefaultCredentials::getCredentials('https://www.goo...')
2 /home/servi471/public_html/wp-content/plugins/google-api-php-client-2.2.0/src/Google/Client.php(365):
Google_Client->createApplicationDefaultCredentials() #3
/home/servi471/public_html/wp-content/plugins/google-api-php-client-2.2.0/src/Google/Client.php(786):
Google_Client->authorize() #4
/home/servi471/public_html/wp-content/plugins/google-api-php-client-2.2.0/src/Google/Service/Resource.php(232):
Google_C in
/home/servi471/public_html/wp-content/plugins/google-api-php-client-2.2.0/vendor/google/auth/src/CredentialsLoader.php
on line 123
I use this code:
require_once WP_PLUGIN_DIR . '/google-api-php-client-2.2.0/vendor/autoload.php';
require_once WP_PLUGIN_DIR . '/google-api-php-client-2.2.0/src/Google/Client.php';
require_once WP_PLUGIN_DIR . "/google-api-php-client-2.2.0/vendor/google/apiclient-services/src/Google/Service/Calendar/Resource/CalendarList.php";
require_once WP_PLUGIN_DIR . "/google-api-php-client-2.2.0/vendor/google/apiclient-services/src/Google/Service/Oauth2.php";
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . dirname(__FILE__) . '/oauth-credentials.json');
$client = new Google_Client();
$redirect_uri = 'https://myredirect-uri';
$client->setRedirectUri($redirect_uri);
$client->setRedirectUri($redirect_uri);
$client->setClientId('myclient-di.apps.googleusercontent.com');
$client->setClientSecret('myclient-secret');
$client->setAccessType("offline"); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Calendar::CALENDAR);
$user_to_impersonate = 'owner-of-agenda#gmail.com';
$client->setSubject($user_to_impersonate);
$client->setAuthConfig(GOOGLE_APPLICATION_CREDENTIALS);
$client->useApplicationDefaultCredentials();
if (file_exists(CREDENTIALS_PATH)) {
$token = file_get_contents(CREDENTIALS_PATH);
echo "<h4>_Token</h4>";
var_dump($token);
$client->setAccessToken($token);
}
echo "<br><br>CLIENT";
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
var_dump($calendarList);
echo "<h4>End of example</h4>";
I see that an token is generated.
Could someone please assist me in making this connection?
I solved it, The JSON-key-file did not contain the type field. But I removed some statements and went back to the minimum of data. Added also the statement:
$client->setApprovalPrompt('force');
There was something you did not see.
There is a dropdown Create Credentials click on that and you will see three options:
API Key
OAuth Client ID
Service Account Key
Choose service account key, select your project name and download the json file from there, put that json file in here, putenv('GOOGLE_APPLICATION_CREDENTIALS=SellerWizard.json');

Google PHP Client Library - 'Login Required' exception

I am getting the following error when attempting to access my Google Analytics data: exception 'Google_Service_Exception' with message 'Error calling GET ...my query...': (401) login required
I'm not sure how to fix this, and I've already spent hours trying to set this up with no success.
Here's my code:
$client = new \Google_Client();
$client->setApplicationName("My App");
$client->setDeveloperKey('my API key');
$analytics = new \Google_Service_Analytics($client);
$OBJresult = $analytics->data_ga->get(
'ga:myprofileid' .,
'2012-01-01',
date("Y-m-d"),
'ga:visits',
array(
'filters' => 'ga:pagePath==/home',
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'sort' => '-ga:pageviews'
)
);
If you are only accessing your own data then you should go with a service account. If you want to be able to login and see other peoples data then you should use Oauth2.
service account Example:
<?php
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '[Your client id]';
$Email_address = '[YOur Service account email address Address]';
$key_file_location = '[Locatkon of key file]';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials($Email_address,
array($scopes),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );
?>
<html>
Results for date: 2014-12-14<br>
<table border="1">
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td><b>".$header['name']."</b></td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
Helpful Links:
Code ripped from Service account tutorial
Google Analytics oauth2 tutorial
Google's new official tutorial Hello Analytics php
The code shown does not authenticate anywhere.
I am not an expert on this API, but according to this link you are missing some of the following options.
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Application name');
$client->setClientId('INSERT HERE');
$client->setClientSecret('INSERT HERE');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('INSERT HERE'); // API key
The accepted answer didn't work for my service account. What worked instead:
Create a service account at IAM & Admin panel. Make sure to get the key file in JSON format.
Download that key file to a location reachable from your script (but not reachable from the Web!)
Run the following code:
$service_url = "https://www.googleapis.com/auth/analytics.readonly";
$client = new Google_Client();
$client->setAuthConfigFile($key_file_location); // path to your json key file
$client->addScope($service_url); // URL to the service you're planning to use
// Run your queries here
DalmTo's answer did the trick for me, but if you don't want to hardcode $client_id and such you can simplify it a bit:
public function __construct() {
$this->client = new Google_Client();
$credentials = $this->client->loadServiceAccountJson(__DIR__.'/../../google-service-account.json', [Google_Service_Calendar::CALENDAR]);
$this->client->setAssertionCredentials($credentials);
if($this->getAuth()->isAccessTokenExpired()) {
$this->getAuth()->refreshTokenWithAssertion($credentials);
}
}
/**
* #return \Google_Auth_OAuth2
*/
public function getAuth() {
return $this->client->getAuth();
}
Where google-service-account.json is the key file they give you when you create your service account. It looks like this:
{
"type": "service_account",
"project_id": "xxxxxxxxxx",
"private_key_id": "xxxxxxxxxxxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n",
"client_email": "xxxxxxxxxx#xxxxxxx.iam.gserviceaccount.com",
"client_id": "xxxxxxxxxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxx.iam.gserviceaccount.com"
}

Inserting Google Calendar Entries with Service Account

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>";
}

Google_Auth_Exception When trying to get OAuth 2.0 Service Account Authentication

This is my code:
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'Google/Client.php';
require_once 'Google/Service/AdExchangeSeller.php';
$scriptUri = "http://example.com/some_seller_api.php";
$client_id = 'XXXXXX.apps.googleusercontent.com';
$service_account_name = 'XXXXXXXXX#developer.gserviceaccount.com';
$key_file_location = '/XXXXX/privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Example_app");
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/adexchange.seller.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_AdExchangeSeller($client);
$acc = $service->adclients->listAdclients();
I do everything like in official manual and example from https://github.com/google/google-api-php-client/blob/master/examples/service-account.php
And i've got an error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }''
What am I doing wrong?
It appears that you haven't authorized your application with the target service. One of the OAuth2 steps is that your application (the one that's going to be accessing the service) needs to be "registered" (or authorized) with the target service. This is the way you will register what's the callback URL, etc.
Per your code, you are accessing the Ad Exchange Seller REST API. Open the following link and follow the step by step guide in order to fix the issue you are having:
https://developers.google.com/ad-exchange/seller-rest/getting_started#auth

google service account authentication with google-api-php-client using calendar api

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

Categories