C# 具有API密钥的分析报告v4

C# 具有API密钥的分析报告v4,c#,asp.net,google-api,google-analytics-api,google-api-dotnet-client,C#,Asp.net,Google Api,Google Analytics Api,Google Api Dotnet Client,我需要在我正在用asp.net web表单(C#)构建的CMS web应用程序的仪表板页面中集成来自Google Analytics的一个非常基本的报告 我记得我在2015年使用API V3进行的测试中能够做到这一点,但现在,使用V4,我总是收到一条错误消息,即身份验证需要OAuth2 我需要访问我拥有的特定分析帐户,而不是在CMS中导航的用户帐户 所以我使用GoogleAPI管理器提供的API密钥。我已经给了那个API密钥所有的权限。 API键类似于此:“D471CCE04612F143FF0

我需要在我正在用asp.net web表单(C#)构建的CMS web应用程序的仪表板页面中集成来自Google Analytics的一个非常基本的报告

我记得我在2015年使用API V3进行的测试中能够做到这一点,但现在,使用V4,我总是收到一条错误消息,即身份验证需要OAuth2

我需要访问我拥有的特定分析帐户,而不是在CMS中导航的用户帐户

所以我使用GoogleAPI管理器提供的API密钥。我已经给了那个API密钥所有的权限。 API键类似于此:“D471CCE04612F143FF0BE319AAC2E17D0159ADD”

这是密码

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);
    }
}
使用Google.api.AnalyticsReporting.v4;
使用Google.api.Services;
使用制度;
使用Google.api.AnalyticsReporting.v4.Data;
使用System.Collections.Generic;
使用System.Threading.Tasks;
使用System.IO;
使用Google.api.Auth.OAuth2;
使用系统线程;
使用Google.api.Util.Store;
使用System.Web;
公共静态类GoogleAnalyticsAPI
{
静态字符串vmcApiKey=“”;
公共静态无效测试()
{
AnalyticsReportingService ars=GetService(vmcApiKey);
//创建DateRange对象。
DateRange DateRange=new DateRange(){StartDate=“2017-01-01”,EndDate=“2017-04-28”};
//创建度量对象。
度量会话=新度量{Expression=“ga:sessions”,Alias=“sessions”};
//创建标注对象。
维度浏览器=新维度{Name=“ga:browser”};
//创建ReportRequest对象。
//创建ReportRequest对象。
ReportRequest ReportRequest=新的ReportRequest
{
ViewId=“”,
DateRanges=新列表(){dateRange},
维度=新列表(){browser},
Metrics=新列表(){sessions}
};
列表请求=新列表();
请求。添加(报告请求);
//创建GetReportsRequest对象。
GetReportsRequest getReport=new GetReportsRequest(){ReportRequests=requests};
//调用batchGet方法。
GetReportsResponse response=ars.Reports.BatchGet(getReport.Execute();
}
公共静态分析报告服务GetService(字符串apiKey)
{
尝试
{
if(string.IsNullOrEmpty(apiKey))
抛出新的ArgumentNullException(“api键”);
返回新的AnalyticsReportingService(新的BaseClientService.Initializer()
{
ApiKey=ApiKey,
ApplicationName=“AnalyticsReportingAPI密钥示例”,
});
}
捕获(例外情况除外)
{
抛出新异常(“未能创建新的分析报告服务”,ex);
}
}
在Test()方法的最后一行,ars.Reports.BatchGet(getReport.Execute();我得到了错误:

Google.api.Requests.RequestError 请求缺少必需的身份验证凭据。需要OAuth 2访问令牌、登录cookie或其他有效身份验证凭据

但是再次使用OAUTH2身份验证,我访问用户数据,这不是我想要的。
我需要由浏览CMS的用户独立访问我拥有的特定帐户。

API密钥仅用于访问公共数据,这意味着您只能将其用于

Google Analytics数据是用户拥有的私有数据。由于这是您试图访问的自己的数据,因此您应该创建一个服务帐户。服务帐户经过预授权。转到Google开发者控制台并创建。然后获取服务帐户电子邮件地址,并将其作为帐户级别的用户添加到谷歌分析网站。它必须是帐户级别。您现在已授权服务帐户访问该帐户的数据

服务帐户验证

// Copyright 2017 DAIMTO :  www.daimto.com
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
//     Template File Name:  ServiceAccount.tt
//     Build date: 01/02/2017 22:31:50
//     C# generater version: 1.0.0
//     
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

// About 
// 
// Unoffical sample for the AnalyticsReporting v4 API for C#. 
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
// 
// API Description: Accesses Analytics report data.
// API Documentation Link https://developers.google.com/analytics/devguides/reporting/core/v4/
//
// Discovery Doc  https://www.googleapis.com/discovery/v1/apis/AnalyticsReporting/v4/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library 
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.AnalyticsReporting.v4/ 
// Install Command: PM>  Install-Package Google.Apis.AnalyticsReporting.v4
//
//------------------------------------------------------------------------------  
using Google.Apis.AnalyticsReporting.v4
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace GoogleSamplecSharpSample.AnalyticsReportingv4.Auth
{

    public class static ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static AnalyticsReportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");

                // These are the scopes of permissions you need. It is best to request only what you need and not all of them
                string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics };             // View your Google Analytics data

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new AnalyticsReportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "AnalyticsReporting Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  AnalyticsReporting service.
                    return new AnalyticsReportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "AnalyticsReporting Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Create service account AnalyticsReportingService failed" + ex.Message);
                throw new Exception("CreateServiceAccountAnalyticsReportingFailed", ex);
            }
        }
    }
}
//版权所有2017 DAIMTO:www.DAIMTO.com
//
//根据Apache许可证2.0版(“许可证”)获得许可;除非符合
//许可证。您可以通过以下方式获得许可证副本:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//除非适用法律要求或书面同意,否则根据许可证分发的软件将在
//以“现状”为基础,无任何明示或暗示的保证或条件。有关
//管理许可证下的权限和限制的特定语言。
//------------------------------------------------------------------------------
//

创建服务后,您应该能够使用示例页面上的代码

我有一个关于V3服务帐户的老教程