Twitter crossposter with OAuth

Recently (seems in august of 2010) Twitter was changed, and now it doesn’t support basic authentication (as usual via CURL), all authentication is done via OAuth.В  In this article I made tutorial how to create crossposter to Twitter (using Twitter OAuth).

Step 1. HTML

As usual, we start with the HTML.

I prepared several templates which we will use. First template for guests only.

templates/twitter_login.html

HTML
<h3>Hell Guest, <a href="tw_login.php">Login to Twitter</a></h3>

Next template – post form for logged members.

templates/twitter_post.html

HTML
<h3>Hello @__twitter_name__</h3>
<hr />
<form method="post">
    <table>
        <tr>
            <td valign="top">What`s happening?</td>
            <td><textarea name="message" rows="4" cols="75" class="input_area"></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><small>(Twitter will trucate your tweet if your tweet size exceed 140 characters limit.)</small></td>
        </tr>
        <tr>
            <td></td><td><input type="submit" name="post" value="Tweet" /></td>
        </tr>
    </table>
</form>

And last one – nice twitter widget which allow us to see posts of members. We will use it to see out posts.

templates/twitter_widget.html

HTML
<img src="https://dev-school.net/logo-tuts.png" alt="logo">

<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: 10,
  interval: 6000,
  width: 'auto',
  height: 300,
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#000000',
      color: '#ffffff',
      links: '#4aed05'
    }
  },
  features: {
    scrollbar: true,
    loop: false,
    live: false,
    hashtags: true,
    timestamp: true,
    avatars: true,
    behavior: 'all'
  }
}).render().setUser('__twitter_name__').start();
</script>

Step 2. SQL

We will need to execute next SQL in our database. In this case we will storing oauth info of members.

SQL
CREATE TABLE `atwitter_oauth_users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `oauth_provider` varchar(10),
    `oauth_uid` text,
    `oauth_token` text,
    `oauth_secret` text,
    `username` text,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Step 3. PHP

Now is most interested, functional itself

Used libraries I put to ‘inc’ folder, this is OAuth.php and twitteroauth.php files. I don`t will include source code of these libraries in this article, here are many code, both libraries located in our package.

Our first file – just config file, containing Twitter consumer Key and Secret plus database details

Important, you will need to register your own application and obtain Twitter consumer key and secret code at http://dev.twitter.com/apps/new

During registering you will need point to callback url (http://www.yoursite.com/tw_login.php), also select ‘Read & Write’ to allow posting to your twitter, next fields like application URL can be like http://www.yoursite.com/

Here are my result with these settings:
settings

inc/header.php

PHP
$sConsumerKey    = 'YOUR_TWITTER_CONSUMER_KEY';
$sConsumerSecret = 'YOUR_TWITTER_CONSUMER_SECRET';

$sDbName = 'YOUR_DATABASE_NAME';
$sDbUserName = 'YOUR_DATABASE_USERNAME';
$sDbUserPass = 'YOUR_DATABASE_USER_PASS';

Next file – our main file. This file will draw ‘Hello guest’ for guests, and when we logged it it will show our posts from Twitter plus form where we can Tweet out thoughts. Hope that code very understandable

index.php

PHP
// set error reporting level
if (version_compare(phpversion(), "5.3.0", ">=") == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);

require_once('inc/header.php');

session_start();

echo '<link rel="stylesheet" href="templates/css/main.css" type="text/css" />';

// cross posting
if($_POST['post']) {
    $sPostingRes = "<h3><div class='success'>Your tweet not posted to Twitter (error happen)</div></h3>";

    $bPostRes = performTwitterPost($_POST['message']);

    if ($bPostRes) {
        $sPostingRes = "<h3><div class='success'>Your tweet has posted to Twitter</div></h3>";
    }
    echo $sPostingRes;
}

if ($_SESSION['oauth_username'] != '') {

    $aTmplWidgValues = array(
        '__twitter_name__' => $_SESSION['oauth_username']
    );
    $sFileWidgContent = file_get_contents('templates/twitter_widget.html');
    $aWidgKeys = array_keys($aTmplWidgValues);
    $aWidgValues = array_values($aTmplWidgValues);
    echo str_replace($aWidgKeys, $aWidgValues, $sFileWidgContent); // draw widget

    $aTmplFormValues = array(
        '__twitter_name__' => $_SESSION['oauth_username']
    );
    $aFormKeys = array_keys($aTmplFormValues);
    $sFileFormContent = file_get_contents('templates/twitter_post.html');
    $aFormValues = array_values($aTmplFormValues);
    echo str_replace($aFormKeys, $aFormValues, $sFileFormContent); // draw posting form

} else {
    require_once('templates/twitter_login.html'); // draw login
}

function performTwitterPost($sMessage) {
    global $sConsumerKey, $sConsumerSecret;

    require_once('inc/twitteroauth.php');
    $oTweet = new TwitterOAuth($sConsumerKey, $sConsumerSecret, $_SESSION['oauth_token'], $_SESSION['oauth_secret']);
    $oTweet->post('statuses/update', array('status' => $sMessage));
    return true;
}

Next two files we will using for authentication of members using TwitterOAuth

tw_login.php

PHP
require_once('inc/header.php');
require_once('inc/twitteroauth.php');

global $sConsumerKey, $sConsumerSecret;

session_start();

$oTwitterOauth = new TwitterOAuth($sConsumerKey, $sConsumerSecret);
$aRequestToken = $oTwitterOauth->getRequestToken('http://www.yoursite.com/tw_oauth.php'); // getting authentication tokens

// saving token params into the session
$_SESSION['oauth_token'] = $aRequestToken['oauth_token'];
$_SESSION['oauth_token_secret'] = $aRequestToken['oauth_token_secret'];

if($oTwitterOauth->http_code==200) { // in case of success
    $sUrl = $oTwitterOauth->getAuthorizeURL($aRequestToken['oauth_token']); // generate authorization url
    header('Location: '. $sUrl); // redirecting
} else {
    die('Error happened due authorization');
}
PHP
require_once('inc/header.php');
require_once('inc/twitteroauth.php');

global $sConsumerKey, $sConsumerSecret;

session_start();

if (! empty($_GET['oauth_verifier']) && ! empty($_SESSION['oauth_token']) && ! empty($_SESSION['oauth_token_secret'])) {
} else { // some params missed, back to login page
    header('Location: http://www.yoursite.com/tw_login.php');
}

$oTwitterOauth = new TwitterOAuth($sConsumerKey, $sConsumerSecret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

$aAccessToken = $oTwitterOauth->getAccessToken($_GET['oauth_verifier']); // get access tokens

$_SESSION['access_token'] = $aAccessToken; // saving access token to sessions

$oUserInfo = $oTwitterOauth->get('account/verify_credentials'); // get account details

if(isset($oUserInfo->error)){
    header('Location: http://www.yoursite.com/tw_login.php'); // in case of any errors - back to login page
} else {

    global $sDbName, $sDbUserName, $sDbUserPass;
    $vLink = mysql_connect('localhost', $sDbUserName, $sDbUserPass);
    mysql_select_db($sDbName);

    $vOAuth1 = mysql_query("SELECT * FROM `atwitter_oauth_users` WHERE `oauth_provider` = 'twitter' AND `oauth_uid` = '{$oUserInfo->id}'"); // searching for user in database
    $aOauthUserInfo = mysql_fetch_array($vOAuth1);

    if (empty($aOauthUserInfo)) { // if user info not present - add them into database
        mysql_query("INSERT INTO `atwitter_oauth_users` (`oauth_provider`, `oauth_uid`, `username`, `oauth_token`, `oauth_secret`) VALUES ('twitter', {$oUserInfo->id}, '{$oUserInfo->screen_name}', '{$aAccessToken['oauth_token']}', '{$aAccessToken['oauth_token_secret']}')");
        $vOAuth2 = mysql_query("SELECT * FROM `atwitter_oauth_users` WHERE `id` = '" . mysql_insert_id() . "'");
        $aOauthUserInfo = mysql_fetch_array($vOAuth2);
    } else {
        mysql_query("UPDATE `atwitter_oauth_users` SET `oauth_token` = '{$aAccessToken['oauth_token']}', `oauth_secret` = '{$aAccessToken['oauth_token_secret']}' WHERE `oauth_provider` = 'twitter' AND `oauth_uid` = '{$oUserInfo->id}'"); // update tokens
    }

    $_SESSION['oauth_id'] = $aOauthUserInfo['id'];
    $_SESSION['oauth_username'] = $aOauthUserInfo['username'];
    $_SESSION['oauth_uid'] = $aOauthUserInfo['oauth_uid'];
    $_SESSION['oauth_provider'] = $aOauthUserInfo['oauth_provider'];
    $_SESSION['oauth_token'] = $aOauthUserInfo['oauth_token'];
    $_SESSION['oauth_secret'] = $aOauthUserInfo['oauth_secret'];

    mysql_close($vLink);

    header('Location: http://www.yoursite.com/index.php');
}

if(!empty($_SESSION['oauth_username'])){
    header('Location: http://www.yoursite.com/index.php'); // already logged, back to our main page
}

Make attention, that in my article I used ‘http://www.yoursite.com/’, of course you will need apply your own URL

 

Conclusion

Today we learn not very easy lesson, but very useful. Now we will able to implement this tool into our projects to make it more friendly with another networks like Twitter. Good luck!