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]
Modification points:
getContent()
of Class HTTPResponse returns the byte array. I think that this is the reason of your issue.getContentText()
.[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's404 page not found
. I think that the reason of your issue is due tovar bitlink = 'bitlink'
in the endpoint of'https://api-ssl.bitly.com/v4/bitlinks/' + bitlink + '/clicks/summary'
.bit.ly/###
as the value ofbitlink
.bit.ly/###
is not used, an error likeYou are currently forbidden to access this resource.
occurs. Please be careful this.'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:
Note:
References: