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

Unable to get Google API access token using auth code - redirect uri mismatch

我正在尝试使用 Google API PHP 客户端库在用户驱动器 space 中创建一个文件夹。不幸的是,我一直收到 "redirect_uri_mistmatch Bad Request" 错误。

我查看了几篇试图解决该问题的帖子,但均无济于事。我已经采取的步骤是,

代码分布在 3 个不同的文件中,这些文件在执行期间的不同点最终都需要彼此 - 如果这会有所作为,尽管我已经尝试将所有内容合并到 1 个文件中但仍然遇到相同的问题。 我的服务器也 运行 落后于 CloudFlare,如果这有所不同,但我在处理此问题时会切换开发人员模式。

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

$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

确切错误

array(2) { ["error"]=> string(21) "redirect_uri_mismatch" ["error_description"]=> string(11) "Bad Request" }

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

我之前遇到过类似的问题,这是因为在回调时没有设置重定向 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");

希望对您有所帮助。