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.
Related
I have integrated my web application with google login. When i am running in core php everything works fine but it's not working in yii framework with same codes. I got the following error while i am running,
Google_Service_Exception
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Controller
require_once Yii::app()->basePath . '/extensions/GoogleAPI/vendor/autoload.php';
public function actionIndex()
{
// echo Yii::app()->request->basePath; exit;
$gClient = new Google_Client();
$gClient->setClientId(".....");
$gClient->setClientSecret(".....");
$gClient->setApplicationName("Omega");
$gClient->setRedirectUri("http://localhost/project/index.php/site/GoogleLogin");
$gClient->addScope("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email");
$loginURL = $gClient->createAuthUrl();
$this->render('index',array('loginURL'=>$loginURL));
}
//Redirecting function
public function actionGoogleLogin()
{
$googleClient= new Google_Client();
$oAuth = new Google_Service_Oauth2($googleClient);
$userData = $oAuth->userinfo_v2_me->get();
print_r($userData); exit;
}
View page
<a href="#" class="btn-google m-b-0" onclick="window.location = '<?php echo $loginURL ?>';">
<i class="fa fa-google"></i>
Google
</a>
I have search in th enet but i can't find the solutions. Please help. Below is the code.
<?php
require_once '../../vendor/autoload.php';
define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY)
));
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setScopes(array('https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.apps.readonly', 'https://www.googleapis.com/auth/drive'));
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$service = new Google_Service_Drive($client);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Test Folder',
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
printf("Folder ID: %s\n", $file->id);die();
?>
I can list all the files from the drive but I can't create a folder. What I'm missing? Below is the error. Can someone help me to solve this problem of mine. Thanks in advance.
PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
I hope this will assist you in solving your problem, I found your error here:
https://developers.google.com/drive/v3/web/handle-errors
To help you navigate to a solution, here is the snippet, hope this assists you in some way:
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. If this fails, direct the user through the OAuth flow, as described in Authorizing Your App with Google Drive.
If you want to know more about Authorizing your app with google drive, please refer to this site:
https://developers.google.com/drive/v3/web/about-auth
Hope you are able to find a solution with the resources provided.
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?
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?
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!