Tuesday, July 08, 2014

Working With Google URL Shortener Service API and Create,Track,Maintain Analytics with Google Account - Javascript API


URL shorteners are really useful for stats counting ,providing small sized URL instead of a huge links.Many Business on Internet Social Media needs stats on how many peoples clicked and used the url.However there are lot of service such as +Klout , +Buffer  and so many sites have their own url shorteners and make stats for users and business organiztions based on data clicks,reactions from Popular social networks.So,Creating and maintaining Shortened URL with Performance and scalability is important,Thats why Google gives us API platform where we could Read,Create,Analyse the Shortened URL by them.we are Just using the service provided by Google in rightful way by providing access Tokens , Login.


Working With Google URL Shortener Service API and Create,Track,Maintain Analytics with Google Account - Javascript API
google URL shortner API service
Files   :  Download   |  Live Demo 

Scope : 

I have Written a simple Web application that connect with your Google account and Can fetch Your all Shortened URLs,Analytics and create new URL and shorten them within an instance.

Installation and Requirements : 

First of All Log into your Google Developer Console for registering our API service and to get API KEY and for Oauth Login. Click here






  • Create a Project and move inside [*note :  I haven't enable Billing for using Cloud or API Service-be cautious while using those service]



  • Under APIs And Auth select API -> enable URL SHORTENER API  alone is enough.



  • Then Move to Credentials Tab.Create API public Key with suitable requirements.select Browser key.


  • API KEY set up
    Then Move To Create Client ID : 
    Application type : Web Application with Authorized javascript Domain Origins and Redirect URL.I have given Both as same Since it is Single page web app under index.php in my localhost
    Get your Corresponding API key from Public API and CLIENT ID for our Web application.

    we need two Scripts from google namely client.js and jquery for easy handling.


     <script src="https://apis.google.com/js/client.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>


    Initialize App with Login and Fetching Access Token :
          Juts use Client ID here and Load with gapi.auth.authorize( ) function to authorize our application with an Google account.


      var apiKey = "API _ KEY here";
     var clientId =  "CLIENT _ KEY _ HERE ";
       var scopes ="https://www.googleapis.com/auth/urlshortener";



    Authorize function :

    gapi.auth.authorize   - method just takes client id and scope for authenticating user and provides you access token with gapi.auth.gettoken()


      function auth() {
            var config = {
              'client_id': clientId,
              'scope': scopes
            };
            gapi.auth.authorize(config, function(data) {
              console.log('login complete');
              console.log(gapi.auth.getToken());
             if(data.access_token)
             { $("#login").hide();
                    $("#call").show();
              }
           });
          }


    Create A New Shortened URL : 

    Generally client.load is used initialize with three params namely : scope ,version ,and a call back function to execute.This is the general approach to call API and bring data inside your application for any type of API data pulling,updating service.
    gapi.client.urlshortener.url.insert - is the main function which request the server API for result data and operation.this function just passes the Long url parameter to create shortened URL in return as JSON object.
      
           function load() {
             gapi.client.setApiKey(apiKey);
             gapi.client.load('urlshortener', 'v1', create);
    }
        function create() {
        var url = $("#url").val();
      var request = gapi.client.urlshortener.url.insert({
        'resource': {'longUrl': url }
      });
      request.execute(function(response) {
             // success do something here with responded data
             console.log(response.id);
       });
    }


    Retrieveing Long URL by inputing Short URL : 

    By the same above method gapi.client.urlshortener.url.get is responsible for fetching the relative long URL.
      
           function loadforretrieve() {
             gapi.client.setApiKey(apiKey);
             gapi.client.load('urlshortener', 'v1',read);
    }
        function read() {
         var url = $("#url").val();
      var request = gapi.client.urlshortener.url.get({
        'resource': {'shortUrl': url }
      });
      request.execute(function(response) {
             // success do something here with responded data
             console.log(response);
        });
    }



    Retrieving USER ACCOUNT shortened URL and Analytics :

    Similarly By the two Methods  gapi.client.urlshortener.url.list( ); will list you all URL already shortened by particular logined user.
     gapi.client.urlshortener.url.list({"projection" : "FULL"}); will list you with analytics ,clicks with month,days basis have a look at the response on console after performing the action.
      
           function loadforuser() {
             gapi.client.setApiKey(apiKey);
             gapi.client.load('urlshortener', 'v1',userapi);
    }
        function userapi() {
         var url = $("#url").val();
      var request = gapi.client.urlshortener.url.list);
      request.execute(function(response) {
             // success do something here with responded data
             console.log(response);
        });
    }


    You can achieve this function calls simply by button inputs onclick events and you should do with logic since you have jquery for hiding login button after authentication and displaying input box to create.

    If you have any doubt just ask in comments/mail me s.shivasurya@gmail.com.if you can find any bugs comment below.Share is care.

    SHIVA SURYA

    I love to work on WAMP/LAMP/Eclipse platform /Node.js ,i love to create PHP API centric WEB/MOBILE application.The age changes from Desktop to Smartphone Apps,i Love to create Native Android and Phonegap apps with JQuery,Ionic,Bootstrap framework with REST API service at backend.I too welcome Orders for Application/website devlopment with PHP/Mysql/Android apps-contact me at s.shivasurya@gmail.com

    0 comments:

    Post a Comment

    feel free to post your comments!

     

    Copyright @ 2014 i-visionblog .Copyrighted.com Registered & Protected  Z6HO-DGFO-S2CO-JRZG