Files

3.4 KiB

Author: Greg R. Jacobs Date: Feb 07, 2015 Description: Wanted to have a Google Sheet with 3 columns.

First was long URL

Second needed to dynamically shorten using Goo.gl and an API key obtained from: https://code.google.com/apis/console

Third to update with clicks on shortened url (this instance is referencing allTime clicks on the short URL). */ function shortenURL(longUrl,key) {

var serviceUrl="https://www.googleapis.com/urlshortener/v1/url?key="+key;

var options={ muteHttpExceptions:true, method:"post", contentType: "application/json", payload : Utilities.jsonStringify({'longUrl': longUrl }) };

var response=UrlFetchApp.fetch(serviceUrl, options);

if(response.getResponseCode() == 200) { var content = Utilities.jsonParse(response.getContentText()); if ( (content != null) && (content["id"] != null) ) return content["id"]; }

return longUrl; }

function GetShortUrlClicks(shortURL,key) { var url = "https://www.googleapis.com/urlshortener/v1/url?key="+key+"&shortUrl="+shortURL+"&projection=ANALYTICS_CLICKS"; if(shortURL != "") { var response = UrlFetchApp.fetch(url); var jsonResponse = response.toString(); var data = JSON.parse(jsonResponse); Logger.log(data.analytics.allTime.shortUrlClicks);

return data.analytics.allTime.shortUrlClicks; } else{} }