使用 Google Apps 脚本创建 Google Analytics 4 属性

基于 this documentation,我正在尝试在 Google Apps 脚本中创建 ga4 属性:

  var service = getService();
  if (service.hasaccess()) {

    var apiURL = "https://analyticsadmin.googleapis.com/v1alpha/properties";

    var resource = {
      "displayName": "Automating ga4 creation","timeZone": "America/Los_Angeles","currencyCode": "USD","parent": "accounts/123"
    };

    Logger.log(resource);

    var headers = {
      "Authorization": "Bearer " + getService().getaccessToken()
    };
    
    var options = {
      "headers": headers,"method" : "POST","muteHttpExceptions": true,"resource": resource
    };
    
    var response = UrlFetchApp.fetch(apiURL,options);

    Logger.log(response);

  } else {
    var authorizationUrl = service.getauthorizationUrl();
    Logger.log('Open the following URL and re-run the script: %s',authorizationUrl);
    Browser.msgBox('Open the following URL and re-run the script: ' + authorizationUrl)
  }    
}

但我收到此错误:

  "error": {
    "code": 400,"message": "The value for the 'parent' field was invalid but must be in format 'accounts/123'.","status": "INVALID_ARGUMENT"
  }
}

根据the documentation

,我的回复格式没问题

这是我的Logger.log(resource)

{parent=accounts/123,displayName=Automating ga4 creation,currencyCode=USD,timeZone=America/Los_Angeles}

注意:

1- 出于隐私考虑,我已将我的 Google Analytics(分析)帐户 ID 替换为 123

2- OAuth 有效,因为我已经能够列出属性。

提前致谢。

jdwcjs 回答:使用 Google Apps 脚本创建 Google Analytics 4 属性

UrlFetchApp.fetch() 无法识别 resource 对象中的 options 字段。您需要将其更改为 payload。此外,您还需要在将资源传递给 options 对象下的 JSON.stringify() 属性之前payload,并且还必须将 contentType 属性设置为 application/json。>

所以您的 options 对象应该如下所示:

var resource = {
    "displayName": "Automating GA4 creation","timeZone": "America/Los_Angeles","currencyCode": "USD","parent": "accounts/123"
};

var headers = {
    "Authorization": "Bearer " + getService().getAccessToken()
};
    
var options = {
    "headers": headers,"contentType":"application/json","method" : "POST","muteHttpExceptions": true,"payload": JSON.stringify(resource)
};
 
本文链接:https://www.f2er.com/16537.html

大家都在问