Twitter Salesforce Integration: Post on twitter from Salesforce

This Article will Cover:

  • API Basics
  • Create Twitter Application
  • Calling Twitter API with Postman
  • Calling Twitter API with Salesforce
  • Bonus: Calling Twitter API with Python
  • Demo Video

Prerequisite

  • Basic Knowledge of HTTP Request and Response

Introduction

Get ready to have awesome fun with integration

API Basics

The first step of working with any API is collecting a few pieces of information:

  • What URL provide access to appropriate resource?
  • What parameters do I need to include in the request?
  • Is authentication required?

You get all this information from Official API Twitter Documentation

After checking the documentation, we get following information:

  • The complete URL is https://api.twitter.com/1.1/statuses/show.json
  • We will need to make an authenticated request to access this resource.
  • Twitter requires all API access be done over HTTPS to improve the security

Create Twitter Application

Create a new application in Twitter here.

After you create the app you will be provided with the following information:

  • Consumer Key (API Key)
  • Consumer Secret (API Secret)
  • Access Token
  • Access Token Secret

Note: Dont share keys and token with anyone for security reasons

Calling Twitter API with Postman Client

Now that we’ve collected all the information needed to fetch the tweet, let’s try fetching it using Postman. This application helps to be more efficient while working with APIs. Using Postman, we can construct complex HTTP requests quickly.

Step 1. Google Install Postman and go to the Postman official site to download the application.

Step 2:
  1. Open Postman application and click on authorization tab.
  2. Select authorization type as OAuth 1.0. (OAuth is a system that provides a way for users to grant access to third party applications without revealing their credentials)
  3. Add authorization data to Request Headers.
  4. Add consumer key,consumer secret,access token, token secret generated from twitter app.
Step 3:
Use API reference to create url according to your use case.

I wanted to get collection of the most recent Tweets posted by the user for this api reference guides to use statuses/user_timeline.json

URL-   https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=smritiworld

Step 4: Click send and you will get the response

Calling Twitter API using Salesforce 

Step 1: Before going to callouts, we have to add the Twitter API URL (https://api.twitter.com) in remote site settings.

Step 2: The authorization header should contain certain parameters

 how will you know what you need to pass in request header?

Simple Answer is Twitter API documentation. 

  • oauth_consumer_key –  The consumer key from Twitter app
  • oauth_nonce – An unique string to identify the request
  • oauth_signature –  A value which is generated by all of the request parameters and two secret values through a signing algorithm.
  • oauth_signature_method –  The signature method to generate oauth_signature. eg: HMAC-SHA1
  • oauth_timestamp – The number of seconds since the Unix epoch at the point the request is generated
  • oauth_version – Always be 1.0 for any request.

Step 3: Now your requirement is to post a tweet from Salesforce. So go to API Reference.

In API Reference it is given that Post Statuses/Update is used for tweeting.

So  to post Hello on timeline append value to endpoint

Request Method: POST

Example EndPoint: https://api.twitter.com/1.1/statuses/update.json?status=hello

  • Complete Code:
public class TwitterPost_Utility 
{    
    //oauth_nonce- parameter is a unique token your application should generate for each unique request. 
        public static String generateOathNonce()
        {
            //A collection of binary data stored as a single object.Blobs can be accepted as Web service arguments
            //Generates an Advanced Encryption Standard (AES). keysize=128,192,256
            Blob blobKey = crypto.generateAesKey(256);
            //convertToHex- Returns a hexadecimal (base 16) representation of the inputBlob.
            String key = EncodingUtil.convertToHex(blobKey);
            //base64Encode-Converts a Blob to an unencoded String representing its normal form.
            String oathNonce = EncodingUtil.base64Encode(Blob.valueOf(key));
            //(math.random() * 10)- generate random no between 1-10
            oathNonce = oathNonce.replaceAll('[^a-zA-Z0-9]+',''+integer.valueOf(math.random() * 10));
            //The substring begins at the specified beginIndex and extends to the character at index endIndex
            oathNonce = oathNonce.substring(0,42);
            return oathNonce;
        }
    
    //oauth_timestamp parameter indicates when the request was created. 
    public static long generateTimeStamp()
        {
            long timestamp = datetime.now().getTime(); 
            timestamp = timestamp / 1000;
            return timestamp;
        }
    
 public static void twitterPost(String ApiKey, String ApiSecret, String AccessToken, String AccessTokenSecret, String message)
    {
        if(String.isNotBlank(ApiKey) && String.isNotBlank(ApiSecret) && String.isNotBlank(AccessToken) && String.isNotBlank(AccessTokenSecret) && String.isNotBlank(message))
        {
            String oathNonce = TwitterPost_Utility.generateOathNonce();
            Long timestamp = TwitterPost_Utility.generateTimeStamp();
            //oauth_signature parameter contains a value which is generated by running all of the other request 
            //parameters and two secret values through a signing algorithm
            String signature = '';
           //Encodes a string into the application 
            message = Encodingutil.urlEncode(message, 'UTF-8');
            String othSecret = Encodingutil.urlEncode(Accesstokensecret, 'UTF-8');
            String consumSecret = Encodingutil.urlEncode(APIsecret, 'UTF-8');
            String othToken = Encodingutil.urlEncode(Accesstoken, 'UTF-8');
            String othNonce = Encodingutil.urlEncode(oathNonce, 'UTF-8');
            String consumKey = Encodingutil.urlEncode(APIkey, 'UTF-8');
            message = message.replaceAll('\\+','%20');
            String paramString = 'include_entities=true&'+
                                 'oauth_consumer_key='+consumKey+'&'+
                                 'oauth_nonce='+othNonce+'&'+
                                 'oauth_signature_method=HMAC-SHA1&'+
                                 'oauth_timestamp='+timestamp+'&'+
                                 'oauth_token='+othToken+'&'+
                                 'oauth_version=1.0&'+
                                 'status='+message;
            string baseString = 'POST&'+EncodingUtil.urlEncode('https://api.twitter.com/1.1/statuses/update.json', 'UTF-8')+'&'+ 
                  EncodingUtil.urlEncode(paramString, 'UTF-8');
            string signString = consumSecret+'&'+othSecret;
            blob blobBaseString = Blob.ValueOf(baseString);
            blob blobSignString = Blob.ValueOf(signString);
            blob signBlob = crypto.generateMac('hmacSHA1',blobBaseString ,blobSignString );        
            signature =  EncodingUtil.base64Encode(signBlob);
            
            if(String.isNotBlank(signature))
            {
                  signature = Encodingutil.urlEncode(signature, 'UTF-8');
                  HttpRequest req = new HttpRequest();
                  req.setEndpoint('https://api.twitter.com/1.1/statuses/update.json?include_entities=true');
                  req.setMethod('POST');
                  string reqstring = 'OAuth oauth_consumer_key="'+consumKey+'",'+
                                     'oauth_nonce="'+othNonce+'",'+
                                     'oauth_signature="'+signature +'",'+
                                     'oauth_signature_method="HMAC-SHA1",'+
                                     'oauth_timestamp="'+timestamp+'",'+
                                     'oauth_token="'+othToken+'",'+
                                     'oauth_version="1.0"';
                  system.debug('### req String :'+reqstring);
                  req.setHeader('Authorization',reqstring);
                  req.setHeader('Content-Type','application/x-www-form-urlencoded');
                  req.setBody('status='+message);
                  if(!Test.isRunningTest())
                  {
                      Http http = new Http();
                      HTTPResponse res = http.send(req);
                      system.debug(res.getBody());
                  }
            }
        }
    }

}

Bonus Point: For geeks who love Coding

Calling Twitter API using Python

We can use Tweepy Library in python to call Twitter API

import tweepy

ak = 'XXXX'

aks = 'XXXX' 

at = 'XXXX

ats = 'XXXX'
def OAuth():
    try:
        auth = tweepy.OAuthHandler(ak,aks)
        auth.set_access_token(at,ats)
        return auth
        
    except Exception as e:
        return none

oauth = OAuthuth()
apicall = tweepy.API(oauth)

apicall.update_status('Here is a sample tweet from API call program. Smriti Sharan')
print ('Tweet Created')

Hope you enjoyed the article. For more of these kind of articles stay tuned !

Get latest updates

If you like the Video then subscribe to Youtube Channel

If you like the Article then subscribe to the Blog

Together we can learn faster

You can join the Whatsapp group 

You can join Facebook group

You can join Twitter

You can join Instagram 

References

TwitterCommunity: Twitter Integration with Salesforce

StackOverflow: Authenticate To Twitter

Twitter Integration With Salesforce

Twitter Integration

Salesforce Twitter Integration Using Oauth

Tweet Utils

Integration with Twitter

Twitter API

PostMan

How to make calls to Twitter API using Postman

StackOverflow: How to make call to twitter API using Stack Overflow

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes