简体   繁体   English

PHP - Google表格API OAuth2-无法获得令牌

[英]PHP - Google Sheets API OAuth2- can't get token

i am trying to create a token/refreshToken so my website will be able to submit data to Google Sheets without asking the end user for permissions and i am struggling with this for few hours now.. 我正在尝试创建令牌/ refreshToken,因此我的网站将能够向Google表格提交数据,而无需向最终用户请求权限,我现在正在努力争取这几个小时。

I tried many different codes i found on the web + Google's docs and i made some progress but i can't get it to work and i can't figure what i am missing.. 我尝试了很多不同的代码,我在网上找到+谷歌的文档,我取得了一些进展,但我无法让它工作,我无法想象我错过了什么..

At this point i get no error (neither in my logs) but also i don't get any redirect or new window for authorizing the app 此时我没有收到任何错误(在我的日志中都没有)但我也没有获得任何重定向或新窗口来授权应用程序

<?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>';
?>

Thanks in advance! 提前致谢!

I looked at my code and tried this- 我查看了我的代码并尝试了这个 -

// 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>';
}

and now i do get a token back from Google 现在我确实从Google获得了一个令牌

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM