Setting up Twitter API, getting the last few Tweets - javascript

I am completely new to using Twitter in general and have never embedded "latest tweets" on any project. I am simply trying to embed the 3-4 newest tweets on the site footer with no additional features of functionality. I have been researching how to do this for quite some time now and having some trouble.
I added the following code snippet to the project, which works quite well, however, I am not sure how to update the snippet so it uses my Twitter account instead of the one it is set up with.
<div id="twitter_update_list">
</div>
<script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline.json?screen_name=stackoverflow&include_rts=true&count=4&callback=twitterCallback2">
</script>
In addition, I keep reading that the most commonly used Twitter API will stop working soon because Twitter wants people to use their own, as opposed to third party.
I am not sure how to proceed from here. I would greatly appreciate any suggestions in this regard. To recap, all I am trying to do is grab the 3-4 latest tweets from my account.
many thanks in advance!

So you REALLY don't want to do this client-side anymore. (Just went through numerous docs, and devs suggest to do all oAuth server-side)
What you need to do:
First: sign up on https://dev.twitter.com, and make a new application.
Second: NOTE: Your Consumer Key / Secret along with Access Token / Secret
Third: Download Twitter OAuth Library (In this case I used the PHP Library https://github.com/abraham/twitteroauth , additional libraries located here: https://dev.twitter.com/docs/twitter-libraries)
Fourth: (If using PHP) Make sure cURL is enabled if your running on a LAMP here's the command you need:
sudo apt-get install php5-curl
Fifth: Make a new PHP file and insert the following: Thanks to Tom Elliot http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/
<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library you downloaded in step 3
$twitteruser = "twitterusername"; //user name you want to reference
$notweets = 30; //how many tweets you want to retrieve
$consumerkey = "12345"; //Noted keys from step 2
$consumersecret = "123456789"; //Noted keys from step 2
$accesstoken = "123456789"; //Noted keys from step 2
$accesstokensecret = "12345"; //Noted keys from step 2
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
echo json_encode($tweets);
echo $tweets; //testing remove for production
?>
And boom, you're done. I know this isn't a pure js solution but again reading through the new Twitter API 1.1 docs they REALLY don't want you to do this client-side. Hope this helps!

How to get last few tweets of user with core PHP functionality only (no CURL or Twitter oAuth library needed):
Register your app/webpage https://apps.twitter.com (You may need to verify your personal account mobile number too)
Note Consumer Key and Consumer Secret
PHP Code:
// auth parameters
$api_key = urlencode('REPLACEWITHAPPAPIKEY'); // Consumer Key (API Key)
$api_secret = urlencode('REPLACEWITHAPPAPISECRET'); // Consumer Secret (API Secret)
$auth_url = 'https://api.twitter.com/oauth2/token';
// what we want?
$data_username = 'Independent'; // username
$data_count = 10; // number of tweets
$data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended';
// get api access token
$api_credentials = base64_encode($api_key.':'.$api_secret);
$auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'."\r\n";
$auth_context = stream_context_create(
array(
'http' => array(
'header' => $auth_headers,
'method' => 'POST',
'content'=> http_build_query(array('grant_type' => 'client_credentials', )),
)
)
);
$auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), true);
$auth_token = $auth_response['access_token'];
// get tweets
$data_context = stream_context_create( array( 'http' => array( 'header' => 'Authorization: Bearer '.$auth_token."\r\n", ) ) );
$data = json_decode(file_get_contents($data_url.'&count='.$data_count.'&screen_name='.urlencode($data_username), 0, $data_context), true);
// result - do what you want
print('<pre>');
print_r($data);
Tested with XAMPP for Windows and Centos6 default installation (PHP 5.3)
Most probable problem with this might be that openssl is not enabled in php.ini
To fix check if extension=php_openssl.dll or extension=php_openssl.so line is present and uncommented in php.ini

Actually twitter has many restrictions, as there is lot of contest from companies like Nike and others. The reading of tweet is limited in the sense that if you are reading through the latest API its actually a bit behind time.
They have also controlled the DM delay which means you cannot DM instantly even if you do, the other party will only receive after X amount of time. If you do through script, and even if you try to DM a lot from one single ip twitter will simply BLOCK you.

Related

How to use the WP REST API with a custom endpoint using the Javascript library?

I have a custom endpoint which does nothing but return a test string. I can reach that endpoint by navigating to mydomain.com/wp-json/mytools/v1/method/get_user_data and it correctly returns my test string, but, I want to be able to reach that endpoint using Javascript, and, I read that the wp-api handles authentication automatically so I should be able to get a current logged in user with this method.
What I need is to be able to use something like wp.api.mytools.method.get_current_user and get the information for the currently logged in user. Is this even possible?
This is the way I created the endpoint:
register_rest_route( 'mytools/v1', '/method/(?P<method>[\w]+)', array(
'methods' => 'GET',
'callback' => 'invoke_method',
));
And this is the invoke_method function:
function invoke_method( WP_REST_Request $request ) {
return wp_get_current_user();
}
This functionality is already implemented by WordPress at the WP_REST endpoint '.../wp-json/wp/v2/users/me. In addition to the logged-in cookie WP REST authentication requires a nonce specified by a query argument '_wpnonce'. The value of this nonce is generated by calling wp_create_nonce( 'wp_rest' ). A normal WordPress front-end page will include the script .../wp-includes/js/api-request.js. This script will define a global wpApiSettings.nonce which will contain this nonce so you can use the request '.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce. So, you can use jQuery.get().
jQuery.get(
'.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce,
function( response ) {
var userData = JSON.parse( response );
) }
);
If you only want to get the current user I don't think you need Backbone.js. Backbone.js will synchronise collections and models using CRUD and you are not doing any of this.
Overall, yes, it IS possible.
Specifically, if wp-api if you're referring to the node-wpapi JS library, then yes it does handle authentication. Otherwise, you will need to implement Authentication yourself, using Cookie, Nonce, Basic-Auth or JWT.
For second part, it is definitely possible to use something like wp.api.mytools.method.get_current_user to get information. What you'll need is a client library (node-wpapi), and extend it to include your classes and functions, such as mytools and method.
Hope this helps to clarify

How to hide my API key between PHP and Javascript?

This is a challenge I am facing in Reactjs, though I don't believe that it is necessarily attributed to it. I am trying to make an API call in React. And while it works, the code also reveals my API key, which below is indicated by my javascript variable sting. When I preview the code in my browser, sting quite clearly shows my API key.
render: function() {
if (this.state.trial) {
return this.iftroo();
}
}
});
var Troo = React.createClass({
render: function() {
var sting = "<?php
$con = mysqli_connect('localhost', 'root', '', 'worldly') or die("Trying");
$query = "select * from testi";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)){
echo $row["userName"];}
?>";
var weather = new XMLHttpRequest();
weather.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=imperial&appid="+sting, false);
weather.send(null);
var r = JSON.parse(weather.response);
var tempurature = r.main.temp;
return (
<p>
{tempurature}
</p>
I understand that in order to get this to work, I will likely have to embed my javascript code inside my PHP. However, doing so leads to errors, such as PHP not recognizing javascript var characters.
What measures can I take to hide my API keys from the browser?
If you want to hide the API key from the browser then you must simply never give it to the browser.
You can't use the API key from client side JavaScript and keep it hidden from the client.
Make any HTTP request that needs to use it from your server (e.g. using PHP's cURL library).
You could generate one-time jwt api keys, for a special user, with expiration time, and what ever information assigned it.
edit
OK, now I see, that the api key is for an external service. Don't know how the policy for the weather service is, but.. I think this is not the right way to go, you should make this request on the server.

Concern with Facebook's login decoding sign_request performance

I am completely new to the Facebook API. I would like to incorporate Facebook login into my application. I am using the Javascript SDK on the front-end to log the user in and retrieve the user_id and signed_request from Facebook. I then plan to send these two pieces of information via AJAX to my server (either php/hack (hhvm), node, java, or whichever language I can determine is quickest for decoding) every time my logged in user does an action on my application to validate if the user is indeed logged in and is the person they say they are. For me to accomplish this, I need to decode the signed_request, for example in php:
function parse_signed_request($signed_request) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$secret = "appsecret"; // Use your app secret here
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
// confirm the signature
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
which then I will be able to extract the following JSON object:
{
"oauth_token": "{user-access-token}",
"algorithm": "HMAC-SHA256",
"expires": 1291840400,
"issued_at": 1291836800,
"user_id": "218471"
}
to be able to compare if the user_id the user sent over matches the one in the JSON object. Then if it matches I can complete my business logic (DB manipulation).
My big concern here is a user will be sending many requests to my server, so every time I will need to decode this signed_request which can really kill my server performance. I was thinking I maybe could call Facebook from my server, pass the user_id, and receive the signed_request string, which I can then match with the signed_request string the user sent over from the client_side and see if they match. This would be more efficient, but it does not seem Facebook offers anything like this. Is there any other methods besides the heavy performing decoding to validate a user? I have gone through quite a bit of the Facebook SDK's information but could not find a solution. If I must decode, which language/library would be the best performing at this type of operation?
PS. I plan on using cordova later to create a mobile app so I must use only Javascript on the front end and can't use a server language such as php to create html for the client.
Decoding the signed request will not kill your server. It's way fast than making an external request.
If you're using php you should look into the Facebook SDK for PHP and use this helper: https://developers.facebook.com/docs/php/FacebookJavaScriptLoginHelper/4.0.0

How to get your website visitors to follow twitter accounts from your website

I am new on this forum, so accept my apologies if my question is inappropriate or is not clear enough.
I have a website where Twitter users are listed having follow button against each user, but when visitor click on 'follow' button then that user get followed from my Twitter account (which have app that is being used for authentication) instead of visitors account. so basically i want these accounts to be followed by visitors twitter account not mine.
when user clicks on follow button an ajax call is made to send username to page where following code runs to get that user followed.
<?php
ini_set('display_errors', 1);
require_once('lib/TwitterAPIExchange.php');
$uname=$_REQUEST['name'];
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "XXXXXX-XXXXXXXXXX",
'oauth_access_token_secret' => "XXXXXXXXXX",
'consumer_key' => "XXXXXXXXXX",
'consumer_secret' => "XXXXXXXXXX"
);
// Choose the url you want from the docs, this is the users/show
$url = 'https://api.twitter.com/1.1/friendships/create.json';
// The request method, according to the docs, is GET, not POST
$requestMethod = 'POST';
$varl=$uname;
// Set up your get string, we're using my screen name here
//$getfield = '?screen_name='.$varl;
$postfields = array(
'screen_name' => $varl
);
// Create the object
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
TwitterAPIExchange.php is php wrapper for twitter api request should i share that too ? Thanks in advance if anyone can help.
Don't do that from the server side. It's not necessary or appropriate.
Use Twitter web intents for this. They allow users of your site to perform a variety of actions using their logged-in Twitter account, including posting statuses, retweeting statuses, and following other Twitter users.

Facebook php api in Ajax facebox

I'm trying to load some php fql calls in to an ajax facebox (its like lightbox), i include a file with the following code in, but it does not work without the redirect ($my_url), is there any way to make the code ignore the redirect? Or do i need to use the javascript sdk from facebook?
$app_id = 'APP ID';
$app_secret = 'APP SECRET';
$my_url = 'LINK HERE';
$code = $_REQUEST["code"];
$bruger = "me()";
//auth user
if(empty($code)) {
$dialog_url = 'https://www.facebook.com/dialog/oauth?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url) ;
echo("<script>top.location.href='" . $dialog_url . "'</script>");
}
$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url)
. '&client_secret=' . $app_secret
. '&code=' . $code;
// response is of the format "access_token=AAAC..."
$access_token = substr(file_get_contents($token_url), 13);
Have you tried using the Facebook PHP SDK? I highly recommend moving away from depreciated FQL as once you get to grips with the new API it is very easy to use
Once you have set up $facebook you can then just make API calls with $facebook->api('/query');
I'm not 100% sure what information you are trying to retrieve from your question however but I have put together a Lightbox / Facebook myself, even using tag data to pick people out of the picture so feel free to provide more detail and I will try to provide a more comprehensive answer
EDIT:
In order to build queries and test data returned you can use the Graph API Explorer and construct the query you want to test against your own Facebook Application
I'm trying to fetch friendlist
After you've setup $facebook then you can retrieve your friends by using
$fb_friends = $facebook->api("/me?fields=friends");
Next:
50 latest tagged photos and likes
To retrieve the latest 50 tagged photos and likes you'll need to do:
$fb_photos = $facebook->api("/me?fields=photos.limit(50)");
$fb_likes = $facebook->api("/me?fields=likes.limit(50)");
// I should mention that each time api() is called, the server makes a HTTPS request to Facebook, so it is worth condensing api queries to reduce load time:
$fb_data = $facebook->api("/me?fields=photos.limit(50),likes.limit(50)");
$fb_photos = $fb_data['photos'];
$fb_likes = $fb_data['likes'];
If you want the latest 50 of photos and likes chronologically sorted, you can array_merge() the two arrays and use a subval sort function for created_time, then just take the first 50.
I'm going to insert all the basic info into mysql (stuff like name, facebook id, email ect.) I'm going to use the fb id inserted into myslq, to view the friendlist, likes and photos
Right then, when you user logs on you will need to request extended permissions from them to access data like photos, likes and friends. When your user logs into facebook with the link you provide to them on your website, you need to call
$loginUrl = $facebook->getLoginUrl(array( 'scope' => 'read_stream,user_likes,user_photos,friends_photos,user_friends'));`
The scope is defined by the permissions stated here
Once you have been granted access to that information by the user you can retrieve profile information with $user = $facebook->api("/me"); and store the facebook ID, name etc in your database.
To get a better look at the data you'll be handing for photos then make sure that you click Get access token at the top of the page and grant permission to access photos and likes
Any more questions feel free to ask and I will provide more detail, hope that helps mate!

Categories

Resources