使用 OAuth 和 Google Analytics Admin API 管理 Analytics 帐户

问题描述 投票:0回答:1

我正在尝试使用 Google Analytics Admin API 访问属性和管理设置(当客户请求我们管理其广告时,尝试链接 Google Analytics 和 Google Ads)。理想情况下,这可以通过 OAuth 完成,并且在注册时从浏览器授予访问权限。但是,如果有一种方法可以发送管理邀请(例如使用 Google Ads 帐户),也可以。

我尝试设置服务帐户,但不知道如何授予其访问帐户的权限。然后我尝试使用 OAuth 授予访问权限,我能够从中获取令牌,但无法在 AnalyticsAdminServiceClient 库中使用该令牌(或者至少不知道如何使用)。

这是我尝试使用 OAuth 的方法:

import yaml
from google.analytics.admin import AnalyticsAdminServiceClient

yaml_file = open('./oauth_analytics.yaml')
parsed_yaml_file = yaml.load(yaml_file, Loader=yaml.FullLoader)

test_auth_code = parsed_yaml_file['test_auth_code']
client_id = parsed_yaml_file['client_id']
client_secret = parsed_yaml_file['client_secret']

#get a refresh token
from google.oauth2.credentials import Credentials

credentials = Credentials(
    None,
    refresh_token=test_auth_code,
    token_uri="https://oauth2.googleapis.com/token",
    client_id=client_id,
    client_secret=client_secret
)

# Use the refresh token to obtain an access token.
client = AnalyticsAdminServiceClient(credentials=credentials)

print(client.list_accounts())

\当我运行该代码时,出现以下异常:

google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.

我发现这个问题的答案显示了我正在使用的相同方法(但我假设它对他们有用,可能有一些明显的我遗漏的东西):How do I call Google Analytics Admin API (for GA4) using Node.js 中的 OAuth2 客户端?

python google-analytics oauth google-analytics-api
1个回答
0
投票

如果您想使用 Oauth2 而不是服务帐户,您的代码应该看起来更像这样

from google.analytics.admin import AnalyticsAdminServiceClient

# pip install google-analytics-admin

CREDENTIALS_FILE_PATH = 'C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json'
GA4_PROPERTY_ID = '250796939'

from google_auth_oauthlib import flow

def list_accounts(credentials=None):
    """
    Lists the available Google Analytics accounts.

    Args:

    """
    # Using a default constructor instructs the client to use the credentials
    # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = AnalyticsAdminServiceClient(credentials=credentials)

    request = AnalyticsAdminServiceClient.ListAccountSummariesRequest()
    request.page_size = 1

    # Make the request
    results = client.list_account_summaries(page_size = 1)

    # Displays the configuration information for all Google Analytics accounts
    # available to the authenticated user.
    print("Result:")
    for account in results:
        print(account)

def get_credentials():
    """Creates an OAuth2 credentials instance."""

    appflow = flow.InstalledAppFlow.from_client_secrets_file(
        CREDENTIALS_FILE_PATH,
        scopes=["https://www.googleapis.com/auth/analytics.readonly"],
    )
    # TODO(developer): Update the line below to set the `launch_browser` variable.
    # The `launch_browser` boolean variable indicates if a local server is used
    # as the callback URL in the auth flow. A value of `True` is recommended,
    # but a local server does not work if accessing the application remotely,
    # such as over SSH or from a remote Jupyter notebook.
    launch_browser = True
    if launch_browser:
        appflow.run_local_server()
    else:
        # note yes this is deprecated.  It will work if you change the redirect uri in the url given you from urn:ietf:wg:oauth:2.0:oob
        # to http://127.0.0.1  The client library team needs to fix this.
        appflow.run_console()
    return appflow.credentials



def main():
    credentials = get_credentials()
    list_accounts(credentials)

if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.