1

查詢谷歌搜索API控制檯我需要使用服務帳戶檢索從谷歌搜索控制檯(網站站長工具)的一些數據。無法使用服務帳戶

到目前爲止,我已經能夠檢索,我需要追加到請求的URL服務帳戶的access_token。問題是,我無法找到一個方法來做到這一點,這是我使用的代碼:

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); 
     }); 
    } 

這是由函數調用的網址:

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'作爲一個有效的密鑰因此不追加到URL,這就是爲什麼我得到一個401 Unauthorized作爲響應。

如果我使用'key'代替'access_token'參數被附加到URL,但'key'用於OAuth2認證,這樣的服務帳戶令牌我傳遞無效。

有沒有人有解決方案或解決方法?

回答

1

如果您的應用程序請求的私人資料,這個要求必須由誰有權訪問這些數據的驗證用戶的授權。根據Search Console API的the documentation中的規定,您的應用程序必須使用OAuth 2.0來授權請求​​。沒有其他授權協議被支持。

如果你的應用是correctly configured,使用谷歌API時,驗證的請求看起來就像一個未經身份驗證的請求。如the documentation中所述,如果應用程序已收到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); 

在這一點上,你retrieveSearchesByQuery功能將需要被修改,因爲它並不需要爲了通過它查詢獲得通過爭論令牌了。 JavaScript客戶端庫應該自動將它包含在請求中。

您還可以使用API Explorer檢查什麼參數是針對特定查詢的支持,並檢查相關要求。

如果需要使用外部產生的訪問令牌,這應該是與服務帳戶的情況下,你需要使用gapi.auth.setToken method來套OAuth 2.0 token object自己的應用程序:

gapi.auth.setToken(token_Object); 
+0

謝謝!最後的解決方案是有效的,但使用以下語法:'gapi.auth。setToken({access_token:「YOUR_TOKEN_HERE」 });',因爲該方法接受一個tokenObject而我有一個字符串。現在我可以正確登錄並檢索數據 – Signo

相關問題