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

使用Node.js Firebase云函数调用AdSense API v2遇403权限错误

Firebase云函数调用AdSense API v2返回403权限错误

我需要在Node.js环境的Firebase云函数中每日生成前一日的AdSense收益报表,基于AdSense API v2编写了以下代码:

const { google } = require("googleapis");
const adsense = google.adsense("v2");

const auth = new google.auth.GoogleAuth({
  scopes: ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"],
});

const authClient = await auth.getClient();
google.options({ auth: authClient });

const res = await adsense.accounts.reports.generate({
  account: "accounts/pub-1522817738845966",
  dateRange: "YESTERDAY",
  metrics: ["TOTAL_EARNINGS"],
  dimensions: ["DATE"],
});

但调用时始终返回错误:

code: 403, message: 'The caller does not have permission'

我已经确认:

  • Google Cloud控制台中AdSense API已启用
  • AdSense账户与Firebase管理员账户为同一账号
  • 在API Explorer中使用相同参数可返回200响应(未获取到期望数据),响应内容如下:
200
{
  "headers": [
    {
      "name": "DATE",
      "type": "DIMENSION"
    },
    {
      "name": "TOTAL_EARNINGS",
      "type": "METRIC_CURRENCY",
      "currencyCode": "EUR"
    }
  ],
  "warnings": [
    "部分广告客户端无法提供请求的部分指标数据。"
  ],
  "startDate": {
    "year": 2023,
    "month": 4,
    "day": 6
  },
  "endDate": {
    "year": 2023,
    "month": 4,
    "day": 6
  }
}

排查与解决方案

1. 给云函数默认服务账号添加AdSense权限

Firebase云函数默认使用[你的项目ID]@appspot.gserviceaccount.com作为服务账号,需要给这个账号授予AdSense访问权限:

  • 登录AdSense后台,进入设置 > 访问和授权 > 用户管理
  • 输入上述服务账号邮箱,添加为用户并赋予只读权限(生成报表足够)
  • 等待5-10分钟让权限生效

2. 简化API认证范围

代码中同时请求了adsense和adsense.readonly两个范围,实际上生成只读报表只需要adsense.readonly,修改认证配置:

const auth = new google.auth.GoogleAuth({
  scopes: ["https://www.googleapis.com/auth/adsense.readonly"],
});

3. 排除本地测试环境的凭据干扰

如果在本地测试云函数,需要确保没有设置GOOGLE_APPLICATION_CREDENTIALS环境变量指向其他凭据文件,避免覆盖云函数默认的服务账号。

4. 关于API Explorer的警告说明

API Explorer返回的警告提示部分广告客户端没有TOTAL_EARNINGS数据,可能是这些客户端尚未产生收益,或者需要调整报表的维度/指标组合(比如添加AD_CLIENT_ID维度查看具体客户端数据)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:27:06