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

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)

Related

Accessing a Google BigQuery dataset from a PHP script running on a Google Compute VM instance

I am attempting to access a BigQuery dataset from a PHP script running on a Google Compute VM instance - on which I have installed Bitnami's LAMP stack.
The dataset is owned by another party, but the party has given me a full ownership role to the dataset, using my email address. They have also given me a read role to another dataset, again using my email address.
My PHP script is intended to read data from the dataset tables to which I have been given read permission, massage that data, and write it to tables in the dataset to which I have been given the full ownership role.
I have spent many hours attempting to work out how to setup the correct authorisations, running everything under my email address as mentioned, but to date I am still getting errors of the "you do not have permission..." type either when trying to read data from one dataset or write it to the other.
The BigQuery datasets are not owned by me as mentioned, but I have been given both the Project ID and names of the datasets involved, and the owner of both has used my email address to set up the access permissions discussed above.
Has anyone a simple step-by-step guide as to how to achieve the above. Does the owner of the datasets need two do anything more than as already described? I am finding working through many pages of Google Help very confusing!
You need service account key file, that comes with a different email address. The service account email should be given permission and not your email. Actually both, because one is used by you to work on the UI, the other is on the app you develop.
I've included a full PHP example for you.
You need to setup the service account default credentials see lines with putenv and useApplicationDefaultCredentials(). This is a working code I have using the library https://github.com/google/google-api-php-client
You need to obtain your service account key file from the console: https://console.cloud.google.com/iam-admin/serviceaccounts/
composer.json
{
"require": {
"google/cloud": "^0.13.0",
"google/apiclient": "^2.0"
}
}
php file
# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;
$query="SELECT repository_url,
repository_has_downloads
FROM [publicdata:samples.github_timeline]
LIMIT 10";
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.dirname(__FILE__) . '/.ssh/dummyname-7f0004z148e1.json');//this can be created with other ENV mode server side
$client->useApplicationDefaultCredentials();
$builder = new ServiceBuilder([
'projectId' => 'edited',
]);
$bigQuery = $builder->bigQuery();
$job = $bigQuery->runQueryAsJob($query);
$info=$job->info();
// print_r($info);
// exit;
$queryResults = $job->queryResults();
/*$queryResults = $bigQuery->runQuery(
$query,
['useLegacySql' => true]);*/
if ($queryResults->isComplete())
{
$i = 0;
$rows = $queryResults->rows();
foreach ($rows as $row)
{
$i++;
$result[$i] = $row;
}
}
else
{
throw new Exception('The query failed to complete');
}
print_r($result);

Accessing GDrive from Google App Engine with domain-wide delegation service account

This is my first time using Google App Engine, so some of my terminology might be a bit off, bear with me.
I had some php code running in a web app outside of GAE that was using the google-api-php-client library to access gdrive folders and create files. It was working wonderfully.
I'm trying to migrate to GAE with a project that has domain-wide delegation so that my app can access/create files in my gdrive account. For example, let's say my domain is kennywyland.com and my Google account that I'm using is kenny#kennywyland.com.
I create my Google Client like this, which I got from https://developers.google.com/api-client-library/php/auth/service-accounts:
$client = new Google_Client();
$client->setAuth(new Google_Auth_AppIdentity($client));
$client->getAuth()->authenticateForScope('https://www.googleapis.com/auth/drive');
Then I create the gdrive service like this:
$service = new Google_Service_Drive($client);
I didn't get any errors from this and I am able to perform queries without error messages being thrown, however, I'm getting back completely empty result sets. I've got plenty of files in my gdrive account, so I would assume that I should see them when I publish the following code to GAE and run it (the retreiveAllFiles() function is from Google's code example found here: https://developers.google.com/drive/v2/reference/files/list#try-it):
$allfiles = retrieveAllFiles($service);
print_r($allfiles);
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
However, I get an empty result set. The print_r() prints an empty array:
Array ( )
What am I missing? I feel like my project/app is able to successfully access the gdrive server, but it's just not able to see any files in my account associated with this work domain.
The solution involved one primary change which required one further change. The primary change was that I was using the google-api-php-client v1 but I needed to be using the v2 release candidate (which is oddly located in the https://github.com/google/google-api-php-client/tree/v1-master branch).
They have a list of code changes needed to upgrade from 1.0 to 2.0 (thank you, very handy githubers!)
https://github.com/google/google-api-php-client/blob/master/UPGRADING.md
I ended up configuring my client with the following code and then it was immediately able to access gdrive as if it were the currently logged in person (assuming 'kenny#kennywyland.com' in my example, who is part of my special domain with domain-wide delegation).
require_once('vendor/autoload.php');
$client = new Google_Client();
$client->setAuthConfig('myapp-xxxxxxxx.json');
$user_to_impersonate = "kenny#kennywyland.com";
$client->setSubject($user_to_impersonate);
$client->addScope('https://www.googleapis.com/auth/drive');
$service = new Google_Service_Drive($client);
The myapp-xxxxxxx.json file was generated in my Developer Console for my App's Service Account.

Calling a google apps script execution api from PHP using a service account

I'm trying to call a very simple google apps script from php using a service account so that only my server can access it, not users of the website.
Here is how I do. I create the script here https://script.google.com
function get() {
return ContentService.createTextOutput('get method');
}
and a new project is automatically associated when i save it.
Then I open File > Project Properties to get the scriptId = MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt
I access the developer console of the associated project threw Resources > Project Developers console by clicking on the project link at the top of the popup displayed.
Then I click 'Activate and manage API' and activate the 'Google Apps Script Execution API'. I click on 'Credentials' and see that the previous operation automatically created OAuth2 credentials. But what I need is service account credentials. Then I create one Add credentials > Service account and download generated p12 file. I get the clientId = 109160023321840004240 and clientMail = account-1#project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com for this service account.
I go back to my script and share it with the service account email with read&write access File > Share. First of all i get an email in my personal mailbox which notifies me that
Delivery to the following recipient failed permanently:
account-1#project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com
Then I publish the script as an execution API Publish > Publish as an execution API with access to everybody.
Now lets go on the PHP server side. Using the 'Google APIs Client Library for PHP' available here https://github.com/google/google-api-php-client I try to call my script function from PHP:
$client = new Google_Client();
$client->setClientId('109160023321840004240');
$client->setApplicationName('myScript');
$cred = new Google_Auth_AssertionCredentials(
'account-1#project-id-okwrcpiqeewhwvpdhb.iam.gserviceaccount.com',
[/*no scope nedeed for this simple script*/],
file_get_contents('path_to_myScript.p12')
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Script($client);
$scriptId = 'MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt';
// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction('get');
$response = $service->scripts->run($scriptId, $request);
And here is the response I get all the time
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (403) The caller does not have permission
If, when I deploy the script, I choose to give access to 'Me only', i get the following response.
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (404) Requested entity was not found.
I would be so happy if one of you have an idea to help me :)
apps script does not yet support service accounts with execution api. see https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461
google said they are looking into it but apparently wont happen soon (based on google replies on google+ posts about this like https://plus.google.com/+MartinHawksey/posts/Zquix9XqzkK)

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.

How can I log into multiple accounts at the same time using the Google Api PHP Client

Background: We've got two Accounts that each hold several profiles.
I am developing an application in PHP using the provided API.
I can successfully retrieve data from both accounts separately, but whenever I instantiate the Google_Client object a second time (using a different variable name, of course), it instantly logs me out of the first account and overwrites the first account's settings.
Has anyone successfully managed to log into two accounts at the same time using the PHP API Client and could give me a hint on how to accomplish that?
Relevant code sections:
$client1 = new Google_Client();
$client1 ->setAssertionCredentials($omitted);
$client1 ->setClientId($id);
$client1 ->setAccessType('offline_access');
$gaClient1 = new Google_AnalyticsService($client);
//I can now successfully query the Analytics API, but when I do this
$client2 = new Google_Client();
//and query gaClient1 again, it throws a "you must login/401"-error
I guess the problem is that the api uses caching with files to handle request. Now when the second client is created, it is using the same cache folder and thus it is overwriting the previous settings.
now in your config.php is the following:
'ioFileCache_directory' =>
(function_exists('sys_get_temp_dir') ?
sys_get_temp_dir() . '/Google_Client' :
'/tmp/Google_Client')
This is the part that is always returning the same result. When creating a client, you can send in your own config array and it will be combined with the master. So you could use:
$client1 = new Google_Client(array('ioFileCache_directory' => '/tmp/dirclient1'));
$client2 = new Google_Client(array('ioFileCache_directory' => '/tmp/dirclient2'));
Also in your code you created a $client1, but later on you use $gaClient1 = new Google_AnalyticsService($client);. Shouldnt that be $gaClient1 = new Google_AnalyticsService($client1);?

Categories