Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript code to interact with the Bitly API
function bitlyGroupId() {
var accessToken = ''; // paste in your access token from https://bitly.is/accesstoken
var headers = {'Authorization' : 'Bearer '+accessToken};
var params = {'headers' : headers};
var fetchUrl = 'https://api-ssl.bitly.com/v4/groups';
var response = UrlFetchApp.fetch(fetchUrl, params);
var group_guid = JSON.parse(response.getContentText()).groups[0].guid;
Logger.log(group_guid)
return group_guid
}
function bitlyShorten(longUrl) {
var accessToken = ''; // paste in your access token from https://bitly.is/accesstoken
var group_guid = bitlyGroupId(); // or you can run the function and paste in the group_guid here
var fetchUrl = 'https://api-ssl.bitly.com/v4/shorten';
var headers = {
'Authorization': 'Bearer '+ accessToken,
'Content-Type': 'application/json',
};
var payload = {
//'domain' : 'bit.ly',
//'title' : '',
//'tags' : ['', ''],
'group_guid' : group_guid,
'long_url' : longUrl
};
var params = {
'method' : 'post',
'headers' : headers,
'payload' : JSON.stringify(payload),
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(fetchUrl, params);
var shortUrl = JSON.parse(response.getContentText()).link;
Logger.log(shortUrl);
return shortUrl;
}
function bitlyExpand(bitlink_id) {
// bitlink_id should not be in the form bit.ly/xxxxxx
// or something like var bitlink_id = bitly_url.substring(bitly_url.indexOf('//')+2);
var accessToken = ''; // paste in your access token from https://bitly.is/accesstoken
var fetchUrl = 'https://api-ssl.bitly.com/v4/expand'
var headers = {
'Authorization': 'Bearer '+ accessToken,
'Content-Type': 'application/json',
};
var payload = {
'bitlink_id' : bitlink_id
};
var params = {
'method' : 'post',
'headers' : headers,
'payload' : JSON.stringify(payload),
};
var response = UrlFetchApp.fetch(fetchUrl, params);
var longUrl = JSON.parse(response.getContentText()).long_url;
return longUrl;
}
function bitlyStats(bitlink_id) {
// bitlink_id should not be in the form bit.ly/xxxxxx
// or something lik var bitlink_id = bitly_url.substring(8);
var accessToken = '';
var fetchUrl = 'https://api-ssl.bitly.com/v4/bitlinks/' + bitlink_id + '/clicks/summary';
var headers = {
'Authorization': 'Bearer '+ accessToken,
'Content-Type': 'application/json',
};
var params = {
'method' : 'get',
'headers' : headers,
};
var response = UrlFetchApp.fetch(fetchUrl, params);
var clickCount = JSON.parse(response.getContentText()).total_clicks;
return clickCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.