首页 > 解决方案 > 使用 Google Apps 脚本中的高级服务指定 API 版本?

问题描述

我需要在我的脚本中使用 2.1 版的 Content API 但是,我不确定如何传递版本号。

这是代码的相关部分:

var products = ShoppingContent.Products.list(merchantId, {
    pageToken: pageToken,
    maxResults: maxResults,
    includeInvalidInsertedItems: true
});

我试过通过version: 2.1但没有雪茄。

谢谢

标签: google-apps-scriptgoogle-content-api

解决方案


特定客户端库的版本仅在您启用特定高级服务时指定。并非所有客户端库都支持所有版本,例如Drive高级服务不支持 v3 端点。

对于ShoppingContent客户端库,Apps 脚本仅提供与版本 2 的绑定:

在此处输入图像描述

因此,要使用 v2.1,您需要将 Shopping Content API 视为外部 API,并使用UrlFetchApp. 您需要根据需要对请求进行授权,使用该方法构建您自己的OAuth2 授权标头ScriptApp.getOAuthToken(),例如:

function addAuthHeader(headers) {
  var token = ScriptApp.getOAuthToken();
  headers['Authorization'] = 'Bearer ' + token;
}
function getBaseURI(version) {
  return 'https://www.googleapis.com/content/' + version + '/';
}

function listProducts(merchantId, pageToken) {
  const base = getBaseURI('v2.1');
  const path = merchantId + '/products';
  if (pageToken)
    path + '?pageToken=' + pageToken;

  const headers = {
    /* whatever you need here */
  };
  addAuthHeader(headers);

  const fetchOptions = {
    method: 'GET',
    /* whatever else you need here
      https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchurl-params
     */
    headers: headers
  };
  var pageResponse = UrlFetchApp.fetch(base + path, fetchOptions);
  var onePageOfResults = JSON.parse(pageResponse.getContentText());
  /* whatever else */
}

推荐阅读