Multichannels on YouTube with YouTube Analytics API - php

I have a youtube account with 5 channels. With the YouTube Analytics API can I get data from the primary youtube channel. But the other channels I get always error message
forbidden
Also I am the owner from these all channels.
Here my sourcecode:
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setScopes( array(
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtubepartner-channel-audit',
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/yt-analytics-monetary.readonly',
'https://www.googleapis.com/auth/youtubepartner')
);
$client->setAccessType("offline");
$json_str = file_get_contents("access_token.json");
$json = json_decode($json_str, true);
if (isset($json['access_token']) && $json['access_token']) {
$client->setAccessToken($json_str);
$youtube = new Google_Service_YouTubeAnalytics($client);
$report = $youtube->reports->query('channel==UC0xxxxxxxxxxx', '2017-04-01', '2017-04-30', 'views');
echo json_encode($report);
} else {
$redirect_uri = 'https://xxxxxxxxxx/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
If i have in the query-Command channel==MINE or the YouTube Channel-ID (UC0xxxxxxx) is work very well. But the other Channel-ID from the same youtube account I get this error:
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
How I can fix it?

Related

Wordpress PHP Google Sheets API Access

I'm having issues accessing Google Sheets through PHP in WordPress (WP). I've accessed the same sheet before in a local python program and I recall that once the code first ran the google authorization window popped up asking for approval. This WP shortcode isn't getting to that point and instead outputs an error message to the WP page stating a valid API Key is missing. What am I missing here?
Shortcode:
require_once __DIR__ . '/vendor/autoload.php';
function excel_tester_function() {
$client = new Google_Client();
$client->setApplicationName('Google Sheets and PHP');
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAccessType('online');
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Sheets($client);
$spreadsheetId = '{SHEET_ID}';
$get_range = '{RANGE}';
$response = $service->spreadsheets_values->get($spreadsheetId, $get_range);
$values = $response->getValues();
foreach ($val as $values) {
print($val);
}
}
add_shortcode('excel-tester', 'excel_tester_function');
Error:
Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 403, "message": "The request is missing a valid API key.", "errors": [ { "message": "The request is missing a valid API key.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } } in...
Please advise. Let me know if there is any info I can provide that could help solve this. Thank you.

Login with google account and get all profile info using Google api

As I am trying to login with google account and get the info of that logged in info but I am getting the error.
This is my code,
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secret_gmail.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$_SESSION['access_token'];
echo "<pre>";
print_r($_SESSION['access_token']);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$drive = new Google_Service_Drive($client);
$files = $drive->files->listFiles(array())->getItems();
echo json_encode($files);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/api/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
and the response is,
Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
You are requesting METADATA permission. you need DRIVE_READONLY not DRIVE_METADATA_READONLY
$client->addScope(Google_Service_Drive::DRIVE_READONLY );
FYI google official documentation

Allow users to upload videos to my youtube channel without login

I have selected Application type "other and web application" while creating separate projects in Youtube developer console and using following code.
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube');
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken('ya29.GlyKBK9LdtYRLNDYUdhXlhTiY_d51nLUZrIdikYoRY3M_5YQOpt5Pkx-uJ1RYpsvPOKyf4hTNBhKwOJ_fEncTURyNBeZa9ISRoVAmcuFaAlI_YgcQAs97GCbHklvXg');
$client->setScopes($scope);
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
But it always give following error.
A service error occurred: { "error": { "errors": [ { "domain":
"global", "reason": "authError", "message": "Invalid Credentials",
"locationType": "header", "location": "Authorization" } ], "code":
401, "message": "Invalid Credentials" } }
I am not getting what I am doing wrong and what could be the possible fix for this?

PHP How to upload to Youtube user's channel

Need to make user's authorizations so server will upload videos to users channels.
Authentication part:
$client = new Google_Client();
$client->setAuthConfigFile(PROPPATH.'/inc/client_secret.json');
$client->setRedirectUri('https://back url');
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setAccessType('offline');
$credentialsPath = PROPPATH.'/youtube_auth/user_'.get_current_user_id().'.json';
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
} else {
$authUrl = $client->createAuthUrl();
if(!isset($_GET['code'])) {
echo '<script>window.location = "'.$authUrl.'";</script>';
} else {
$authCode = $_GET['code'];
$accessToken = $client->authenticate($authCode);
file_put_contents($credentialsPath, $accessToken);
}
Authentication seems like works and saves some key.
2nd part, trying upload video:
$client = new Google_Client();
$client->setAuthConfigFile(PROPPATH.'/inc/client_secret.json');
$client->setScopes('https://www.googleapis.com/auth/youtube');
$youtube = new Google_Service_YouTube($client);
$client->setAccessToken(file_get_contents(PROPPATH.'/youtube_auth/user_2.json'));
$client->setAccessType('offline');
if ($client->getAccessToken()) {
$video = new Google_Service_YouTube_Video();
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$insertRequest = $youtube->videos->insert("", $video);
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
...
And i'm getting error:
A service error occurred: { "error": { "errors": [ { "domain":
"global", "reason": "authError", "message": "Invalid Credentials",
"locationType": "header", "location": "Authorization" } ], "code":
401, "message": "Invalid Credentials" } }
What i'm missing?
401: Invalid Credentials
Invalid authorization header. The access token you're using is either
expired or invalid.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Suggested action: Refresh the access token using the long-lived
refresh token.

Youtube Data API v3 Failed to start the resumable upload

As of this morning I'm getting this error when trying to upload a Video with the service account and key, this worked at around 6pm yesterday.
I've tried it with both the resumable option set to true and false but to no avail.
This is my code
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$key = file_get_contents($KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/youtube'),
$key)
);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
//$client->setRedirectUri($redirect);
$htmlBody = '';
// YouTube object used to make all API requests.
$youtube = new Google_YoutubeService($client);
I get back a valid bearer signature from here but when I initiate the upload I get the following error when setting the non resumable flag to false:
$media = new Google_MediaFileUpload('video/mp4', null, true, $chunkSizeBytes);
"error": {
"errors": [
{
"domain": "youtube.header",
"reason": "youtubeSignupRequired",
"message": "Unauthorized",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Unauthorized"
}
I hadn't set my access token which referenced the credentials. Make sure you set your access tokens!

Categories