我是OAuth的新手,想要创建一个页面,使用OAuth系统从Google获取用户的联系人列表,这样他们就无需登录.
我该怎么做呢?我正在使用php,所以如果有示例代码可以执行此操作,我将非常感激.我似乎无法在Google上找到它.
请帮忙!
谢谢
fut*_*tta 11
对于访问Google的一般OAuth原则,您可能会发现Google的OAuth游乐场非常有用(其中包含联系人).
这是一个非常基本的例子(使用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.", ";
}
}
?>
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看上述代码.
安装(配置)oauth pecl扩展可能很棘手,您可能需要检查php.ini和/或指定 requesttengine .