谷歌OAuth 2 - redirect_uri_mismatch错误,但API设置中的重定向URI是正确的。

3
我一直在遵循 https://developers.google.com/+/web/signin/server-side-flow 的指引,直到我收到授权码发送到我的服务器。然后在 PHP 中,我尝试使用以下代码获取访问令牌:
    $data = "code=".urlencode(trim($access_code)).
    "&grant_type=authorization_code".
    "&client_id=".urlencode($this->client_id).
    "&client_secret=".urlencode($this->client_secret).
    "&redirect_uri=".urlencode(trim($redirect_uri));

    $curl = curl_init("https://accounts.google.com/o/oauth2/token");
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $result = json_decode(curl_exec($curl), true); 
    curl_close($curl);
    return $result;

在PHP中,redirect_uri与Google开发控制台中的redirect uris完全相同,但调用始终返回:

array(1) { ["error"]=> string(21) "redirect_uri_mismatch" }

我做错了什么?

供参考,这是我的 Google API 设置:

http://such-nom.com
http://www.such-nom.com

并且变量作为$redirect_uri传递:

$redir = 'http://such-nom.com';

编辑:似乎当请求令牌是通过服务器端生成而不是通过谷歌按钮生成时,完全相同的PHP代码可以正常工作。

你应该正确地对作为参数放入另一个URL中的值进行URL编码(或使用http_build_query)-否则可能会产生问题,特别是如果这些值包含具有特殊含义的字符,如& - CBroe
添加了URL编码,结果与之前相同。 - user2145184
1个回答

3
原来问题出在添加斜杠并等待几个小时上。因此,完整的URL列表如下:
http://such-nom.com
http://www.such-nom.com
http://such-nom.com/
http://www.such-nom.com/

谢谢你。我有一种感觉,你刚刚为我节省了几个小时 :) - tonyedwardspz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接