【问题标题】:Google Analytics API - Error: redirect_uri_mismatchGoogle Analytics API - 错误:redirect_uri_mismatch
【发布时间】:2014-12-04 06:35:05
【问题描述】:

我正在尝试按照here 提供的 Google Analytics API 教程进行操作。我一步一步地跟着它。这是我的文件

client_secrets.json

{
  "installed": {
    "client_id": "xxxxxxxxxxxxxxx.apps.googleusercontent.com",
    "client_secret": "xxxxxxxxxxxxxxxxx",
    "redirect_uris": ["http://127.0.0.1:8000/oauth2callback/"],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
  }
}

hello_analytics_api_v3_auth.py

#!/usr/bin/python

import httplib2

from apiclient.discovery import build

from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run

CLIENT_SECRETS = 'client_secrets.json'
MISSING_CLIENT_SECRETS_MESSAGE = '%s is missing' % CLIENT_SECRETS

FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
  scope='https://www.googleapis.com/auth/analytics.readonly',
  message=MISSING_CLIENT_SECRETS_MESSAGE)

TOKEN_FILE_NAME = 'analytics.dat'

def prepare_credentials():
  storage = Storage(TOKEN_FILE_NAME)
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = run(FLOW, storage)
  return credentials

def initialize_service():
  http = httplib2.Http()

  #Get stored credentials or run the Auth Flow if none are found
  credentials = prepare_credentials()
  http = credentials.authorize(http)

  #Construct and return the authorized Analytics Service Object
  return build('analytics', 'v3', http=http)

hello_analytics_api_v3.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

# import the Auth Helper class
import hello_analytics_api_v3_auth

from apiclient.errors import HttpError
from oauth2client.client import AccessTokenRefreshError


def main(argv):
  # Initialize the Analytics Service Object
  service = hello_analytics_api_v3_auth.initialize_service()

  try:
    # Query APIs, print results
    profile_id = get_first_profile_id(service)

    if profile_id:
      results = get_results(service, profile_id)
      print_results(results)

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)

  except HttpError, error:
    # Handle API errors.
    print ('Arg, there was an API error : %s : %s' %
           (error.resp.status, error._get_reason()))

  except AccessTokenRefreshError:
    # Handle Auth errors.
    print ('The credentials have been revoked or expired, please re-run '
           'the application to re-authorize')


def get_first_profile_id(service):
  # Get a list of all Google Analytics accounts for this user
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account
    firstAccountId = accounts.get('items')[0].get('id')

    # Get a list of all the Web Properties for the first account
    webproperties = service.management().webproperties().list(accountId=firstAccountId).execute()

    if webproperties.get('items'):
      # Get the first Web Property ID
      firstWebpropertyId = webproperties.get('items')[0].get('id')

      # Get a list of all Views (Profiles) for the first Web Property of the first Account
      profiles = service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

      if profiles.get('items'):
        # return the first View (Profile) ID
        return profiles.get('items')[0].get('id')

  return None


def get_results(service, profile_id):
  # Use the Analytics Service Object to query the Core Reporting API
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='2014-01-10',
      end_date='2014-09-08',
      metrics='ga:sessions').execute()


def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'First View (Profile): %s' % results.get('profileInfo').get('profileName')
    print 'Total Sessions: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'


if __name__ == '__main__':
  main(sys.argv)

为了测试输出,我使用终端运行命令

python hello_analytics_api_v3.py 

运行此程序会打开浏览器,要求我验证我的 Google 帐户,然后我收到 400 错误

错误:redirect_uri_mismatch

请求中的重定向 URI:http://localhost:8080/ 不匹配 已注册的重定向 URI。

Google 是如何将http://localhost:8000/ 作为重定向 URI 的?这是我在 Google Developer Console 应用中指定的内容

重定向 URIS http://127.0.0.1:8000/oauth2callback/

JAVASCRIPT 起源http://127.0.0.1:8000/

【问题讨论】:

  • 你输入了 8000 你确定不是 8080 吗?
  • @DaImTo 不,我在端口 8000 上运行我的本地服务器。
  • 试试这个教程,它可能是最新的。 marinamele.com/use-google-analytics-api-with-python 同时,我认为您应该仔细检查您的 client_secret.json,想知道它是从教程中读取的,而不是您创建的。
  • @DaImTo 我检查了。 client_secret.json 正在被读取。它转到的回调 URL 具有我在 client_secret.json 中指定的 client_id
  • 它说您正在调用localhost:8080,这与 8000 不同,如果它从该文件中获取它,那么它很奇怪。

标签: python google-analytics google-oauth google-analytics-api


【解决方案1】:

在我的控制台中,我设置了一个 Web 应用程序。相反,我必须设置一个已安装的应用程序,因为我通过终端访问它。

这里给出了更全面的教程-http://www.marinamele.com/use-google-analytics-api-with-python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2020-11-08
    • 2014-08-29
    • 1970-01-01
    • 2021-01-05
    • 2017-04-10
    • 2023-03-30
    相关资源
    最近更新 更多