Salesforce and Twitter Integration

Updated: Jan 17

This tutorial provides the step by step guide to integrate Salesforce and Twitter.


1) Prerequisites :-

  1. You need to have a twitter account. Go to http://twitter.com to create one.You need to apply for the developer account. Do it here https://developer.twitter.com/en/apply/user. Remember twitter Api are now private, and you need to apply for developer account in order to create apps and access api. Fill the form and submit, it will take upto 1 week to get the necessary access.

  2. You can check the status by going to https://developer.twitter.com/en/dashboard. Here you will see three sandboxes (Search Tweets: 30-Days , Search Tweets: Full Archive , Account Activity API).

2) Create Twitter apps :-


  1. Go to https://developer.twitter.com/en/dashboard. Click on your user name at the right upper corner and click on apps.

2. Click on create an App.


3. Fill the App details form as follows.

App Name :- you twitter app name. Could be anything.

App Description :- Any text you deem appropriate.

Website Url :- https://twitter.com/home

Sign in with Twitter :- Enabled

Callback URL :-  https://developer.twitter.com/

Describe the app usage :- (Sample) It is an integration with salesforce. I am going extract twitter data to salesforce and use it to display on contact.

And Click on Create.


4. Now go to "Keys and Token" tab, next to app details tab. Here you will see Consumer Api Keys (API key, API secret key) and Access Token. These two keys are required to provide authentication while accessing twitter api. We can create Access Token by two ways. First, click on create in this tab. Second, via programmatically. In this tutorial we will create Access token via apex.


3) Create Custom Settings

Create List custom settings "Twitter API Settings" and create a field "value" in it.Now create two record in this custom settings as follows.

Name - API Key , value - (Your Api Key created in second step)

Name - API Secret Key , value - (Your Api secret key in second step)


4) Add twitter end point to 'Remote Site Settings'

Go to Remote Site settings in salesforce. Create new as follows.

Remote Site URL - https://api.twitter.com

5) Call Twitter API from Salesforce

Code to get Access Token - In this function the API key and API secret key will be used in a post http callout. This function will return the accessToken that will be used to make api call without user's context. Check api reference page for more information.

public String retrieveAccessToken(){
        String API_Key=EncodingUtil.urlEncode(Twitter_API_Settings__c.getInstance( 'API Key' ).value__c, 'UTF-8');
        String API_Secret_Key=EncodingUtil.urlEncode(Twitter_API_Settings__c.getInstance( 'API Secret Key' ).value__c, 'UTF-8');      
        
		String Consumer_API_key=API_Key + ':' + API_Secret_Key;
        
		Blob httpRequestHeader=Blob.valueOf(Consumer_API_key);
        System.debug('Twitter HeaderBlob ' + httpRequestHeader);        
        
		HttpRequest req=new HttpRequest();
        req.setEndpoint('https://api.twitter.com/oauth2/token');
        req.setMethod('POST');        
        
		string basicAuthorizationHeader='Basic ' + EncodingUtil.base64Encode(httpRequestHeader);
        req.setHeader('Authorization',basicAuthorizationHeader);
        req.setBody('grant_type=client_credentials');        
        System.debug('Twitter Http request ' + req);        
        
		Http http=new Http();        
        HttpResponse res=http.send(req);
        String accessToken;        
        if(res.getStatusCode()==200)
        {
            JSONParser parser=JSON.createParser(res.getBody());
            System.debug('Twitter JSON response ' + parser);
            while(parser.nextToken()!=null)
            {
                if(parser.getCurrentToken()==JSONToken.FIELD_NAME && parser.getText() == 'access_token')
                {
                    parser.nextToken();
                    accessToken=parser.getText();
                }
            }
        }
        return accessToken;
    }

2. Call Twitter api to get user's information - Lookup api will return all the information regarding a twitter handle, for eg. Name, Description, followers count, friends count, profile picture url etc. The JSON return by this api is huge, but I am storing few fields only. Moreover, you can provide a list of twitter handle separated by comma, that's why I took List instead of single object. This method will work for list of users as well.

// Class to store twitter users information
public   class users {
        public String id;	
        public String id_str;	
        public String name;	//Saurabh
        public String screen_name;	
        public String location;	
        public String description;	
        public Integer followers_count;	//28
        public Integer friends_count;	//189
        public Integer listed_count;	//0
        public String profile_image_url;	
        public String profile_image_url_https;	
        
        public List<users> parse(String json) {
            return (List<users>) System.JSON.deserialize(json, List<users>.class);
        }
    }

// Method to get twitter user's information and desearlize into above class

public users getTwitterInfo(string twitterHandle)
    {
        HttpRequest req=new HttpRequest();
        req.setEndpoint('https://api.twitter.com/1.1/users/lookup.json?screen_name='+twitterHandle);
        req.setMethod('GET');
        String bearerAuthorizationHeader='Bearer '  + retrieveAccessToken();
        req.setHeader('Authorization',bearerAuthorizationHeader);
        
        Http http=new Http();
        System.debug('Twitter Request :- ' + req);
        HttpResponse res=http.send(req);
        if(res.getStatusCode()!=200)
        {
            System.debug('Twitter Response :- ' + res.getBody());
            return null;
        }
        String sBody=res.getBody();
        System.debug('Twitter sBody :- ' + sBody);
        
        Map <String, users> TwitterResultsMap = new Map<String, users> ();
        users tObj=new users();
        List<users> tresult=tObj.parse(sBody);
        
        for(users t: tresult)
        {
            TwitterResultsMap.put(t.screen_name,t);
        }
        System.debug('TwitterResultsMap :- ' + TwitterResultsMap);
        return TwitterResultsMap.get(twitterHandle);        
    }


So, this is the demo to access twitter api, for more api visit Twitter API documentation page. I will publish another article in which I will create a Lightning component and display twitter user's profile pic and other information.

Let me know if you like this article.

©2019 by SFDC Blogs.