How to write data to Google Sheet using PHP - php

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

Related

PHP Google_Service_Dataflow not finding file in bucket

I've come across an issue using the googleapis/google-api-php-client library, specifically the Dataflow Service that I cannot solve.
When I try to use the library I set up the request like so:
$this->client = new \Google_Client();
$this->client->setAuthConfig(config_path('google-service-account.json'));
$this->client->setIncludeGrantedScopes(true);
$this->client->addScope(\Google_Service_Dataflow::CLOUD_PLATFORM);
$body = [
"gcsPath" => "gs://{$this->bucket}/{$this->template}",
"location" => "us-central1",
];
$parameters = new \Google_Service_Dataflow_LaunchTemplateParameters;
$parameters->setJobName($this->jobname);
$parameters->setParameters($body);
$service = new \Google_Service_Dataflow($this->client);
$request = $service->projects_templates->launch($this->project, $parameters);
And I get the following error:
{
"error": {
"code": 400,
"message": "(11f8b78933fc59c3): Bad file name: , expected
'gs://\u003cbucket\u003e/\u003cpath\u003e'",
"errors": [
{
"message": "(11f8b78933fc59c3): Bad file name: , expected
'gs://\u003cbucket\u003e/\u003cpath\u003e'",
"domain": "global",
"reason": "badRequest"
}
],
"status": "INVALID_ARGUMENT"
}
}
It seems that the path is getting corrupted along the way, I've checked and it gets fine until the Guzzle object is instantiated to send the request inside the library.
I'm pretty lost at this point so any suggestion or clue is welcome.
Thank you in advance.
No gcsPath is given in the query params for the request constructed by the SDK.
This is because gcsPath is set to be an option for Google_Service_Dataflow_LaunchTemplateParameters.
It is documented that request query parameters be given as optional params
(See https://github.com/googleapis/google-api-php-client-services/blob/v0.81/src/Google/Service/Dataflow/Resource/ProjectsTemplates.php#L73.)
$opt_params = [
"gcsPath" => "gs://{$this->bucket}/{$this->template}",
"location" => "us-central1",
];
$template_params = [
// Keep template params here.
];
$launch_params = new \Google_Service_Dataflow_LaunchTemplateParameters;
$launch_params->setJobName($this->jobname);
$parameters->setParameters($template_params);
$service = new \Google_Service_Dataflow($this->client);
$request = $service->projects_templates->launch($this->project, $parameters, $opt_params);

How to merge cells using the PHP version of the Google Sheet API v4

I've succesfully set up my credentials and access following the Quickstart guide & the API v4 documentation.
Everything works great, I successfully tried to:
Update the spreadsheet title
Read/write values in each cell
etc.
However I keep getting the following error while trying to merge some cells:
Fatal error: Uncaught Google_Service_Exception: { "error": { "code":
400, "message": "Invalid JSON payload received. Unknown name
\"merge_type\" at 'requests': Cannot find field.\nInvalid JSON payload
received. Unknown name \"range\" at 'requests': Cannot find field.",
"errors": [ { "message": "Invalid JSON payload received. Unknown name
\"merge_type\" at 'requests': Cannot find field.\nInvalid JSON payload
received. Unknown name \"range\" at 'requests': Cannot find field.",
"domain": "global", "reason": "badRequest" } ], "status":
"INVALID_ARGUMENT" } }
Source code:
<?php
include_once(__DIR__.'/vendor/autoload.php');
include_once(__DIR__.'/client.php');
$id_spreadsheet = '12xymzMe8OLbX9vw84'; // My spreadsheet ID (redacted for Stackoverflow)
/* Retrieve the API access */
$service = new Google_Service_Sheets(getClient());
/* Merge header columns */
$range = new Google_Service_Sheets_GridRange();
$range->setStartRowIndex(0);
$range->setEndRowIndex(1);
$range->setStartColumnIndex(1);
$range->setEndColumnIndex(24);
$range->setSheetId(0);
$request = new Google_Service_Sheets_MergeCellsRequest();
$request->setMergeType('MERGE_COLUMNS');
$request->setRange($range);
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(['requests' => $request]);
$response = $service->spreadsheets->batchUpdate($id_spreadsheet, $batchUpdateRequest);
echo '<pre>', var_export($response, true), '</pre>', "\n";
If you've not resolved this issue, the problem is in the request you are sending,
try to set your request in Google_Service_Sheets_BatchUpdateSpreadsheetRequest setRequests method
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$batchUpdateRequest->setRequests($request);
$response = $service->spreadsheets->batchUpdate($id_spreadsheet, $batchUpdateRequest);
echo '<pre>', var_export($response, true), '</pre>', "\n";

invalid api keys permission denied error in google api using php

I am using google api first time my code execute perfectly even give me data using people service api...but second time it give me following error
Type: Google_Service_Exception
Message: { "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" } }
i am using codeignitor and this is redirected uri controller function...thanks in advance and sorry for poor english..
$client = $this->google_client_setup();
$client->authenticate($this->input->get('code'));
$access_token = $client->getAccessToken();
$people_service = new Google_Service_PeopleService($client);
$profile = $people_service->people->get(
'people/me', array('personFields' => 'names,emailAddresses'));
$access_token = $access_token['access_token'];
$email = $profile['emailAddresses'][0]['value'];
$name = $profile['names'][0]['displayName'];
$user = [
'email' => $email,
'name' => $name,
'is_admin' => 0
];
It's hard to tell, but I would think that if it says it's missing valid api key, you should treat that as answer ;)
Are you being redirected somewhere after first run? That could explain problem Javier commented on.
I'd suggest to dump two things to debug the code:
$this->input->get('code')
and if this is ok, then
$access_token
this should give you idea what your problem is :)
Good luck!

Issue with google api Google_Service_Exception

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 ?

Google Speech Api PHP fails

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

Categories