2017-09-07 180 views
7

我正在開發一個項目,我們希望通過GMB API收集關於GMB性能的數據。這需要捕獲許多reportInsights結果。我們不會創建或更新此帳戶的任何記錄。然而,我嘗試了Oauth2方法,這需要我提供許可,並且由於我們不訪問或更新任何用戶數據,我希望避免Oauth。通過服務帳戶訪問Google My Business API時出現403錯誤

從文檔和此用例中,我認爲服務帳戶是最好的方法,並且我已在Google API控制檯中創建該憑據。

我可以創建憑證,但是,當我運行的過程中,我得到以下錯誤:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://mybusiness.googleapis.com/$discovery/rest?version=v3 returned "The request is missing a valid API key."> 

這似乎很奇怪,因爲我有一組有效的服務帳戶憑據。我確實在Google API控制檯中包含了一個有效的API密鑰,但我得到了同樣的錯誤。

這裏是我的Python代碼:

import os 
import httplib2 
import json 
import argparse 
import apiclient.discovery 

from oauth2client.service_account import ServiceAccountCredentials 

from apiclient.discovery import build 

api_name = 'mybusiness' 
api_version = 'v3' 
api_key = '<my valid api key from google api console that has permission for this GMB project>' 

discovery_uri = 'https://mybusiness.googleapis.com/$discovery/rest?version={}'.format(api_version) 

flow_scope='https://www.googleapis.com/auth/plus.business.manage' 

credentials_file = '/Google_My_Business-service_account.json' # the service account credentials from the Google API console that have permission for this GMB project 

credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials_file, scopes=flow_scope) 

print("credentials: ", credentials) 

http = credentials.authorize(httplib2.Http()) 
print("http: ", http) 

# Build the service object 
service = build(api_name, api_version, http=http, developerKey=api_key, discoveryServiceUrl=discovery_uri) 

該錯誤是從最後一行拋出。任何幫助表示讚賞。

+0

您是否嘗試過重新生成密鑰?有時它們會過期,或者存在限制,您可以在[開發者控制檯](https://console.developers.google.com/apis/credentials)中登錄 – zipa

+0

各種憑據都是最近的,並且擁有最高級別的權限。你有關於我應該爲服務帳戶和API密鑰設置的指南嗎? – analyticsPierce

+0

谷歌爲每個項目提供了一個長期的電子郵件地址,並且我更換了該地址,並解決了Google Analytics API項目的問題。 – zipa

回答

1

試着改變你的代碼如下

from oauth2client.client import AccessTokenCredentials 
credentials = AccessTokenCredentials('<an access token>', 'my-user-agent/1.0') 
http = httplib2.Http() 
http = credentials.authorize(http) 

然後若該問題,請嘗試以下從JSON文件

from oauth2client.client import AccessTokenCredentials 
credentials = AccessTokenCredentials.from_json(credentials_file) 
http = httplib2.Http() 
http = credentials.authorize(http) 
+0

你的兩條線看起來完全一樣。我有一個API密鑰,它顯示在代碼中。我會再次檢查它,但它不應該有任何問題。 – analyticsPierce

+0

Opps你的權利我會改變它。你想改變開發人員密鑰到密鑰 – James

+0

當我嘗試了你的建議,我得到了:TypeError:build()得到了一個意想不到的關鍵字參數'key' – analyticsPierce

0

問題是與發現服務URL獲得證書。似乎不能通過發現api服務訪問私人apis(即使使用apikeys)。因此,解決方案是將發現服務url更改爲顯示mybusiness服務的有效json文件。

discovery_uri = "https://developers.google.com/my-business/samples/mybusiness_google_rest_v3p3.json" 
相關問題