Bitly API V4 in Google Apps Script: getting errors when trying to call clicks summary

1.3k Views Asked by At

I am fairly new to Apps Script and this is my first custom function using an API.

I have been following this code to integrate Bitly into Google Sheets. https://gist.github.com/misterhay/38a500545ce7abc75b875f33f01c9f51

The code they provide for ShortenBitly works perfectly, however I cannot get ExpandBitly or Stats functions to work.

Below is my code for BitlyStats, and the error code I am getting.

/**
 * Retrieves the final URL from a bitlink  
 *
 * @param {string} the bitly link
 * @return {string} the total clicks
 * @customfunction
 */

function bitlyStats(bitlink) {
  var bitlink = 'bitlink'
  Logger.log(bitlink)
  var accessToken = 'MYTOKEN';
  var fetchUrl = 'https://api-ssl.bitly.com/v4/bitlinks/' + bitlink + '/clicks/summary';
  Logger.log(fetchUrl)
  var headers = {
    'Authorization': 'Bearer '+ accessToken,
    'Content-Type': 'application/json',
  };
  var params = {
    'method' : 'get',
    'headers' : headers,
    'muteHttpExceptions' : true
  };
  var response = UrlFetchApp.fetch(fetchUrl, params);
  Logger.log(response.getContent());
  var clickCount = JSON.parse(response.getContent()).total_clicks;
  return clickCount;
}

This is the error message;

SyntaxError: Unexpected token , in JSON at position 2
bitlyStats @ Code.gs:26

The Log for line 25 reads:

[52.0, 48.0, 52.0, 32.0, 112.0, 97.0, 103.0, 101.0, 32.0, 110.0, 111.0, 116.0, 32.0, 102.0, 111.0, 117.0, 110.0, 100.0, 10.0]

2

There are 2 best solutions below

1
On BEST ANSWER

Modification points:

  • getContent() of Class HTTPResponse returns the byte array. I think that this is the reason of your issue.
  • When you want to retrieve the text value, please use getContentText().
  • And, about your current value of [52.0, 48.0, 52.0, 32.0, 112.0, 97.0, 103.0, 101.0, 32.0, 110.0, 111.0, 116.0, 32.0, 102.0, 111.0, 117.0, 110.0, 100.0, 10.0], when this byte array is decoded, it's 404 page not found. I think that the reason of your issue is due to var bitlink = 'bitlink' in the endpoint of 'https://api-ssl.bitly.com/v4/bitlinks/' + bitlink + '/clicks/summary'.
    • In this case, as a test case, please use your sample shortened URL like bit.ly/### as the value of bitlink.
    • If the value of bit.ly/### is not used, an error like You are currently forbidden to access this resource. occurs. Please be careful this.
  • At the GET method, 'Content-Type': 'application/json' is not required to be used in the request header.

When these points are reflected to your script, it becomes as follows.

Modified script:

function bitlyStats(bitlink) {
  var bitlink = 'bit.ly/###'; //  Please set your sample shortened URL here.

  Logger.log(bitlink)
  var accessToken = 'MYTOKEN';
  var fetchUrl = 'https://api-ssl.bitly.com/v4/bitlinks/' + bitlink + '/clicks/summary';
  Logger.log(fetchUrl)
  var headers = {
    'Authorization': 'Bearer '+ accessToken,
  };
  var params = {
    'method' : 'get',
    'headers' : headers,
    'muteHttpExceptions' : true
  };
  var response = UrlFetchApp.fetch(fetchUrl, params);
  Logger.log(response.getContentText());
  var clickCount = JSON.parse(response.getContentText()).total_clicks;
  return clickCount;
}

Note:

  • In this modified script, it supposes that your access token is valid value for using the API. Please be careful this.

References:

0
On

This is a working code for Bitly using v4 API to shorten a long URL. You can also create a copy of this sheet and bulk create bitly links using the function bitlyShortenUrl in the 3rd column- https://docs.google.com/spreadsheets/d/1TS-aQcDu3rRv-LexEoIqDiX0ydv69ijkXQP-nuQdBz4/edit#gid=0

function bitlyShortenUrl(longLink, accessToken) {
  var form = { 
    "domain": "bit.ly",
    "long_url": longLink
  };
  var url = "https://api-ssl.bitly.com/v4/shorten";

  var options = {
      "headers": { Authorization: `Bearer ${accessToken}` },
      "method": "POST",
      "contentType" : "application/json",
      "payload": JSON.stringify(form)
  };
  var response = UrlFetchApp.fetch(url, options);
  var responseParsed = JSON.parse(response.getContentText());
  return(responseParsed["link"]);
}

PS: Bitly access token details given here https://support.bitly.com/hc/en-us/articles/230647907-How-do-I-generate-an-OAuth-access-token-for-the-Bitly-API-