PHP: OAuth Sample Code

The following code uses the OAuth Client library found here: (http://code.google.com/p/oauth-php/) -- but any library will work.

/**
   * testapiAction
   * The following code tests the OAUTH authentication method of our API.
   * It uses the OAUTH clientside library -- but any oauth library would work.
   * Much of this code will be handled by your library -- but we're spelling everything out here.
   * the most important pieces of information are: consumer key, secret, the end_point URLS and the callback url.  (and the URL of the API too)
   * @author Christian
   */
  public function testapiAction()
  {
  	
  	//The following codes are the consumer key and secret
  	//every application that uses our api will need one of these and you can register one at http://appv3.sgizmo.com/Account/restful-register (in an account)
    $key = 'put your key here'; // this is your consumer key
    $secret = 'put your secret here'; // this is your secret

    //This is the main "head" of the api -- all oauth calls go through the API.
    $host = 'http://api.alchemer.com/head';
    
    //This is the URL that we use to request a new access token
    $request_token = $host .'/oauth/request_token';
    
    //After getting an access token we'll want to have the user authenicate 
    $authorize_url = $host .'/oauth/authenticate';
    
    //this final call fetches an access token.
    $access_token = $host .'/oauth/access_token';
    
    
    //CREATE an OAUTH SESSION
    $options = array
    (
      'consumer_key' => $key,
      'consumer_secret' => $secret,
      'request_token_uri' => $request_token,
      'authorize_uri' => $authorize_url,
      'access_token_uri' => $access_token
    );

    //create the acctual session (this is where perminant tokens would be loaded in real code... but just testign here)
    OAuthStore::instance("Session", $options);

    
    try
    {
     
      // Okie dokie, let's see if we are already in the process of getting a token or not
      if (empty($_GET["oauth_token"]))
      { // nope, no token -- so let's start by requesting an access token from the alchemer api
      	
        $getAuthTokenParams = array('xoauth_displayname' => 'Christian Vaneks Groovy Test', //this is the name of the application asking for Approval. It will be shown on the approval page
                'oauth_callback' => 'http://beta.sgizmo.com/Widget/testapi');  // this is the call back to my application (this test code)

        //Request a Request Token - this is done totally server-to-server
        $tokenResultParams = OAuthRequester::requestRequestToken($key, 0, $getAuthTokenParams);

        //Okie dokie, now let's authorize (this requires a redirect) -- when we come back we'll be in the next part of this IF statement
        header("Location: " . $authorize_url . "?oauth_token=" . $tokenResultParams['token']);
      }
      else 
      {
      	
        //We have a request token that's been authorized at this point (assuming the login and the "approve" button was pressed successfully)
        $oauthToken = $_GET["oauth_token"];
        
        //Let's load the auth token from the GET parameter
        $tokenResultParams = $_GET;
        
        try {
        	//the next step is to ask for an access token (which actually lets us grab data).
            OAuthRequester::requestAccessToken($key, $oauthToken, 0, 'POST', $_GET);
        }
        catch (OAuthException2 $e)
        {
        	echo "Errors occured" . $e;
        	//if an error occurs here it's likely the result of a signature verification problem.  It might also be be-becuase the request token expired (unlikely for us) 
            return;
        }

		
        //WE HAVE ACCESS!!!
        //Yes, at this point the token has been flagged as authorized and turned into an access token - ready to make calls.
        
        //so let's make a simple call to get the user list from the API for this account 
        $request = new OAuthRequester("http://api.alchemer.com/head/AccountUser.debug", 'GET', $tokenResultParams);
        
        //making request...
        $result = $request->doRequest(0);
        
        //Request has been made!  Let's display the results
        if ($result['code'] == 200) // codes in the 200s mean success. 
        {
          //print out the token information (just for fun)
          echo '

Token Result

'; print_r($tokenResultParams); //this is the entire $result array returned from the OAuthClient library echo '

Result

'; print_r($result); //this is likely what we are interested in -- the body of the response from the other server echo '

Body

'; print_r($result['body']); } else { //if we didn't get 200 back it's an error echo 'Error'; } } } catch(OAuthException2 $e) { //general error catching. sure hope we don't need it! echo "OAuthException: " . $e->getMessage(); } exit; }