调用Google Business Profile Performance API的GetDailyMetricsTimeSeries报404错误
解决Business Profile Performance API调用GetDailyMetricsTimeSeries返回404的问题
你怀疑的方向是对的——使用服务账号调用Business Profile Performance API访问特定商家位置时,必须指定subject参数(即该位置关联的用户邮箱),否则服务账号无法定位到对应的资源,导致404错误。
修改后的Go代码实现
需要通过jwt.Config配置服务账号的模拟用户信息,再生成对应的TokenSource传入服务初始化选项:
import ( "context" "log" "golang.org/x/oauth2/jwt" "google.golang.org/api/businessprofileperformance/v1" "google.golang.org/api/option" ) // 定义你的Scope const Scope = businessprofileperformance.BusinessProfilePerformanceReadonlyScope func main() { ctx := context.Background() // 配置JWT参数 jwtConfig := &jwt.Config{ Email: "你的服务账号邮箱(来自client_secret.json的client_email字段)", PrivateKey: []byte("你的服务账号私钥(来自client_secret.json的private_key字段,注意保留换行符)"), TokenURL: "https://accounts.google.com/o/oauth2/token", Scopes: []string{Scope}, Subject: "关联location_id的用户邮箱(商家位置的所有者/有权限的账号)", // 关键参数:指定要模拟的用户 } // 创建带subject的TokenSource tokenSource := jwtConfig.TokenSource(ctx) // 初始化Performance服务 performanceService, err := businessprofileperformance.NewService(ctx, option.WithTokenSource(tokenSource), ) if err != nil { log.Println(err.Error()) return } // 后续调用逻辑保持不变 cm := performanceService.Locations.GetDailyMetricsTimeSeries("locations/12345...") cm.DailyMetric("WEBSITE_CLICKS") cm.DailyRangeStartDateYear(2022) cm.DailyRangeStartDateMonth(6) cm.DailyRangeStartDateDay(1) cm.DailyRangeEndDateYear(2022) cm.DailyRangeEndDateMonth(12) cm.DailyRangeEndDateDay(30) response, err := cm.Do() if err != nil { log.Println(err.Error()) return } if c := response.HTTPStatusCode; c >= 200 && c <= 299 { // 修正原代码逻辑错误:将||改为&& j, _ := response.MarshalJSON() log.Println(string(j)) } }
额外注意事项
- 确保你的服务账号已在Google Cloud控制台开启域范围委派,并授权访问Business Profile Performance API的相关权限
Subject字段必须是该商家位置的所有者邮箱,或拥有该位置访问权限的账号邮箱- 原代码中判断HTTP状态码的逻辑存在错误,
c >= 200 || c <= 299会匹配所有状态码,应改为c >= 200 && c <= 299
内容的提问来源于stack exchange,提问作者Wellington Ataide
相关产品推荐
相关产品推荐

