php - 如何使用 Google OAuth 获取 Google 通讯录信息?

标签 php oauth

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

我该怎么做?我正在使用 php,所以如果有示例代码可以做到这一点,我将不胜感激。我似乎无法在 Google 上找到它。

请帮忙!

谢谢

最佳答案

有关访问 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 .

关于php - 如何使用 Google OAuth 获取 Google 通讯录信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1706407/

相关文章:

php - cURL 在调用 curl_exec 时挂起服务器。

php - 带有 php 支付页面的 ssl

html - 在 cookie 中存储 OAuth token 是不好的做法吗?

OAuth 和粘性 session

objective-c - 脂肪 secret API "invalid signature"

php - 通过 Javascript 传递 MySQL 查询

php - 如何在 html + php(codeIgniter) 中渲染一棵树

php - 为程序风格使用准备好的语句

azure - 为什么使用 ClientCredential 进行 AcquireToken 失败并出现 invalid_client (ACS50012)?

c# - Google Analytics .net api OAuth编译错误