使用Google Apps脚本创建Google Analytics 4属性 [英] Create a Google Analytics 4 propery with Google Apps Script

查看:18
本文介绍了使用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起作用,因为我能够列出属性。

提前谢谢。

推荐答案

UrlFetchApp.fetch()无法识别options对象中的resource字段。您需要将其更改为payload。此外,在将资源传递给Options对象下的payload属性之前,您还需要JSON.stringify()资源,并且还必须将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)
};
 

这篇关于使用Google Apps脚本创建Google Analytics 4属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆