簡體   English   中英

通過服務帳戶訪問Google My Business API時出錯403

[英]Getting 403 error when accessing Google My Business API through Service Account

我正在開展一個項目,我們希望通過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)

從最后一行拋出錯誤。 任何幫助表示贊賞。

嘗試將代碼更改為以下內容

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)

問題在於發現服務網址。 似乎無法通過發現api服務訪問私有api(即使您使用apikeys)。 因此,解決方案是將發現服務URL更改為顯示mybusiness服務的有效json文件。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM