通过服务帐户访问Google My Business API时出错403

ana*_*rce 9 python google-oauth google-my-business-api

我正在开展一个项目,我们希望通过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.">
Run Code Online (Sandbox Code Playgroud)

这看起来很奇怪,因为我有一组有效的服务帐户凭据.我确实包含了来自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)
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*mes 2

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

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

然后,如果可行,请尝试以下操作从 JSON 文件获取凭据

from oauth2client.client import AccessTokenCredentials
credentials = AccessTokenCredentials.from_json(credentials_file)
http = httplib2.Http()
http = credentials.authorize(http)
Run Code Online (Sandbox Code Playgroud)