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 ?
Related
I want to write data to Google Sheet.
I can get data from my GoogleSheet successfully. But I try to write data I got the following error.
An uncaught Exception was encountered
Type: Google_Service_Exception
Message: { "error": { "code": 403, "message": "The caller does not have permission", "errors": [ { "message": "The caller does not have permission", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } }
This is my code.
$client = new \Google_Client();
$client->setApplicationName('SheetsPHP');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/../../credentials.json');
$sheets = new \Google_Service_Sheets($client);
$spreadsheetId = '.....';
$range = '시트1!B2:G5';
$values = [['b', 'c', 'd', 'e', 'f', 'g']];
$body = new Google_Service_Sheets_ValueRange([
'values' => $values
]);
$params = [
'valueInputOption' => "RAW"
];
$result = $sheets->spreadsheets_values->update($spreadsheetId, $range, $body, $params);
I have shared the service account email already.
Please let me know what is wrong.
just for testing try to modify your permission only for reading
$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
maybe the problem is with writing permissions
There is a script deployed to Google Script which is bound to Google Cloud project and is published/deployed as API executable. All credentials from Google Cloud are in place.
public function runCreateDriveScript($clientName, $orderName)
{
$scriptId = env('GOOGLE_SCRIPT_ID');
$service = $this->getService();
$request = new \Google_Service_Script_ExecutionRequest();
$request->setFunction('main');
$request->setParameters(["fdf"]);
try {
$response = $service->scripts->run($scriptId, $request);
if ($response->getError()) {
$error = $response->getError()['details'][0];
printf("Script error message: %s\n", $error['errorMessage']);
if (array_key_exists('scriptStackTraceElements', $error)) {
print "Script error stacktrace:\n";
foreach ($error['scriptStackTraceElements'] as $trace) {
printf("\t%s: %d\n", $trace['function'], $trace['lineNumber']);
}
}
}
} catch (\Exception $e) {
// The API encountered a problem before the script started executing.
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
Caught exception: { "error": { "code": 403, "message": "The caller does not
have permission", "errors": [ { "message": "The caller does not have
permission", "domain": "global", "reason": "forbidden" } ], "status":
"PERMISSION_DENIED" } }
What am I missing? What should I do in order to call Google Script by API? Is there a good manual on that topic?
How do i create permission on google sheet on docs. Here it's show the error
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
here my code. i use php library.
function insertPermission($fileId) {
$client = $this->getClient();
$client->setScopes(Google_Service_Drive::DRIVE);
$service = new Google_Service_Drive($client);
$newPermission = new Google_Service_Drive_Permission(
array(
"role"=> "writer",
"type"=> "domain",)
);
try {
return $service->permissions->create($fileId, $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
After set permisson it's denied and return this error.
The permissions.create method can be used to insert permissions into a file on google drive.
POST https://www.googleapis.com/drive/v3/files/fileId/permissions
{
"role": "writer",
"type": "user",
"emailAddress": "test#test.com"
}
In order to run the above request the currently authenticated user must have been authenticated using the following scopes and of course have permissions on the file already
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
insufficientPermissions
Means that the user you are authenticated with either hasn't granted your application permissions to make these changes or they themselves do not have the permissions. First thing i would do would be check the scopes your application has requested and add the scopes needed and re-authenticated the user and try again.
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'm trying to use Google speech API in PHP to read text from audio, but it fails with the following: request must contain 'config' field.
This is the code:
<?php
require '../lib/vendor/autoload.php';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setAuthConfig(__DIR__.'/config.json');
$client->authorize();
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false)));
$client->setHttpClient($guzzleClient);
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$speechService = new Google_Service_Speech($client);
$syncRecognize = new Google_Service_Speech_SyncRecognizeRequest();
$config = new Google_Service_Speech_RecognitionConfig();
$config->audioChannels = 1;
$config->encoding = 'LINEAR16';//'audio/wav';
$config->sampleRate = 8000;
$audio = new Google_Service_Speech_RecognitionAudio();
$audio->setContent(file_get_contents('c1.wav'));
$syncRecognize->setAudio($audio);
$syncRecognize->setConfig($config);
$response = $speechService->speech->syncrecognize($syncRecognize);
I receive the following:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"code": 400,
"message": "Invalid recognition 'config': request must contain 'config' field.",
"errors": [
{
"message": "Invalid recognition 'config': request must contain 'config' field.",
"domain": "global",
"reason": "badRequest"
}
],
"status": "INVALID_ARGUMENT"
}
}
I can't find any documentation for PHP, so any help would be appreciated.
Try:
$audio->setContent(base64_encode(file_get_contents('c1.wav')));