开始使用 AdMob API

本文档适用于希望通过 AdMob API 了解其 AdMob 帐号相关信息的开发者。要使用本文档,您必须熟悉网络编程概念和网络数据。

在开始之前,请确保您已拥有:

此外,您还需要熟悉“向请求授权”部分中介绍的如何向请求授权的内容。

获取授权令牌

使用 oauth2l 可自动执行获取访问令牌的流程。对于您的应用,您可以使用设置应用中列出的库。

oauth2l fetch --json <path_to_credentials_json> https://www.googleapis.com/auth/admob.report

将 <path_to_credentials_json> 替换为您在注册云应用时下载的 credentials.json 文件所在的路径。首次运行时,该命令会一步步引导您完成 OAuth 2.0 授权流程。后续运行则自动刷新令牌。

获取帐号信息

您可以通过调用 getlist accounts 方法来请求帐号信息。请参阅以下示例:

# Replace the <access_token> with one received in the previous section.
curl -X GET \
      https://admob.googleapis.com/v1/accounts \
      -H "Authorization: Bearer <access_token>"
您可以使用 oauth2l 生成“授权”标题,如下所示:
# The approach wouldn't work without initial steps described in the Get authorization token.
curl -X GET \
     https://admob.googleapis.com/v1/accounts \
     -H "$(oauth2l header --json <path_to_credentials_json> https://www.googleapis.com/auth/admob.report)"

响应大致类似如下所示:

{
  "account": [
    {
      "publisherId": "pub-1234567890123456",
      "reportingTimeZone": "Europe/Paris",
      "currencyCode": "EUR"
    }
  ]
}

生成广告联盟报告

您可以通过调用 networkReport:generate 方法生成广告联盟报告。在请求 URI 中,加入获取帐号信息步骤中接收到的 publisherId,例如,v1/accounts/pub-1234567890123456/networkReport:generate。然后,使用以下代码生成广告联盟报告:

curl -X POST \
     https://admob.googleapis.com/v1/accounts/pub-1234567890123456/networkReport:generate \
     -H "$(oauth2l header --json <path_to_credentials_json> https://www.googleapis.com/auth/admob.report)" \
     -H "Content-Type: application/json" \
     --data @- << EOF
{
  "report_spec": {
    "date_range": {
      "start_date": {"year": 2019, "month": 4, "day": 1},
      "end_date": {"year": 2019, "month": 4, "day": 2}
    },
    "dimensions": ["DATE"],
    "metrics": ["CLICKS", "AD_REQUESTS", "IMPRESSIONS", "ESTIMATED_EARNINGS"],
    "dimension_filters": [{"dimension": "COUNTRY", "matches_any": {"values": ["US"]}}],
    "sort_conditions": [{"metric":"CLICKS", order: "DESCENDING"}],
    "localization_settings": {"currency_code": "USD", "language_code": "en-US"}
  }
}
EOF

此请求会返回以下响应:

[{
  "header": {
    "dateRange": {
      "startDate": {"year": 2019, "month": 4, "day": 1},
      "endDate": {"year": 2019, "month": 4, "day": 2}
    }
  }
},
{
  "row": {
    "dimensionValues": {"DATE": {"value": "20190401"}},
    "metricValues": {
      "CLICKS": {"integerValue": "31"},
      "AD_REQUESTS": {"integerValue": "7409"},
      "IMPRESSIONS": {"integerValue": "3440"},
      "ESTIMATED_EARNINGS": {"microsValue": "6381903"}
    }
  }
},
{
  "row": {
    "dimensionValues": {"DATE": {"value": "20190402"}},
    "metricValues": {
      "CLICKS": {"integerValue": "30"},
      "AD_REQUESTS": {"integerValue": "8828"},
      "IMPRESSIONS": {"integerValue": "3724"},
      "ESTIMATED_EARNINGS": {"microsValue": "9010390"}
    }
  }
},
{
  "footer": {
    "matchingRowCount": "2"
  }
}]

现在,您可以开始随意使用不同的维度指标和其他广告联盟报告属性了。