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>
Related
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
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?
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.
This is my code in service.php file :
putenv('GOOGLE_APPLICATION_CREDENTIALS=service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject('xxxx#xxx.com');
$client->setScopes('https://mail.google.com','https://www.googleapis.com/auth/gmail.modify');
$service = new Google_Service_Gmail($client);
$messages_response = $service->users_messages->listUsersMessages('xxxx#xxx.com');
foreach ($messages_response as $key => $value) {
$message = $service->users_messages->get('xxxx#xxx.com', $value->getId());
$message_text = base64_decode(strtr($message->getPayload()->getParts()[0]->body['data'],'-_', '+/'));
$headers = $message->getPayload()->getHeaders();
foreach ($headers as $key_headers => $value_headers) {
if($value_headers['name'] == 'Subject')
{
error_log($value_headers['value']);
}
}
}
IF I run this code from console using php service.php I get the subjects of emails without any issue.
But if I place the same code in my controller method let's assume User.php Controller having method test() and I place same code in this test() method I am getting this error:
Exception of type 'Google_Service_Exception' occurred with Message: {
"error": { "errors": [ {
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission" } ], "code": 403, "message": "Insufficient Permission" } }
in File vendor\google\apiclient\src\Google\Http\REST.php at Line 118
I have placed the service-account.json in my controllers folder as well.
Any help or suggestions ?