10

我正在开展一个项目,我们希望通过 GMB API 收集有关 GMB 性能的数据。这需要捕获许多 reportInsights 结果。我们不会为此帐户创建或更新任何记录。但是,我尝试了 Oauth2 方法,这需要我提供许可,并且由于我们没有访问或更新任何用户数据,因此我想避免使用 Oauth。

从文档和这个用例来看,我认为服务帐户是最好的方法,我已经在 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)

从最后一行抛出错误。任何帮助表示赞赏。

4

2 回答 2

2

尝试将您的代码更改为以下内容

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)
于 2017-09-12T17:32:57.510 回答
1

问题在于发现服务 url。似乎无法通过发现 api 服务访问私有 api(即使您使用 apikeys)。因此,解决方案是将发现服务 url 更改为显示 mybusiness 服务的有效 json 文件。

discovery_uri = "https://developers.google.com/my-business/samples/mybusiness_google_rest_v3p3.json"
于 2017-10-10T10:10:59.327 回答