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

问题描述:

我试图使用Google API PHP客户端库在用户驱动器空间中创建文件夹。不幸的是,我不断收到“redirect_uri_mistmatch错误请求”错误。无法使用授权码获取Google API访问令牌 - 重定向uri不匹配

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

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

代码是跨所有最终执行过程中需要彼此在不同的点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"); 

我希望帮助。