【问题标题】:How to get Google Contacts information using Google OAuth?如何使用 Google OAuth 获取 Google 通讯录信息?
【发布时间】:2010-12-14 22:51:24
【问题描述】:

我是 OAuth 新手,想创建一个页面,使用 OAuth 系统从 Google 获取用户的联系人列表,这样他们就不必登录。

我该怎么做?我正在使用 php,所以如果有执行此操作的示例代码,我将不胜感激。我似乎在 Google 上找不到它。

请帮忙!

谢谢

【问题讨论】:

  • 另外,雅虎通讯录等有没有办法做到这一点?

标签: php oauth


【解决方案1】:

对于访问 Google 的一般 OAuth 原则,您可能会发现 Google's OAuth playground 非常有用(其中包括联系人)。

这是一个非常基本的示例(使用 php oauth pecl 扩展和 simplexml,它只打印出 25 个第一个联系人的姓名):

<?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.", ";
    }
}
?>

可以看到上面的代码in action here

安装(配置)oauth pecl 扩展可能很棘手,may have to check your php.ini and/or specify a requestengine

【讨论】:

  • 嗯,没有看到这实际上是一个最近回复的老问题 :)
  • 似乎有一个小错误——在获取访问令牌后,代码首先使用 SESSION vars 设置令牌,然后才分配它们。我认为它应该是相反的 - setToken 应该在分配之后进行。
  • 绝对是stasM;我错误地复制/粘贴了“$oauth->setToken($_SESSION['token'],$_SESSION['secret']);”在那里 2 次,感谢发现!
  • 嗨,futta,你能告诉我你从哪里得到 OAuth 类吗?谢谢。
【解决方案2】:

注释掉 setRequestScheme 方法调用并使用 max-results,您应该能够获得超过 25 个条目。

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

$query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full/?max-results=999999');

【讨论】:

    【解决方案3】:

    希望我的帖子对所有人都有帮助(PHP 中的 Google 联系人列表阅读器(Google OAuth)) http://anandafit.info/2011/03/08/google-contact-list-reader-in-php-google-oauth/

    【讨论】:

      【解决方案4】:

      好的。首先futtta我对pecl和梨的东西有一些问题。所以我决定坚持使用 ZEND。我很感谢你发帖,你的代码仍然帮助了我:-)....

      这是我到目前为止所得到的,从上面发布的 ibm 页面中获取了一些代码,但将其更改为使用 oauth 进入。

      <?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">
      <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>
      

      还有一些问题,对我来说它只发布 25 个结果,我似乎无法让 setmaxresults 工作...... ZEND 似乎有问题......如果有人知道解决方法,请发布。

      b

      【讨论】:

        【解决方案5】:

        你需要从Google Contacts Data APIOAuth开始,当你完成后,this应该足以作为参考。

        【讨论】:

          猜你喜欢
          • 2012-06-25
          • 1970-01-01
          • 2011-11-23
          • 1970-01-01
          • 1970-01-01
          • 2015-08-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多