Javascript 无法使用服务帐户查询Google搜索控制台API
我需要使用服务帐户从谷歌搜索控制台(网站管理员工具)检索一些数据 到目前为止,我已经能够为需要附加到请求url的服务帐户检索Javascript 无法使用服务帐户查询Google搜索控制台API,javascript,google-api,google-webmaster-tools,service-accounts,Javascript,Google Api,Google Webmaster Tools,Service Accounts,我需要使用服务帐户从谷歌搜索控制台(网站管理员工具)检索一些数据 到目前为止,我已经能够为需要附加到请求url的服务帐户检索access\u令牌。问题是我找不到这样做的方法,这是我正在使用的代码: function retrieveSearchesByQuery(token) { gapi.client.webmasters.searchanalytics.query( { 'access_token': token,
access\u令牌。问题是我找不到这样做的方法,这是我正在使用的代码:
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\u token'
识别为有效密钥,因此它不会将其附加到url,这就是为什么我会收到401未经授权的作为响应
如果我使用'key'
而不是'access\u token'
则参数会附加到url,但'key'
用于OAuth2
身份验证,因此我传递的服务帐户令牌无效
是否有人对此有解决方案或解决方法?如果您的应用程序请求私有数据,则该请求必须由有权访问该数据的经过身份验证的用户授权。如搜索控制台API的中所述,应用程序必须使用OAuth 2.0来授权请求。不支持其他授权协议
如果您的应用程序是,当使用GoogleAPI时,经过身份验证的请求看起来与未经身份验证的请求完全相同。如中所述,如果应用程序已收到OAuth 2.0令牌,JavaScript客户端库会自动将其包含在请求中
您提到您已检索到一个access\u令牌
,如果接收正确,API客户端将自动为您发送此令牌,您不必自己附加它
一个非常基本的认证工作流程,一旦认证,发送一个请求看起来像下面的代码。搜索控制台API可以使用以下作用域:https://www.googleapis.com/auth/webmasters
和https://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
函数将需要修改,因为它不再需要通过参数获取令牌才能在查询中传递。JavaScript客户端库应自动将其包含在请求中
您还可以使用检查特定查询支持哪些参数,并检查关联的请求
如果需要使用外部生成的访问令牌(服务帐户也应如此),则需要使用设置应用程序的您自己:
gapi.auth.setToken(token_Object);
谢谢最后一个解决方案是有效的,但使用以下语法:gapi.auth.setToken({access_-token:“YOUR_-token_-HERE”})代码>,因为当我有一个字符串时,该方法接受一个tokenObject。现在我可以正确登录和检索数据了