I need to integrate a very basic report from Google Analytics in the dashboard page of a CMS web application I'm building with asp.net web forms (C#).
I remember I was able to do it on a test made in 2015 with API V3, but now, with V4, I get always an error message that OAuth2 is needed for authentication.
I need to access to a specific analytics account I own, not the account of the user that navigate in the CMS!
So I use the API KEY given by Google API Manager. I have given to that API Key all the permission.
The API key is similar to this: "d471c3ce04612f143ff0Be319aac2e17d0159add"
here is the code
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.Services;
using System;
using Google.Apis.AnalyticsReporting.v4.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using System.Web;
public static class GoogleAnalyticsAPI
{
static string vmcApiKey = "<<API-KEY>>";
public static void Test()
{
AnalyticsReportingService ars = GetService(vmcApiKey);
// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2017-01-01", EndDate = "2017-04-28" };
// Create the Metrics object.
Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };
//Create the Dimensions object.
Dimension browser = new Dimension { Name = "ga:browser" };
// Create the ReportRequest object.
// Create the ReportRequest object.
ReportRequest reportRequest = new ReportRequest
{
ViewId = "<<VIEW-ID>>",
DateRanges = new List<DateRange>() { dateRange },
Dimensions = new List<Dimension>() { browser },
Metrics = new List<Metric>() { sessions }
};
List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };
// Call the batchGet method.
GetReportsResponse response = ars.Reports.BatchGet(getReport).Execute();
}
public static AnalyticsReportingService GetService(string apiKey)
{
try
{
if(string.IsNullOrEmpty(apiKey))
throw new ArgumentNullException("api Key");
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
ApiKey = apiKey,
ApplicationName = "AnalyticsReporting API key example",
});
}
catch(Exception ex)
{
throw new Exception("Failed to create new AnalyticsReporting Service", ex);
}
}
On the last line of Test() method, ars.Reports.BatchGet(getReport).Execute(); I get the error:
Google.Apis.Requests.RequestError
Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.
But again with OAUTH2 authentication I access the user data and is not what I want.
I need to access a specific account I own, independently by the user that is browsing the CMS.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…