As discussed in Using OAuth with Authenticated Methods, using the Manage and Workroom methods requires the OAuth authentication protocol, which enables a user to grant the client application access to his or her data. To authenticate with Elance using OAuth, a Web application written in PHP must take the following steps:

  1. Install one of the publicly available OAuth libraries for PHP.
  2. Call https://api.elance.com/oauth/getRequestToken to obtain an unauthenticated Request Token from Elance.
  3. Redirect the user to the verification URL (returned by /oauth/getRequestToken). This prompts Elance to ask your application's user (known in OAuth as the resource owner) to enter his or her Elance username and password.
  4. Run the callback URL when called by Elance, which will call https://api.elance.com/oauth/getAccessToken to retrieve the authenticated access token.
  5. Call one or more Elance API methods that require authentication.

The following examples demonstrate OAuth authentication against the Elance API using the oauth-php library developed by Andy Smith. Besides handling the signing of OAuth requests, oauth-php maintains a small set of data tables called the OAuth store that records the current request and access tokens associated with a site. oauth-php contains classes that enable managing the store in server session state, or in a database system such as Oracle or MySQL. For the following examples, we will be using MySQL.

I. Step 1: Library Installation

To get started, download the oauth-php library to your Web site, and install it into a directory within your PHP installation's include path (include_path in your php.ini). Next, navigate to the library/store/mysql directory in your Web browser, and execute the install.php file to create the database table required for the OAuth store. If your php.ini is not configured to access your MySQL installation, open install.php in a text editor, and change the following lines to reflect your environment:

/*
mysql_connect('localhost', 'root');
if (mysql_errno())
{
	die(' Error '.mysql_errno().': '.mysql_error());
}
mysql_select_db('test');
*/

II. Step 2: Get Request Token

Your first PHP file will call /oauth/getRequestToken on api.elance.com to obtain the Request Token. Before we can call this method, however, we need to initialize oauth-php. First, make sure to include a PHP require_once statement for the following four PHP files:

require_once 'oauth-php/library/OAuthDiscovery.php'; 
require_once 'oauth-php/library/OAuthRequester.php'; 
require_once 'oauth-php/library/OAuthRequestVerifier.php'; 
require_once 'oauth-php/library/OAuthServer.php';

Next, add some code to initialize the OAuth store. Tell oauth-php to connect to your MySQL database with the following code:

$store_options = array('server' => '127.0.0.1', 'username' => 'root',
                 'password' => '',  'database' => 'oauth');
 
$store = OAuthStore::instance("MySQL", $store_options);

Finally, register the Elance API with OAuth. You will need to register your Consumer Key and your Consumer Secret, and tell oauth-php the URL for each OAuth method. oauth-php uses this information both to sign requests as well as to store Request Tokens and Access Tokens for the Elance API in the Store. The following code calls $store->getServer() to test if the current server is already registered, and registers it with $store->updateServer() if it isn't.

$consumer_key = '8dfc475b57fee5b7dc08cc0f1d5a0fcdab409b3d';
$user_id = 1;
 
$store = OAuthStore::instance("MySQL", $store_options);
 
$server = null; 
try {
	$server = $store->getServer($consumer_key, $user_id);
} catch (OAuthException2 $e) {
    $server = array(
        'consumer_key' => $consumer_key,
        'consumer_secret' => '2TP0meIiyjzYbZO3qaffRJHYP8zJbpDfz7emLtPMKoqFPND0f5QtTnQMkdEGjUB',
        'server_uri' => 'https://api.elance.com/',
        'signature_methods' => array('HMAC-SHA1'),
        'request_token_uri' => 'https://api.elance.com/oauth/getRequestToken',
        'authorize_uri' => 'https://api.elance.com/oauth/authorizeToken', 
        'access_token_uri' => 'https://api.elance.com/oauth/getAccessToken'
    );
 
    $store->updateServer($server, $user_id);
}

You may have noticed that oauth-php takes a numeric user identifier. This enables PHP OAuth clients to maintain different sets of application credentials (Consumer Key and Consumer Secret) if the API requires it. This is not necessary for the Elance API; you can use the same Consumer Key and Consumer Secret for any number of uses.

That's a lot of code. The good news is, we're ready to obtain our Request Token! This is simply a matter of calling the static method OAuthRequester:requestRequestToken().

$token = OAuthRequester::requestRequestToken($consumer_key, $user_id);

If the call is successful, it will return an array containing three values: token, token_secret, and authorize_uri. authorize_uri is the URI to which the user must be redirected in order to verify their credentials with Elance.

Note that you do not have to do anything with the Request Token Secret. Behind the scenes, the oauth-php library has stored both the Request Token and Request Token Secret in the OAuth store. The library will use the Request Token Secret to sign your request when you are ready to exchange your Request Token for an Access Token.

III. Step 3: Redirect User to Verification URI

Our final step in this PHP file is to perform this redirection. token is the request token granted by the successful request. The token must be appended to authorize_uri as a GET parameter. An optional parameter, oauth_callback, can also be appended to the request. For this example, oauth_callback is assumed to be a second PHP file, whose contents we will discuss in details below. The URI is sent to the user using the PHP header() method, which will cause the user's browser to redirect to the verification URI.

$callback_uri = "http://www.example.com/verify-token-callback.php";
$authorization_uri = $token['authorize_uri'] . '?oauth_token=' . $token['token'] . '&oauth_callback=' . $callback_uri;
header("Location: " . $authorization_uri);
exit();

IV. Step 4: Exchange Request Token for Token

After being redirected to Elance, the user will be asked to verify that he or she grants your application access to his or her Elance account. If that request is denied, the oauth_callback URI is not called. If it is granted, Elance calls your callback URI with three two parameters: oauth_token, the Request Token, and oauth_verifier, a verification code confirming that the user granted your application account access. Both of these values will be needed to exchange your application's Request Token for an Access Token.

Your callback PHP script should include the same require_once statements as the previous PHP file. Since the OAuth store has already been initialized for Elance, you need only load the store from the database:

$store_options = array('server' => '127.0.0.1', 'username' => 'root',
                 'password' => '',  'database' => 'oauth');
 
$store = OAuthStore::instance("MySQL", $store_options);

Your code must now call OAuthRequester::requestAccessToken() in oauth-php to exchange your Request Token for an Access Token:

$consumer_key = '8dfc475b57fee5b7dc08cc0f1d5a0fcdab409b3d';
$user_id = 1;
 
$options = array();
$options['oauth_verifier'] = $_GET['oauth_verifier'];
 
try
{
    OAuthRequester::requestAccessToken($consumer_key, $_GET['oauth_token'], $user_id, 'POST', $options);
}
catch (OAuthException $e)
{
	// Handle error
}

If OAuthRequester::requestAccessToken() does not throw an exception, then the request was successful. Elance grants your application an Access Token and an Access Token Secret, which oauth-php inserts into the OAuth store. These values will be included with and used to sign all requests you make against any authenticated methods.

V. Step 5: Call Elance Authenticated Methods

To call Elance authenticated methods with oauth-php, create an instance of the OAuthRequester class. You will need to supply the endpoint of the method you wish to call, the HTTP method to use (GET or POST), and the array of arguments required by the method. oauth-php uses the URI endpoint and the $user_id passed to the OAuth store to look up your stored credentials, including the Consumer Key, Consumer Secret, Access Token, and Access Token Secret.

The following code calls the manage/getJobList method, which returns the list of accepted jobs for the authenticated user. It passes the debug parameter in order to return pretty-printed JSON. (For an example of how to consume a JSON response in PHP, see Accessing Elance from PHP.)

<?php
 
require_once 'oauth-php/library/OAuthDiscovery.php'; 
require_once 'oauth-php/library/OAuthRequester.php'; 
require_once 'oauth-php/library/OAuthRequestVerifier.php'; 
require_once 'oauth-php/library/OAuthServer.php';
 
$store_options = array('server' => '127.0.0.1', 'username' => 'root',
                 'password' => '',  'database' => 'oauth');
 
$user_id = 1;
 
$store = OAuthStore::instance("MySQL", $store_options);
 
$options = array( 'debug' => 'true');
$manage_request = new OAuthRequester("https://api.elance.com/api/manage/getJobList", 'GET', $options);
 
$result = "";
 
try {
    $result = $manage_request->doRequest($user_id);
} catch (OAuthException $e){
    // Handle error.
}
 
/* 
The output from <span style="font-family:monospace;">doRequest()</span> is the full array of header and body values 
returned by the cUrl HTTP library. We access the JSON response using the body array key.
*/
 
echo "<pre>" . $result["body"] . "</pre>";
 
exit();
?>