Sep 292014
 
Article PHP

Our previous post on “How to connect to Twitter from a single user application in PHP” explained the procedure to connect to Twitter from a PHP script.

This post explains how to create a sample multiuser application “OpenAlfa Tweet Scheduler” that can send tweets on behalf of the users.

Installation

The first step is connecting to https://dev.twitter.com/apps, to register in Twitter the application “OpenAlfa Tweet Scheduler” to be developed:

create-app

After the application has been created, go to the “Settings” tab to configure:

  • “Read and Write” access (because it is meant to send tweets)
  • Allow the application to be used to Sign in with Twitter (because the application needs to authenticate with the credentials of the user in order to send tweets)

configurar-multiusuario

Returning to the “Details” tab, write down the “Consumer Key” and “Consumer secret” assigned to the application.

Finally, the “twitteroauth” library must be installed, as explained in our previous post.

Setting up the configuration file

Under the directory where we want to place the application, create a configuration file “config.php”, with the definitions of the consumer key and consumer secret assigned by Twitter, and the callback url in our site.

Example:

<?php
define('CONSUMER_KEY', 'WRITE_HERE_THE_CONSUMER_KEY');
define('CONSUMER_SECRET', 'WRITE_HERE_THE_CONSUMER_SECRET');
define('OAUTH_CALLBACK', 'http://tools.openalfa.com/twitter/scheduler/cb.php');

Writing a page to sign in with Twitter

Create a “connect.php” page. This page should include some text about the purpose of the service, and a button that will send the user to Twitter, to authenticate and grant access to the application.

Example

    <h2>OpenAlfa Tweet Scheduler.</h2>
    <a href="./redirect.php">
      <img src="./images/lighter.png" alt="Connect to Twitter"/>
    </a>

The HTML code above renders the following screen:

tweet-scheduler-connectClicking on the button loads the next script “redirect.php”. As the script name indicates, redirect.php is responsible to redirect the browser to the twitter authorization page.

The scripts starts by loading the twitteroauth library, and then sends to twitter a request for temporary credentials.

<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

/* Create the connection to Twitter */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

/* Request the temporary credentials */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);

/* Store the credentials retrieved in the session */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

Twitter sends a pair of temporary credentials (token+secret), that will be used to create the authorization url sent to the browser.

The temporary credentials are stored in the session to be used in the next step.

Note: The generated url is:

https://api.twitter.com/oauth/authenticate?oauth_token=REQUEST_TOKEN_RETRIEVED_FROM_TWITTER

Finally, the browser is redirected to twitter:

switch ($connection->http_code) {
  case 200:
    /* Build the authorization url and redirect to Twitter. */
    $url = $connection->getAuthorizeURL($token);
    header('Location: ' . $url);
    break;
  default:
    /* An error has happened. */
    echo 'Error connecting to Twitter.';
    echo "\nHTTP CODE: " . $connection->http_code;
}

The page displayed asks the user to grant access to the application:

twitter-authorize

In this page, twitter informs the user about the name of the application requesting access (“OpenAlfa Tweet Scheduler”), and the permissions that will be granted to it. In the example above, the aplication will be able to send tweets on behalf of the user, but won’t be granted access to the user’s direct messages, and won’t be able to see the user’s password.

If the user validates entering the username and password and clicking on the “Sign in” button, twitter will redirect to the callback url (“cb.php”) specified.

The callback script “cb.php” starts by sending a request to twitter to obtain permanent access credentials. The request must be signed with the temporary credentials, that had been previously saved in session:

<?php

session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

/* Create a TwitteroAuth object with the applications credentials an the temporary token */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
               $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

/* Request a permanent access token */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);

/* Save the token in session. Usually, this token is saved also in a database 
   to be re-used in the future. */
$_SESSION['access_token'] = $access_token;

/* Delete the temporary request token */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);

/* Redirect the user to the main page of the service ("index.php") */
if (200 == $connection->http_code) {
  /* The user has been verified and has granted access */
  $_SESSION['status'] = 'verified';
  header('Location: ./index.php');
} else {
  header('Location: ./clearsessions.php');
}

With the permanent credentials, the application can use the Twitter API to perform operations on behalf of the user, such as sending a tweet.

The following example sends a test tweet:

function send_tweet($access_token) {
    $tweet = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
                 $access_token['oauth_token'], $access_token['oauth_token_secret']);
    $message = "This is a test message.";
    $tweet->post('statuses/update', array('status' => "$message"));
}

Index of posts about programming in PHP

 Posted by at 7:35 pm

 Leave a Reply

(required)

(required)