GET Channel ID using Youtube API v3 with Service Account - youtube-api

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.

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.

Can't get any account info, or review info

I've tried for hours now to figure this out but I'm completely stuck.
I have been approved for My Business APi and I created a service account and downloaded the json file for authentication.
I am using google-api-php-client and with google-api-my-business-php-client which provides the 'Google_Service_MyBusiness' class for use.
My code looks like this: -
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/google-api-my-business-php-client/MyBusiness.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/myfile.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
if (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
// use the application default credentials
$client->useApplicationDefaultCredentials();
} else {
echo missingServiceAccountDetailsWarning();
return;
}
$client->setApplicationName("my_app");
$client->addScope('https://www.googleapis.com/auth/plus.business.manage');
$service = new Google_Service_MyBusiness($client);
$accounts = $service->accounts;
$accountsList = $accounts->listAccounts()->getAccounts();
But all that I ever get back is
Google_Service_Exception: That’s an error. The requested URL <code>/v3/accounts</code> was not found on this server. That’s all we know.
I notice that the documentation is now v4, i.e. v4/accounts, could this be the issue? Are these libraries out of date? How can I retrieve account and review data with v3?
Any help would be appreciated.
My end goal is the retrieve all the reviews for a location but right now just trying to get this to work as a prelude.
Answering my own question - I think the main issue is it turns out that My Business api doesn't support service accounts, you need to use oauth2.
Turns out that V3 is depreciated also so the libray I was using for MyBusiness API is useless, the other one works fine for updating access tokens.
For the reviews I am just using Curl and Simply building the URL with the ?access-token= value on the end of it.
For example to list all reviews
https://mybusiness.googleapis.com/v4/accounts/[acc-number]/locations/[location-id]/reviews?access_token=

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.

Obtain youtube username from google Plus api - access token scope insufficientPermissions

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);

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.

Resources