【问题标题】:PHP - Google Sheets API OAuth2- can't get tokenPHP - Google Sheets API OAuth2 - 无法获取令牌
【发布时间】:2016-11-01 16:00:09
【问题描述】:

我正在尝试创建一个令牌/refreshToken,以便我的网站能够在不向最终用户请求权限的情况下向 Google 表格提交数据,而我现在已经为此苦苦挣扎了几个小时......

我尝试了许多在网络上找到的不同代码 + Google 的文档,我取得了一些进展,但我无法让它工作,我无法弄清楚我错过了什么。..

此时我没有收到任何错误(在我的日志中也没有),但我也没有收到任何重定向或用于授权应用程序的新窗口

<?php
    session_start();

    require_once('php-google-oauth/Google_Client.php');
    include_once('lib/autoload.php');
    include_once('php-google-oauth/auth/Google_OAuth2.php');

    $CLIENT_ID = 'xxxxxxxxxxxx.apps.googleusercontent.com';
    $SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxx';
    $REDIRECT = 'http://mywebsite.com';
    $APIKEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    // $KEY = file_get_contents('php-google-oauth/client_secret.json');

    $client = new Google_Client();
    $client->setApplicationName("Contacts to Google Sheets");
    $client->setClientId($CLIENT_ID);
    $client->setClientSecret($SECRET);
    $client->setRedirectUri($REDIRECT);
    $client->setScopes(array('https://spreadsheets.google.com/feeds'));
    $client->setAccessType('offline');   // Gets us our refresh token

    // Step 1:  The user has not authenticated so we give them a link to login
    if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
        $authUrl = $client->createAuthUrl();
    }

    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['token'] = $client->getAccessToken();
        header('Location: ' . filter_var($REDIRECT, FILTER_SANITIZE_URL));
    }

    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
        $token = $client->getAccessToken();
    }

    echo '<script>console.log("TOKEN: '. $token .'");</script>';
?>

提前致谢!

【问题讨论】:

  • 如果它可以帮助你,请尝试检查这个Github。如果您正确设置代码,它可以作为您的指南。另外,请确保您阅读了有关在 Sheets API 中授权请求的documentation。另一件事是您应该在开发者控制台中启用 Sheets API 以访问此 API。欲了解更多信息,请查看此thread

标签: php access-token google-sheets-api


【解决方案1】:

我查看了我的代码并尝试了这个-

// Step 1:  The user has not authenticated so we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
    $authUrl = $client->createAuthUrl();
    echo '<a href="'. $authUrl . '">Click here</a>';
}

现在我确实从 Google 收到了一个令牌

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 2015-02-11
    • 1970-01-01
    • 2016-10-13
    • 2013-03-05
    • 2016-10-13
    • 2015-04-09
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多