我使用谷歌的oauth访问用户数据,这是我的功能。
public function actionOauth2callback(){
$client_key = 'client-key-here';
$client_secret = 'client-secret-here';
$api_key = 'api-key';
$redirect_uri = 'http://localhost:8888/proj/user/oauth2callback';
if (!isset($_REQUEST['code']) && !isset($_SESSION['access_token'])) {
// Print the below message, if the code is not received !
echo "Please Authorize your account: <br />";
echo '<a href = "https://accounts.google.com/o/oauth2/auth?client_id='. $client_key. '&redirect_uri='.$redirect_uri .'&scope=https://www.googleapis.com/auth/plus.me&response_type=code">Click Here to Authorize</a>';
}
else {
if(!isset($_SESSION['access_token'])) {
// Initialize a cURL session
$ch = curl_init();
// Set the cURL URL
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
// The HTTP METHOD is set to POST
curl_setopt($ch, CURLOPT_POST, TRUE);
// This option is set to TRUE so that the response
// doesnot get printed and is stored directly in
// the variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// The POST variables which need to be sent along with the HTTP request
curl_setopt($ch, CURLOPT_POSTFIELDS, "code=" . $_REQUEST['code'] . "&client_id=" . $client_key . "&client_secret=" . $client_secret . "&redirect_uri=".$redirect_uri."&grant_type=authorization_code");
// Execute the cURL request
$data = curl_exec($ch);
// Close the cURL connection
curl_close($ch);
// Decode the JSON request and remove the access token from it
$data = json_decode($data);
$access_token = $data->access_token;
// Set the session access token
$_SESSION['access_token'] = $data->access_token;
}
else {
// If session access token is set
$access_token = $_SESSION['access_token'];
}
// Initialize another cURL session
$ch = curl_init();
// Set all the options and execute the session
curl_setopt($ch, CURLOPT_URL, "https://gdata.youtube.com/feeds/api/users/default?v=2&access_token=" . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
curl_close($ch);
// Get the data from the JSON response
print_r($data);
$data = json_decode($data);
print_r($data);
}
但是我的数据响应格式有问题,它不是JSON或XML,只是string
这样
tag:youtube.com,2008:user:JNbz_VZ2LG1WD4zjKEY9uQ2010-06-02T13:11:26.000Z2012-09-29T20:32:13.000ZHuyTranHoanghttps://gdata.youtube.com/feeds/api/users/chenhuanghuiJNbz_VZ2LG1WD4zjKEY9uQ22HuymTran HoangVNJNbz_VZ2LG1WD4zjKEY9uQchenhuanghui
任何人都可以告诉我,我有什么不对?
非常感谢你
答案 0 :(得分:1)
所有Google数据API都支持使用JSON
参数输出alt
,您需要查看Developer's Guide: JSON / JavaScript
您的网址应如下所示
http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json