I'm trying to get Youtube username via google plus api. I use php Services from Plus ang YT api and I'm using symfony 2. Obtaining access token works ok, and i'm not going to put it here.
There is also no problem with google plus service, after authorization i'm getting all the information that i need. In YT case, i'm getting error :
insufficientPermissions error
So i check my access token scope in here:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ACCESS_TOKEN
and scope of my Access token is only for Google Plus, i'm not able to force the google Api php clinet to make the YT scope aviable too.
Any ideas?
Here is my code :
require_once '../src/google_api_php_client/src/Google_Client.php';
require_once '../src/google_api_php_client/src/contrib/Google_PlusService.php';
require_once '../src/google_api_php_client/src/contrib/Google_YouTubeService.php';
$client = new Google_Client();
$client->setScopes('https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/plus');
$youtube = new Google_YouTubeService($client);
if(!empty($allR['code'])){
$client->setClientId('clientIDxxx');
$client->setClientSecret('SecretXXX');
$client->setRedirectUri('postmessage');
$client->authenticate($allR['code']);
$token = json_decode($client->getAccessToken());
}
First of all, make sure you enabled YouTube Data API v3 rom your devconsole.
Then instead of setting scopes, try setting client id and secret from devconsole.
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// YouTube object used to make all Data API requests.
$youtube = new Google_YoutubeService($client);
$plus = new $youtube = new Google_PlusService($client);
Related
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.
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.
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.
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.
I am using the Google API Client to access Google Analytics. I want to access the data in offline mode, so I need a refresh token. How do I get a refresh_token?
try using the following code:
<?php
require_once 'apiClient.php';
const REDIRECT_URL = 'INSERT YOUR REDIRECT URL HERE';
const CLIENT_ID = 'INSERT YOUR CLIENT ID HERE';
const CLIENT_SECRET = 'INSERT YOUR CLIENT SECRET';
const ANALYTICS_SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
// Build a new client object to work with authorization.
$client = new apiClient();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URL);
$client->setScopes(array(ANALYTICS_SCOPE));
$client->setAccessType('offline');
$auth = $client->authenticate();
if ($client->getAccessToken()) {
$token = $client->getAccessToken();
$authObj = json_decode($token);
$refreshToken = $authObj->refresh_token;
}
?>
For PHP SDK of Google Client v2:
php composer.phar require google/apiclient:^2.0
You can try the PHP code to refresh accessToken as following:
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Analytics::ANALYTICS_READONLY)
));
$client = new Google_Client();
$client->setApplicationName('YOUR APPLICATION NAME');
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Input AccessToken from such as session or database
$accessToken = json_decode('YOUR CURRENT ACEESS TOKEN');
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
// Get RefreshToken as json which can be reused
$refreshToken = json_encode($client->getAccessToken());
}
Offline access issue
In addition, if you want to keep the existing behavior in your server-side applications, you need to set approval_prompt to force, otherwise you may get NULL returned from getRefreshToken(), which Google document doesn't mention:
$client->setApprovalPrompt('force');
Referring Upcoming changes to OAuth 2.0 endpoint