You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google API Python Client完成OAuth后获取用户邮箱的凭证疑问

问题分析与解决方案

原代码依赖的是已废弃的oauth2client库中的OAuth2Credentials类,和你现在使用的google.oauth2.credentials.Credentials(属于新版google-auth生态)不兼容,直接传入会报错;而传入JSON凭证文件更是错误的——函数需要的是已完成用户授权的凭证对象,不是客户端配置文件。

下面提供两种可行方案:

方案一:适配新版Credentials修改原函数

直接调整原代码的服务构建逻辑,适配新版google.oauth2.credentials.Credentials:

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from googleapiclient.errors import HttpError
import logging

def get_user_info(credentials):
    """Send a request to the UserInfo API to retrieve the user's information.

    Args:
        credentials: google.oauth2.credentials.Credentials instance to authorize the request.
    Returns:
        User information as a dict (包含email、id等字段).
    """
    user_info_service = build(
        serviceName='oauth2', version='v2',
        credentials=credentials  # 直接传入新版Credentials,无需手动授权http客户端
    )
    user_info = None
    try:
        user_info = user_info_service.userinfo().get().execute()
    except HttpError as e:
        logging.error('An error occurred: %s', e)
    if user_info and user_info.get('id'):
        return user_info
    else:
        raise Exception("No user ID found in response")  # 替换你自定义的NoUserIdException

方案二:直接用Requests调用UserInfo API

如果不想依赖google-api-python-client,可以直接发送HTTP请求调用接口,代码更轻量化:

import requests
from google.oauth2.credentials import Credentials
import logging

def get_user_info(credentials):
    """Retrieve user info via direct API call."""
    url = "https://www.googleapis.com/oauth2/v2/userinfo"
    headers = {"Authorization": f"Bearer {credentials.token}"}
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        user_info = response.json()
    except requests.exceptions.RequestException as e:
        logging.error('An error occurred: %s', e)
        user_info = None
    if user_info and user_info.get('id'):
        return user_info
    else:
        raise Exception("No user ID found in response")

关键注意事项

  1. Scopes权限:确保你在OAuth授权流程中申请了https://www.googleapis.com/auth/userinfo.email或https://www.googleapis.com/auth/userinfo.profile权限,否则API不会返回邮箱等用户信息。
  2. 凭证对象来源:google.oauth2.credentials.Credentials对象应该是用户完成OAuth授权后生成的(比如通过google-auth-oauthlib库的流程获取),不是客户端配置的JSON文件。

内容的提问来源于stack exchange,提问作者Mykola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:51:41