URL Shortener Service

URL Shortener Service

22.Sep.2021

The URL Shortener service allows you to use the   Google URL Shortener API in Apps Script. This API gives users the ability to manage and report on their goo.gl short links.

For detailed information, please refer to the official documentation .

I provide step-by-step instructions for setting up your own copy of this script with working examples below:

Add a new trigger at OnCreate  and paste in this code (modify accordingly with your APIs). //  ============================================================================================================================= //  v2 - JK Nwokedi © 2015 //  https://drive.google.com/open?id=0Bz5b1qFfNeJHWVdXQmloMVlRcW8 //  ============================================================================================================================= var service = new URLShortenerService(); /* Check if script has the correct OAuth2 scope */ var request = Auth.currentSession().getEffectiveScopes(); try { Logger.log("check for goo.gl: " + request); } catch (e) {} /* * This will take you to a page where you can create an app and get your API key from there * https://console.developers.google.com/flows/enableapi?apiid=urlshortener&keyType=CLIENT_SIDE_AND_PLATFORM&rpcTimeoutSecs=60&rpcSigningEnabled=true&rpcTransportSecurityOverride=EXPORT_RSA */ /* * The following is a sample OAuth 2.0 Authorization Request, using the URL Shortener Service from above: * This request requires user authorization. In practice you will want to prompt users with a consent screen which * describes what you intend to do with their data and provides them the option to consent or deny your application's access. See https://developers.google.com/identity/protocols/OAuth2WebServer#displaying-the-user-consent-screen for more information on how to display a consentscreen within your client app. * Note that there are additional methods of acquiring an access token, but those require additional setup (see https://developers.google.com/oauthplayground/#p=authentication). */ var oauth2Client = new OAuth2WebServer(); oauth2Client.setAccessTokenUrl("https://accounts.google.com/o/oauth2/token"); service.setOAuth2Client(oauth2Client); /* * Step 2: Redirect to Google to authorize the application * Once you create the above client ID, you will be given a client_id value which your website should use when communicating with Google's servers * You can find this value in your console project's settings under "client ID" */ function openGoogle() { return UserPreferences.get('sp', 'webclientid'); } function getAccessToken() { return service.getOAuth2AuthenticationUrl(new URLRequest(openGoogle())); } Logger.log("OPEN GOOGLE");      openGoogle();    //  =============================================================================================================================    var request = Auth.currentSession().getEffectiveScopes(); /* * Step 3: Exchange authorization code for access/refresh token * Using the client ID and redirect URI, generate a code value which you will exchange for an access token */ function getCode(redirectUri) { return service.authorizationHandler().createAuthorizationUrl({ "response_type": "code", "client_id": redirectUri, "redirect_uri": redirectUri, "scope": request }); } /* * Step 4: Exchange authorization code for token. */ function getAccessToken(code) { var params = {'code': code}; return service.getOauth2AuthenticationUrl(params); } Logger.log("GIVE CODE");      getCode('<YOUR REDIRECT URI HERE>'); Logger.log("GOT ACCESS TOKEN");    //  =============================================================================================================================    /* * Step 5: Use access token to request a short URL */ var url = https://www.googleapis.com/urlshortener/v1/url?access_token=ACCESS-TOKEN" + '&longUrl=' + longUrl; Logger.log("URL: " + url);    //  ============================================================================================================================= try {      new URLRequest(url).get();           onSuccess(); } catch (e) {           onError(); } /* * Step 6a: Get a list of all URLs for the authenticated user * To get a list of all your short links, make an HTTP GET request to: https://www.googleapis.com/urlshortener/v1/urls */ function getAll() { var params = {'access_token': token}; return service.getUrlList('', params); } Logger.log("GET ALL");       //  =============================================================================================================================    function onSuccess() {      Logger.log("SUCCESS"); }    //  =============================================================================================================================    function onError(error) {           Logger.log("ERROR " + error); } try {      new URLRequest(url).get();           onSuccess(); } catch (e) {           onError(); } try{    /* * Step 6b: Get a specific short link for the authenticated user */ var params = {'access_token': token}; return service.getUrl('https://www.googleapis.com/urlshortener/v1/url?key=' + longUrl, params); } catch (e) {           Logger.log("GET FAIL " + e); } try{    /* * Step 7: Delete a short URL */ var params = {'access_token': token, 'longUrl': longUrl}; return service.deleteUrl(params); } catch (e) {           Logger.log("DELETE FAIL " + e); }    //  =============================================================================================================================    function newToken() {        if (!token) throw('You must supply a valid access token.');         return token; } try{    /* * 5a: Create a short link */ var newURLString = "{&longUrl='"+longUrl+"&}"; var newURL = service.createUrl({'shortUrl': newURLString});        //  ============================================================================================================================= } catch (e) {           Logger.log("CREATE FAIL " + e); } try{    /* * 5b: Create a short link */ var params = {'shortUrl': 'https://goo.gl/1eXOjr', 'longUrl': longLink}; return service.createShortUrl(params); } catch (e) {           Logger.log("CREATE FAIL " + e); } try{    /* * 5c: Create a short link */ var params = {'urlHeader': 'My URL', 'longUrl': longLink}; return service.createShortUrl('REPLACE_WWW', params); } catch (e) {           Logger.log("CREATE FAIL " + e); } try{    /* * 5d: Create a short link */ var params = {'urlHeader': 'My URL', 'description': 'bla bla bla', 'longUrl': longLink}; return service.createShortUrl('ADD_TAGS', params); } catch (e) {           Logger.log("CREATE FAIL " + e); }

try{    /* * 5e: Create a short link with custom id parameter */ var params = {'urlHeader': 'My URL', 'longUrl': longLink, 'customId': 23}; return service.createShortUrl('ADD_TAGS', params); } catch (e) {           Logger.log("CREATE FAIL " + e); } try{    /* * 5f: Update a short link */ var oldShortURLString = "{&shortUrl='"+oldShort+"&}" var newShortURLString = "{&shortUrl='"+newShort+"&}"      var params = {'accessToken': token, 'longUrl': longLink, 'shortUrlUpdateMasked': oldShortURLString}; return service.updateShortUrls(params); } catch (e) {           Logger.log("UPDATE FAIL " + e); }    //  =============================================================================================================================    function createUrl(params) {        new URLRequest(url).setUrl('https://www.googleapis.com/urlshortener/v1/url')           .get();           onSuccess(); }    //  =============================================================================================================================    function createShortUrl(type, params) {         var newShortURLString = "{&shortUrl='"+params.longUrl+"&}"         var newShortURL = service.createUrl({'shortUrl':newShortURLString})         var returnObj = {             'shortUrl': newShortURLString,             'id': params.customId         };        onSuccess(returnObj); }    //  =============================================================================================================================    function deleteUrl(params) {         var newURLString = "{&longUrl='"+params.longUrl+"'}"         var newURL = service.createUrl({'shortUrl':newURLString})         return service.deleteUrls([{'url': newURL}, params]); }    //  =============================================================================================================================    function updateShortUrls(params) {         var resultStrings = []; for (var i in params) {                 resultStrings['result'] += createUrl({                     'longUrl': params.longUrl,                     'shortUrl': i         }); }         return resultStrings; }

 

In the above URL Shortener service example snippets: Lines 1-44 Calculates a new access token if one is not supplied in the call to create a short link. Lines 45-51 The various functions for creating a short link. These functions are described in detail below. Line 55 A function used to delete an existing long URL from your account's short links by supplying the id of the short link you want deleted as well as your long token . Lines 56-62 A function used to update multiple existing short links' attributes by supplying an array of objects containing information about each individual short link you want to update, as well as your long token . Lines 64-69 A function used to perform the actual short link creation call by supplying the parameters passed in through the params object. The type parameter tells us whether we are adding or updating an existing URL. With reqwest , this is handled by making a specific request with all of the correct fields filled in versus querying for an endpoint's information and then passing that into another request -- all in one call to the API. Hence, reqwest doesn't support PATCH requests (although you could implement it using multiple calls).

We are social