views:

684

answers:

4

I am new to OAuth, and want to create a page that gets the user's contact list from Google using the OAuth system so they don't have to login.

How do I do this? I am using php, so I would really appreciate if there is example code that does this. I can't seem to find it on Google.

Please help!

Thanks

+1  A: 

You need to start with Google Contacts Data API and OAuth, when you're done, this should be enough for a reference.

David Kuridža
+1  A: 

For general OAuth principles to access Google, you might find Google's OAuth playground very useful (contacts are included there).

this is a very basic example (using the php oauth pecl extension and simplexml, it just prints out the names of the 25 first contacts):

<?php
$cons_key="your consumer key";
$cons_sec="your consumer secret";

$callback="http://".$_SERVER[HTTP_HOST].$_SERVER[PHP_SELF];

$req_token_url="https://www.google.com/accounts/OAuthGetRequestToken";
$auth_token_url="https://www.google.com/accounts/OAuthAuthorizeToken";
$acc_token_url="https://www.google.com/accounts/OAuthGetAccessToken";

$scope="https://www.google.com/m8/feeds/";
$scopes=urlencode($scope);
$req_scope_token_url=$req_token_url."?scope=".$scopes;
$endpoint="https://www.google.com/m8/feeds/contacts/default/full/";

session_start();

if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;

try {
  $oauth = new OAuth($cons_key,$cons_sec);
  if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
        $oauth = new OAuth($cons_key,$cons_sec);
        $oauth->setRequestEngine(OAUTH_REQENGINE_CURL);
        $request_token_info = $oauth->getRequestToken($req_scope_token_url,$callback);
        if(!empty($request_token_info)) {
                $_SESSION[token]=$request_token_info[oauth_token];
                $_SESSION[secret]=$request_token_info[oauth_token_secret];
                $_SESSION[state]=1;
                header('Location: '.$auth_token_url.'?oauth_token='.$_SESSION[token]);
                exit;
        }
  } else if($_SESSION['state']==1) {
    $oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
    $access_token_info = $oauth->getAccessToken($acc_token_url);
    $_SESSION['state'] = 2;
    $_SESSION['token'] = $access_token_info['oauth_token'];
    $_SESSION['secret'] = $access_token_info['oauth_token_secret'];
  }

  $oauth->fetch($endpoint);
  parseAtom($oauth->getLastResponse());

} catch(OAuthException $E) {
  print_r($E);
}

function parseAtom($atomstring) {
  global $oauth;
  $atom=simplexml_load_string($atomstring);
  foreach ($atom->entry as $entry) {
        print $entry->title.", ";
        }
}
?>

you can see the above code in action here.

installing (configuring) the oauth pecl extension can be tricky, you may have to check your php.ini and/or specify a requestengine.

futtta
hmm, did not see this actually was an old question with a recent reply :)
futtta
there seems to be a small bug - after getting access token, the code first uses SESSION vars to set the token and only then assigns them. I think it should be in reverse - setToken should go after assignments.
StasM
+1  A: 

OK. first of all futtta i had some problems with pecl and pear stuff. so i decided to stick with ZEND. I do appreciate you posting though, your code still helped me :-)....

here is what i've got so far, taking some of the code from the ibm page posted above, but altering it to use oauth to get in.

<?php

session_start();

require_once 'common.php';
require_once 'Zend/Oauth/Consumer.php';
require_once 'Zend/Crypt/Rsa/Key/Private.php'; 

require_once 'Zend/Gdata.php';
require_once 'Zend/Gdata/Query.php';




$oauthOptions = array(
    'requestScheme'        => Zend_Oauth::REQUEST_SCHEME_HEADER,
    'version'              => '1.0',
    'consumerKey'          => 'PUT KEY HERE',
    'consumerSecret'       => 'PUT KEY HERE',
    'signatureMethod'      => 'HMAC-SHA1',
    'requestTokenUrl'      => 'https://www.google.com/accounts/OAuthGetRequestToken',
    'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
    'accessTokenUrl'       => 'https://www.google.com/accounts/OAuthGetAccessToken'
);


?>


<!DOCTYPE html 
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Listing contacts</title>
    <style>
    body {
      font-family: Verdana;      
    }
    div.name {
      color: red; 
      text-decoration: none;
      font-weight: bolder;  
    }
    div.entry {
      display: inline;
      float: left;
      width: 400px;
      height: 150px;
      border: 2px solid; 
      margin: 10px;
      padding: 5px;
    }
    td {
      vertical-align: top;
    }
    </style>    
  </head>
  <body>

     <?



 $consumer = new Zend_Oauth_Consumer($oauthOptions); 

if (!isset($_SESSION['ACCESS_TOKEN_GOOGLE'])) { 
    if (!empty($_GET)) { 
        $token = $consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN_GOOGLE'])); 
        $_SESSION['ACCESS_TOKEN_GOOGLE'] = serialize($token); 
    } else { 
        $token = $consumer->getRequestToken(array('scope'=>'http://www.google.com/m8/feeds')); 
        $_SESSION['REQUEST_TOKEN_GOOGLE'] = serialize($token); 
        $consumer->redirect(); 
        exit; 
    } 
} else { 
    $token = unserialize($_SESSION['ACCESS_TOKEN_GOOGLE']); 
    //$_SESSION['ACCESS_TOKEN_GOOGLE'] = null; 
} 



$http  = $token->getHttpClient($oauthOptions);
$gdata = new Zend_Gdata($http);
$gdata->setMajorProtocolVersion(3);

$gdata->getHttpClient()->setRequestScheme(Zend_Oauth::REQUEST_SCHEME_QUERYSTRING);


$query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full?);
//$query->setMaxResults(10);
$feed = $gdata->getFeed($query);

?>



      <h2><?php echo $feed->title; ?></h2>
      <div>
      <?php echo $feed->totalResults; ?> contact(s) found.
      </div>

      <?php
      // parse feed and extract contact information
      // into simpler objects
      $results = array();
      foreach($feed as $entry){
        $xml = simplexml_load_string($entry->getXML());
        $obj = new stdClass;
        $obj->name = (string) $entry->title;
        $obj->orgName = (string) $xml->organization->orgName; 
        $obj->orgTitle = (string) $xml->organization->orgTitle; 

        foreach ($xml->email as $e) {
          $obj->emailAddress[] = (string) $e['address'];
        }

        foreach ($xml->phoneNumber as $p) {
          $obj->phoneNumber[] = (string) $p;
        }
        foreach ($xml->website as $w) {
          $obj->website[] = (string) $w['href'];
        }

        $results[] = $obj;  
      }


    ?>

    <?php
    // display results
    foreach ($results as $r) {
    ?>
    <div class="entry">
      <div class="name"><?php echo (!empty($r->name)) ? 
       $r->name : 'Name not available'; ?></div>
      <div class="data">
        <table>
          <tr>
            <td>Organization</td>
            <td><?php echo $r->orgName; ?></td>
          </tr>
          <tr>
            <td>Email</td>
            <td><?php echo @join(', ', $r->emailAddress); ?></td>
          </tr>
          <tr>
            <td>Phone</td>
            <td><?php echo @join(', ', $r->phoneNumber); ?></td>
          </tr>
          <tr>
            <td>Web</td>
            <td><?php echo @join(', ', $r->website); ?></td>
          </tr>
        </table>
      </div>
    </div>
    <?php
    }
    ?>

  </body>
</html>

There are still some problems, for me it only posts 25 results and i cannot seem to get setmaxresults to work... there seems to be problems with ZEND for that... if someone knows a work around, please post.

b

benjaminlotan
A: 

Hi futta,

Can you show me where you got the OAuth class from?

Thanks.

webasker