如何获得 Google oauth2 刷新令牌?

How to obtain a Google oauth2 refresh token?

以下代码使用 Google oauth2 机制登录用户。我们需要在用户离线时处理用户日历的更新,所以我们最终需要'refresh token'。 grantOfflineAccess() return 的结果是否是刷新令牌(在下面,我可以看到 response.code 持有一个可能是刷新令牌的值)?

如何获取可用于(服务器端)创建新访问密钥以离线访问用户 Google 日历的刷新令牌?

<script type="text/javascript">
    function handleClientLoad() {
        gapi.load('client:auth2', initClient);
    }

    function initClient() {
        gapi.client.init({
            apiKey: 'MY_API_KEY',
            clientId: 'MY_CLIENT_ID.apps.googleusercontent.com',
            discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
            scope: 'https://www.googleapis.com/auth/calendar'
        }).then(function () {
            var GoogleAuth = gapi.auth2.getAuthInstance();
            GoogleAuth.signIn();
            GoogleAuth.grantOfflineAccess().then(function (response) {
                var refresh_token = response.code;
            });
        });
    }

</script>

<script async defer src="https://apis.google.com/js/api.js"
        onload="this.onload=function(){};handleClientLoad()"
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

您在从 Java 脚本中获取 刷新令牌 时遇到问题是有原因的。那是不可能的。

Java脚本是一种客户端编程语言,要使其正常工作,您必须将您的客户端 ID 和客户端密码连同刷新令牌。这对在网页上查看源代码的任何人都是可见的。

我想你明白为什么这可能是个坏主意。主要问题是 gapi 不会 return 图书馆只是没有那种能力(不是我在原始 JavaScript 中尝试过看看是否如果我很好地询问,OAuth 服务器会 return 它 )。

您将需要切换到某些服务器端语言。我听说这可以用 Node.js 来完成,但我自己还没有尝试过。 Java、PHP、Python 也是有效的选项。

基于您的请求中的 , you should include the specific scopes。您的客户端配置应该有 $client->setAccessType("offline");$client->setApprovalPrompt("force");.

After allowing access, you will be returned an access code that you can exchange for an access token. The access token returned is the one you need to save in a database. Later on, if the user needs to use the calendar service, you simply use the access token you already saved.

这是一个示例代码:

/*
 * @$accessToken - json encoded array (access token saved to database)
*/

$client = new Google_Client();
$client->setAuthConfig("client_secret.json");
$client->addScope("https://www.googleapis.com/auth/calendar");

$_SESSION["access_token"] = json_decode($accessToken, true);

$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Calendar($client);

//REST OF THE PROCESS HERE