微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何使用Google OAuth获取Google联系人信息?

我是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.

原文地址:https://www.jb51.cc/php/131699.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐