Skip to content

Instantly share code, notes, and snippets.

@putrikarunia
Last active November 3, 2020 01:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save putrikarunia/85a23692b277ed4cf802571983de0520 to your computer and use it in GitHub Desktop.
// ======================================================
// Refresh Google's Access Token when Expired
// ======================================================
// Access tokens from Google can expire, use this function to refresh the access token
// the `refresh_token` can be retrieved from Cotter's API
// REQUIREMENTS:
// - GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET env variables using Google OAuth 2.0 Credentials
async function refreshGoogleToken(refresh_token) {
const body = {
"client_id": GOOGLE_CLIENT_ID,
"client_secret": GOOGLE_CLIENT_SECRET,
"refresh_token": refresh_token,
"grant_type": "refresh_token"
}
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
}
const response = await fetch(`https://oauth2.googleapis.com/token`, config)
const resp = await response.json()
console.log(resp)
if (response.status !== 200) throw new Error("Fail refreshing token")
return resp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment