如何从 Google Analytics API 获取用户名?

How to get user name from Google Analytics API?

我正在使用 Google 分析 API 和 SDK。登录用户后,我想显示他的名字。相反,当我要求用户的广告帐户时,API returns 只是没有显示名称的电子邮件。我正在使用 https://www.googleapis.com/auth/analytics.edit 范围。

这是我得到的:

object(Google_Service_Analytics_Accounts)[86]
  protected 'collection_key' => string 'items' (length=5)
  protected 'internal_gapi_mappings' => ...
  protected 'itemsType' => string 'Google_Service_Analytics_Account' (length=32)
  protected 'itemsDataType' => string 'array' (length=5)
  public 'itemsPerPage' => int 1000
  public 'kind' => string 'analytics#accounts' (length=18)
  public 'nextLink' => null
  public 'previousLink' => null
  public 'startIndex' => int 1
  public 'totalResults' => int 2
  public 'username' => string 'me@gmail.com' (length=12)
  protected 'modelData' => ...
  protected 'processed' => ...

如何获取用户名?我需要使用其他一些 Google API 吗?

不幸的是,Google Analytics API 无法访问除电子邮件之外的用户信息。

即使您检查 Account users list 它也不会 return 用户名:

 "userRef": {
    "kind": "analytics#userRef",
    "id": "117200475532672775346",
    "email": "xxx@gmail.com"
   },

一个选项是添加 profile 范围,它是 Google+ API 的一部分。然后您就可以使用 people.get。只需添加 me 作为用户 ID,它将 return 当前通过身份验证的人的个人资料信息:

 "objectType": "person",
 "id": "117200475532672775346",
 "displayName": "Linda Lawton",
 "name": {
  "familyName": "Lawton",
  "givenName": "Linda"
 },

或者我想您可以从 Google Analytics(分析)帐户请求中获取 ID。它们似乎是相同的 ID。