Creating a Google Document via the REST API v1 & PHP - php

I've been exploring the various Document APIs and have settled on Google Docs API v1 to try to accomplish what I want.
What I want to accomplish:
Create A Doc
Dump some text into it
Place the doc into a G Suite Drive Folder
What I've got
All the respective relevant APIs enabled + Service Account Credentials (have used this with other Google Services just fine)
All of the Google API PHP stuff installed via composer
What I think is a method to correctly authenticate into the "Documents" REST API (please see below)
public function initializeDocs() {
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName($appName);
$client->setAuthConfig("$KEY_FILE_LOCATION");
$client->setScopes(['https://www.googleapis.com/auth/documents']);
$document = new Google_Service_Docs_Document($client);
$document->setTitle($title);
return $document; // Just seeing what get outputs
/*
...Getting Stuck here below is the code from Google's "Creating and managing documents" documentation
$document = new Google_Service_Docs_Document(array(
'title' => $title
));
$document = $service->documents->create($document);
printf("Created document with title: %s\n", $document->title);
After this....(can/will address in separate post, if possible)
1) Add content
2) Set document creator?
3) "Upload" / move to Drive folder location
*/
}
My issues:
I'm having a hard time finding/undersanding 'create' methods; Google's Creating and managing documents references the 'Documents Collection'
At least in the PHP library, I'm not seeing where I would find that (I searched the ~/vendor/google/apiclient-services/src/Google/Service/Docs directory and didn't see any 'create' method);
Could someone please point me in the right direction? Many thanks in advance!

Related

How to set Google Play `inAppUpdatePriority` using google-php-api-client

I found following thread at : https://issuetracker.google.com/issues/133299031#comment14
Hello, In-app update priority of the release can be set using the Play Developer Publishing API's ⁠Edits methods. There is a new 'inAppUpdatePriority' field under ⁠Edits.tracks.releases. The documentation does not mention the new field yet but you should still be able to set it. In-app update priority can not be set from the Google Play Console at the moment.
I am using google-api-php-client with Service Account authentication, I would like to ask how to set 'inAppUpdatePriority' using google-api-php-client I have tried following in my PHP code.
$publisher->edits_tracks->update(self::PACKAGE_NAME, self::EDIT_ID, 'production', new \Google_Service_AndroidPublisher_Track);
After hours of testing with Google API PHP Client, I managed to edit the inAppUpdatePriority field, with Laravel, this way:
try {
$packageName = "your.package.name";
$versionCode = "version_code_as_string"; //example "50"
$client = new \Google\Client();
//you need to setup your own Service Account or other API access methods
$client->setAuthConfig("path/to/your/json/file");
$client->addScope(AndroidPublisher::ANDROIDPUBLISHER);
$service = new \Google\Service\AndroidPublisher($client);
//create new edit
$appEdit = $service->edits->insert($packageName, new \Google\Service\AndroidPublisher\AppEdit());
//uncomment if you want to get hold of available tracks
// $tracksResponse = $service->edits_tracks->listEditsTracks($packageName, $appEdit->id);
// dd($tracksResponse);
$trackRelease = new \Google\Service\AndroidPublisher\TrackRelease();
$trackRelease->versionCodes = [$versionCode];
//set desired update priority
$trackRelease->inAppUpdatePriority = 5;
$trackRelease->status = "completed";
$postBody = new \Google\Service\AndroidPublisher\Track();
$postBody->setReleases([$trackRelease]);
//desired track to update. One of the followings: production,beta,alpha,internal
$track = "production";
$update = $service->edits_tracks->update($packageName, $appEdit->id, $track, $postBody);
//commit changes to Google Play API
$service->edits->commit($packageName, $appEdit->id);
// dd($update);
} catch (Exception $ex) {
if ($ex->getCode() == 404) {
//this catches if some info is wrong (tested with a version code that has not been upload to Google Play Console)
}
}
Notes:
You should note that for this to work (without implementing your propre way of uploading app via Google Play API), you need to first upload your app via Google Play Console to your desired track, then click Save, then Review release and */!\DON'T CLICK Rollout release/!*, then run the above mentioned code which will Commit (Rollout) the changes (if you try to rollout release after running the above code, you will get an error that you can ignore).
Any changes to inAppUpdatePriority won't be applied if your release is already rolled out.
You should have already published at least one release in the desired track before you can use this (tested with Internal testing only)

DialogFlow - How to Batch Update Intents via API?

I'm looking for a basic example on how to utilize DialogFlow's batchUpdate, and how to utilize batchUpdateResponse to show an actual response once complete.
Have found no examples for DialogFlow V1 or V2 (at this point either would be helpful), the below is all I've managed to setup - looking for the missing arguments to be added:
$intentsClient->batchUpdateIntents($formattedParent, $languageCode, $test_3);
Currently using PHP https://github.com/googleapis/google-cloud-php/tree/83ae284c025f6e93b9ce835b987932c425b5a9de/Dialogflow but any language is fine here.
Ended up figuring this out through the use of https://developers.google.com/apis-explorer/ and the Google Client Library for PHP (https://github.com/googleapis/google-api-php-client).
Below is a basic example for updating the text on two intents at once, via PHP. Hopefully this helps someone in the future, am somewhat surprised at the general lack of helpful documentation and/or examples for using DialogFlow's API V2 (or even V1 for that matter). So many awesome things can be done by using this rather than their Dashboard to train your bot!
// Global variable pointing to the .json file downloaded with private key from DialogFlow
putenv('GOOGLE_APPLICATION_CREDENTIALS=directory-of-file/google-service-acount-key.json');
// Setup Google Client
require __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$httpClient = $client->authorize();
// Setup array to update intent (minified)
$update_intent = array('intentBatchInline'=>array('intents'=>array(
0=>array('name'=>'projects/YOUR-PROJECT-NAME/agent/intents/FIRST-INTENT-ID','displayName'=>'FIRST-INTENT-NAME','messages'=>array(0=>array('text'=>array('text'=>array(0=>'FIRST-INTENT-TEXT-TO-UPDATE',),),),),),
1=>array('name'=>'projects/YOUR-PROJECT-NAME/agent/intents/SECOND-INTENT-ID','displayName'=>'SECOND-INTENT-NAME','messages'=>array(0=>array('text'=>array('text'=>array(0=>'SECOND-INTENT-TEXT-TO-UPDATE',),),),),),),),
);
// Post to DialogFlow API
$response = $httpClient->post('https://dialogflow.googleapis.com/v2/projects/PROJECT-NAME-HERE/agent/intents:batchUpdate', [
GuzzleHttp\RequestOptions::JSON => $test_batch_intent_1
]);
// Print out response for troubleshooting
print_r($response->getBody()->getContents());
echo "<br /><br />Here's to getting past DialogFlow API's hurdles! :)";
exit;
This is similar to my answer. Where I have given a complete example. Do check it out.
Stack Overflow answer.
And this is based out of NodeJs. As you told the language does not matter.
And do check out this documentation for different kinds of examples. This document covers even the batchUpdate functionality.
Please check these out:
GitHub repo
GitHub repo

How to access google photos using api in php?

I want to fetch all the photos on Google photos on my web site using php.
Is it possible?. I know Picasa Web Albums Data API deprecated. I have got try it from Picasa. but i am not able to download library from https://developers.google.com/gdata/articles/php_client_lib.
There is currently no Google Photos API. The only thing available is Picasa. You may be able to upload the pictures to your google drive account and display them on your website that way. However your probably going to have to set the pictures to public.
There is an API now for Google photo's.
But I've not been successfull in making it work myself
https://developers.google.com/photos/
I am trying to do the same thing, so far, I setup the api:
From Google Console API --> enabled the photos library api.
Following this example : https://github.com/google/google-api-php-client/blob/master/examples/simple-query.php
I managed to setup the api with the following code :
include_once __DIR__ . '/vendor/autoload.php';
include_once 'base.php';
# create client
$client = new Google_Client();
$client -> setApplicationName("Client_Library_examples");
if(!$apiKey = getApiKey()) {
echo missingApiKeyWarning();
}
$client -> setDeveloperKey($apiKey);
The autoload and base.php files were copied from the mentioned link. I copied my api to a file .apiKey.
Up to this point, the code works fine, the example in the previous link explains how to create a new google service for e-books. There must be a similar thing for google photos but couldn't find any yet.
I found the following but I am not getting anything with the echo :
$response = file_get_contents('https://photoslibrary.googleapis.com/v1/albums');
$response = json_decode($response);
echo $response

How can I access full referral path for one session/user through Google Reporting API V4

How can I access the full referral path for one session/user through Google Reporting API V4 ? In this case in PHP.
For example we have following code found on Google's Reporting API V4 Documentation.
(https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php)
function getReport(&$analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
This part is interesting:
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
Dimensions & Metrics Explorer
(https://developers.google.com/analytics/devguides/reporting/core/dimsmets)
The path of the referring URL (e.g., document.referrer). If someone
places on their webpage a link to the property, this is the path of
the page containing the referring link.
The full referring URL including the hostname and path.
I am assuming that I have to go this way just fetching the desired dimensions/metrics:
$sessions->setExpression("ga:referralPath");
$sessions->setAlias("referral_path");
or
$sessions->setExpression("ga:fullReferrer");
$sessions->setAlias("full_referrer");
Would be this the right approach?
If not is there another way to accomplish this?
And another question:
When making a request with this metrics/dimensions:
$sessions->setExpression("ga:referralPath");
$sessions->setAlias("referral_path");
How Google knows from which session to take the referralPath?
Try to read through Traffic Sources - Dimensions and Metrics, this reference document lists and describes all the dimensions and metrics available through the Real Time Reporting API.
Here's a sample of dimension: rt:referralPath - The path of the referring URL (e.g. document.referrer). If someone places a link to your property on their website, this element contains the path of the page that contains the referring link. This value is only set when rt:medium=referral.
Note: Use Google Analytics superProxy to handle many of the implementation details of working with Google Analytics APIs on authentication, caching, and transforming API responses to formats used directly with visualization and chart libraries.
You may also try to read Management API, this API is a guides that will help you initially get an application up and running and then the documentation will dive into the various topics which should help you interact with the API to perform such things as account, user, and data management. There is also a complete set of reference documents, which give details of every parameter of each API endpoint and include API sample code.

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.

Categories