Wednesday 20 November 2013

Salesforce Integration With Klout




Recently from the client side got a requirement of getting Twiitter Account rating in Salesforce using Klout.
Go to Klout
Here what we are doing is just creating a visualforce page which is having custom fields of Account on the click of a button on detail page, our visualforce page will open, where user will get its Twitter Account rating.
It can be easily understand by the snaps below

Write your twitter Screen Name and click on the button "Get Rating"


After clicking that button user will get its Twitter rating as shown


Now the question rises how to do this thing?

So first of all, create an Account in Klout(Link provided above) then on the dashboard Click on "REGISTER AN APP", fill all the formalities and then you'll find this, marked in red is the key which we'll use to get Twitter score.


Here is the apex class

/**     Description    :    Ths class will Integrate Salesforce with Klout. 

  *

  *    Created By     :    Abhi Tripathi

  *

  *    Created Date   :    07/30/2013

  *

  *    Revisison Log  :    v1.0 - Created

  *

  *    Version        :    V1.0

**/



public with sharing class KloutWithSalesforceTwitterRatingUpdate {



  //Wrapper Class for First Response

  public class firstResponseParsingWrapper {

   

    //Response variables

    public String id;

    public String network;

   

    //Constructor

    public firstResponseParsingWrapper(String id, String network) {

      this.id = id;

      this.network = network;

    }

  }

 

  //Wrapper for second response

  public class KloutFinalResponseWrapper {

   

    //Score from the response

    public String score;

   

    //Constructor

    public KloutFinalResponseWrapper(String score) {

      this.score = score;

    }

  }

 



  //account

  public Account account { get; set; }

  public String twitterScore { get; set; }

 

  //constructor

  public KloutWithSalesforceTwitterRatingUpdate(ApexPages.StandardController stdController){

   

    //Initiallize

    twitterScore = '';



    //account record

    this.account = (Account)stdController.getRecord(); 

  }

   

    //Method for making callout and populating values retrieved from response is going to be diplayed on Visualforce Page

    public void kloutTwitterRating() { 



    try {

      //Http

      Http http = new Http();

     

      //Request

      HttpRequest req = new HttpRequest();

      req.setEndpoint('http://api.klout.com/v2/identity.json/twitter?screenName='+ twitterScore +'&key=4j6pe8zamj4dmh2by9tzv5sc');

      req.setMethod('GET');

     

      //Send request

      HTTPResponse firstResponse = http.send(req);

      System.debug('res::::::' + firstResponse.getBody());

     

      //Body

      String body = firstResponse.getBody();

     

      //Deserializing response

      KloutWithSalesforceTwitterRatingUpdate.firstResponseParsingWrapper parsedResponse = (KloutWithSalesforceTwitterRatingUpdate.firstResponseParsingWrapper)JSON.deserialize(body, firstResponseParsingWrapper.class);

      System.debug('parsedResponse:::::::' + parsedResponse);

     

      //String for id in response

      String responseId = parsedResponse.id;

      System.debug('responseId:::::::' + responseId);

   

      //Second request for score

      HttpRequest finalReq = new HttpRequest();

      finalReq.setEndpoint('http://api.klout.com/v2/user.json/'+ responseId +'/score?key=4j6pe8zamj4dmh2by9tzv5sc'); 

      finalReq.setMethod('GET');

     

      //Send request

      HTTPResponse lastResponse = http.send(finalReq);

      System.debug('lastResponse::::::' + lastResponse.getBody());

     

      //Body

      String finalBody = lastResponse.getBody(); 

     

      //Deserializing response

      KloutWithSalesforceTwitterRatingUpdate.KloutFinalResponseWrapper parseFinalResponse = (KloutWithSalesforceTwitterRatingUpdate.KloutFinalResponseWrapper)JSON.deserialize(finalBody, KloutFinalResponseWrapper.class);

      System.debug('parseFinalResponse::::::' + parseFinalResponse);

     

      //Assigning value

      account.Twitter_Rating__c = parseFinalResponse.score;

      account.Validate_Score_Successfully__c = true;

      account.Validate_Score_Last_Attempt__c = date.today();   

   



    }catch (exception e) {

     

      //Error messages

      ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'UserName Not Found, Sorry Try Again');

            ApexPages.addMessage(errormsg);

      System.debug('e:::::::' + e); 

    }   

   

  }

}


Here is the Visualforce Page

 <apex:page standardController="Account" extensions="KloutWithSalesforceTwitterRatingUpdate">  
    <!-- heading-->    
   <apex:sectionHeader title="Screen Name" subtitle="Twitter Rating"/>  
   <!-- form -->  
   <apex:form >  
     <!-- page messages-->  
     <apex:pageMessages />  
     <!-- page block -->  
     <apex:pageBlock mode="edit">  
         <!-- button -->  
         <apex:pageBlockButtons >   
           <apex:commandButton value="Get Rating" action="{!KloutTwitterRating}" />  
           <apex:commandButton value="Cancel" action="{!cancel}" />  
         </apex:pageBlockButtons>  
       <!-- block section -->  
       <apex:pageBlockSection title="Twitter Screen Name">  
         <!--Input Text>-->  
         <apex:pageBlockSectionItem >  
           Your Twitter Screen Name  
           <apex:inputText value="{!twitterScore}"/>  
         </apex:pageBlockSectionItem>  
       </apex:pageBlockSection>  
       <apex:pageBlockSection title="Rating With Related Values">  
         <!--Score-->  
         <apex:outputField value="{!account.Twitter_Rating__c}" />  
         <apex:outputField value="{!account.Validate_Score_Successfully__c}" />  
         <apex:outputField value="{!account.Validate_Score_Last_Attempt__c}" />   
       </apex:pageBlockSection>  
     </apex:pageBlock>   
   </apex:form>  
 </apex:page>  


Now get your Twitter Rating in your salesforce.
Cheers.......!!!!!


2 comments:

  1. This really...very good explanation.
    It found very easy and smart way of codding !
    Thanks alot Abhi.
    You rocks...!

    ReplyDelete