gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:42:17 24 4
gpt4 key购买 nike

我需要使用服务帐户从 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);
});
}

这是函数调用的 url:

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

相反,它应该是这样的:

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

gapi.client.webmasters.searchanalytics.query 无法将 'access_token' 识别为有效 key ,因此它不会将其附加到网址中,这就是为什么我收到 401 Unauthorized 作为响应。

如果我使用 'key' 而不是 'access_token',则参数将附加到网址,但 'key' 用于 OAuth2 身份验证,因此我传递的服务帐户 token 无效。

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

最佳答案

如果您的应用程序请求私有(private)数据,则该请求必须由有权访问该数据的经过身份验证的用户授权。如 the documentation 中指定Search Console API 的一部分,您的应用程序必须使用 OAuth 2.0 来授权请求​​。不支持其他授权协议(protocol)。

如果您的申请是correctly configured ,当使用 Google API 时,经过身份验证的请求看起来与未经身份验证的请求完全相同。如 the documentation 中所述,如果应用程序收到 OAuth 2.0 token ,JavaScript 客户端库会自动将其包含在请求中。

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

一个非常基本的身份验证工作流程,一旦通过身份验证,发送请求将类似于以下代码。 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);

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

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

如果您需要使用外部生成的访问 token (服务帐户就属于这种情况),则需要使用 gapi.auth.setToken method设置 OAuth 2.0 token object自己申请:

gapi.auth.setToken(token_Object);

关于javascript - 无法使用服务帐户查询 Google Search Console API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38653502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com