Google speech api Credentials Not Working - php

I've enabled the Google text-to-speech api, generated an oAuth2 file and an api key, and when I run the code below from localhost and execution hits the "$textToSpeechClient =" line, both return the same error ("Could not load the default credentials."). I would prefer using the api key (in the commented out section), but I'll use either one. I installed the PHP client using Composer.
I tried getting paid support from Google, but I'm not able to sign up because "You must be assigned Support > Support Account Administrator for the organization in IAM to continue." When I go there, there is no apparent way to do that.
Help on any of these fronts would be appreciated.
require __DIR__ . '/vendor/autoload.php';
$client = new Google\Client();
$client->setAuthConfig(__DIR__ . '\googleAuthorization.json');
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
// $client->setDeveloperKey("AIzaSyAzSZjgfLS76q1234abcdefgtoGuKAqz5xE");
// $client->addScope(Google\Service\Drive::DRIVE);
// $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// $client->setRedirectUri($redirect_uri);
// if (isset($_GET['code'])) {
// $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
// }
$textToSpeechClient = new TextToSpeechClient();

Problem solved (with the help of 3 google support staff in a video chat in at least 3 different time zones).
The Google text-to-speech api requires that the PHP command:
putdev()
be available so you can run:
putenv(
"GOOGLE_APPLICATION_CREDENTIALS=absolute-path-to-your-json-authentication-file.json"
);
In my default php.ini server configuration, putdev was included in the rather long disable_functions= list. Removing putdev from that list allowed authentication to proceed as expected.
Why this is needed for the text-to-speech api and not the cloud storage api is still a mystery.

Related

Zoho crm api v2 for php

I am trying to connect with Zoho CRM using PHP. I followed PHP SDK for Zoho CRM and installed the package.
<?php
require 'vendor/autoload.php';
use zcrmsdk\crm\setup\restclient\ZCRMRestClient;
use zcrmsdk\oauth\ZohoOAuth;
$configuration =array("client_id"=>"clientid","client_secret"=>"clientsecret","redirect_uri"=>"redirecturl","currentUserEmail"=>"useremail");
$a = ZCRMRestClient::initialize($configuration);
$oAuthClient = ZohoOAuth::getClientInstance();
$refreshToken = "refreshtoken";
$userIdentifier = "emailid";
$oAuthTokens = $oAuthClient->generateAccessTokenFromRefreshToken($refreshToken,$userIdentifier);
$result = ZCRMRestClient::getModule("Contacts");
print_r($result);
exit;
?>
error I am getting:
Not able to get access token from refresh token, invalid client_id.
But I am using correct credentials to connect Zoho API.
Spent a day on this myself when I set it up.
Make sure that you are using the same domain for the api and the oauth client app.
They have 2 domains:
https://accounts.zoho.com
https://accounts.zoho.eu
If you created the oauth clinet app on one, use the same one for the api endpoint.
Further to this, if you are using accounts_url=https://accounts.zoho.eu in the oauth_configuration.properties file, then you should also set apiBaseUrl=www.zohoapis.eu in the configuration.properties file.
Given the parameters are read from these two properties files, I don't think you need that configuration array.

How to update Google Sheets file with API PHP Client

I've been taking a look at the Google API PHP Client and would like to use it to add rows to a Google Sheet. From the code, it looks like one would use this method:
public function insert($fileId, Google_Service_Drive_Property $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_Drive_Property");
}
but I can't really tell what the parameters would be. Am I heading in the right direction? Also, not quite sure on how to connect to a specific Sheet. Please advise.
Thanks!
Use Google sheets class from zend framework 1.12. They have very nicely coded library for Google Spreadsheets
https://github.com/zendframework/zf1/tree/master/library/Zend/Gdata/Spreadsheets
I figured out how to work this and wanted to share with you guys. As I stated in a comment, I did not think using Zend's GData class was a good way for me since it's very dependent on other classes throughout the framework, thus being too heavy.
So I ended up using this Spreadsheet Client on top of Google's API. Google's API is used to authenticate my service, then I start calling the Spreadsheet Client library afterwards.
After spending over a day of Googling for various problems I had for the authentication process, here's what I did to make things work:
Created a new project for Google API here
Clicked "APIs" menu on the left side under "APIs & Auth"
Searched the Drive API and enabled it (can't remember if it was necessary)
Clicked the "Credentials" menu on the left
Clicked "Create new Client ID" button under OAuth
Selected "Service Account"
After info showed & json downloaded (not needed), I clicked "Generate new P12 Key" button
I saved the p12 file somewhere I could access it through PHP
Then in the code, I added the following lines:
$email = 'somethingsomethingblahblah#developer.gserviceaccount.com';
$CLIENT_ID = $email;
$SERVICE_ACCOUNT_NAME = $email;
$KEY_FILE = 'path/to/p12/file';
$SPREADSHEETS_SCOPE = 'https://spreadsheets.google.com/feeds';
$key = file_get_contents($KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array($SPREADSHEETS_SCOPE),
$key
);
$client = new Google_Client();
$client->setScopes(array($SPREADSHEETS_SCOPE));
$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$client->setClientId($CLIENT_ID);
$accessToken = $client->getAccessToken();
Also, I had to make sure I:
Shared my spreadsheet specifically with the email address on my service account in the code above
Synced my server's time (I'm running Vagrant CentOS so it's slightly different)
I believe you can run this code with other services beyond Spreadsheets, such as Youtube, Analytics, etc., but you will need to get the correct scope link (see $SPREADSHEETS_SCOPE above). Remember, this is only when using the Service Account on the Google Console, which means you are programmatically getting data from your code. If you are looking to have others users sign in using the API, then it's different.

Download url not working in Google Drive API PHP

I am having issue with the Google Drive API, i was able to fetch the files using API But i can't download via this link. I guess, must some auth, but i have used refresh tokens to authenticate.Please see below for my code
$this->load->library('google-api-php-client/src/Google_Client');
include APPPATH . '/libraries/google-api-php-client/src/contrib/Google_DriveService.php';
// Library Files Configuration to get access token and Refresh Token
$client = new Google_Client();
$client->setAccessType('offline'); // default: offline
$client->setApplicationName('xxx'); //name of the application
$client->setClientId('yyyy'); //insert your client id
$client->setClientSecret('zzz'); //insert your client secret
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$client->refreshToken($drive_data->refreshtoken);
$client->getAccessToken();
$parameters = array();
$files = $service->files->listFiles($parameters);
foreach ($files['items'] as $key => $items)
{
Download
}
Anybody knows how to get the download url with authentication?
This is having the answer:
(Java) Download URL not working
There seem to be some changes on v2 of GDrive, instead of using "downloadUrl" you may have to use "webContentLink" for getting the download link
To get downloadUrls, you need to get the metadata of a file. You can do so by using the get method. The method will return a File Resource representation. In this resource, there is a downloadUrl property. If you're able to access the files and get the URL already, then there should be no problem with your authentication setup. There could be permission issues where you may not have access to certain drive files, but if you receive no error for it, you should be fine there too. I am not particularly familiar with PHP, but perhaps you are not downloading it correctly? Here it seems to be done differently.
I also suggest that you check out the Drive PHP Quickstart App to use as a reference.
I have bumped into the same problem today and just found a solution for my case. I hope that this helps the one or another confused PHP coder out there who also does not get a downloadUrl. I assume that you are working with the examples of the v2 API, as seen on https://developers.google.com/drive/v2/reference.
First, I have altered the head to not only access the metadata but get full access (mind the DRIVE constant):
<?php
require 'vendor/autoload.php';
const DRIVE = "https://www.googleapis.com/auth/drive";
define('APPLICATION_NAME', 'MAGOS poller');
define('CREDENTIALS_PATH', 'credentials.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(Google_Service_Drive::DRIVE)));
Then I have deleted my credentials file (credentials.json) and reran the script so it authenticated once more against gDrive and recreated the credentials file. After that
$downloadUrl = $file->getDownloadUrl();
finally worked like a charm.

Error 500 when using Google_PredictionService Google API sample

Updated:
My project is to be able to provide a web based application which allows the visitor to upload/download/delete files using GoogleDrive. The project requires it to be server based, which does not require credentials from the user to be able to perform these functions.
In a nutshell, the web application stores the files on a single dedicated google drive account, instead of storing the files on the server.
I researched Google's developer site, and was directed to using the example below as a starting point, to configure the PHP application to use the Drive Account I set up.
I followed the instructions per Google's page:
https://code.google.com/p/google-api-php-client/wiki/OAuth2#Service_Accounts
When I execute this script, I am receiving the following 500 error:
PHP Catchable fatal error: Argument 3 passed to
Google_HostedmodelsServiceResource::predict() must be an instance of
Google_Input, none given, called in
/data/sites/scott/htdocs/dfs_development/drive/serviceAccount.php on
line 62 and defined in
/data/sites/scott/htdocs/dfs_development/apis/google-api-php-client/src/contrib/Google_PredictionService.php
on line 36
What am I doing wrong here? I am uncertain what $project variable should hold, and it seems the predict() function needs 3 args, however I am at a loss to know what it should be.
Here is my code, which I obtained from the URL above. Thank you in advance for your response.
require_once '../apis/google-api-php-client/src/Google_Client.php';
require_once '../apis/google-api-php-client/src/contrib/Google_PredictionService.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = '##########.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = '#########developer.gserviceaccount.com';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = 'pathto/secretlystored/######-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("My Google Drive");
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/prediction'),
$key)
);
$client->setClientId(CLIENT_ID);
$service = new Google_PredictionService($client);
// Prediction logic:
$id = 'dfslocalhost';
$predictionData = new Google_InputInput();
$predictionData->setCsvInstance(array('Je suis fatigue'));
$input = new Google_Input();
$input->setInput($predictionData);
$result = $service->hostedmodels->predict($id, $input); ## 500 ERROR occurs here..
print '<h2>Prediction Result:</h2><pre>' . print_r($result, true) . '</pre>';
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
thats because Google_PredictionService API has not actived in your google API console dev.

Authentication with Google Calendar API using Server Account and PHP

I'm struggling with this one: I am trying to create an event in a Google Calendar from a PHP script, using a Service Account.
Here’s what I’ve done:
Created a Google Cloud Project
Enabled the Calendar API
Created an OAuth 2.0 Service Account, with Client ID, Email address and Public Key
Downloaded the keyfile and saved this in my website
Shared my Calendar with the Email address created in the Service Account (with Manage Sharing rights)
And here is my code:
<?php
require_once 'google_api_src/Google_Client.php';
require_once 'google_api_src/contrib/Google_CalendarService.php';
const CLIENT_ID = 'xxxxxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'xxxxxxxxxxxxx#developer.gserviceaccount.com';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = 'google_api_src/xxxxxxxxx-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Hall Booking");
session_start();
if (isset($_SESSION['token']))
{
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format
$key = file_get_contents(KEY_FILE);
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar', "https://www.googleapis.com/auth/calendar.readonly"),
$key));
$service = new Google_CalendarService($client);
//Save token in session
if ($client->getAccessToken())
{
$_SESSION['token'] = $client->getAccessToken();
}
?>
I have debugged the code as far as I can, but the token is always set to null after the call to SetAssertionCredentials. There are no PHP errors.
Any idea what is wrong, or how to debug further please?
Do I have to make any changes to config.php in the api src folder (I haven’t so far)?
Is the Application Name important? What’s it used for?
OK - so it turns out that the above code is working fine. My misunderstanding was in thinking that the Google_CalendarService performed the authentication. In fact, the authentication is only performed when an actual call to the calendar is made (such as insert Event).
However, I think that saving the token in the session is in the wrong place - it should be after an action has been performed.
To answer my other questions: No, you don't have to make any changes to config.php. The Application Name can be set to anything (but I don't know what it's used for).
One other problem I came across: I was creating an event using a calendar ID of 'primary'. This sent back a success message, but I could not see the event in the calendar (I only have one calendar for that account). It was only when I changed 'primary' to 'mycalendarid#gmail.com' that it started working. Sounds like a bug in the API to me?
Checkout the demo: http://amazewebs.com/demo
Or get 1-to-1 help on this: http://amazewebs.com/go-premium
I have gotten this working with a service account, you are using the wrong URL in your code, or at least I have it working with no problems with my method...
See my code here: http://amazewebs.com
Or here:
<!-- language: php -->
<?php
ini_set('display_errors', 1);
require_once '../google-api/Google_Client.php';
require_once '../google-api/contrib/Google_CalendarService.php';
session_start();
const CLIENT_ID = '<YOUR-CLIENT-ID-HERE>.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = '<YOUR-SERVICE-EMAIL-HERE>#developer.gserviceaccount.com';
const KEY_FILE = '<YOUR-FINGERPRINT-HERE>-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("<PUT-YOUR-PROJECT-NAME-HERE");
$client->setUseObjects(true); //IF USING SERVICE ACCOUNT (YES)
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
/* This next snippet of code is commonly written wrong, be sure to use the correct URL specified as below: */
$key = file_get_contents(KEY_FILE);
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME, 'https://www.google.com/calendar/feeds/<YOUR-CALENDAR-ID-HERE-WITHOUT-THE-TRAILING"#group.calendar.google.com">/private/full/',
$key)
);
$client->setClientId(CLIENT_ID);
$cal = new Google_CalendarService($client);
$event = new Google_Event();
$event->setSummary('<PUT-AN-EVENT-TITLE-HERE-OR-PASSED-VARIABLE>');
$event->setLocation('<PUT-A-LOCATION-HERE-OR-PASSED-VARIABLE>');
...The Full script can be found # AmazeWebs.com
& Also I recommend downloading the older google api library as it doesn't seem to work with their latest 0.6.7!
...I have downloaded and packaged all the files in the correct path structure for you: http://amazewebs.com/downloads/google-api.zip
Alternatively, you can download every individual file and package it yourself if you want to download it from google directly:
http://google-api-php-client.googlecode.com/svn/trunk/src/
Good luck :)

Categories