Twitter Widget Not Working? Twitter Updates to API Version 1.1

Posted By: on June 27th, 2013
Filed Under: Technology, Web Dev

If you are using a third-party/custom Twitter widget or plugin for your website that does not require authentication, chances are that it has stopped displaying tweets and could also be producing the following error message:

 {"errors": [{"message": "The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}

Previously, retrieving a user timeline status only involved making a simple request to the API through a query string:

<?php

$json = file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=YOUR_SCREEN_NAME&count=1", true);
$decode = json_decode($json, true);
$decode = reset($decode);
$text = $decode['text'];

echo $text;

?>

The aforementioned error notification comes as a result of the changes that were introduced to the Twitter API with the implementation of Version 1.1. The new version was initially announced in June of 2012 and outlined in greater detail on August 16, 2012. As of June 11, 2013, Version 1.0 has been officially retired.

Where do I go from here?

Great question! If you are using an existing third-party plugin or widget that is maintained, check for an update and follow the instructions to authenticate with Twitter for use on your website. If you are using a custom application (especially one that makes use of the ‘GET statuses/user_timeline’ API request), explore some options for updating or modifying your existing application to work within the new authentication requirements. Here are a couple methods that may provide a workable solution for your needs.

Method 1: Authenticate & Use ‘GET statuses/user_timeline’ API Request

Step 1: Create/Login to Your Twitter Developer Account

You can register for a developer account and login here.

Step 2: Create an Application

Select ‘My Applications’ from your login drop-down menu. Click on ‘Create a new application’, and fill in the required details to set up a new application.

TopDraw-Twitter_Developer

Step 3: Create Access Tokens for OAuth Requests

Create OAuth access tokens to use in your application for signing requests on your behalf.

TopDraw-Twitter_Developer-Application

Step 4: Write the Code to Make Requests via the API

Make note of your application access tokens.

TopDraw-Twitter_Developer-OAuth

The following example is a working PHP solution that retrieves the latest status from an authenticated user timeline, outputs the text of the retrieved tweet and parses/links any ‘@’ mentions, hashtags and links.

<?php

$consumer_key = 'YOUR_CONSUMER_KEY';
$consumer_secret = 'YOUR_CONSUMER_SECRET';
$access_token = 'YOUR_ACCESS_TOKEN';
$access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET';

$request_method = 'GET';
$path = 'api.twitter.com/1.1/statuses/user_timeline.json'; // the host and call path for the API request

$query = array( // arguments for the request query, a comprehensive list of args may be found at https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
    'screen_name' => 'YOUR_ACCOUNT_SCREEN_NAME',
    'count' => '1', // change to suit the number of status items you would like to be returned
    'exclude_replies' => true,
    'include_rts' => false
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $access_token,
    'oauth_nonce' => (string)mt_rand(),
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

// the values in the arrays must be encoded before merging and sorting
$oauth = array_map("rawurlencode", $oauth);
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query);
asort($arr); // sort and maintain element association
ksort($arr); // sort by array key

$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$path";
$base_string = $request_method."&".rawurlencode($url)."&".rawurlencode($querystring);

// build and encode the authentication key
$key = rawurlencode($consumer_secret)."&".rawurlencode($access_token_secret);
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// append the request query arguments
$url .= "?".http_build_query($query);
//$url = str_replace("&amp;","&",$url); //include this line if you encounter parsing errors, thanks to http://stackoverflow.com/ user @Frewuill for the fix

$oauth['oauth_signature'] = $signature;
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

$options = array( CURLOPT_HTTPHEADER =>
                  array("Authorization: $auth"),
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false
);

$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$decode = json_decode($json);


/*** basic formatting for output of one retrieved user timeline status, modification of this code will be necessary to display more than one retrieved user status ***/

$text = preg_replace( // parses for URL links in the text of the tweet
    '@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@',
     '<a href="$1">$1</a>',
    $decode['text']);
$text = preg_replace( // parses for '@' mentions
    '/@(\w+)/',
    '<a href="http://twitter.com/$1">@$1</a>',
    $text);
$text = preg_replace( // parses for hashtags
    '/(?:^|\s)+#(\w+)/',
    ' <a href="http://search.twitter.com/search?q=%23$1">#$1</a>',
    $text);

?>

<div id="tweet-news">
  <div class="head"><h3>TWITTER USERNAME</h3><a href="https://twitter.com/USERNAME">@USERNAME</a></div>
  <p><?php echo $text; ?></p>
</div>

Ensure that when outputting and formatting the data returned from the request that you are adhering to the display requirements of the API.

Method 2: Use Twitter Embeddable Timelines

This is not the most optimal solution in many cases: reliant on JavaScript… difficult to customize… design doesn’t match… the list goes on. However, they are: easy to set up, easy to use, and require very little or no coding!

For the purposes of most of my sites, there are enough options included with the embeddable timelines to form a decent solution that adheres to Twitter’s Terms of Service and display requirements, while also bypassing the set up and coding that are required when developing an application that uses OAuth.

Step 1: Login to Your Twitter Account & Create Widget

Select ‘Settings’ from your profile drop-down menu. Navigate to ‘Widgets’ in the left-side settings menu. Click on ‘Create new’ in the ‘Widget’ tab.

TopDraw-Twitter-Widget

Step 2: Choose Your Settings

Enter the settings for the formatting of your widget under the ‘Configuration’ section of ‘Create a user widget’.

Step 3: Copy the Code

Copy and paste the generated code into the HTML of your website.

TopDraw-Twitter-Widget_Settings_Code

Step 4: Add Custom Configuration

Don’t like the header, footer or background of the widget? No problem. Add this code to the <a> tag of the embed code:

data-chrome="noheader nofooter transparent"

Want to limit the number of tweets that are retrieved by the embedded timeline?

data-tweet-limit="5"

Want to modify the link colour, borders, language and more? View a full list of client side options here.


Due diligence is necessary when developing using Twitter’s API, with consideration for their developer rules of the road, display requirements and terms of service.


Find us on Google+

Peter Wegren
Peter graduated from the Digital Media and IT program at NAIT in the spring of 2013, and is working as one of our web developers. He is an active member of the web and tech communities in Edmonton. He attends events such as Nerds Night Out, and helps with the planning and organization of SMBYEG (Social Media Breakfast Edmonton).