How to Access twitter from Salesforce - twitter

I am struggling to get this done, I need to connect to twitter rest Api 1.1 to get user details, time line etc.
What I came across is:
I have a Twitter App with access token ,secrete etc.
Now how to use all that access token etc to send (GET or POST) request to Twitter from Salesforce. How to set header or how to authenticate request.
A tutorial would be very help full all I could find was tutorials for php etc I need it for "salesforce"
Note: I don't want to use a external lib

You should be able to do this directly from Apex using the HTTP REST library. Here is the first Google result for "salesforce apex twitter integration" with this sample code from Navatar_DbSup:
VF CODE:
<apex:inputTextarea id="tweetInput" onkeyup="return maxLength();" onKeyPress="return maxLength();" value="{!newTweet}" rows="2" cols="73"/>
<apex:commandButton id="tweetBtn" style="height:35px;" value="Tweet" action="{!postTweet}" />
Controller code:
*** post tweets into twitter*/
public String newTweet{get;set;}
public Void postTweet()
{
Http h = new Http();
HttpRequest req = new HttpRequest();
Method = 'POST';
req.setMethod(Method);
req.setEndpoint('https://api.twitter.com/1/statuses/update.xml');
newTweet = newTweet.replace('%','%25').replace('&','%26').replace('#','%40').replace(';','%3B').replace('?','%3F').replace('/','%2F').replace(':','%3A').replace('#','%23').replace('=','%3D').replace('+','%2B').replace('$','%24').replace(',','%2C').replace(' ','%20').replace('<','%3C').replace('>','%3E').replace('{','%7B').replace('}','%7D').replace('[','%5B').replace(']','%5D').replace('`','%60').replace('|','%7C').replace('\\','%5C').replace('^','%5E').replace('"','%22').replace('\'','%27').replace('!','%21').replace('*','%2A').replace('(','%28').replace(')','%29').replace('~','%7F');
req.setBody('status='+newTweet);
req.setHeader('Content-Type','application/x-www-form-urlencoded');
OAuth oa = new OAuth();
if(!oa.setService())
{
message=oa.message;
}
oa.sign(req);
HttpResponse res = h.send(req);
system.debug('&&&&&&&&&&&&&&&&7' + res.getBody());
PostTweetbody = res.getBody() + '___' + message;
newTweet = '';
}

Related

How can i make Soap calls with OAuth2 in SalesForce?

I successfully authenticate using OAuth2 to Salesforce and i get back
access_token,signature,scope,id_token,instance_url,id,token_type,issued_at in json format.
Now in my c# code I make calls using Soap , the first is login, but this is no longer needed as I have authenticated already with OAuth.
I try to setup the service and then call
_service = new SalesForceEnterpriseService.SforceService() { Timeout = 60000, Url =
instance_url };
_service.SessionHeaderValue = new SessionHeader() { sessionId = access_token };
_service.QueryOptionsValue = new QueryOptions { batchSize = 200, batchSizeSpecified =
true };
DescribeGlobalResult result = _service.describeGlobal(); <----but it fails here
I get an exception:
Client found response content type of 'text/html; charset=UTF-8', but expected
'text/xml'.
The request failed with the error message:
What i found is that the Url returned with a Login from Soap is different to that returned after authenticating using OAuth2.
OAuth returns somethin like
"https://<mysalesforce>.salesforce.com
whereas the Soap Login returns
"https://<mysalesforce>.salesforce.com/services/Soap/u/54.0/<??number>
Any help with this would be great.

Get access_token using Windows Service's or Console App. for Instagram Api

My windows service is collect instagram datas from instagram api. I was using client_id but this uses format is removed.
Instagram api is want to access_token but Oauth 2.0 is web-based. or not?
I using .NET and my application type is windows service and web request don't work because this call url: "https://www.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code" is have one more contain redirect. so web response haven't contain my web application link also auto redirect is open..
what should I do?
Thanks..
Steps to get instagram access token
register ur application in instagram account.
get a client id and client secret.
Step 1: HIT the below url.
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
step 2: after hitting above url you will be taken to login page. enter the login credentials and take the code from address bar.
it will be live for only 20 seconds i guess.
step 3: The code which you got put it in CODE parameter in the below source code, then run the below code in console application n hit breakpoint at response. you will get access token and userid.
public void GetDataInstagramToken()
{
try
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "CLIENT-ID");
parameters.Add("client_secret", "CLIENT-Secret");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "REDIRECT-URI");
parameters.Add("code", "CODE");
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
var response = System.Text.Encoding.Default.GetString(result);
// deserializing nested JSON string to object
var jsResult = (JObject)JsonConvert.DeserializeObject(response);
string accessToken = (string)jsResult["access_token"];
}
catch (Exception)
{
//exception catch
}
}

Google Script API + Oauth + Tumblr

Hello,
I'm trying to acess, perform a post, into Tumblr with Oauth api provided by Tumblr) http://tumblr.com/api). I'm using Google Script and I've tryied too many solutions but anyone worked. To implement i've basaed myself into this(https://developers.google.com/apps-script/articles/twitter_tutorial) Google script twitter tutorial, once on Tumblr API web page they say that twitter api is almost the same that tumblr.
Contextualizing,
I've already set the Oauth class methods with data below and substituted consumer and secret keys with values got from the api i've created.
var oauthConfig = UrlFetchApp.addOAuthService("tumblr");
oauthConfig.setAccessTokenUrl(
"http://www.tumblr.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"http://www.tumblr.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"http://www.tumblr.com/oauth/authorize");
oauthConfig.setConsumerKey(<i>consumerkey</i>);
oauthConfig.setConsumerSecret(<i>consumerSecret</i>);
Error,
The code below isnt working as it should be.
var requestData = {
"method": "POST",
"oAuthServiceName": "tumbler",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"https://api.tumblr.com/v2/blog/{blog}.tumblr.com/post?type=text&body=word",
requestData);
The Script to Twitter is almost the same and it works. Im able to perform tweets.
var result = UrlFetchApp.fetch(
"https://api.twitter.com/1/statuses/update.json?status=" + tweet,
requestData);
Response From Server
Request failed for returned code 400. Server response: {"meta":{"status":400,"msg":"Bad Request"},"response":{"errors":["Post cannot be empty."]}}
Possible Solutions
A possible solution can work using this information(got from tumblr.com/api):
OAuth
The API supports the OAuth 1.0a Protocol, accepting parameters via the Authorization header, with the HMAC-SHA1 signature method only. There's probably already an OAuth client library for your platform.
My question is, what am I doing wrong?(my post inst empty, i have 2 params). Had anyone had the same problem? Someone has suggestions?
Thank You.
I don't know anything about the tumblr api, but your http post is empty (the oAuth parameters aren't in the post body, they're advanced options), the body of the post needs to go in the "payload" parameter. See the section "Advanced parameters" in the docs. Or, as you aren't using the post can't you use a get request instead? Remove the method: POST parameter (GET is the default).
Thank You very much Daniel. It worked now!!
Everybody that want use Tumblr + Google Script API + oAuth can use de code below to perform posts.
I created I Google Spreadsheet and then a script there. Before to be able to post I neded to create and app into tumblr.com/api and get secret and consumer keys. Also I've deployed the Google script as an web app(ensure that the version is the last one(the final code)) before to create a new version. After that you go tu publish > deploy as web app !
That twitter tutorial I put on my first question is the only path you need to conclude your job.
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("tumblr");
oauthConfig.setAccessTokenUrl(
"http://www.tumblr.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"http://www.tumblr.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"http://www.tumblr.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "tumblr",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"http://api.tumblr.com/v2/blog/{your_blog}.tumblr.com/posts/queue",
requestData);
}
function doGet(e) {
var tweet = e.parameter.tumblr;
var app = UiApp.createApplication().setTitle("Approved");
var panel = app.createFlowPanel();
authorize();
var encodedTweet = encodeURIComponent(tweet);
var payload =
{
"body" : encodedTweet,
"type" : "text"
};
var requestData = {
"method" : "POST",
"oAuthServiceName": "tumblr",
"oAuthUseToken": "always",
"payload" : payload
};
try {
var result = UrlFetchApp.fetch(
"https://api.tumblr.com/v2/blog/{your_blog}.tumblr.com/post",
requestData);
panel.add(app.createLabel().setText("You have approved: \"" + tweet + "\""));
} catch (e) {
Logger.log(e);
panel.add(app.createLabel().setText(e));
}
app.add(panel);
return app;
}

LinkedIn RestSharp and OAuthBase Example

anyone ever used C# in combination with the library RestSharp and OAuthBase in order get some interaction with LinkedIn?
I'm looking for a working example using these tools to do proper authorization (oAuth 2.0) and to publish a post using the share API on LinkedIn.
So far I've been successful using these tools to obtain valid access tokens (I can use it to obtain profile information for example), but posting via the share API got me stuck on authentication.
Any help would be very much appreciated!!
it turned out to be much simpler than I was thinking.... (doesn't it allways?)
The main point to take into account is: oAuth 2.0 does not require signatures, nonce, timestamps, authorization headers ... none of that.
If you want to post on LinkedIn using the sahres API and using oAuth2.0 ... OAuthbase is not needed.
Simply follow the oauth 2.0 authentication flow as described here:
http://developer.linkedin.com/documents/authentication
And then you can use the following code as a starting point:
var shareMsg = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new
{
title = "Test post to LinkedIn",
submitted_url = "http://www.somewebsite.com",
submitted_image_url = "http://www.somewebsite.com/image.png"
},
visibility = new
{
code = "anyone"
}
};
String requestUrl = "https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=" + accessToken;
RestClient rc = new RestClient();
RestRequest request = new RestRequest(requestUrl, Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = DataFormat.Json;
request.AddBody(shareMsg);
RestResponse restResponse = (RestResponse)rc.Execute(request);
ResponseStatus responseStatus = restResponse.ResponseStatus;
Happy coding!!

Yelp API Google App Script OAuth

I am trying to use Google Apps Script to query the Yelp Search Api and put the results into a spreadsheet. I having issues making the call to yelp using this example as a model:
var consumerKey = "... register your app with Twitter ...";
var consumerSecret = "... register your app with Twitter ...");
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("http://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("http://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("http://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(consumerKey);
oauthConfig.setConsumerSecret(consumerSecret);
// "twitter" value must match the argument to "addOAuthService" above.
var options = {
"oAuthServiceName" : "twitter",
"oAuthUseToken" : "always"
};
var url = "http://api.twitter.com/1/statuses/user_timeline.json";
var response = UrlFetchApp.fetch(url, options);
var tweets = JSON.parse(response.getContentText());
// Handle tweets
https://developers.google.com/apps-script/class_oauthconfig
This class only has methods for setting the access token URLs which Yelp doesn't appear to provide. They just provide the Token and Token Secret directly. I assumed that these would be set like the Consumer Key and Secret but I haven't found a way.
The Yelp API uses oAuth1.0a to authorize and identifiy the API caller not the end user that might be using the application. This is not like a Twitter scenario where you have to let your users login. Therefore, you dont need any access token URLs or other details. You are able to create all the necessary tokens to get started. Here is how your API console should look like once everything is setup (I've obfuscated my keys for obvious reasons) -
Now, you'll need to make the API calls from the server side using UrlFetchApp and not use the jQuery AJAX APIs as that Yelp API doesn't seem to allow CORS and JSONP is not allowed with HtmlService. Otherwise you'll get errors like this below in the console -
Lastly, here is some sample code to get you started. I based these off their JavaScript sample -
var auth = {
consumerKey: "YOURKEY",
consumerSecret: "YOURSECRET",
accessToken: "YOURTOKEN",
accessTokenSecret: "YOURTOKENSECRET",
};
var terms = 'food';
var near = 'San+Francisco';
var accessor = {
consumerSecret: auth.consumerSecret,
tokenSecret: auth.accessTokenSecret
};
var parameters = [];
parameters.push(['term', terms]);
parameters.push(['location', near]);
parameters.push(['oauth_consumer_key', auth.consumerKey]);
parameters.push(['oauth_consumer_secret', auth.consumerSecret]);
parameters.push(['oauth_token', auth.accessToken]);
var message = {
'action': 'http://api.yelp.com/v2/search',
'method': 'GET',
'parameters': parameters
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
parameterMap.oauth_signature = OAuth.percentEncode(parameterMap.oauth_signature)
var url = OAuth.addToURL(message.action,parameterMap);
var response = UrlFetchApp.fetch(url).getContentText();
var responseObject = Utilities.jsonParse(response);
//have my JSON object, do whatever we want here, like add to spreadsheets
I also added a couple of GS script files with the contents of the oAuth JS code and SHA1 JS code from the links provided (just copy paste into new files in the script editor). However, if you feel adventurous, you could also use the Utilities APIs to manually sign and encode the necessary oAuth params.
Hope this helps. I was able to get Yelp responses with all the provided samples.

Resources