– andare al link https://console.developers.google.com;
– creare un nuovo progetto;
– selezionare il progetto creato;
– abilitare l’utilizzo delle API in questo caso shorturl;
– aggiungere le credenziali selezionando API key e se serve per il web selezionare browser;
– aggiungere i domini che possono richiamare le API e salvare;
– verrà restituta la API key da inserire nello script sottostante
Per maggiori informazioni (https://support.google.com/cloud/answer/6158862?hl=en&ref_topic=6262490)
Di seguito lo script per chiamare le API di google (modificare APIKEY con la propria chiave):
(function(){ 'use strict'; // Map the hostname of the current URL (by regex) to the Google API keys of the corresponding // Google Developer Center Projects. To localize, create your own Google Developer Center Projects, // one for each environment (dev, staging, www), create API keys and enter them below. // More info: https://developers.google.com/url-shortener/v1/getting_started#auth, subsection // "Acquiring and using an API Key". var hostnamePatternsApiKeys = { 'miosito.com': 'APIKEY' }; var urlshortener = function() { }; // Begin static initialization urlshortener.enabled = true; urlshortener.apiKey = null; // Find an entry in hostnamePatternsApiKeys that matches the current hostname. for (var hostnamePattern in hostnamePatternsApiKeys) { if (location.host.match(hostnamePattern) == location.host) { urlshortener.apiKey = hostnamePatternsApiKeys[hostnamePattern]; break; } } if (urlshortener.apiKey == null) { if (console) console.log("urlshortener init error: can't find API key to match current hostname in hostnamePatternsApiKeys"); urlshortener.enabled = false; } // End static init urlshortener.shortenUrl = function(url, callback) { if (!urlshortener.enabled) { callback.apply(null, [url]); return; } var request = gapi.client.urlshortener.url.insert({ resource: { longUrl: url } }); request.execute(function(response) { var shortUrl = response.id; if (callback) { callback.apply(response, [shortUrl]); } //console.log("Short URL for [" + url + "] = [" + shortUrl + "]"); }); }; var init = function() { urlshortener.enabled = true; }; var googleApiLoaded = function () { gapi.client.setApiKey(urlshortener.apiKey); gapi.client.load('urlshortener', 'v1').then(init); }; window.googleApiLoaded = googleApiLoaded; $(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>'); window.urlshortener = urlshortener; })();
Di seguito la chiamata effettuare per avere lo short url:
urlshortener.shortenUrl(href, function (url) { console.log(url); });