Twitter integration with Salesforce


#1

Hi all!

I need to integrate with twitter from salesforce and fetch the recent twitter feeds of any particular user. Can you please suggest me how to implement this feature.

Thanks in advance!


#2

Seems like GET statuses/user_timeline is what you need.


#3

Hi Andy,

Thanks much for your quick response. Actually what I need is -

  1. We send a user name (EX: John) from Salesforce to Twitter.
  2. Based on the user name (John) provided from salesforce , I need to get all the Ids (max 10) of those users whose name matching with the name (John) present in the twitter .
  3. After fetching all the user Ids, we need to fetch the current tweets based on the Id.

Please suggest!

Thanks in Advance!


#4

Well there should only be one username match rather than 10 - how are you intending to identify the correct Twitter user?

Once you have the ID, you can simply pass that to the user_timeline endpoint (provided that it is not a private account).

There’s plenty more in the REST API reference documentation.


#5

Hi Andy,

Thank you very much for your quick response on this.

Below is the first step -

I will pass the user name called John from Salesforce to Twitter. There can be multiple Twitter Accounts available with the name John. I need to fetch all those Accounts from Twitter with the Ids whose name is John.

Below is the second step -

After getting all the Twitter Accounts with the name John, we will select one among those and pass the selected name to Twitter for getting the recent tweets for selected Account.

Please let me know if it is making sense.

Also I have found the URL for search - https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2

But when I am using this, I am getting Authentication issue.

AUTHENTICATION

String keyencoded = EncodingUtil.urlEncode(API_Key__c, 'UTF-8');
String secretkeyencoded = EncodingUtil.urlEncode(API_Secret_Key__c, 'UTF-8');
 
//Create Final Key String
String sFinal = keyencoded + ':' + secretkeyencoded;
//Convert to Blob
Blob headerValue = Blob.valueOf(sFinal);
 
//Build Request
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.twitter.com/oauth2/token');
req.setMethod('POST');
 
//Add Auth Header
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
 
//You need to add this to the request - proved easy to miss in instructions...
req.setBody('grant_type=client_credentials');
 
//Make request
Http http = new Http();
HTTPResponse res = http.send(req);

I am getting the access_token using the Callout

{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAC6UfgAAAAAAojUiD%2BUvejb5DeTPusRaX3Of1tg%3D4uNaaiw9jsiuKLCHA1FlUuauQIcuMsB8PjI261YoAbLqTlePJe"}

SEARCH

HttpRequest req2 = new HttpRequest();
//I actually store the endpoint in the same custom setting and build dynamically, but for purposes of demo:
req2.setEndpoint('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2');
req2.setMethod('GET');
 
//Call Bearer token Method
String authorizationHeader = 'Bearer ' + access_token;
req2.setHeader('Authorization', authorizationHeader);
 
Http http = new Http();
HTTPResponse res = http.send(req2);
String sBody = res.getBody();

Getting the Exception System.HttpResponse[Status=Forbidden, StatusCode=403]

Response Body - {"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]}

Thanks in Advance!


#6

(reformatted your post so the code was clearer - there’s a toolbar in the editor which lets you quote and markup code easily)

There are a bunch of issues here.

First of all, you need to sort out the OAuth problem. If you are getting a status forbidden you need to ensure your consumer keys and tokens are correctly configured, your machine’s time is accurate and close to the server (OAuth is time-dependent), and you have configured the library you are using properly. If you use a known API library then most of the heavy lifting for authentication will be done for you.

You said you want to SEARCH for users. In that case take a look at users/search but be aware there may be a wide range of results if you simply ask for all users with β€œJohn” in their profile, and you’ll end up paging through them. I think you’d be better passing a known Twitter handle to users/show.

See the REST API reference - there are a bunch of relevant methods that could be useful.

The β€œsearch” you refer to on the timeline API is really just requesting that specific user’s timeline, with two Tweets shown.


#7

Hi Andy,

Hope you are doing good.

I am sorry till now the User search stuff was not fixed by me…

Http h = new Http();
HttpRequest req = new HttpRequest();
HttpResponse res;
String sq = β€˜%23twitter’;

sq = sq.replace(’*’,’%2A’).replace(’+’,’%20’);
String endPointValue = β€˜https://api.twitter.com/1.1/users/search.json?q=’+sq+’&page=1&count=3’;

req.setEndpoint(endPointValue);

req.setBody(β€˜Content-Type=’ +EncodingUtil.urlEncode(β€˜application/x-www-form-urlencoded’,β€˜UTF-8’).replace(’*’,’%2A’).replace(’+’,’%20’).replace(’!’,’%21’).replace(’(’,’%28’).replace(’)’,’%29’)+

β€˜&oauth_consumer_key=’ + EncodingUtil.urlEncode(β€˜Consumer Key’, β€˜UTF-8’).replace(’*’,’%2A’).replace(’+’,’%20’).replace(’!’,’%21’).replace(’(’,’%28’).replace(’)’,’%29’)+

β€˜&oauth_nonce=’ + EncodingUtil.urlEncode(β€˜c1ff53033e97cad9034ed1faeb5f80e4’, β€˜UTF-8’).replace(’*’,’%2A’).replace(’+’,’%20’).replace(’!’,’%21’).replace(’(’,’%28’).replace(’)’,’%29’)+

β€˜&oauth_signature=’ + EncodingUtil.urlEncode(β€˜o6a4w8VhekhSPOdKREWoCqmPzks%3D’, β€˜UTF-8’).replace(’*’,’%2A’).replace(’+’,’%20’).replace(’!’,’%21’).replace(’(’,’%28’).replace(’)’,’%29’)+

β€˜&oauth_signature_method=’ + EncodingUtil.urlEncode(β€˜HMAC-SHA1’, β€˜UTF-8’).replace(’*’,’%2A’).replace(’+’,’%20’).replace(’!’,’%21’).replace(’(’,’%28’).replace(’)’,’%29’)+

β€˜&oauth_timestamp=’+ EncodingUtil.urlEncode(β€˜1432381966’, β€˜UTF-8’).replace(’*’,’%2A’).replace(’+’,’%20’)+

β€˜&oauth_token=’+EncodingUtil.urlEncode(β€˜Oath_Token’, β€˜UTF-8’).replace(’*’,’%2A’).replace(’+’,’%20’).replace(’!’,’%21’).replace(’(’,’%28’).replace(’)’,’%29’)
+
’&oauth_version=’+EncodingUtil.urlEncode(β€˜1.0’, β€˜UTF-8’));

req.setMethod(β€˜GET’);
res = h.send(req);
system.debug(’------------’+res.getbody());

But I am getting the Authentication issue -

{β€œerrors”:[{β€œcode”:32,β€œmessage”:β€œCould not authenticate you.”}]}

Can you please help me how to get rid off the issue… Please help…


#8

It is probably worth looking for a library that supports OAuth for you rather than you trying to build out that URL via string concatenation - you’ll need to set appropriate headers and other things as well if you are trying to do OAuth by hand.


#9

public class TwitterController {

private ApexPages.StandardController TwitterController ;
public String sBody{get;set;}
public String tweets{get;set;}
public String access_token {get;set;}
public Scontroller(ApexPages.StandardController controller)
{
      
    String keyencoded = EncodingUtil.urlEncode('CYXp886M6g04xwouOHLYg4UJf','UTF-8');
	String secretkeyencoded = EncodingUtil.urlEncode('5qC4A3JZDF8you0VtKx95AJqROlXi2oihTkJgVNNsv8pVQ2cjT', 'UTF-8');
	String sFinal = keyencoded + ':' + secretkeyencoded;
	Blob headerValue = Blob.valueOf(sFinal);
	HttpRequest req = new HttpRequest();
    req.setEndpoint('https://api.twitter.com/oauth2/token');
    req.setMethod('POST');
    String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
    req.setHeader('Authorization', authorizationHeader);
    req.setBody('grant_type=client_credentials');
    Http http = new Http();
    HTTPResponse res = http.send(req);
	
    JSONParser parser = JSON.createParser(res.getBody());
    while(parser.nextToken() != null)
    {
        if(parser.getCurrentToken() == JSONToken.FIELD_NAME)
        {
            String fieldName = parser.getText();
            parser.nextToken();
            if(fieldName == 'access_token')
            {
                access_token = parser.getText();
            }
            
        }
    }
  
    	       
}

public String gettweetsss(){
    
    HttpRequest req2 = new HttpRequest();

      	req2.setEndpoint('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=12');
        req2.setMethod('GET');
         
        //Call Bearer token Method
        String authorizationHeader = 'Bearer ' + access_token;
        req2.setHeader('Authorization', authorizationHeader);
         
        Http http = new Http();
        HTTPResponse res = http.send(req2);
       
        tweets = res.getBody();
        return tweets;  
}    

}

It works!


#10

Can some share the code and process for how to get the email Id of an user from salesforce using integration? .