无法使用服务帐户查询 Google Search Console API

LS_*_*LS_ 3 javascript google-api service-accounts google-search-console

我需要使用服务帐户从 Google Search Console(网站管理员工具)检索一些数据。

到目前为止,我已经能够检索access_token服务帐户的信息,我需要将其附加到请求的 URL 中。问题是我找不到办法这样做,这是我正在使用的代码:

function retrieveSearchesByQuery(token)
    {
        gapi.client.webmasters.searchanalytics.query(
        {
            'access_token': token,
            'siteUrl': 'http://www.WEBSITE.com',
            'fields': 'responseAggregationType,rows',
            'resource': {
                'startDate': formatDate(cSDate),
                'endDate': formatDate(cEDate),
                'dimensions': [
                    'date'
                ]
            }
        })
        .then(function(response) {
            console.log(response);
        })
        .then(null, function(err) {
            console.log(err);
        });
    }
Run Code Online (Sandbox Code Playgroud)

这是该函数调用的 url:

https://content.googleapis.com/webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE.com/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json"
Run Code Online (Sandbox Code Playgroud)

相反,它应该是这样的:

https://content.googleapis.com/webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE.com/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json&access_token=XXX"
Run Code Online (Sandbox Code Playgroud)

无法gapi.client.webmasters.searchanalytics.query识别'access_token'为有效密钥,因此它不会将其附加到网址,这就是我收到响应的原因401 Unauthorized

如果我使用'key'而不是'access_token'参数被附加到 url,但'key'用于OAuth2身份验证,那么我传递的服务帐户令牌无效。

有人对此有解决方案或解决方法吗?

HiD*_*Deo 5

如果您的应用程序请求私有数据,则该请求必须由有权访问该数据的经过身份验证的用户授权。根据Search Console API文档中的规定,您的应用程序必须使用 OAuth 2.0 来授权请求​​。不支持其他授权协议。

如果您的应用程序配置正确,那么在使用 Google API 时,经过身份验证的请求看起来与未经身份验证的请求完全相同。如文档中所述,如果应用程序已收到 OAuth 2.0 令牌,JavaScript 客户端库会自动将其包含在请求中。

您提到您已检索到一个access_token,如果正确接收,API 客户端将自动为您发送此令牌,您不必自己附加它。

一个非常基本的身份验证工作流程,一旦通过身份验证,发送请求将类似于以下代码。Search Console API 可以使用以下范围:https://www.googleapis.com/auth/webmastershttps://www.googleapis.com/auth/webmasters.readonly

var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/webmasters';

function auth() {
  // Set the API key.
  gapi.client.setApiKey(apiKey);

  // Start the auth process using our client ID & the required scopes.
  gapi.auth2.init({
      client_id: clientId,
      scope: scopes
  })
  .then(function () {
    // We're authenticated, let's go...
    // Load the webmasters API, then query the API
    gapi.client.load('webmasters', 'v3')
      .then(retrieveSearchesByQuery);
  });
}

// Load the API client and auth library
gapi.load('client:auth2', auth);
Run Code Online (Sandbox Code Playgroud)

此时,您的retrieveSearchesByQuery函数将需要修改,因为它不再需要通过参数获取标记来将其传递到查询中。JavaScript 客户端库应自动将其包含在请求中。

您还可以使用API Explorer检查特定查询支持哪些参数并检查关联的请求。

如果您需要使用外部生成的访问令牌(服务帐户应该是这种情况),您需要使用该gapi.auth.setToken方法自行为应用程序设置OAuth 2.0 令牌对象:

gapi.auth.setToken(token_Object);
Run Code Online (Sandbox Code Playgroud)