【问题标题】:Unable to get Google API access token using auth code - redirect uri mismatch无法使用身份验证代码获取 Google API 访问令牌 - 重定向 uri 不匹配
【发布时间】:2017-09-13 21:32:11
【问题描述】:

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

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

  • 对于我在 Google 中的客户 ID,已验证的 URL 都是正确且最新的 开发者控制台。
  • 在开发控制台中清除并重新输入上述 URL。
  • 更新 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" }

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

【问题讨论】:

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


    【解决方案1】:

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

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-19
      • 2023-02-03
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2018-10-22
      相关资源
      最近更新 更多