Display Google Admin SDK JSON Response in PHP - php

Thanks to Emily, I found the php client library already. I need to retrieve a users data. There is a function in the API that can do so :
Google_DirectoryService.php
/**
* retrieve user (users.get)
*
* #param string $userKey Email or immutable Id of the user
* #param array $optParams Optional parameters.
* #return Google_User
*/
public function get($userKey, $optParams = array()) {
$params = array('userKey' => $userKey);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Google_User($data);
} else {
return $data;
}
}
index.php
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DirectoryService.php';
$client = new Google_Client();
$client->setApplicationName("IAA SIS");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://mypage.com/oauth2callback');
$client->setDeveloperKey('xxx');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$service = new Google_DirectoryService($client);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$results = $service->users->get('$email', 'public', $optParams); //Pass email to function parameter ? I'm not sure.
?>
I think the way I pass the parameter is wrong which i got error after adding the last line. How do I pass users login email to the function correctly ?
The error i got is :
[08-Jan-2014 03:17:33 America/Chicago] PHP Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/admin/directory/v1/users/me?key=: (403) Insufficient Permission' in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php:66
Stack trace:
#0 /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 /home2/iaapro/public_html/php/google-api-php-client/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest))
#2 /home2/iaapro/public_html/php/google-api-php-client/src/contrib/Google_DirectoryService.php(653): Google_ServiceResource->__call('get', Array)
#3 /home2/iaapro/public_html/php/google-plus-access.php(44): Google_UsersServiceResource->get('me')
#4 /home2/iaapro/public_html/php/index.php(2): include_once('/home2/iaapro/p...')
#5 {main}
thrown in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php on line 66
In addition, I have checked "Enable API Access" on admin.google.com and enable Admin SDK on Google APIs Console.
Can anyone gives me some help please ?

Finally, I figured out how to call the array using Google directory service API. Please refer to the code below:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
require_once 'google-api-php-client/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('Your_Client_ID');
$client->setClientSecret('Your_Client_Sercret');
$client->setRedirectUri('http://example.com/oauth2callback');
$client->setDeveloperKey('Your_API_Key');
//************************************************************
$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);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>

Have you checked out the Google API PHP client library? (https://code.google.com/p/google-api-php-client/)
Also, they have a github page: https://github.com/google/google-api-php-client
Once you downloaded the library from the site, you can see that the library has the Google_DirectoryService

Related

How to set up Gogle's People API

I've been trying to set up the sample PHP Quickstart.
When I try running it as is I get the following error :
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php:685
Stack trace:
#0 /opt/lampp/htdocs/rev_wip/vendor/google/apiclient/src/Client.php(406): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /opt/lampp/htdocs/rev_wip/quickstart.php(40): Google\Client->createAuthUrl()
#2 /opt/lampp/htdocs/rev_wip/quickstart.php(64): getClient()
#3 {main}
thrown in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php on line 685
So I add a URI :
// $redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
Now I get (when I run it on the browser) :
Authorization Error
Error 400: redirect_uri_mismatch
You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.
If you're the app developer, register the redirect URI in the Google Cloud Console.
Learn more
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you’re the app developer, make sure that these request details comply with Google policies.
redirect_uri: http://localhost/rev_wip/quickstart.php
I am thinking that this example is a Desktop APP and so there should be no Redirect URI. I, however get the common redirect URI error when I run it on the CLI.
How should I go about it?
Thank you all in advance.
Here is the code that I am working with:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName('People API PHP Quickstart');
$client->setScopes(Google_Service_PeopleService::CONTACTS_READONLY);
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = __DIR__ . '/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath) , true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath) , 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_PeopleService($client);
// Print the names for up to 10 connections.
$optParams = array(
'pageSize' => 10,
'personFields' => 'names,emailAddresses',
);
$results = $service
->people_connections
->listPeopleConnections('people/me', $optParams);
if (count($results->getConnections()) == 0) {
print "No connections found.\n";
}
else {
print "People:\n";
foreach ($results->getConnections() as $person) {
if (count($person->getNames()) == 0) {
print "No names found for this connection\n";
}
else {
$names = $person->getNames();
$name = $names[0];
printf("%s\n", $name->getDisplayName());
}
}
}
?>
In the tutorial you're linking to there's a section called "Troubleshooting" under which there's a section about the exact error you're facing:
https://developers.google.com/people/quickstart/php#uncaught_invalidargumentexception_missing_the_required_redirect_uri
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type.
This code requires an OAuth client ID of type Other, which will be
created for you when using the button in Step 1. If creating your own
client ID please ensure you select the correct type.
This suggests you didn't complete step 1 properly or that you have supplied your own client ID of the wrong type.

Accessing Google sheets through Google Service Account PHP

I am new to the Google APIs and also to somewhat to PHP. I know there has been quite some similar questions, but going through them all in the last few days I didn't manage to handle my problem.
I am building an app which reads from and writes to google sheets, and using a simple API key with a public sheet I am able to read without problems. I didn't manage to figure out the Service Account authorization though.
I have made the sheet private and authorized the service account e-mail address editor access to the sheet.
I double and triple checked the client_id, email address, sheet id.
Here is my code:
function update_stat($spreadsheet_range)
{
session_start();
$client_id = 'XXXXXXXXXX';
$email_address = 'xxx#xxxx.iam.gserviceaccount.com';
$service_account_file = __DIR__ . '/sheetsCS.json';
$spreadsheet_id = 'xxxxxxxxxxxxxxxxxxxxxx';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file);
date_default_timezone_set("Europe/Rome");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);
$result = $service->spreadsheets_values->get($spreadsheet_id, $spreadsheet_range);
return $result;
}
No matter what I try, I get the following error:
[25-Nov-2020 09:22:07 Europe/Rome] PHP Fatal error: Uncaught Google\Service\Exception: {"error":"invalid_grant","error_description":"Invalid JWT Signature."} in /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php:128
Stack trace:
#0 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php(103): Google\Http\REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#1 [internal function]: Google\Http\REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#2 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Task/Runner.php(181): call_user_func_array(Array, Array)
#3 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php(66): Google\Task\Runner->run()
#4 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-int in /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php on line 128
What am I missing to make this work?
You might also want to check this Quickstart guide for Google Sheets API in PHP
https://developers.google.com/sheets/api/quickstart/php
Contents:
Guidelines on how to enable Google Sheets API
How to install Google Client Library
Setup a sample code
Run the sample code
Sample Code:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s\n", $row[0], $row[4]);
}
}

Google Gmail API Error with code

Ok so im trying to play with the Gmail API but I keep runnning with this error. I looked at the google support forums and found nothing. The error code that i get is this below
Warning: fgets() expects parameter 1 to be resource, string given in
/home4/ab60883/public_html/email/quickstart.php on line 32
Fatal error: Uncaught exception 'Google_Auth_Exception' with message
'Invalid code' in
/home4/ab60883/public_html/email/google-api-php-client-master/src/Google/Auth/OAuth2.php:89 Stack trace: #0
/home4/ab60883/public_html/email/google-api-php-client-master/src/Google/Client.php(128):
Google_Auth_OAuth2->authenticate('', false) #1
/home4/ab60883/public_html/email/quickstart.php(35):
Google_Client->authenticate('') #2
/home4/ab60883/public_html/email/quickstart.php(68): getClient() #3
{main} thrown in
/home4/ab60883/public_html/email/google-api-php-client-master/src/Google/Auth/OAuth2.php
on line 89
is there something I'm doing wrong? I'm suppose to get a box to put my verification code but nothing. Any ideas?
require_once dirname(__FILE__).'/google-api-php-client-master/src/Google/autoload.php';
define('APPLICATION_NAME', 'Gmail API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-php-quickstart.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Gmail::GMAIL_READONLY)
));
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->authenticate($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, $accessToken);
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, $client->getAccessToken());
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
Make sure you are running the script from the command line and not your browser.
STDIN is the CLI equivalent of an HTML input tag.
Run php quickstart.php in the terminal.
If for some reason it can't find the file, make sure you put it in the root of your project.

USING OAUTH2 TO GET USER CONTACT LIST

I am trying to access a users contact list using google Oauth2 but seem to be running into an error insufficient permision. My code is as below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Google extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
require_once 'google-api-php-client/autoload.php'; // or wherever
autoload.php is located
$client = new Google_Client();
$scriptUri = "http://localhost/tcaller/google/";
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('Tcaller');
$client->setClientId('******');
$client->setClientSecret('****');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('******'); // API key
$client->setScopes(array('https://www.google.com/m8/feeds' , 'https://www.googleapis.com/auth/contacts.readonly'));
$plus = new Google_Service_Plus($client);
if (isset($_GET['logout'])) { // logout: destroy token
$this->session->unset_userdata("token");
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$tokenArr = array('token' => $client->getAccessToken());
$this->session->set_userdata($tokenArr);//gets valid access token
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //set into session storage
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if ($this->session->userdata('token')) { // extract token from session and configure client
$token = $this->session->userdata('token');
$client->setAccessToken($token);
try {
$me = $plus->people->get('me');
print_r($me);
} catch (apiServiceException $e) {
// Handle exception. You can also catch Exception here.
// You can also get the error code from $e->getCode();
echo 'error';
}
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die();
}
}
}
?>
I am getting the error
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https://www.googleapis.com/plus/v1/people/me?key=%2A%2A%2A%2A%2A%2A:
(403) Insufficient Permission' in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php:111
Stack trace: #0
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(63):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client)) #1 [internal function]:
Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request)) #2
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Task\Runner.php(172):
call_user_func_array(Array, Array) #3
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(47):
Google_Task_Runner->run() #4
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Client.php(564):
Google_Http_REST::execute(Object(Google_Client), Object(Google_H in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php
on line 111
Am i missing something
You should not need to use a separate API key and call $client->setDeveloperKey() as you're obtaining and using an OAuth 2.0 access token already with a client secret. Moreover, it seems that that is incorrect and/or not associated with the same project. So please try with that call removed.

Copy google doc spreadsheet using php api

I want to copy Google Doc spreadsheet file.This code I am using
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('myclientid');
$client->setClientSecret('myclient secret');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
copyFile($service,'my schema id','Copy Of Schema');
I am not able to get $service instance. SO I searched and get the above way to do but now it is giving 401 login required error.
Please help me
You need to check for sufficient authorization from the user
you need to generate authorization URL:
$authUrl = $client->createAuthUrl();
Redirect user to the authUrl
Make user paste the authorization code:
$authCode = trim(fgets(STDIN));
Authenticate
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
Once above it done, you have now authenticated the user with OAuth to access drive.
Reference: Click here

Categories