如何解决OAuth 2.0中的access_token

时间:2012-03-09 14:52:50

标签: php javascript html5 google-chrome

我正在努力获取已记录的用户详细信息。  它出现在错误之后。

注意:未定义的属性:第46行的C:\ xampp \ htdocs \ google \ oauth \ validate.php中的stdClass :: $ access_token

这是我的代码:

<?php
//setting parameters
$authcode= $_GET["code"];
$clientid='my';
$clientsecret='my';
$redirecturi='https://localhost/google/oauth/validate.php';
$fields=array(
'code'=>  urlencode($authcode),
'client_id'=>  urlencode($clientid),
'client_secret'=>  urlencode($clientsecret),
'redirect_uri'=>  urlencode($redirecturi),
'grant_type'=>  urlencode('authorization_code')
);
//url-ify the data for the POST
$fields_string='';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//to trust any ssl certificates
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//extracting access_token from response string
$response= json_decode($result);
$accesstoken= $response->access_token;
//passing accesstoken to obtain contact details
 $xmlresponse=  file_get_contents('https://www.google.com/m8/feeds/contacts/default /full?oauth_token='.$accesstoken);
//reading xml using SimpleXML
$xml=  new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');
foreach ($result as $title) {
echo $title->attributes()->address . "<br><br>";
}
?>

1 个答案:

答案 0 :(得分:1)

Google APIs PHP Client有一个示例应用程序演示如何获取经过身份验证的用户的联系人列表。

示例应用程序还演示了如何通过OAuth 2.0流程并获取访问令牌。

实施例: http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/contacts/simple.php