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