我正在尝试编写一个小型PHP代码,它应该能够对Google帐户进行身份验证,然后将一个文件上传到它的Google。
这一过程应分两个步骤进行:
注意,通过使用Google客户端库,一切工作都很顺利。
我想要实现的是不使用Google,而是使用描述这里的简单身份验证步骤。
通过使用前面提到的这些身份验证步骤,我发送了一个请求:
作为交换,重定向页面应该包含"code=xxxx“参数,例如:
其中xxx是由Google加到上面提到的redirect_uri的授权代码。
问题是,谷歌返回一个错误消息,比如临时移动,还提供了一个链接“文档移动了这里”。如果我点击那个链接,那么一切都很好。
但我不希望用户干预,因为这段代码在服务器级别工作,而不是在客户端级别。
如何解决这个?请不要回答“使用谷歌客户端库!”因为我已经说过这样做会有效,但我不希望Google客户端库依赖!
我的PHP代码是:
$CLIENT_ID = '[the client ID from Google Developer Console]';
$CLIENT_SECRET = '[the client secret from Google Developer Console]';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$ch = curl_init();
if (isset($_GET['code']))
{
$url = 'https://accounts.google.com/o/oauth2/token';
$post_fields = 'code=' . $_GET['code'] . '&client_id=' . $CLIENT_ID . '&client_secret=' . $CLIENT_SECRET . '&redirect_uri='
. $REDIRECT_URI . '&grant_type=authorization_code';
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Host:accounts.google.com', 'Content-Type:application/x-www-form-urlencoded', 'Content-Length:' . strlen($post_fields))
);
}
else
{
$url = sprintf('https://accounts.google.com/o/oauth2/auth?scope=email%%20profile&redirect_uri=%s&response_type=code&client_id=%s',
$REDIRECT_URI, $CLIENT_ID
);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$error_no = curl_errno($ch);
curl_close($ch);
echo $result;
?>
发布于 2014-09-04 02:49:34
这类问题的解决方案是
还请更改此块:
...
else
{
$url = sprintf('https://accounts.google.com/o/oauth2/auth?scope=email%%20profile&redirect_uri=%s&response_type=code&client_id=%s',$REDIRECT_URI, $CLIENT_ID);
}
有了这个:
...
else
{
$url = sprintf('https://accounts.google.com/o/oauth2/auth?scope=email%%20profile&redirect_uri=%s&response_type=code&client_id=%s',$REDIRECT_URI, $CLIENT_ID);
header('Location:'.$url);
}
https://stackoverflow.com/questions/25662642
复制相似问题