I am using the following code to retrieve the list of users associated with my google apps account.
There is no problem with authentication but when the redirection made this error is appearing.
index.php
<?php
require_once 'test_user/src/Google_Client.php';
require_once 'test_user/src/contrib/Google_PlusService.php';
require_once 'test_user/src/contrib/Google_Oauth2Service.php';
require_once 'test_user/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('****');
$client->setClientSecret('****');
$client->setRedirectUri('****');
$client->setDeveloperKey('****');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
$adminService = new Google_DirectoryService($client); // Call directory API
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
//$users = $adminService->users->get($email);
$list_users = $adminService->users->listUsers();
print '<h2>Response Result:</h2><pre>' . print_r($list_users, true) . '</pre>';
$_SESSION['access_token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("location:$authUrl");
}
?>
error i'm getting:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling
GET https://www.googleapis.com/admin/directory/v1/users?
key=AIzaSyBp0yBFCCosu113tbNbw7yAIjIt1ndFFIs: (400) Bad Request' in
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php:66 Stack trace: #0
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php(36):
Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
/var/www/vhosts/vx44.com/httpdocs/test_user/src/service/Google_ServiceResource.php(186):
Google_REST::execute(Object(Google_HttpRequest)) #2
/var/www/vhosts/vx44.com/httpdocs/test_user/src/contrib/Google_DirectoryService.php(695):
Google_ServiceResource->__call('list', Array) #3
/var/www/vhosts/vx44.com/httpdocs/test_user/test_user.php(52):
Google_UsersServiceResource->listUsers('nelson302.com') #4 {main} thrown in/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php on line 66
Note that i've enabled Admin SDK on Google APIs Console.
What am i doing wrong here? thank you for helping
Try replacing:
$list_users = $adminService->users->listUsers();
with:
$adminOptParams = array('customer' => 'my_customer');
$list_users = $adminService->users->listUsers($adminOptParams);
this is explained in the Admin SDK Developer's Guide.
Related
I am trying to add google spreadsheet using google drive api in php. But I am getting the following error after authentication.
Uncaught exception 'Google_Exception' with message 'Cant add services after having authenticated' in /var/www/html/spreadsheet/google/src/Google_Client.php:119 Stack trace: #0 /var/www/html/spreadsheet/google/src/contrib/Google_DriveService.php(1046): Google_Client->addService('drive', 'v2') #1 /var/www/html/spreadsheet/index.php(20): Google_DriveService->__construct(Object(Google_Client)) #2 {main} thrown in /var/www/html/spreadsheet/google/src/Google_Client.php on line 119
My code:
<?php
require '/var/www/html/spreadsheet/google/src/Google_Client.php';
require '/var/www/html/spreadsheet/google/src/contrib/Google_DriveService.php';
require '/var/www/html/spreadsheet/google/src/contrib/Google_Oauth2Service.php';
$client = new Google_Client();
$client->setClientId('xxxxx-vdbo5lga3sq7g8q4g8adgqh72m0ng8ef.apps.googleusercontent.com');
$client->setClientSecret('BCGuyCPHwNflflBU5jDQ25LQ');
$client->setRedirectUri('http://localhost/spreadsheet/index.php');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_DriveService($client);
//Inserting a file
$file = new Google_DriveFile();
$file->setTitle('Mysheet');
$file->setDescription('My first sheet through php');
$file->setMimeType('application/vnd.google-apps.spreadsheet');
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.spreadsheet',
'uploadType' => 'multipart'
));
print_r($createdFile);
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
?>
You have to create a new service, before you authenticate the Client:
<?php
// ...
$client = new Google_Client();
$client->setClientId('clientID');
$client->setClientSecret('clientSecret');
$client->setRedirectUri('redirectURI');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
// create Drive service before authentication
$service = new Google_DriveService($client);
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$client->setAccessToken($_SESSION['access_token']);
}
// ...
} else {
// ...
}
Btw: See the simplefileupload example in the google-api-php-client repo.
Using code below I successfully received a token and using this token also get user detail, but when I try to post/insert moment in user wall I see the following error message
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https:--www.googleapis.com/plus/v1/people/me/moments/vault: (401) Unauthorized' in $_SESSION['access_token_gp']
I got user token when user login using my site in login page I ask for below permission
$client->addScope("email");
$client->addScope("https://www.googleapis.com/auth/plus.stream.write");
$client->addScope("https://www.googleapis.com/auth/plus.login");
If I print_r($tokenInfo); you will see all scope which I ask at login time.
The full code:
session_start();
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/autoload.php');
$client_id = 'my_client_id';
$client_secret = 'my_secret_key';
$redirect_uri = 'my_redirect_url';
// code to post in google plus start here //
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
if (isset($_SESSION['access_token_gp'])) {
// Verify the token
$token = json_decode($_SESSION['access_token_gp']);
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$token->access_token;
$req = new Google_Http_Request($reqUrl);
$tokenInfo = get_object_vars(json_decode($client->getAuth()->authenticatedRequest($req)->getResponseBody()));
if($tokenInfo['expires_in'] <= 0){
$client->authenticate($_SESSION['access_token_gp']);
$_SESSION['access_token_gp'] = $client->getAccessToken();
} else {
$client->setAccessToken($_SESSION['access_token_gp']);
}
$plusservicemoment = new Google_Service_Plus_Moment();
$plusservicemoment->setType("http://schemas.google.com/AddActivity");
$plusService = new Google_Service_Plus($client);
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setId($tokenInfo['user_id']);
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("The madexme Platform");
$item_scope->setDescription("A page that describes just how madexme is work!");
//$item_scope->setImage("full image path here");
$plusservicemoment->setTarget($item_scope);
$result = $plusService->moments->insert('me','vault',$plusservicemoment);
//print_r($result);
}
// code to post in google plus end here //
Make sure you have the latest client lib from GitHub. There is something wrong with your Oauth2 connection. This code is partially converted from my Google Google Calendar API tutorial. I don't have the power to test it right now. But this should be close. I will test it tonight.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array(https://www.googleapis.com/auth/plus.login'));
//For loging out.
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$service = new Google_Service_Plus($client);
$moment = new Google_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_ItemScope();
$itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
$moment->setTarget($itemScope);
$plus->moments->insert('me', 'vault', $moment);
?>
Again I hope you understand that this is not going to show up on the users Google+ page / timeline.
This is my code to insert an activity:
const SERVICE_ACCOUNT_EMAIL = "xxxxxx";
const KEY_FILE = 'key.p12';
$client_id = 'yyyyyyyyy';
$client_secret = 'zzzzzzzzz';
$redirect_uri = 'ttttttttt';
$client = new Google_Client();
$client->setApplicationName("Prueba_social123");
$key = file_get_contents(KEY_FILE);
$user_credentials = new Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array("https://www.googleapis.com/auth/plus.me",
"https://www.googleapis.com/auth/plus.stream.write"),
$key);
$user_credentials->sub = "xxxxxxxxx#gmail.com";
$client->setAssertionCredentials($user_credentials);
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey('wwwwwwwwwwwwwwwwwwwwww');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.stream.write') );
$plus = new Google_Service_Plus($client);
$oauth2 = new Google_Service_Oauth2($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
$plusdomains = new Google_Service_PlusDomains($client);
$activityObject = new Google_Service_PlusDomains_ActivityObject();
$activityObject->setOriginalContent("Prueba de actividad desde la API de mensajes123");
$activityAccess = new Google_Service_PlusDomains_Acl();
$activityAccess->setDomainRestricted(true);
$resource = new Google_Service_PlusDomains_PlusDomainsAclentryResource();
$resource->setType("public");
$resources = array();
$resources[] = $resource;
$activityAccess->setItems($resources);
$activity = new Google_Service_PlusDomains_Activity();
$activity->setObject($activityObject);
$activity->setAccess($activityAccess);
$plusdomains->activities->insert("me", $activity);
....................
And I get the ERROR:
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling POST
https://www.googleapis.com/plusDomains/v1/people/me/activities?key=xxxxxxxxxxxxxxxx:
(403) Forbidden' in
/var/www/html/public/pruebas_sociales/google-api/src/Google/Http/REST.php:79
Stack trace: #0
/var/www/html/public/pruebas_sociales/google-api/src/Google/Http/REST.php(44):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request)) #1
/var/www/html/public/pruebas_sociales/google-api/src/Google/Client.php(512):
Google_Http_REST::execute(Object(Google_Client),
Object(Google_Http_Request)) #2
/var/www/html/public/pruebas_sociales/google-api/src/Google/Service/Resource.php(195):
Google_Client->execute(Object(Google_Http_Request)) #3
/var/www/html/public/pruebas_sociales/google-api/src/Google/Service/PlusDomains.php(491):
Google_Service_Resource->call('insert', Array, 'Google_Service_...')
4 /var/www/html/public/pruebas_sociales/google-api/examples/idtoken.php(114):
Google_Service_PlusDomains_Activities_ in
/var/www/html/public/pruebas_sociales/google-api/src/Google/Http/REST.php
on line 79
I'm with the problem from two weeks ago. How I can fix it? Help.
I couldn't connect able to display events,insert events by using php client library.
This is the error i got.
I am using v3 version of client library
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/calendars/primary?key=****************: (401) Login Required' in /var/www/html/google-api-php-client1/src/Google/Http/REST.php:79
Stack trace:
#0 /var/www/html/google-api-php-client1/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /var/www/html/google-api-php-client1/src/Google/Client.php(503): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /var/www/html/google-api-php-client1/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /var/www/html/google-api-php-client1/src/Google/Service/Calendar.php(1269): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#4 /var/www/html/simple.php(27): Google_Service_Calendar_Calendars_Resource->get('primary') #5 {main} thrown in /var/www/html/google-api-php-client1/src/Google/Http/REST.php on line 79
since you are getting 401 login required error so you need to set setAccessToken.visit here Error with Google Calendar API - 401 Login required when adding a calendar event
may be you need to issue refreshToken() using the original authenticated access code that contains a refresh token.
// example
$google_client->refreshToken($token->refresh_token);
and use 'setDeveloperKey'. it works.you can see this:https://code.google.com/p/google-api-php-client/issues/detail?id=218
Finally solved problem.
This is the perfect example to get list of events of calender.
<?php
// ...
ini_set('display_errors', 1);
error_reporting(E_ALL);
set_include_path('google-api-php-client1/src');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
//
$client = new Google_Client();
//print_r($client);exit;
//$client->setUseObjects(true);
$client->setApplicationName("your-app-name");
$client->setClientId("CLIENT id");
$client->setClientSecret('CLIENT SECRET');
$client->setDeveloperKey('DEVELOPER KEY');
$client->setRedirectUri('your url mostly localhost');
$client->setScopes(array(
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
));
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
//print_r($_SESSION['token']);exit;
//header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
if (isset($_SESSION['token'])) {
//echo 'innn';exit;
$client->setAccessToken($_SESSION['token']);
//echo 'innn';exit;
}
}
if ($client->getAccessToken()) {
//echo 'innn';exit;
$service = new Google_Service_Calendar($client);
//echo '<pre>'; print_r($service);exit;
//$calendar = $service->calendars->get('primary');
//echo $calendar->getSummary();
$events = $service->events->listEvents('primary');
while(true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary();
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->events->listEvents('primary', $optParams);
} else {
break;
}
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Script to add event.
Actual problem is Google Calendar version 3 not matching with its documentation.
So I checked Calender.php for all available classes.
$event = new Google_Service_Calendar_Event();
$event->setSummary('Interview');
$event->setLocation('Hell');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-09-04T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-09-04T11:00:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('email#abc.com');
// ...
$attendees = array($attendee1,
// ...
);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();
I am using the following code to retrieve the list of users associated with my Google apps admin account. It's working fine when using a Google apps admin account but when using other Google apps/Gmail accounts an error appears.
Code:
<?php
require_once 'test_user/src/Google_Client.php';
require_once 'test_user/src/contrib/Google_PlusService.php';
require_once 'test_user/src/contrib/Google_Oauth2Service.php';
require_once 'test_user/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('****');
$client->setClientSecret('****');
$client->setRedirectUri('****');
$client->setDeveloperKey('****');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
$adminService = new Google_DirectoryService($client); // Call directory API
error_reporting(E_ALL);
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$users = $adminService->users->get($email);
//print_r($users);
//$list_users = $adminService->users->listUsers();
$adminOptParams = array('customer' => 'my_customer');
$list_users = $adminService->users->listUsers($adminOptParams);
print '<h2>Response Result:</h2><pre>' . print_r($list_users, true) . '</pre>';
$_SESSION['access_token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("location:$authUrl");
}
?>
Error:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET
https://www.googleapis.com/admin/directory/v1/users/william.nelson920#gmail.com?key=AIzaSyBp0yBFCCosu113tbNbw7yAIjIt1ndFFIs: (404) Resource Not
Found: userKey' in /var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php:66 Stack trace: #0
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
/var/www/vhosts/vx44.com/httpdocs/test_user/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2
/var/www/vhosts/vx44.com/httpdocs/test_user/src/contrib/Google_DirectoryService.php(653): Google_ServiceResource->__call('get', Array) #3
/var/www/vhosts/vx44.com/httpdocs/test_user/test_user.php(54): Google_UsersServiceResource->get('william.nelson9...') #4 {main} thrown in
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php on line 66
The Directory API is restricted for Google Apps Admin only. It allows domain administrators to retrieve domain users' information.
You should be able to get user information from your own domain (and your own domain ONLY). In your case, you are trying to get the user information of 'william.nelson920#gmail.com'. Since gmail.com is a consumer Google Apps product, and I don't think you are the administrator of gmail.com? The API is throwing the correct error indicating that this user does not exist in your domain.
Here is more info about the get request from Google documentation
https://developers.google.com/admin-sdk/directory/v1/guides/manage-users#get_user
Hope this helps!