在自定义电子表格功能

时间:2015-05-24 23:30:52

标签: google-apps-script google-sheets google-docs add-on url-shortener

我想在公共谷歌附加组件中使用API​​(url shortener)。 目前我的代码返回:

  

超出未经身份验证的使用的每日限制。继续使用需要注册。

  • 这可能吗?
  • 如果是,我需要一个身份验证令牌吗?
    • 如果是,我应该选择哪种密钥类型?
    • 如何实施此类用途的授权?
    • 我需要付钱吗?
  • 如果不是,其他附加组件如何使用外部API

非常感谢您的回答,

1 个答案:

答案 0 :(得分:1)

编辑:OP在评论中指出这是一个自定义函数。自定义功能以有限授权运行。可用内容的完整列表如下:
https://developers.google.com/apps-script/guides/sheets/functions#using_apps_script_services

下面使用REST API来获取缩短的URL。这将适用于自定义功能。您只需启用URL Shortener API并生成服务器API密钥。使用以下链接中的IP作为服务器api密钥:
https://developers.google.com/apps-script/guides/jdbc#setup_for_google_cloud_sql

/**
 * Returns a shortened URL of the input.
 *
 * @param {string} longUrl The long URL to shorten.
 * @return The shortened url.
 * @customfunction
 */
function getShortUrl(longUrl) {

   var payLoad = {"longUrl": longUrl};
   var apiKey = PropertiesService.getScriptProperties().getProperty("ServerApiKey");
   var url  = "https://www.googleapis.com/urlshortener/v1/url?key="+ apiKey;
  var options = { method:"POST",
                 contentType:"application/json",
                 payload:JSON.stringify(payLoad),
                 muteHttpExceptions:true};

  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() != 200){throw new Error("Unable to shorten url");}
  return JSON.parse(response).id;
}

原帖

以下是使用UrlShortener高级服务的快速入门。您需要打开服务并在开发人员控制台中激活Url Shortener api。这将为您的加载项每天提供1,000,000个请求的配额。

function myFunction() {
  var url = UrlShortener.newUrl();
  url.longUrl = "http://www.example.org";  
  var short = UrlShortener.Url.insert(url);
  Logger.log(short);

  //list all users shortened urls
  Logger.log(UrlShortener.Url.list());
}
相关问题