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

如何通过Google Ads API与Python获取用户可访问的账户名称和ID

解决Google Ads API获取账户名称时的权限错误问题

问题分析

你遇到的USER_PERMISSION_DENIED错误,核心原因是代码中查询账户信息的逻辑有误:

  • list_accessible_customers()返回的资源名称包含所有你有权访问的账户(包括经理账户和普通广告账户)
  • 当你用经理账户ID执行SELECT ... FROM customer_client时,实际是查询该经理账户下的子账户,但你的授权令牌可能没有访问这些子账户的权限,从而触发权限错误
  • 你需要的是当前账户本身的名称,而非其子账户信息,应该查询customer资源而非customer_client

修正后的代码

from google.ads.googleads.errors import GoogleAdsException

def one(request):
    client = credenciales(request)
    ga_service = client.get_service("GoogleAdsService")
    customer_service = client.get_service("CustomerService")
    
    # 获取所有可访问的账户资源名称
    accessible_customers = customer_service.list_accessible_customers()
    customer_resource_names = accessible_customers.resource_names

    list_clients = []

    for resource_name in customer_resource_names:
        # 提取账户ID(也可以直接用resource_name作为customer_id参数)
        custom_id = resource_name.split('/')[-1]
        
        # 修正查询语句:查询当前账户本身的信息,而非子账户
        query = '''
            SELECT
              customer.descriptive_name,
              customer.id,
              customer.status
            FROM customer
        '''

        try:
            # 执行查询,这里也可以直接传入resource_name作为customer_id
            stream = ga_service.search_stream(customer_id=custom_id, query=query)
            
            for batch in stream:
                for row in batch.results:
                    data_clients = {
                        "descriptive_name": row.customer.descriptive_name,
                        "id": row.customer.id,
                        "status": row.customer.status.name  # 将枚举转为可读名称
                    }
                    list_clients.append(data_clients)
        except GoogleAdsException as ex:
            # 捕获并打印错误,方便排查特定账户的权限问题
            print(f"处理账户 {custom_id} 时出错:")
            for error in ex.failure.errors:
                print(f"错误消息: {error.message}")
                print(f"错误代码: {error.error_code}")

    context = {
        'list_clients': list_clients,
    }
    return render(request, 'one.html', context)

关键优化点

  1. 更换查询资源:将customer_client改为customer,直接获取当前账户的名称和状态,避免查询子账户触发权限问题
  2. 错误捕获:添加GoogleAdsException捕获逻辑,方便定位具体哪个账户出现权限问题
  3. 状态可读性:将status枚举值转为名称(如ENABLED),更易理解
  4. 参数兼容性:search_stream的customer_id参数支持传入完整的资源名称(如customers/123-456-7890),也可以用提取的ID,两种方式都有效

额外排查建议

  • 确认你的授权令牌(通过credenciales(request)获取的client)拥有Google Ads API的访问权限,且关联的Google账号确实能访问这些账户
  • 如果仍有部分账户报错,检查这些账户是否被移除了你的访问权限,或者处于暂停状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:13