How to get install and uninstall stats from Google Developer Play store? - google-developers-console

Does google developer API provides install and uninstall information? I found one that provide reviews but I couldn't find anything related to install/uninstall. Is there any option to get install/uninstall information using API?

I found solution using C#.
var storageService = new StorageService(new BaseClientService.Initializer
{
ApplicationName = "App Name",
ApiKey = "APIKey goes here ",
});
var storage = StorageClient.Create();
string localPath = "C:\\test\test.csv";
using (var outputFile = File.OpenWrite(localPath))
{
storage.DownloadObject("gs://pubsite_prod_rev_23628868/stats/installs/", "installs", outputFile);
}
ApiKey --> Create a google project and generate API Key
gs://pubsite_prod_rev_23628868/stats/installs/ --> You can get this path in your Google Developer Dashboard under Reports

Related

Get user profile details from Google using access token

We have mobile app developed in react native in which we have to implement Google and Facebook login. We have RN libraries using which we will get Facebook and Google user's profile details. But our requirement is like we need to just pass the access token to web api which is developed in asp.net core, and using the access token we have to verify the access token in asp.net core web api and fetch the user's profile details using Facebook or Google Apis.
It is working fine for Facebook api, below is the code for the same
var httpClient = new HttpClient { BaseAddress = new Uri("https://graph.facebook.com/v2.9/") };
var response = await httpClient.GetAsync($"me?access_token={token}&fields=id,name,email,first_name,last_name,age_range,birthday,gender,locale,picture");
Similarly, when we pass access token(id_token) for google, it is not working, and below is code for the same,
var token ="eyJhb.eyJpc....";
var httpClient1 = new HttpClient { BaseAddress = new Uri("https://www.googleapis.com/oauth2/v3/") };
var response1 = await httpClient1.GetAsync($"userinfo?access_token={token}");
Can anyone please assist me, how can we verify the access token and fetch the user's profile details?
Thanks In Advance.
You can verify your "id_token" and get some user profile details at the same time by making GET request to the next endpoint:
"https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123".
var token ="eyJhb.eyJpc....";
var httpClient1 = new HttpClient { BaseAddress = new Uri("https://oauth2.googleapis.com/") };
var response1 = await httpClient1.GetAsync($"tokeninfo?id_token={token}");
as described in google documentation "https://developers.google.com/identity/sign-in/web/backend-auth" (Calling the tokeninfo endpoint) section.
However in case you want to access google api services:
"id_token" is not meant to be used to access google api services, then you will need to have an "access_token" not an "id_token", you can follow the next documentation for that :
"https://developers.google.com/identity/protocols/oauth2"

How to use YouTube Data API

I tried using YouTube Data API.
I really took a good look at everything I found on the internet. The code itself isn't the problem, but I did not find out, where to use this code. Do I simply create a python file (in Visual Studio Code for example) and run it there? Because it didn't work when I tried this...
I also saw many people using the API with the commander only, others used something in chrome (localhost:8888...). So I don`t really know what's the way to go or what I should do.
Thanks for any help :)
Best regards!
I'm not a python developer but as a guess you could start here:
https://developers.google.com/youtube/v3/quickstart/python
using pip to install the dependencies you need.
You should be able to create a simple python file that authenticates with the API and then calls a method on the on the google api client and then output it. There are some examples here:
https://github.com/youtube/api-samples/blob/master/python/
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: upload a video.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted
/// </summary>
internal class UploadVideo
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Upload Video");
Console.WriteLine("==============================");
try
{
new UploadVideo().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = #"REPLACE_ME.mp4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
}
}
Make sure you have python installed on your PC
Create a project: Google’s APIs and Services dashboard
Enable the Youtube v3 API: API Library
Create credentials: Credentials wizard
Now you need to get an access token and a refresh token using the credentials you created
Find an authentication example in one of the following libraries:
https://github.com/googleapis/google-api-python-client
https://github.com/omarryhan/aiogoogle (for the async version)
Copy and paste the client ID and client secret you got from step 4 and paste them in the authentication example you found in step 6 (Should search for an OAuth2 example), this step should provide with an access token and a refresh token
Copy and paste a Youtube example from either:
https://github.com/googleapis/google-api-python-client
https://github.com/omarryhan/aiogoogle (for the async version)
Replace the access token and refresh token fields with the ones you got.
Now you should be able to run the file from any terminal by typing:
python3 yourfile.py
[EDIT]
The API key is not the same as the access token. There are 2 main ways to authenticate with Google APIs:
Access and refresh token
API_KEY.
API key won't work with personal info. You need to get an access and refresh token for that (method 1).
Once you get an access token, it acts in a similar fashion to the API_KEY you got. Getting an access token is a bit more complicated than only working with an API_KEY.
A refresh token is a token you get with the access token upon authentication. Access tokens expire after 3600 seconds. When they expire, your authentication library asks Google's servers for a new access token with the refresh token. The refresh token has a very long lifetime (often indefinite), so make sure you store it securely.
To get an access token and a refresh token (user credentials), you must first create client credentials. Which should consists of 1. a client ID and 2. a client secret. These are just normal strings.
You should also, set a redirect URL in your Google app console in order to properly perform the OAuth2 flow. The OAuth2 flow is the authentication protocol that many APIs rely on to allow them to act on a user's account with the consent of the user. (e.g. when an app asks you to post on your behalf or control your account on your behalf, it typically will use this protocol.)
Aiogoogle's docs does a decent job in explaining the authentication flow(s) available by Google.
https://aiogoogle.readthedocs.io/en/latest/
But this is an async Python library. If you're not familiar with the async syntax, you can read the docs just to get a general idea of how the authentication system works and then apply it to Google's sync Python library.
About point no.6. The links I posted with Aiogoogle being one of them, are just client libraries that help you access Google's API quicker and with less boilerplate. Both libraries have documentation, where they have links to examples on how to use them. So, open the documentation, read it, search for the examples posted, try to understand how the code in the example(s) work. Then maybe download it and run it on your own machine.
I recommend that your read the docs. Hope that helps.

Call Azure API from WebJob/ Shared code between WebJob and web api

I have a web api in an ASE and an associated web job. I am trying to call this web api from the web job but it always fails with winhttpexception: a security error has occurred. I have put in all the tls related settings but still getting the error.
Any suggestions on the error?
Also is there a way to share code between WebJob and web api?
I was able to resolve the issue by setting the below in my code.This resolved the Security Error.
using(var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (sender,certificate,chain,sslPolicyErrors) => true
})
You could create a console app and publish it as Azure WebJobs. For username and password you could click Get Publish Profile in your Azure webapp overview to get them.
Then you could use the following code in Console App to call your Azure Webapi.
string userName = "$xxxxxx";
string userPassword = "xxxxxxxxxxxxx";
string webAppName = "xxxxxx";
var base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{userName}:{userPassword}"));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64Auth);
var baseUrl = new Uri($"https://{webAppName}.azurewebsites.net/api/values");
var result = client.GetAsync(baseUrl).Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsStringAsync();
readTask.Wait();
var value = readTask.Result;
Console.WriteLine(value.ToString());
}
}
Console.WriteLine("run successfully");
Output as below:

Google .Net Service Account access to Calendar

I am updating a web service application that calls Google's calendar API's to list calendar events for a particular calendar and insert new calendar events. I am trying to upgrade it to version 3 of the api's. For authentication I am using a Service Account Credential that I created in the Google Developers Console (https://console.developers.google.com). I am able to create the CalendarService using the following code :
using System;
using Google.Apis.Auth.OAuth2;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Services;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
...
string SERVICE_ACCOUNT_EMAIL =
"....googleusercontent.com";
string SERVICE_ACCOUNT_PKCS12_FILE_PATH = #"C:\temp\API Project-123456789.p12";
// Create the service.
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
Scopes = new[] { CalendarService.Scope.Calendar }
, User = "something#mycompany.com"
}.FromCertificate(certificate));
// Create the service.
var cs = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
But when I call the list method to query a public calendar:
Events events = service.Events.List("something#mycompany.com").Execute();
A TokenResponseException is thrown with the following error message:
Error:"invalid_grant", Description:"", Uri:""
FYI : I have gone into the AdminHome for my company and under security Manage clients API Access and registered the SERVICE_ACCOUNT_EMAIL above to http://www.google.com/calendar/feeds/.
Any help with this would be greatly appreciated.
I believe you need to register the Client ID of the service account of your App, I have successfully got it working using this difference.
Here is a similar issue I resolved with inserting events.
Google API Calender v3 Event Insert via Service Account using Asp.Net MVC
Here is the google documention on domain-wide-authorization.
https://developers.google.com/+/domains/authentication/delegation

What is the easiest way to detect whether a user is logged in via google apps marketplace?

I have a web application which users log into using google oauth2.
I have a google apps marketplace listing for this application, and some portion of the google oauth2 users didn't need to grant permission to my application because their google apps domain administrator did it while installing the apps marketplace listing.
I'd like to be able to detect this second group of users, to analyze how frequently the apps marketplace listing is being used to log into my application. At the moment all google oauth2 logins look the same to my application.
Is there a simple API call I can make to find out whether the current user is in this group?
I use this code for finding out marketplace listing info for given appId and target domain:
InputStream p12File = Config.class.getResourceAsStream(Config.SERVICE_ACCOUNT_PRIVATE_KEY_RESOURCE_PATH);
PrivateKey serviceAccountPrivateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), p12File, "notasecret", "privatekey", "notasecret");
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport t = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential.Builder bgc = new GoogleCredential.Builder()
.setTransport(t)
.setJsonFactory(jsonFactory)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKey(serviceAccountPrivateKey)
.setServiceAccountId(Config.SERVICE_ACCOUNT_ID);
GoogleCredential gc = bgc.build();
String token = gc.getAccessToken();
if(token == null) {
gc.refreshToken();
token = gc.getAccessToken();
}
HttpGet request = new HttpGet("https://www.googleapis.com/appsmarket/v2/customerLicense/" + applicationId + "/" + customerDomain);
request.setHeader("Authorization", "Bearer " + token);
DefaultHttpClient client = new DefaultHttpClient(httpParams);
HttpResponse resp = client.execute(request);
// ... read API JSON response