无法使用验证码获取Google API访问令牌 - 重定向uri不匹配

时间:2017-09-13 21:32:12

标签: php google-drive-api google-api-php-client

我正在尝试使用Google API PHP客户端库在用户云端硬盘空间中创建一个文件夹。不幸的是,我一直收到“redirect_uri_mistmatch Bad Request”错误。

我看了几篇试图解决这个问题的帖子都无济于事。我已经采取的步骤,

  • 已验证的网址在Google中对我的客户ID非常正确且最新 开发者控制台
  • 在开发控制台中清除并重新输入所述URls。
  • 更新client-secret.json文件并手动验证URL是否正确 将其制作成文件。
  • 从drive_client-> authenticate()切换到fetchAccessTokenWithAuthCode()以进行错误报告。

代码分布在3个不同的文件中,这些文件最终在执行期间在不同的点上相互要求 - 如果这有所不同,尽管我已经尝试将所有内容组合到1个文件中并且仍然存在相同的问题。 我的服务器也在CloudFlare后面运行,如果这有所不同,但是当我正在处理这个时,我会切换开发者模式。

生成oAuth请求并重定向用户:

class Person(var name: String)

// Usage...
val p = Person("Dave")
println(p.name) // "Dave"
p.name = "Phil"
println(p.name) // "Phil"

回电

$this->_Google_Client = new Google_Client();
$this->_Google_Client->setAuthConfig("path/to/client_secret....json");
$this->_Google_Client->setIncludeGrantedScopes(true);
$this->_Google_Client->setAccessType("offline");
$this->_Google_Client->addScope(Google_Service_Drive::DRIVE_FILE);
$this->_Google_Client->setRedirectUri("https://example.org/accounts/settings/oAuthCallback.php");
$authUrl = $this->_Google_Client->createAuthUrl();

$_SESSION["oAuth_Action"] = "GDrive_API_Setup";//Used internally for something else
header("Location: " . $authUrl);
exit();

确切错误

$code = @$_GET["code"];
$this->_Google_Client = new Google_Client();
$this->_Google_Client->setAuthConfig("path/to/client_secret....json");
$this->_Google_Client->setIncludeGrantedScopes(true);
$this->_Google_Client->setAccessType("offline");
$this->_Google_Client->addScope(Google_Service_Drive::DRIVE_FILE);
$accessToken = $this->_Google_Client->fetchAccessTokenWithAuthCode($code);
$this->_Google_Client->setAccessToken($accessToken);

echo var_dump($accessToken) . " -- " . $code; //Debug where I get error

我遗漏了用于创建实际文件的代码,因为它没有问题(我不会在检索访问令牌之前尝试创建文件夹),以及我之间调用的其他一些内容我的数据库。 谢谢!

1 个答案:

答案 0 :(得分:0)

之前我遇到过类似的问题,原因是重定向uri没有在回拨中设置。您能否添加以下内容:

$this->_Google_Client->setRedirectUri("https://example.org/accounts/settings/oAuthCallback.php");

回调后,行:

$this->_Google_Client->setAccessType("offline");

所以它应该是:

$this->_Google_Client->setIncludeGrantedScopes(true);
$this->_Google_Client->setAccessType("offline");
$this->_Google_Client->setRedirectUri("https://example.org/accounts/settings/oAuthCallback.php");

我希望有所帮助。