NodeJS,如何使用 google api 获取带有刷新令牌的新令牌?

Syd*_* C. 7 google-api google-sheets node.js google-oauth google-api-nodejs-client

按照 google api 文档https://developers.google.com/sheets/api/quickstart/nodejs,无法找到使用 oauth2 客户端的刷新令牌来获取新令牌的方法。

医生说: "The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one."

如何使用 google oAuth2 客户端的刷新令牌获取新令牌?

到目前为止,我已经成功地使用了一个简单的帖子

const getTokenWithRefresh = async (refresh_token) => {
  return axios
  .post("https://accounts.google.com/o/oauth2/token", {
    client_id: clientId,
    client_secret: clientSecret,
    refresh_token: refresh_token,
    grant_type: "refresh_token",
  })
  .then((response) => {
    // TODO save new token here
    console.log("response", response.data.access_token);
    return response.data;
  })
  .catch((response) => console.log("error", response))
}
Run Code Online (Sandbox Code Playgroud)

但理想情况下希望看到更清洁的方法。

And*_*dyW 7

const {google} = require('googleapis')


const getTokenWithRefresh = (secret, refreshToken) => {

    let oauth2Client = new google.auth.OAuth2(
           secret.clientID,
           secret.clientSecret,
           secret.redirectUrls
    )

    oauth2Client.credentials.refresh_token = refreshToken

    oauth2Client.refreshAccessToken( (error, tokens) => {
           if( !error ){
                // persist tokens.access_token
                // persist tokens.refresh_token (for future refreshs)
           }
    })

}

Run Code Online (Sandbox Code Playgroud)

refreshAccessToken()已被弃用(我真的很想知道为什么)。但由于它仍然有效,这仍然是我要走的路