如何使用服务帐户通过 .NET C# 访问 Google Analytics API V3?

2024-02-12

我意识到这个问题之前已经被问过,但几乎没有示例代码,所以我再次询问,但至少有一点方向。

经过几个小时的搜索,我想出了以下部分实现。

namespace GoogleAnalyticsAPITest.Console
{
    using System.Security.Cryptography.X509Certificates;
    using DotNetOpenAuth.OAuth2;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            string Scope = Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
            string scopeUrl = "https://www.googleapis.com/auth/" + Scope;
            const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string ServiceAccountUser = "[email protected] /cdn-cgi/l/email-protection";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"7039572692013fc5deada350904f55bad2588a2a-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = scopeUrl,
                ServiceAccountId = ServiceAccountId//,ServiceAccountUser = ServiceAccountUser
            };
            IAuthorizationState state = AssertionFlowClient.GetState(client);
            AnalyticsService service = new AnalyticsService(authenticator);
            string profileId = "ga:xxxxxxxx";
            string startDate = "2010-10-01";
            string endDate = "2010-10-18";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();
        }
    }
}

我有几个问题。致电给AssertionFlowClient.GetState(client)导致“invalid_scope”响应,如 DotNetOpenAuth 日志中所示

2012-10-19 13:27:36,272 (GMT-4) [8] INFO DotNetOpenAuth - DotNetOpenAuth,版本=4.0.0.11165,文化=中性,PublicKeyToken=2780ccd10d57b246(官方) 2012-10-19 13:27:36,284 (GMT-4) [8] 调试 DotNetOpenAuth.Messaging.Channel - 准备发送 AssertionFlowMessage (2.0) 消息。 2012-10-19 13:27:36,294 (GMT-4) [8] INFO DotNetOpenAuth.Messaging.Channel - 准备传出 AssertionFlowMessage (2.0) 消息https://accounts.google.com/o/oauth2/token https://accounts.google.com/o/oauth2/token: grant_type:断言 断言_类型:http://oauth.net/grant_type/jwt/1.0/bearer http://oauth.net/grant_type/jwt/1.0/bearer断言:(这里有一堆编码字符)

2012-10-19 13:27:36,296 (GMT-4) [8] 调试 DotNetOpenAuth.Messaging.Channel - 发送 AssertionFlowMessage 请求。 2012-10-19 13:27:36,830 (GMT-4) [8] 调试 DotNetOpenAuth.Http - HTTP POSThttps://accounts.google.com/o/oauth2/token https://accounts.google.com/o/oauth2/token2012-10-19 13:27:36,954 (GMT-4) [8] 错误 DotNetOpenAuth.Http - 来自 WebExceptionhttps://accounts.google.com/o/oauth2/token https://accounts.google.com/o/oauth2/token: { “错误”:“无效范围” }

我尝试指定 ServiceAccountId 和 ServiceAccountUser 之一或两者,但没有成功。

其次,即使我获得了 IAuthorizationState,我也不确定如何获得可以传递给 AnalyticsService 构造函数的 IAuthenticator。

以下是我用来启用 D​​otNetOpenAuth 日志记录的 web.config。

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, publicKeyToken=1b44e1d426115821" />
    <!--<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false"/>-->
    <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth">
      <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
    </sectionGroup>
  </configSections>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="DotNetOpenAuth.log"/>
      <appendToFile value="true"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="100KB"/>
      <staticLogFileName value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <appender name="TracePageAppender" type="OpenIdProviderWebForms.Code.TracePageAppender, OpenIdProviderWebForms">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingFileAppender"/>
      <appender-ref ref="TracePageAppender"/>
    </root>
    <!-- Specify the level for some specific categories -->
    <logger name="DotNetOpenAuth">
      <level value="ALL"/>
    </logger>
  </log4net>
  <dotNetOpenAuth>
    <!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
    <!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
    <!--<messaging clockSkew="00:10:00" lifetime="00:03:00" strict="true">-->
    <!--<messaging>
      <untrustedWebRequest timeout="00:00:30" readWriteTimeout="00:00:01.500" maximumBytesToRead="1048576" maximumRedirections="10">
        <whitelistHosts>
          -->
    <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
    <!--
          <add name="localhost"/>            
        </whitelistHosts>
      </untrustedWebRequest>
    </messaging>-->
    <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
    <reporting enabled="false"/>
  </dotNetOpenAuth>
  <appSettings>
    <!--<add key="log4net.Internal.Debug" value="true" />-->
  </appSettings>
  <runtime>
  </runtime>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

以下代码根据我原来的问题进行了更正,基于 Ian Fraser 提供的示例:

https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ

他的代码解决了三个问题:

  1. 看来 AnalyticsService.Scopes.AnalyticsReadonly 不起作用,至少对我或我这样做的方式不起作用。
  2. 由于某种原因,必须将 ServiceAccountUser 分配给 AssertionFlowClient 实例的 ServiceAccountId 属性。
  3. OAuth2Authenticator 提供了我正在寻找的 IAuthenticator。

在您的项目中,包括对以下内容的引用:

  • Lib\DotNetOpenAuth.dll
  • Lib\Google.Apis.dll
  • Lib\Google.Apis.Authentication.OAuth2.dll
  • 服务\AnalyticsService\Google.Apis.Analytics.v3.dll

-

namespace GoogleAnalyticsAPITest.Console
{
    using System.Security.Cryptography.X509Certificates;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
    using Google.Apis.Util;

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();            
            const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string ServiceAccountUser = "[email protected] /cdn-cgi/l/email-protection";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
                ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
                //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);            
            AnalyticsService service = new AnalyticsService(authenticator);            
            string profileId = "ga:64968920";
            string startDate = "2010-10-01";
            string endDate = "2010-10-31";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();            
        }

    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用服务帐户通过 .NET C# 访问 Google Analytics API V3? 的相关文章

  • 为什么两个不同的 Base64 字符串的转换会返回相等的字节数组?

    我想知道为什么从 base64 字符串转换会为不同的字符串返回相同的字节数组 const string s1 dg const string s2 dq byte a1 Convert FromBase64String s1 byte a2
  • 动态加载程序集的应用程序配置

    我正在尝试将模块动态加载到我的应用程序中 但我想为每个模块指定单独的 app config 文件 假设我的主应用程序有以下 app config 设置
  • 秒表有最长运行时间吗?

    多久可以Stopwatch在 NET 中运行 如果达到该限制 它会回绕到负数还是从 0 重新开始 Stopwatch Elapsed返回一个TimeSpan From MSDN https learn microsoft com en us
  • .NET 中是否有内置函数可以对密码进行哈希处理?

    我看到这个问题加密 散列数据库中的纯文本密码 https stackoverflow com questions 287517 encrypting hashing plain text passwords in database 我知道我
  • 类模板参数推导 - clang 和 gcc 不同

    下面的代码使用 gcc 编译 但不使用 clang 编译 https godbolt org z ttqGuL template
  • 从Web API同步调用外部api

    我需要从我的 Web API 2 控制器调用外部 api 类似于此处的要求 使用 HttpClient 从 Web API 操作调用外部 HTTP 服务 https stackoverflow com questions 13222998
  • BitTorrent 追踪器宣布问题

    我花了一点业余时间编写 BitTorrent 客户端 主要是出于好奇 但部分是出于提高我的 C 技能的愿望 我一直在使用理论维基 http wiki theory org BitTorrentSpecification作为我的向导 我已经建
  • 如何使用 ICU 解析汉字数字字符?

    我正在编写一个使用 ICU 来解析由汉字数字字符组成的 Unicode 字符串的函数 并希望返回该字符串的整数值 五 gt 5 三十一 gt 31 五千九百七十二 gt 5972 我将区域设置设置为 Locale getJapan 并使用
  • 用于登录 .NET 的堆栈跟踪

    我编写了一个 logger exceptionfactory 模块 它使用 System Diagnostics StackTrace 从调用方法及其声明类型中获取属性 但我注意到 如果我在 Visual Studio 之外以发布模式运行代
  • OleDbDataAdapter 未填充所有行

    嘿 我正在使用 DataAdapter 读取 Excel 文件并用该数据填充数据表 这是我的查询和连接字符串 private string Query SELECT FROM Sheet1 private string ConnectStr
  • 关于 C++ 转换:参数 1 从“[some_class]”到“[some_class]&”没有已知的转换

    我正在研究 C 并且遇到了一个错误 我不知道确切的原因 我已经找到了解决方案 但仍然想知道原因 class Base public void something Base b int main Base b b something Base
  • 将多个表映射到实体框架中的单个实体类

    我正在开发一个旧数据库 该数据库有 2 个具有 1 1 关系的表 目前 我为每个定义的表定义了一种类型 1Test 1Result 我想将这些特定的表合并到一个类中 当前的类型如下所示 public class Result public
  • IEnumerable 与 IReadOnlyList

    选择有什么区别IEnumerable
  • 垃圾收集器是否在单独的进程中运行?

    垃圾收集器是否在单独的进程中启动 例如 如果我们尝试测量某段代码所花费的进程时间 并且在此期间垃圾收集器开始收集 它会在新进程上启动还是在同一进程中启动 它的工作原理如下吗 Code Process 1 gt Garbage Collect
  • 链接器错误:已定义

    我尝试在 Microsoft Visual Studio 2012 中编译我的 Visual C 项目 使用 MFC 但出现以下错误 error LNK2005 void cdecl operator new unsigned int 2
  • 如何在Xamarin中删除ViewTreeObserver?

    假设我需要获取并设置视图的高度 在 Android 中 众所周知 只有在绘制视图之后才能获取视图高度 如果您使用 Java 有很多答案 最著名的方法之一如下 取自这个答案 https stackoverflow com a 24035591
  • 将控制台重定向到 .NET 程序中的字符串

    如何重定向写入控制台的任何内容以写入字符串 对于您自己的流程 Console SetOut http msdn microsoft com en us library system console setout aspx并将其重定向到构建在
  • 是否可以在 .NET Core 中将 gRPC 与 HTTP/1.1 结合使用?

    我有两个网络服务 gRPC 客户端和 gRPC 服务器 服务器是用 NET Core编写的 然而 客户端是托管在 IIS 8 5 上的 NET Framework 4 7 2 Web 应用程序 所以它只支持HTTP 1 1 https le
  • Windows 和 Linux 上的线程

    我在互联网上看到过在 Windows 上使用 C 制作多线程应用程序的教程 以及在 Linux 上执行相同操作的其他教程 但不能同时用于两者 是否存在即使在 Linux 或 Windows 上编译也能工作的函数 您需要使用一个包含两者的实现
  • 如何防止用户控件表单在 C# 中处理键盘输入(箭头键)

    我的用户控件包含其他可以选择的控件 我想实现使用箭头键导航子控件的方法 问题是家长控制拦截箭头键并使用它来滚动其视图什么是我想避免的事情 我想自己解决控制内容的导航问题 我如何控制由箭头键引起的标准行为 提前致谢 MTH 这通常是通过重写

随机推荐

  • 当新项目添加到模型时,ng-repeat 更改所有项目的排序顺序

    我创建了一个 tessellate 指令 可以让您包装多个 div
  • AngularJS 中的条件 ng-model 绑定

    我有一个模型 它是一个需要处理复杂和简单元素的数组 object element1 html element2 html url element3 html title Title 3 element4 html element5 html
  • 如何使用 Java Apache POI 在 Excel 中添加标题列?

    我正在编写一个java程序 其中我必须从XML文件中获取数据并将其放入excel文件中 在执行此操作时 我必须创建行标题并相应地添加数据 我知道如何创建列标题 我可以通过以下方式做到这一点 HSSFWorkbook workbook new
  • wkhtmltopdf 是否尊重 css 字体颜色?

    我正在使用 wkhtmltopdf 生成页面的 pdf 但它没有以正确的颜色显示任何字体 它们全部显示为黑色 颜色按照您的预期定义 panel dashboard p stat color bed000 并在浏览器中查看时正确显示 我把它称
  • 在执行回调之前等待 .each() .getJSON 请求完成

    我有一个jquery each循环 从 json 请求中检索页面上具有特定类的所有元素的远程数据 一组元素是一组li我想在之后使用另一个函数对标签进行排序li元素已使用远程信息进行更新 之后传入排序函数 each循环不会对列表进行排序 因为
  • 在稀疏表中选择一行第一个非空值

    使用下表 A B C ts 1 null null 2016 06 15 10 00 4 null null 2016 06 15 11 00 4 9 null 2016 06 15 12 00 5 1 7 2016 06 15 13 00
  • h1之后是否有必要使用H2

    如果文本太小 是否必须在 h1 之后使用 H2 那么我们可以在 h1 之后使用 h4 吗 它可以访问吗 从技术上讲 您可以使用这些的任意组合 从语义上讲 使用通用顺序是明智的 如果字体太小 可以使用 CSS 来更改 与标签h1 h6您赋予标
  • SQL Server - 使用递归外键进行级联 DELETE

    我花了很多时间试图找出如何实现删除时级联SQL Server 上的递归主键已经有一段时间了 我已经阅读了有关触发器 创建临时表等的内容 但尚未找到适合我的数据库设计的答案 这是一个用于演示目的的老板 员工数据库示例 TABLE employ
  • Flutter - 失败:构建失败并出现异常。 - 无法启动守护进程。 - Android Studio - VSCode

    每当我尝试使用 flutter run v 运行 flutter 应用程序时 都会收到以下错误 如果我不使用终端 只需单击 运行 则正在运行的 gradle 任务将继续运行 并且不会发生任何情况 I tried 在 gradle prope
  • Angular 2 ng-bootstrap 模态

    我使用组件而不是模板在应用程序中打开模态 然后我需要将对象模型传递给模态组件 问题是打字稿给出了 modalRef componentInstance 不作为属性存在的错误 我完全复制了示例表单演示页面 但再次给出同样的错误 并且永远不会在
  • 为什么有些语句在线程中运行时执行失败?

    我无法理解程序的行为这段代码示例 http rustbyexample com channels html use std comm use std thread Thread static NTHREADS uint 3 fn main
  • 服务器端处理与客户端处理+ajax?

    寻找一些一般性建议和 或想法 我正在创建一个我认为更像是一个网络应用程序而不是网页的东西 因为我想让它像一个 Gmail 应用程序 您可以让页面整天打开 同时将更新 推送 到页面 对于有兴趣我正在使用彗星编程技术 我以前从未创建过如此丰富的
  • 尝试将字符串转换为 MarketDataIncrementalRefresh

    我有一个文本文件FIX messages 所有这些和 MarketDataIncrementalRefresh 类型 X 我正在尝试找到一种使用的方法QuickFIX in C 创造MarketDataIncrementalRefresh消
  • 当用户从其他选项卡返回时重新加载页面

    我在某种重视更新的网站上工作 为此 当用户从另一个选项卡切换到网站的选项卡时 我需要刷新页面 有没有办法用 JavaScript jQuery 做到这一点 我知道location reload 用于刷新页面 但我不知道如何告诉 JavaSc
  • Three.js 2D 文本精灵标签

    我是 Three js 的新手 并且有一些属于 2D 文本的问题 我想要的是 我想要一些标签 例如 x y 和 z 轴 标签应始终面向相机 也许稍后它们应该只在悬停时才被显示 但那是另一个话题 我的问题是什么我找到了这个教程 这正是我想要达
  • 在 MongoDB GROUP BY 中执行 HAVING 的正确方法是什么?

    对于 SQL 中的这个查询 查找重复项 SELECT userId name FROM col GROUP BY userId name HAVING COUNT gt 1 我在 MongoDB 中执行了这个简单的查询 res db col
  • 如何自动读取 x86 ASM 中的值?

    我知道如何在 x86 ASM 中自动写入一个值 但我该如何阅读呢 LOCK 前缀不能与 mov 一起使用 为了增加价值 我正在做 lock inc dword ptr Counter 如何以线程安全的方式读取 Counter 正如我向你解释
  • 仅在需要时注入模块依赖项(如插件) AngularJS

    我有 2 页 我不使用angular s routing 此限制 在其中之一我想使用该指令ui grid http ui grid info docs tutorial 101 intro就像这个演示一样 var app angular m
  • std::string::compare(const char*) 可以抛出异常吗?

    这是超载 4 here https en cppreference com w cpp string basic string compare 在 异常 部分 重载 2 3 5 6 具有 pos1 和 或 pos2 参数 被命名为 thro
  • 如何使用服务帐户通过 .NET C# 访问 Google Analytics API V3?

    我意识到这个问题之前已经被问过 但几乎没有示例代码 所以我再次询问 但至少有一点方向 经过几个小时的搜索 我想出了以下部分实现 namespace GoogleAnalyticsAPITest Console using System Se