Skip to content

Instantly share code, notes, and snippets.

@fitwist
Created July 19, 2024 10:16
Show Gist options
  • Save fitwist/642c9c17267bb210fffd8367b9968dd3 to your computer and use it in GitHub Desktop.
Save fitwist/642c9c17267bb210fffd8367b9968dd3 to your computer and use it in GitHub Desktop.
How to get Google Cloud API access_token via refresh_token in JavaScript
const axios = require('axios');
async function getRefreshToken(clientId, clientSecret, refreshToken) {
const tokenUrl = 'https://oauth2.googleapis.com/token';
const params = new URLSearchParams();
params.append('client_id', clientId);
params.append('client_secret', clientSecret);
params.append('refresh_token', refreshToken);
params.append('grant_type', 'refresh_token');
try {
const response = await axios.post(tokenUrl, params);
return response.data; // Вернет объект с access_token и refresh_token
} catch (error) {
console.error('Error fetching refresh token:', error.response ? error.response.data : error.message);
throw error;
}
}
const clientId = '<client_id>';
const clientSecret = '<client_secret>';
const refreshToken = '<refresh_token>';
getRefreshToken(clientId, clientSecret, refreshToken)
.then(data => {
console.log('New Tokens:', data);
})
.catch(error => {
console.error('Error:', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment