Google Api Client PHP - Create Fusion Table - php

With the newest version of the Google Api Client for PHP it is hard to come by examples that work. The Documentation is also very slim.. Ive tried a LOT and can't figure out how to login/authenticate so I can create/insert into Fusion Tables.
Ive tried with oAuth and with a Service Token (with a p12 file).
I am able to retrieve data from a Fusion Table and log it to FireBug (with FirePHP). But this only needs the Developer ID and no authentication.
If somebody has a working example Id be very grateful!
My trials:
class GoogleClass {
protected $firephp;
public function init() {
session_start();
require_once 'Google/Client.php';
require_once 'Google/Auth/AssertionCredentials.php';
#require_once 'Google/Auth/OAuth2.php';
require_once 'Google/Service/Fusiontables.php';
#require_once 'Google/Service/Urlshortener.php';
#require_once 'Google/Service/Oauth2.php';
/*
Service Auth
$client_id = 'client_id';
$service_account_name = 'service_account_name';
$key_file_location = 'key_file_location';
$client = new Google_Client();
$client->setApplicationName('FusionTableConnect');
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('http://www.googleapis.com/auth/fusiontables'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
$this->firephp->error($e);
}
}
$_SESSION['service_token'] = $client->getAccessToken();
*/
/*
Execute Query to get Table results
*/
$client = new Google_Client();
$client->setDeveloperKey('developerKeyServer'); // Server Application API key - Query
$tableId = 'tableId';
$ft = new Google_Service_Fusiontables($client);
try {
$result = $ft->query->sql("SELECT gm_code FROM $tableId");
$this->firephp->log($result, 'Array');
} catch (Exception $e) {
$this->firephp->error($e);
}
/* ------------------------------------------------------------------------------ */
/*
Google Client setup
$client = new Google_Client();
#$client->setApplicationName('TestApp');
$client->setClientId('clientId'); // Web application Client ID
$client->setClientSecret('clientSecret'); // Web application Secret key
#$client->addScope('https://www.googleapis.com/auth/fusiontables'); // Fusion Tables scope
$client->setRedirectUri('redirectUri');
#$client->setDeveloperKey('developerKeyServer'); // Server Application API key - Query
#$client->setDeveloperKey('developerKeyBrowser'); // Browser Application API key
*/
/*
oAuth2 Identification
$service = new Google_Service_Urlshortener($client);
#$client->addScope(Google_Service_Urlshortener::URLSHORTENER);
$client->setScopes("https://www.googleapis.com/auth/plus.login");
$authUrl = $client->createAuthUrl();
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']);
}
*/
/*
Fusion Tables
$service = new Google_Service_Fusiontables($client);
try {
$result = $service->query->sql("SELECT gm_code FROM tableId");
$this->firephp->log($result, 'Array');
} catch (Exception $e) {
$this->firephp->error($e);
}
$column = new Google_Service_Fusiontables_Column();
$column->setName('foo');
$column->setType('STRING');
$table = new Google_Service_Fusiontables_Table();
$table->setName('bar');
$table->setColumns(array($column));
try {
$service->table->insert($table);
} catch(Exception $e) {
$this->firephp->error($e);
}*/
}
public function firePHPInit($auto) {
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$this->firephp = FirePHP::getInstance(true);
if ($auto) {
$this->firephp->registerErrorHandler(
$throwErrorExceptions=false);
$this->firephp->registerExceptionHandler();
$this->firephp->registerAssertionHandler(
$convertAssertionErrorsToExceptions=true,
$throwAssertionExceptions=false);
/*try {
throw new Exception('Test Exception');
} catch(Exception $e) {
$this->firephp->error($e); // or FB::
}*/
}
}
}

I think this may help you. this is official document for php-client from zend
http://framework.zend.com/manual/1.11/en/zend.gdata.photos.html
But I suggest to use oAuth 2.0

Related

google admin sdk Not Authorized to access this resource/api php

Need help about google admin sdk. I m newbie on google admin sdk. So i am stuck on its showing error while authorizing like code 403: Not Authorized to access this resource/api. Here is my Code.
<?php
include_once '../vendor/autoload.php';
include_once "base.php";
session_start();
echo pageHeader("Service Account Access");
/************************************************
Make an API request authenticated with a service
account.
************************************************/
$client = new Google_Client();
$client->setAuthConfig('client_secret1.json');
$client->setApplicationName("automate user");
$client->setScopes(['https://www.googleapis.com/auth/admin.directory.user']);
$client->setSubject('admin#XXXXX');
$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
//$auth_url = $client->createAuthUrl();
//header('Location: '.filter_var($auth_url, FILTER_SANITIZE_URL));
if(isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
if ($credentials_file = checkServiceAccountCredentialsFile()) {
// set the location manually
$client->setAuthConfig('client_secret1.json');
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS=automate user.json')) {
// use the application default credentials
$client->useApplicationDefaultCredentials();
} else {
echo missingServiceAccountDetailsWarning();
return;
}
$dir = new Google_Service_Directory($client);
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();
$results = $dir->users->get('xxxxx#xxx.org');
if($results) {
echo "Name : ".$results->name->fullName."";
} else{
echo " User doesn't exist : ".$email;
}
}
else {
$redirect_uri = 'http://'.$_SERVER['HTTP_HOST']. '/google/oauth.php';
header('Location: '.filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
pageFooter(__FILE__); ?>
Actually i want o create an user through google api. Please tell me anybody what's i do wrong ? please help me
You can create a user through Users: insert. There is a Try it now to test if you have entered correct/valid data.
Here is a sample code from quickstart to help your progress.
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));
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(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($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_Directory($client);
// Print the first 10 users in the domain.
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 10,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
if (count($results->getUsers()) == 0) {
print "No users found.\n";
} else {
print "Users:\n";
foreach ($results->getUsers() as $user) {
printf("%s (%s)\n", $user->getPrimaryEmail(),
$user->getName()->getFullName());
}
}
For further information about this error, see this SO post.
you need to enable domain-wide delegation for your service
account, and then have the service account impersonate a domain admin
when it makes the request:

Google Drive Rest API authentication issue after entering id, secret, and key

I want to use Google Drive rest Api to list the files on the drive. But there is an authentication problem.
I enter the Client Id , Client secret, and Api key but it's not working. I use the library.
My code is as follows:
<?php
function get_gdrive_file_list($operation) {
include(VIS_PATH_PLUGINS.'gmail_login/src/Google_Client.php');
include(VIS_PATH_PLUGINS.'gmail_login/src/contrib/Google_DriveService.php');
$client = new Google_Client();
$client->setClientId('****************************');
$client->setClientSecret('**********************');
$client->setRedirectUri('**********************');
$client->setDeveloperKey('*********************');
$cal = new Google_DriveService($client);
if (isset($_SESSION['code'])) {
$client->authenticate($_SESSION['code']);
$_SESSION['token'] = $client->getAccessToken();
unset($_SESSION['code']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$calList = $cal->files->listFiles();
echo "Result : ";echo "<pre>";print_r($calList);echo "</pre>";echo "<br>";
}
} ?>

How to use JSON key instead of P12 in Google Spreadsheet Authentication with PHP?

I am working with Google Spreadsheet in PHP. When I use P12 key it works perfect, but when I use JSON key instead of P12 key while Authenticating with Google Spread Sheet, it is giving
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Unable to load private key'
Please tell me how to use JSON key while Authenticating with Google Spread Sheet in PHP.
Here is the solution I found.
For P12 Key
Normally, we use the following code to generate a token.
public static function getToken()
{
$key = file_get_contents( APPLICATION_DIR.'/'.APPLICATION_GOOGLE_CLIENT_KEY_FILE);
$cred = new Google_Auth_AssertionCredentials(
APPLICATION_GOOGLE_CLIENT_EMAIL,
array('https://spreadsheets.google.com/feeds'),
$key
);
$client = new Google_Client();
$client->setAssertionCredentials($cred);
if (!$client->getAuth()->isAccessTokenExpired()) {
return false;
}
else {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service_token = json_decode($client->getAccessToken());
return $service_token->access_token;
}
For JSON Key
But now we don't have P12 key, we have a JSON key, so I just made some changes in the above code, please take a look below:
public static function getToken()
{
$key = APPLICATION_DIR.'/'.APPLICATION_GOOGLE_CLIENT_KEY_FILE;
$data = json_decode(file_get_contents($key)); // here i decoded the json
if (isset($data->type) && $data->type == 'service_account') {
$cred = new Google_Auth_AssertionCredentials(
APPLICATION_GOOGLE_CLIENT_EMAIL, // it's the client email
array('https://spreadsheets.google.com/feeds'), // it's google spreadsheet scope
$data->private_key // here is the private key
);
}
$client = new Google_Client();
$client->setAssertionCredentials($cred);
if (!$client->getAuth()->isAccessTokenExpired()) {
return false;
}
else {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service_token = json_decode($client->getAccessToken());
return $service_token->access_token;
}
Access token will only be valid 1 hour and is sent as decoded json. So you probably have to decode it first.
$token = json_decode($client->getAccessToken());
$serviceRequest = new DefaultServiceRequest($token->access_token);
ServiceRequestFactory::setInstance($serviceRequest);
Using p12 key should work fine then.
session_start();
define('GOOGLE_CLIENT_ID','');
define('GOOGLE_CLIENT_EMAIL','');
define('GOOGLE_SPREADSHEETS_SCOPE','https://spreadsheets.google.com/feeds');
define('GOOGLE_APPLICATION_NAME','whatever');
define('GOOGLE_KEY_FILE','xxxxxxxxxxxxxx.p12'); // pass for key: notasecret
function getToken()
{
$client = new Google_Client();
$client->setApplicationName(GOOGLE_APPLICATION_NAME);
$client->setClientId(GOOGLE_CLIENT_ID);
$key = file_get_contents(GOOGLE_KEY_FILE);
$cred = new Google_Auth_AssertionCredentials(
GOOGLE_CLIENT_EMAIL,
array(GOOGLE_SPREADSHEETS_SCOPE),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service_token = json_decode($client->getAccessToken());
return $service_token->access_token;
}
require("vendor/autoload.php");
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
$_SESSION['access_token']=getToken();
$serviceRequest = new Google\Spreadsheet\DefaultServiceRequest($_SESSION['access_token']);
Google\Spreadsheet\ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();

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

Authorisation error with Google API php client

I try to use Google API PHP client to make my application use its Google Drive account in offline way, because I dont want my application to redirect every time to google for getting authorisation.
So when I connect for the first time and recieve credentials with access_token and refresh_token I backup it and try to use it every time.
Problem is that it works till expiration and than , when API client tries to refresh acces token I'm keep getting this error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_request", "error_description" : "Client must specify either client_id or client_assertion, not both" }
My stored credentials are in json form:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"XXX,"created":1406537500}
My code (taken from Google tutorials with some changes):
function exchangeCode($authorizationCode) {
try {
$client = new Google_Client();
$client->setClientId(self::$clientId);
$client->setClientSecret(self::$clientSacred);
$client->setRedirectUri(self::getRedirectURI());
$_GET['code'] = $authorizationCode;
return $client->authenticate();
} catch (Google_AuthException $e) {
echo 'An Google_AuthException occurred: ' . $e->getMessage();
throw new CodeExchangeException(null);
}
}
function getCredentials($authorizationCode, $state='') {
$emailAddress = '';
try {
$credentials = self::exchangeCode($authorizationCode);
$credentialsArray = json_decode($credentials, true);
if (isset($credentialsArray['refresh_token'])) {
self::storeCredentials($credentials);
return $credentials;
} else {
$credentials = self::getStoredCredentials();
$credentialsArray = json_decode($credentials, true);
if ($credentials != null &&
isset($credentialsArray['refresh_token'])) {
return $credentials;
}
}
} catch (CodeExchangeException $e) {
print 'An CodeExchangeException occurred during code exchange.';
$e->setAuthorizationUrl(self::getAuthorizationUrl($emailAddress, $state));
throw $e;
} catch (NoUserIdException $e) {
print 'No e-mail address could be retrieved.';
}
$authorizationUrl = self::getAuthorizationUrl($emailAddress, $state);
throw new NoRefreshTokenException($authorizationUrl);
}
function buildService($credentials) {
$apiClient = new Google_Client();
$apiClient->setUseObjects(true);
$apiClient->setAccessToken($credentials);
return new Google_DriveService($apiClient);
}
function test()
{
$credentials = self::getStoredCredentials();
if ( empty($credentials) )
{
if (!isset($_GET["code"]))
{
header("location:".self::getAuthorizationUrl("xxx#gmail.com", ''));
die();
}
$credentials = self::getCredentials($_GET["code"]);
echo "NEW: ".$credentials;
}
else
{
echo "STORED: ".$credentials;
}
$service = self::buildService($credentials);
}
The error happends in buildService method when its client object tries to refresh based on credentials passed.

Categories