google drive sdk/google drive api ----using PHP web application - oauth-2.0

I am creating website page using Google drive API which do following stuff:--
provide user set of pdf file which is stored in my Google drive without any type of Login / authentication by any means and file are public.
who visit that page and if he/she want to download that file/pdf then he/she can do so just by clicking on it without any signup and login.
i have no idea how to getting started with it...is it necessary to use OAuth 2...
in simple word i want to use google drive as file hosting site to host my file and reach users through website.
please give me your valuable solution...
thanks

For php look here for a full example and video. You have to download the Google Drive API for the programming language you are using. Then use that API to help you auth and access files. Here is an example from Google developers page using PHP
<?php
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('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>

You will want to use the PHP client library located here: https://developers.google.com/api-client-library/php/
You will then want to authenticate against google using auth2.
Then you can make calls to the Drive API https://developers.google.com/drive/v2/reference/ using the PHP client library.

Related

goog api homegraph - scope

I want to control (read) statuses of a smart swithc associated in my google home app. I did a similat application using the smartdevice api and i am able to control a google thermostat.
Now back to the smart switch, i read that I need to use the homegraph api (correct me if i'm wrong). I followed the docs on google api and tried many times with oauth , setting the scope https://www.googleapis.com/auth/homegraph (as per this link https://developers.google.com/identity/protocols/oauth2/scopes). When I send the request to get the token i receive an error that this scope is not authorised.
Authorization Error
Error 400: invalid_scope
Some requested scopes cannot be shown: [https://www.googleapis.com/auth/homegraph]
my code is below, can anyone lighten me up what is the issue? I searched and there is no php code example fro this type of implementation with the homegraph.
require_once('vendor/autoload.php');
$client = new Google\Client();
$client->setAuthConfig('client_secret_oauth.apps.googleusercontent.com.json');
$client->addScope( 'https://www.googleapis.com/auth/homegraph' );
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/homegraph-api/oauth2callback.php');
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
// code for google client api to interact with homegraph
Thank you.

GET Channel ID using Youtube API v3 with Service Account

Good Day, I Try to Get Channel ID using service account, because I´m using it on other scopes on my project. But when I do request process its give me the service account information. i´m using php btw
Many thanks in advance and any help will be appreciated.
p.d. i´m replace real account info for dummy text.
And of Course the code :
$credentials_file = $this->key_dir . $this->key_file['title'];
$client = new \Google_Client();
$client->setAuthConfig($credentials_file);
$client->addScope('https://www.googleapis.com/auth/youtube');
$client->setApplicationName("Youtube Analytics");
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
if (!empty($accessToken)) {
$service = new \Google_Service_YouTube($client);
$data = $service->channels->listChannels('id,snippet', array('mine' => 'true'));
echo "id: " . $data->items[0]->id . "<br>";
echo "Kind: " . $data->items[0]->kind . "<br>";
echo "Snippet -> title : " . $data->items[0]->snippet['title'] . "<br>";
}
AFAIK, Youtube API doesn't support Service Account Flow. As described in the document :
The service account flow supports server-to-server interactions that do not access user information. However, the YouTube Data API does not support this flow. Since there is no way to link a Service Account to a YouTube account, attempts to authorize requests with this flow will generate a NoLinkedYouTubeAccount error.
Also in the Youtube v3 Google Service Account Access issue, "There are no plans to add support for Service Account authorization to YouTube Data API v3 calls." As stated in the related SO question #21890982 and #21057358 : you'll need your own account for that and you can create an authentication for services using V3 without user intervention.
Hope this helps.

Google Analytics API Returning 401 On Example Code

I am attempting to retrieve the data from our content experiments from google analytics...
I am using the following code, my creds are good, and have been censored for this post...
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://cloud.google.com/console to generate your
// client id, client secret, and to register your redirect uri.
$client->setDeveloperKey('xxxxx');
$service = new Google_Service_Analytics($client);
try {
$results = $service->management_experiments->listManagementExperiments('xxxx', 'xxxx', 'xxxx');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
echo '<pre>';
print_r($results);
echo '</pre>';
I am using the following example ....
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#list
Any ideas on why I am getting a 401 unauthorized? That a login is required?
The problem is that you haven't Authorized access to your data yet. Since you say its only your own data you want to access i sugest you look into a service account. By setting up a service account in Google apis console it will allow you to access your own data with out needing to login and autenticate the code all the time.
Check the following link. Read though Before you begin make sure you do all that.
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service
Register your application in the Google Developers Console
Authorize access to Google Analytics data.
Create an Analytics service object
You have skiped the first two steps and gone directly to step 3 creating the service object. Once you have done step 1 you can use the following code for step 2.
Here is an example of how to use a service account in php ServiceAccount
That sample project is for the PredictionService not the google analytics service. You need to edit it slightly.
require_once '../../src/Google/Client.php';
require_once '../../src/Google/Service/Analytics.php';
// 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
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Analytics Sample");
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME(Email),
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(KEY_FILE))
);
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
Now you have $service that you can use with the rest of your calls. Note: I didnt have time to test that code let me know if it doesnt work and i will give you a hand in fixing it.

Google YouTube API v3 :: Server-to-Server Upload Service

Our project lets users upload videos to OUR public youtube channel when they are signed into our session. We do not want to require additional OAuth2 verification, and instead follow the follow of Google API v2.
My code (php) and error are below, but my general question is: can my server make the insert-video POST using my API key/secrets without requiring the user to authenticate.
This question - Google Calendar API v3 hardcoded credentials - is very similar. Howevr if CURLing Google for the access_token is the only answer, i'll be disappointed. Thanks regardless.
Google API V3 Settings:
Client ID: xxxx.apps.googleusercontent.com
Email address: xxxx#developer.gserviceaccount.com
Client secret: xxxx
Redirect URIs: http://fbtabs.imagendigital.co/unilever/sedal/surprise/galeria
JavaScript origins: https://fbtabs.imagendigital.co
API key:
AIzaSyBgS-jMJQUPIiAyX20xC-encFWTPsR7qxQ
Referers:
Any referer allowed
Activated on: Jul 4, 2013 1:21 PM
Activated by: xxxx#gmail.com – you
Code:
<?php
require_once BASE_CD . 'app/src/Idframework/Tools.php';
require_once BASE_CD . 'app/vendor/google-api-php-client/src/Google_Client.php';
require_once BASE_CD . 'app/vendor/google-api-php-client/src/contrib/Google_YouTubeService.php';
$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxxx');
$client->setRedirectUri('http://fbtabs.imagendigital.co/unilever/sedal/surprise/galeria');
$client->setDeveloperKey('xxxx');
$youtube = new Google_YoutubeService($client);
$snippet = new Google_VideoSnippet();
$status = new Google_VideoStatus();
$video = new Google_Video();
if (isset($_POST['tip_desc'])) $snippet->setDescription($_POST['tip_desc']);
$snippet->setTitle($_POST['tip_name']);
$snippet->setTags(array("sedal","hair","pello","cabello"));
$status->privacyStatus = "public";
$video->setSnippet($snippet);
$video->setStatus($status);
$filename = $_FILES['videoInp']['tmp_name'];
$mime = \Idframework\Tools::get_mime($filename);
try {
$part = "status";
$obj = $youtube->videos->insert($part, $video,
array("data"=>file_get_contents($filename),
"mimeType" => $mime));
} catch(Google_ServiceException $e) {
print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>";
print "Stack trace is ".$e->getTraceAsString();
}
Error:
Notice: Undefined index: content-type in C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\service\Google_MediaFileUpload.php on line 99
Caught Google service Exception 401 message is Error calling POST https://www.googleapis.com/upload/youtube/v3/videos?part=player&uploadType=multipart&key=AIzaSyBgS-jMJQUPIiAyX20xC-encFWTPsR7qxQ: (401) Login Required
Stack trace is #0 C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\io\Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\service\Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\contrib\Google_YouTubeService.php(789): Google_ServiceResource->__call('insert', Array) #3 C:\DATA\IDInteractive\SedalSurprise\youtuber.php(56): Google_VideosServiceResource->insert('player', Object(Google_Video), Array) #4 {main}
First off, letting arbitrary users upload videos into a "master" YouTube channel is not recommended, for the reasons outlined in this blog post.
That being said, if you're determined to do it, then you need to include an access token associated with your channel in each upload request. The appropriate way to get a fresh access token (they expire after an hour) is to take a refresh token that you've previously generated and stored somewhere and make an HTTP request to the appropriate URL to get back an access token, as explained in the OAuth 2 documentation. There's no way around that—I'm not sure whether there's a native method in the Google APIs PHP client library that will automate the process for you, but that's what needs to happen under the hood.
The information in Google Calendar API v3 hardcoded credentials does seem relevant.

OAuth 2.0 with Google Analytics API v3

I used to be able to query the Google Analytics API with my account's login & password.
Google is now using OAuth for authentication which is great...
The only issue is that I only need ONE access token.
I don't wanna allow other users to fetch THEIR analytics data.
I just wanna be able to fetch MY data.
Is there a way I can generate an access token only for my app or my analytics account?
I know such solutions exists... For instance, Twitter provides what they call a "single-user oauth" for apps that don't require a specific user to sign in.
One again, all I'm trying to accomplish here is to fetch MY OWN analytics data via the API.
Is there a way to properly do that?
I'm adding a PHP answer - you may be able to adjust or convert it to garb / ruby code.
You should be able to use Analytics with service accounts now. You will indeed have to use a private key instead of an access token.
Create an app in the API Console
Basically, you go to the Google API Console and create an App.
Enable Google Analytics in the services tab.
In the API Access tab, create a new OAuth ID (Create another client ID... button), select service account and download your private key (Generate new key... link). You'll have to upload the key to your web server later.
On the API Access page, in the Service account section, copy the email address (#developer.gserviceaccount.com) and add a new user with this email address to your Google Analytics profile. If you do not do this, you'll get some nice errors
Code
Download the latest Google PHP Client off SVN (from the command line svn checkout http://google-api-php-client.googlecode.com/svn/trunk/ google-api-php-client-read-only).
You can now access the Analytics API in code:
require_once 'Google_Client.php';
require_once 'contrib/Google_AnalyticsService.php';
$keyfile = 'dsdfdss0sdfsdsdfsdf44923dfs9023-privatekey.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Your product name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'11122233344#developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('11122233344.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:1234';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
Terry Seidler answered this nicely for php. I want to add a java code example.
Api console setup
Start by doing the required steps in the google api console as Terry explained:
Basically, you go to the Google API Console and create an App. Enable
Google Analytics in the services tab. In the API Access tab, create a
new OAuth ID (Create another client ID... button), select service
account and download your private key (Generate new key... link).
You'll have to upload the key to your web server later.
On the API Access page, in the Service account section, copy the email
address (#developer.gserviceaccount.com) and add a new user with this
email address to your Google Analytics profile. If you do not do this,
you'll get some nice errors
Get the necessary libraries
Download the google analytics java client from:
https://developers.google.com/api-client-library/java/apis/analytics/v3
Or add the following maven dependencies:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-analytics</artifactId>
<version>v3-rev94-1.18.0-rc</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.18.0-rc</version>
</dependency>
Now for the code:
public class HellowAnalyticsV3Api {
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
public void analyticsExample() {
// This is the .p12 file you got from the google api console by clicking generate new key
File analyticsKeyFile = new File(<p12FilePath>);
// This is the service account email address that you can find in the api console
String apiEmail = <something#developer.gserviceaccount.com>;
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(apiEmail)
.setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
.setServiceAccountPrivateKeyFromP12File(analyticsPrivateKeyFile).build();
Analytics analyticsService = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(<your application name>)
.build();
String startDate = "2014-01-03";
String endDate = "2014-03-03";
String mertrics = "ga:sessions,ga:timeOnPage";
// Use the analytics object build a query
Get get = analyticsService.data().ga().get(tableId, startDate, endDate, mertrics);
get.setDimensions("ga:city");
get.setFilters("ga:country==Canada");
get.setSort("-ga:sessions");
// Run the query
GaData data = get.execute();
// Do something with the data
if (data.getRows() != null) {
for (List<String> row : data.getRows()) {
System.out.println(row);
}
}
}
You can use a refresh token. Store the refresh token in a db or secure config file, then use it to show the stats.
Google API Offline Access Using OAuth 2.0 Refresh Token will give you an idea of how to capture then store your refresh token.
See also Using OAuth 2.0 for Web Server Applications - Offline Access
Hello I found a solution, it works for me
you have to change this one
immediate: true
to
immediate: false
and it looks like
function checkAuth() {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
}
Google has the 'Service Account' (Calls Google APIs on behalf of your application instead of an end-user), but the way it works is a bit different as it won't use access tokens but a private key instead.
You can find more details at https://developers.google.com/accounts/docs/OAuth2ServiceAccount

Resources