如何使用php表单在google oauth上交换令牌的授权码

时间:2012-11-09 06:21:35

标签: php curl oauth-2.0 google-drive-api

我在几天内获得了授权码,但在尝试通过我的测试代码将其替换为访问/刷新令牌时,我总是不断收到 HTTP 400错误。我是谷歌几天,但仍然找不到解决方法。任何人都可以帮我修复它,谢谢。

<html>
<body>

<?php
$redirect_url = "http://.../callback_google.php";
$client_id=".....";
$client_secret=".....";
$code=$_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token?';
$postField = array ('grant_type=authorization_code',
                    'client_id='.urlencode($client_id),
                    'client_secret='.urlencode($client_secret),
                    'redirect_uri='.urlencode($redirect_url),
                    'code='.urlencode($code) );
$postField = implode('&', $postField);

$options = array(CURLOPT_URL => $url,
                 CURLOPT_HEADER => 1,
                 CURLOPT_RETURNTRANSFER => 1,
                 CURLOPT_USERAGENT => '',
                 CURLOPT_FOLLOWLOCATION => 1,
                 CURLOPT_VERBOSE => 1,
                 CURLOPT_POST => true,
                 CURLOPT_POSTFIELDS => http_build_query($postField) );

$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
print '<pre>' . print_r($result, true) . '</pre>';
?>

</body>
</html>

但我收到错误消息

HTTP/1.1 200 Connection established
Via: 1.1 PROXY
Connection: Keep-Alive
Proxy-Connection: Keep-Alive

HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Fri, 09 Nov 2012 06:04:44 GMT
Content-Type: application/json
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Transfer-Encoding: chunked

JSON响应是

{
  "error" : "invalid_request"
}

任何人都可以帮我解决它,谢谢。

1 个答案:

答案 0 :(得分:0)

(问题在评论中回答。转换为社区维基答案。见Question with no answers, but issue solved in the comments (or extended in chat)

OP写道:

  

此问题已修复,它是由数组和http_build_query引起的。改成:   $postField = 'grant_type=authorization_code&client_id='.urlencode($client_id). &client_secret='.urlencode($client_secret).'&redirect_uri='.urlencode($redirect_‌​url).'code='.urlencode($code);,并删除函数调用http_build_query