+ Start a Discussion
smriti sharan19smriti sharan19 

post on twitter using salesforce

I am trying to post on twitter using Salesforce but unable to do so. It throws error forbidden. Can someone help me on this.
 
public class twittersalesforceIntegration {
    public Static String getBearerToken() {
    //Encode them
    String keyencoded = EncodingUtil.urlEncode('####', 'UTF-8');
    String secretkeyencoded = EncodingUtil.urlEncode('#####', '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);
    system.debug('res'+res);
    String stoken;
    //Parse JSON for Bearer Token
    JSONParser parser = JSON.createParser(res.getBody());
    while (parser.nextToken() != null) {
    if (parser.getCurrentToken() == JSONToken.FIELD_NAME && parser.getText() == 'access_token'){
    parser.nextToken();
    stoken = parser.getText();
    }
    }
    //Return Token so it can be used in next call
    return stoken;
    }    
    public static void submittotwitter () {
    HttpRequest req2 = new HttpRequest();
    req2.setEndpoint('https://api.twitter.com/1.1/statuses/update.json?status=hello');
    req2.setMethod('POST');     
    //Call Bearer token Method
    String authorizationHeader = 'Bearer ' + getBearerToken();
    req2.setHeader('Authorization', authorizationHeader);
     
    Http http = new Http();
    HTTPResponse res = http.send(req2);
    system.debug('res'+res);  
    }    
}

 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Smriti,

Greetings to you!

Please refer to the below links which might help you further.

http://www.bitspace.in/2015/12/twitter-api-integration-with-salesforce.html

https://forceadventure.wordpress.com/2014/03/03/interacting-with-the-twitter-api-from-salesforce/

http://www.saaspie.com/salesforce-twitter-integration-using-oauth/

http://www.bridgefarmconsulting.com/blog/twitter-authentication/

https://twittercommunity.com/t/twitter-integration-with-salesforce/37301

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas